gemi 0.131.0 → 0.133.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/AgentController.d.ts +73 -0
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/AgentProvider.d.ts +25 -0
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/VoiceBridge.d.ts +365 -0
- package/dist/ai/VoiceBridge.d.ts.map +1 -0
- package/dist/ai/index.d.ts +13 -0
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +18 -18
- package/dist/ai/index.js.map +11 -6
- package/dist/ai/providers/endpoints.d.ts +19 -0
- package/dist/ai/providers/endpoints.d.ts.map +1 -1
- package/dist/ai/providers/realtime.d.ts +272 -0
- package/dist/ai/providers/realtime.d.ts.map +1 -0
- package/dist/ai/providers/sideband.d.ts +254 -0
- package/dist/ai/providers/sideband.d.ts.map +1 -0
- package/dist/ai/runtime.d.ts.map +1 -1
- package/dist/ai/types.d.ts +15 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/voice/index.d.ts +23 -0
- package/dist/ai/voice/index.d.ts.map +1 -0
- package/dist/ai/voice/index.js +433 -0
- package/dist/ai/voice/index.js.map +1 -0
- package/dist/ai/voice/state.d.ts +34 -0
- package/dist/ai/voice/state.d.ts.map +1 -0
- package/dist/ai/voice/useVoiceSession.d.ts +82 -0
- package/dist/ai/voice/useVoiceSession.d.ts.map +1 -0
- package/dist/ai/voice/voiceCall.d.ts +57 -0
- package/dist/ai/voice/voiceCall.d.ts.map +1 -0
- package/dist/ai/voice/wire.d.ts +66 -0
- package/dist/ai/voice/wire.d.ts.map +1 -0
- package/dist/ai/voiceConfig.d.ts +70 -0
- package/dist/ai/voiceConfig.d.ts.map +1 -0
- package/dist/ai/voiceMcp.d.ts +89 -0
- package/dist/ai/voiceMcp.d.ts.map +1 -0
- package/dist/ai/voiceStore.d.ts +52 -0
- package/dist/ai/voiceStore.d.ts.map +1 -0
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-4gmhx2ba.js → chunk-0eamc2tr.js} +2 -2
- package/dist/{chunk-4gmhx2ba.js.map → chunk-0eamc2tr.js.map} +1 -1
- package/dist/{chunk-2x0n3ze1.js → chunk-0gg4e94v.js} +2 -2
- package/dist/{chunk-2x0n3ze1.js.map → chunk-0gg4e94v.js.map} +1 -1
- package/dist/{chunk-p642ja42.js → chunk-0rhf4g12.js} +3 -3
- package/dist/{chunk-p642ja42.js.map → chunk-0rhf4g12.js.map} +1 -1
- package/dist/{chunk-dxm5gxqk.js → chunk-1awxdnb6.js} +1 -1
- package/dist/{chunk-2senwsdq.js → chunk-2cnawkke.js} +12 -12
- package/dist/{chunk-2senwsdq.js.map → chunk-2cnawkke.js.map} +3 -3
- package/dist/{chunk-fxm8fqh9.js → chunk-33hdxe7v.js} +1 -1
- package/dist/{chunk-63xekerg.js → chunk-3g5q0cj5.js} +2 -2
- package/dist/{chunk-63xekerg.js.map → chunk-3g5q0cj5.js.map} +1 -1
- package/dist/{chunk-xjs72pb0.js → chunk-3h37f124.js} +2 -2
- package/dist/{chunk-xjs72pb0.js.map → chunk-3h37f124.js.map} +1 -1
- package/dist/{chunk-65fq5a9d.js → chunk-4278e429.js} +2 -2
- package/dist/{chunk-65fq5a9d.js.map → chunk-4278e429.js.map} +1 -1
- package/dist/chunk-47e7fbsp.js +5 -0
- package/dist/{chunk-mvka90rq.js.map → chunk-47e7fbsp.js.map} +1 -1
- package/dist/{chunk-p6b0cyf8.js → chunk-4pvv8qs0.js} +2 -2
- package/dist/{chunk-p6b0cyf8.js.map → chunk-4pvv8qs0.js.map} +1 -1
- package/dist/{chunk-rjyw1thg.js → chunk-4t41m5f1.js} +2 -2
- package/dist/{chunk-rjyw1thg.js.map → chunk-4t41m5f1.js.map} +1 -1
- package/dist/{chunk-f21v4n2v.js → chunk-53rr32zm.js} +1 -1
- package/dist/{chunk-xhvknqvn.js → chunk-5pdgh9a1.js} +2 -2
- package/dist/{chunk-xhvknqvn.js.map → chunk-5pdgh9a1.js.map} +1 -1
- package/dist/{chunk-e4ay1vg9.js → chunk-65j32dtn.js} +2 -2
- package/dist/{chunk-e4ay1vg9.js.map → chunk-65j32dtn.js.map} +1 -1
- package/dist/{chunk-jxvec7jc.js → chunk-6fr6j338.js} +2 -2
- package/dist/{chunk-jxvec7jc.js.map → chunk-6fr6j338.js.map} +1 -1
- package/dist/{chunk-jd1afbrs.js → chunk-6hz63ts4.js} +4 -4
- package/dist/{chunk-jd1afbrs.js.map → chunk-6hz63ts4.js.map} +1 -1
- package/dist/{chunk-4z0rt6ws.js → chunk-6qty7at2.js} +2 -2
- package/dist/{chunk-4z0rt6ws.js.map → chunk-6qty7at2.js.map} +1 -1
- package/dist/{chunk-pzb3agv9.js → chunk-7nxnyw7x.js} +2 -2
- package/dist/{chunk-pzb3agv9.js.map → chunk-7nxnyw7x.js.map} +1 -1
- package/dist/{chunk-7n0zn5h4.js → chunk-8ryrjtn0.js} +2 -2
- package/dist/{chunk-7n0zn5h4.js.map → chunk-8ryrjtn0.js.map} +1 -1
- package/dist/{chunk-c1gq2ttb.js → chunk-8sde8337.js} +2 -2
- package/dist/{chunk-c1gq2ttb.js.map → chunk-8sde8337.js.map} +1 -1
- package/dist/{chunk-cggywjzz.js → chunk-99a4e6zf.js} +2 -2
- package/dist/{chunk-cggywjzz.js.map → chunk-99a4e6zf.js.map} +1 -1
- package/dist/chunk-b6yb3svm.js +6 -0
- package/dist/{chunk-539w9yt3.js.map → chunk-b6yb3svm.js.map} +2 -2
- package/dist/{chunk-822p54vc.js → chunk-beb265c9.js} +2 -2
- package/dist/{chunk-822p54vc.js.map → chunk-beb265c9.js.map} +1 -1
- package/dist/{chunk-hdgbh8hn.js → chunk-cxsvzqd4.js} +2 -2
- package/dist/{chunk-hdgbh8hn.js.map → chunk-cxsvzqd4.js.map} +1 -1
- package/dist/{chunk-pahr13xg.js → chunk-dt95z6et.js} +2 -2
- package/dist/{chunk-pahr13xg.js.map → chunk-dt95z6et.js.map} +1 -1
- package/dist/{chunk-hr8annr1.js → chunk-feajsgns.js} +2 -2
- package/dist/{chunk-hr8annr1.js.map → chunk-feajsgns.js.map} +1 -1
- package/dist/{chunk-2tda49mv.js → chunk-ff60bzvf.js} +2 -2
- package/dist/{chunk-2tda49mv.js.map → chunk-ff60bzvf.js.map} +1 -1
- package/dist/{chunk-b00z33zg.js → chunk-gng5e7pd.js} +1 -1
- package/dist/{chunk-mz73066c.js → chunk-gqgpwb88.js} +2 -2
- package/dist/{chunk-mz73066c.js.map → chunk-gqgpwb88.js.map} +1 -1
- package/dist/{chunk-h0xye69a.js → chunk-ha15x5ns.js} +2 -2
- package/dist/{chunk-h0xye69a.js.map → chunk-ha15x5ns.js.map} +1 -1
- package/dist/{chunk-d5g1caxb.js → chunk-hb9hm8za.js} +3 -3
- package/dist/{chunk-d5g1caxb.js.map → chunk-hb9hm8za.js.map} +1 -1
- package/dist/{chunk-8fvt7kys.js → chunk-hf492gg2.js} +1 -1
- package/dist/{chunk-fgtr9cds.js → chunk-hj88dcss.js} +3 -3
- package/dist/{chunk-fgtr9cds.js.map → chunk-hj88dcss.js.map} +1 -1
- package/dist/{chunk-hnf11jhc.js → chunk-j5g7qc5f.js} +2 -2
- package/dist/{chunk-hnf11jhc.js.map → chunk-j5g7qc5f.js.map} +1 -1
- package/dist/{chunk-e1fhy2h5.js → chunk-jgx8ggbz.js} +2 -2
- package/dist/{chunk-e1fhy2h5.js.map → chunk-jgx8ggbz.js.map} +1 -1
- package/dist/{chunk-35zw2s61.js → chunk-jx2mgvvt.js} +3 -3
- package/dist/{chunk-35zw2s61.js.map → chunk-jx2mgvvt.js.map} +1 -1
- package/dist/{chunk-w26cw41m.js → chunk-jx5zx48j.js} +2 -2
- package/dist/{chunk-w26cw41m.js.map → chunk-jx5zx48j.js.map} +1 -1
- package/dist/{chunk-z1gjgr1c.js → chunk-jy9dkgt0.js} +2 -2
- package/dist/{chunk-z1gjgr1c.js.map → chunk-jy9dkgt0.js.map} +1 -1
- package/dist/{chunk-7j48ymk1.js → chunk-k2xeskp6.js} +2 -2
- package/dist/{chunk-7j48ymk1.js.map → chunk-k2xeskp6.js.map} +1 -1
- package/dist/{chunk-jxmc33m9.js → chunk-ka991yx4.js} +2 -2
- package/dist/{chunk-jxmc33m9.js.map → chunk-ka991yx4.js.map} +1 -1
- package/dist/{chunk-65s63bdh.js → chunk-krk880my.js} +2 -2
- package/dist/{chunk-65s63bdh.js.map → chunk-krk880my.js.map} +1 -1
- package/dist/{chunk-x4yq0c9v.js → chunk-m9vwg9j1.js} +3 -3
- package/dist/{chunk-x4yq0c9v.js.map → chunk-m9vwg9j1.js.map} +1 -1
- package/dist/{chunk-x07rp3fc.js → chunk-mpqvmge4.js} +1 -1
- package/dist/{chunk-n7sbwpce.js → chunk-mw7ft5bs.js} +2 -2
- package/dist/{chunk-n7sbwpce.js.map → chunk-mw7ft5bs.js.map} +1 -1
- package/dist/{chunk-v5esvs66.js → chunk-njpnstck.js} +2 -2
- package/dist/{chunk-v5esvs66.js.map → chunk-njpnstck.js.map} +1 -1
- package/dist/{chunk-p320fd3g.js → chunk-p82868xx.js} +2 -2
- package/dist/{chunk-p320fd3g.js.map → chunk-p82868xx.js.map} +1 -1
- package/dist/{chunk-jbd723h1.js → chunk-pm8wjatv.js} +3 -3
- package/dist/{chunk-jbd723h1.js.map → chunk-pm8wjatv.js.map} +1 -1
- package/dist/{chunk-t227jn4b.js → chunk-q15f5g86.js} +2 -2
- package/dist/{chunk-t227jn4b.js.map → chunk-q15f5g86.js.map} +1 -1
- package/dist/{chunk-838cdh6v.js → chunk-qfra7gah.js} +2 -2
- package/dist/{chunk-838cdh6v.js.map → chunk-qfra7gah.js.map} +1 -1
- package/dist/{chunk-aprjvzrz.js → chunk-rnp5k8m3.js} +2 -2
- package/dist/{chunk-aprjvzrz.js.map → chunk-rnp5k8m3.js.map} +1 -1
- package/dist/{chunk-qz89m7ss.js → chunk-rzqft8q8.js} +2 -2
- package/dist/{chunk-qz89m7ss.js.map → chunk-rzqft8q8.js.map} +1 -1
- package/dist/{chunk-zc5962gh.js → chunk-s025aycr.js} +2 -2
- package/dist/{chunk-zc5962gh.js.map → chunk-s025aycr.js.map} +1 -1
- package/dist/{chunk-y14weak4.js → chunk-s21kn0x8.js} +2 -2
- package/dist/{chunk-y14weak4.js.map → chunk-s21kn0x8.js.map} +1 -1
- package/dist/{chunk-3wnczt5w.js → chunk-s55t7rxw.js} +2 -2
- package/dist/{chunk-3wnczt5w.js.map → chunk-s55t7rxw.js.map} +1 -1
- package/dist/{chunk-fzs7g6mc.js → chunk-s782bzeq.js} +2 -2
- package/dist/{chunk-fzs7g6mc.js.map → chunk-s782bzeq.js.map} +1 -1
- package/dist/{chunk-77ymcf7q.js → chunk-sa6cxt3g.js} +2 -2
- package/dist/{chunk-77ymcf7q.js.map → chunk-sa6cxt3g.js.map} +1 -1
- package/dist/{chunk-dz76qhx8.js → chunk-swwkdm75.js} +2 -2
- package/dist/{chunk-dz76qhx8.js.map → chunk-swwkdm75.js.map} +1 -1
- package/dist/{chunk-58mg4rpd.js → chunk-t33yh84d.js} +2 -2
- package/dist/{chunk-58mg4rpd.js.map → chunk-t33yh84d.js.map} +1 -1
- package/dist/{chunk-mym7egdq.js → chunk-vnw91fe1.js} +2 -2
- package/dist/{chunk-mym7egdq.js.map → chunk-vnw91fe1.js.map} +1 -1
- package/dist/{chunk-4wda9teq.js → chunk-w1cksc5z.js} +3 -3
- package/dist/{chunk-4wda9teq.js.map → chunk-w1cksc5z.js.map} +1 -1
- package/dist/chunk-wevj4981.js +122 -0
- package/dist/{chunk-fx7r6pdf.js.map → chunk-wevj4981.js.map} +3 -3
- package/dist/{chunk-ayjfs5mm.js → chunk-wrsf2abe.js} +2 -2
- package/dist/{chunk-ayjfs5mm.js.map → chunk-wrsf2abe.js.map} +1 -1
- package/dist/{chunk-j1wc4afr.js → chunk-x16ckgq1.js} +2 -2
- package/dist/{chunk-j1wc4afr.js.map → chunk-x16ckgq1.js.map} +1 -1
- package/dist/{chunk-gnaxedwh.js → chunk-x51tegk3.js} +2 -2
- package/dist/{chunk-gnaxedwh.js.map → chunk-x51tegk3.js.map} +1 -1
- package/dist/{chunk-qspam5cf.js → chunk-x5hj0mqp.js} +2 -2
- package/dist/{chunk-qspam5cf.js.map → chunk-x5hj0mqp.js.map} +1 -1
- package/dist/{chunk-dp2yz8bj.js → chunk-x9bk5s21.js} +2 -2
- package/dist/{chunk-dp2yz8bj.js.map → chunk-x9bk5s21.js.map} +1 -1
- package/dist/{chunk-p462p2xe.js → chunk-xvvsc58s.js} +2 -2
- package/dist/{chunk-p462p2xe.js.map → chunk-xvvsc58s.js.map} +1 -1
- package/dist/{chunk-0g5f8ymy.js → chunk-xymr3asa.js} +2 -2
- package/dist/{chunk-0g5f8ymy.js.map → chunk-xymr3asa.js.map} +1 -1
- package/dist/{chunk-j4y0sjdc.js → chunk-ysc7ykss.js} +2 -2
- package/dist/{chunk-j4y0sjdc.js.map → chunk-ysc7ykss.js.map} +1 -1
- package/dist/{chunk-3xy41vc0.js → chunk-z61dj480.js} +3 -3
- package/dist/{chunk-3xy41vc0.js.map → chunk-z61dj480.js.map} +1 -1
- package/dist/{chunk-0q68t71d.js → chunk-z9xxthp1.js} +3 -3
- package/dist/{chunk-0q68t71d.js.map → chunk-z9xxthp1.js.map} +1 -1
- package/dist/{chunk-47eav3ex.js → chunk-zv5qyrqg.js} +2 -2
- package/dist/{chunk-47eav3ex.js.map → chunk-zv5qyrqg.js.map} +1 -1
- package/dist/{chunk-asmszzkp.js → chunk-zyhmn3hy.js} +3 -3
- package/dist/{chunk-asmszzkp.js.map → chunk-zyhmn3hy.js.map} +1 -1
- package/dist/{chunk-zzgt759n.js → chunk-zypmy8yq.js} +2 -2
- package/dist/{chunk-zzgt759n.js.map → chunk-zypmy8yq.js.map} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/ApiRouter.d.ts +27 -5
- 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/defaults.d.ts.map +1 -1
- package/dist/orm/index.js +3 -3
- package/dist/orm/index.js.map +3 -3
- 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 +2 -1
- package/dist/chunk-539w9yt3.js +0 -6
- package/dist/chunk-fx7r6pdf.js +0 -122
- package/dist/chunk-mvka90rq.js +0 -5
- /package/dist/{chunk-dxm5gxqk.js.map → chunk-1awxdnb6.js.map} +0 -0
- /package/dist/{chunk-fxm8fqh9.js.map → chunk-33hdxe7v.js.map} +0 -0
- /package/dist/{chunk-f21v4n2v.js.map → chunk-53rr32zm.js.map} +0 -0
- /package/dist/{chunk-b00z33zg.js.map → chunk-gng5e7pd.js.map} +0 -0
- /package/dist/{chunk-8fvt7kys.js.map → chunk-hf492gg2.js.map} +0 -0
- /package/dist/{chunk-x07rp3fc.js.map → chunk-mpqvmge4.js.map} +0 -0
package/dist/chunk-fx7r6pdf.js
DELETED
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Ng as iQ}from"./chunk-2tda49mv.js";import{fh as lQ}from"./chunk-hr8annr1.js";import{Ch as C,Dh as A8,Eh as WZ,Fh as Q8,Gh as e3,Ih as L$,Jh as v,Kh as R4,Yh as $6,di as YZ,gh as tZ,hi as oX,ii as h$,ji as p$,kh as oG,ki as MQ,lh as PW,mh as TW,mi as NQ,nh as G8,oh as J8,rh as W8,sh as Y8,th as cZ,uh as xG,vh as eG,wh as d9,xh as h}from"./chunk-p642ja42.js";import{pi as d1,qi as W0,ri as l1,si as NW}from"./chunk-47eav3ex.js";import{Ai as N,ti as q3,ui as WQ,yi as X5,zi as g4}from"./chunk-rjyw1thg.js";import{Di as uX,Gi as k3}from"./chunk-fgtr9cds.js";import{Ki as I5,Ni as DQ}from"./chunk-3xy41vc0.js";import{dj as D$,ij as u1}from"./chunk-mym7egdq.js";import{wj as SX}from"./chunk-z1gjgr1c.js";import{Aj as VQ,xj as c$}from"./chunk-j4y0sjdc.js";import{Bj as O1}from"./chunk-w26cw41m.js";import{Cj as a3,Dj as i0,Ej as x1,Fj as cQ,Gj as dQ,Ij as kZ,Jj as PQ,Sj as uQ}from"./chunk-0q68t71d.js";import{fk as C1}from"./chunk-e4ay1vg9.js";import{kk as iG,pk as Q9}from"./chunk-822p54vc.js";import{Bk as i,wk as lG}from"./chunk-zzgt759n.js";import{Ck as pZ,Fk as L}from"./chunk-35zw2s61.js";import{Nk as z9}from"./chunk-dp2yz8bj.js";import{Ok as _Q}from"./chunk-mz73066c.js";import{Yk as Z9}from"./chunk-hdgbh8hn.js";import{_k as aG}from"./chunk-cggywjzz.js";import{dl as m4}from"./chunk-aprjvzrz.js";function u3($){return typeof $==="function"&&$.prototype!==void 0}function l0($){return typeof $==="string"?[$]:$}function l3($,Z){let J=Z?"attachment":"inline",W=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${W}"; filename*=UTF-8''${encodeURIComponent($)}`}function WK($){return"total"in $&&"partial"in $&&"body"in $}function y9(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function sZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":Y8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function YK($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(WK($))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 j8($,Z){if($ instanceof Response)return $;if(!$)return y9();let J=await YK($),{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 y9()}let{range:G}=Z;if(G){if(z<=0)return sZ(Math.max(z,0));if(!X){if(W instanceof Blob){let F=J8(G,z);if(!F)return sZ(z);W=W.slice(F.start,F.end+1),Y=F.start,j=F.end,X=!0}}}let Q=Boolean(G)&&X,K=Q?206:J.status,B=new Headers;if(B.set("Accept-Ranges","bytes"),B.set("Content-Type",J.type||"application/octet-stream"),B.set("X-Content-Type-Options","nosniff"),Q)B.set("Content-Range",W8(Y,j,z)),B.set("Content-Length",String(j-Y+1));else if(z>=0)B.set("Content-Length",String(z));if(J.name)B.set("Content-Disposition",l3(J.name,J.download));if(J.etag)B.set("ETag",J.etag);if(J.lastModified)B.set("Last-Modified",J.lastModified.toUTCString());for(let[F,O]of Object.entries(J.extraHeaders))B.set(F,O);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:K,headers:B})}return new Response(W,{status:K,headers:B})}class r$ extends W0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var v9={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function oZ($){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 v9)))return Math.floor(Number(J[1])*(v9[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var nZ=new WeakMap;function m9($){return nZ.has($)}function h9($){return nZ.get($)?.limit??null}function p9($){let Z=nZ.get($);return Z?Z.read>Z.limit:!1}function jK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function X8($,Z){let J=jK($);if(J!==null&&J>Z)throw new r$(Z)}function i3($,Z,J={}){let W=nZ.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};nZ.set($,Y),XK($,Y)}if(J.checkDeclared!==!1)X8($,Z)}function zK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function z8($,Z){if(Z.stream!==void 0)return Z.stream;let J=zK($);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 r$(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 a$($,Z){if(X8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=z8($,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 g9($){return $.headers.get("Content-Type")??""}function XK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>z8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>a$($,Z)}),J("arrayBuffer",{value:async()=>{let W=await a$($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await a$($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await a$($,Z)))}),J("blob",{value:async()=>new Blob([await a$($,Z)],{type:g9($)})}),J("formData",{value:async()=>new Response(await a$($,Z),{headers:{"Content-Type":g9($)}}).formData()}),J("clone",{value:()=>{X8($,Z.limit);let W=z8($,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 c9($){return u3($)}class Y0{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(!c9(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(c9(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=l0($),this}}class u9{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=l0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of d9($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(p9($.rawRequest))throw new r$(h9($.rawRequest));throw J}}}class l9{constructor(...$){return new Y0(...$)}}class i9 extends Y0{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,W=G8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);return await j8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof Q8)return sZ(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class s9{constructor(...$){return new i9(...$)}}class n9{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new Y0("GET",$,"list"),post:new Y0("POST",$,"store")},this.second={get:new Y0("GET",$,"show"),put:new Y0("PUT",$,"update"),delete:new Y0("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 R0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new Y0("GET",$,Z)}post($,Z){return new Y0("POST",$,Z)}put($,Z){return new Y0("PUT",$,Z)}patch($,Z){return new Y0("PATCH",$,Z)}delete($,Z){return new Y0("DELETE",$,Z)}resource($){return new n9($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${GK($)}.`);return QK($,this)}file($,Z){return new l9("GET",$,Z)}stream($,Z){return new s9("GET",$,Z)}proxy($,Z={}){return new u9($,Z)}}function GK($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function QK($,Z){let J={stream:new Y0("POST",$,"stream"),attach:new Y0("POST",$,"attach"),stop:new Y0("POST",$,"stop"),upload:new Y0("POST",$,"upload")};return class extends R0{static __internal_brand="AgentRoute";static controller=$;static handlers=J;constructor(){super();this.middlewares=[...Z?.middlewares??[]]}routes={"/":J.stream,"/attach":J.attach,"/stop":J.stop,"/files":J.upload};static middleware(Y){if(Y.stream)J.stream.middleware(Y.stream);if(Y.attach)J.attach.middleware(Y.attach);if(Y.stop)J.stop.middleware(Y.stop);if(Y.upload)J.upload.middleware(Y.upload);return this}}}var p1="access_token";function O$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function s3($,Z){let J=O$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var KK=/^[A-Za-z0-9_-]+$/,FK=/^:[A-Za-z_][A-Za-z0-9_]*$/,o9=/^[A-Za-z0-9_-]{1,128}$/,BK=/^[A-Za-z0-9_.:-]+$/;class p extends Error{constructor($){super($);this.name="InvalidChannelError"}}function a9($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function t$($){if(typeof $!=="string"||$.length===0)throw new p("A channel pattern must be a non-empty string.");if($.length>255)throw new p(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(FK.test(W)){let Y=W.slice(1);if(J.has(Y))throw new p(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new p(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!KK.test(W))throw new p(`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 aZ($,Z={}){let J=t$($),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 p(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!o9.test(G))throw new p(`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 p(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new p(`The topic built from "${$}" is longer than 255 characters.`);return Y}function K8($){if(t$($).some((J)=>J.startsWith(":")))throw new p(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function r9($){if(typeof $!=="string"||$.length===0||$.length>64||!BK.test($))throw new p(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function t9($,Z){if($===Z)return!0;if($===F0)return Z.startsWith(`${F0}.`)&&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(":")&&o9.test(W[j]))}var F0="user";function e$($){let Z=typeof $==="object"&&$!==null?$.id:$;return aZ(`${F0}.:id`,{id:Z})}class r{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class n3 extends r{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return i3(this.req.rawRequest,oZ(Z)),{}}}function VK($){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 OK={"body-limit":n3};class c1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:oZ($.bodyLimit)}get aliases(){return{...OK,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!m9($))i3($,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 VK($).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:e9(z)})}}else if(u3(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:e9(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 DK(W.slice(j+1)),z}return Y})()}}function e9($){return $?.runsOnRefusal===!0}async function DK($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class o3{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...l0($)],this}events(...$){return this}}class WW{static __brand="ChannelRouter";channels={};public(){return new o3("public")}private($){return new o3("private",$)}async authorize($,Z,J={},W={}){try{IK(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(!YW(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===F0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=aZ(Z,J??{})}catch(G){if(G instanceof p)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 N.exit(()=>a3.exit(()=>N.run(X,async()=>{let G=N.getStore();try{if(Y.middlewares.length>0)await L(c1).runMiddleware(Y.middlewares);if(Z===F0){let Q=await $W(X);if(!Q)return{ok:!1,code:"denied"};if(j=e$(Q),Y.visibility==="private"&&Y.authorizer){if(await ZW(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 ZW(Y.authorizer,X,z):await $W(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(HK(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 UK($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;jW(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 YW($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function $W($){if(!N.getStore().user&&O$($)===null)return null;try{return await b0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function ZW($,Z,J){if(LK($))return new $().authorize(Z,J);return $(Z,J)}function LK($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function HK($){return $?.kind===d1||u1($)||D$($)}var JW=new WeakSet;function IK($){if(JW.has($))return;jW($),JW.add($)}function jW($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!YW(Y))throw new p(`The channel "${W}" is not declared with this.public() or this.private().`);let j=t$(W);if(j[0].startsWith(":"))throw new p(`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!==F0&&j.length===2&&j[0]===F0)throw new p(`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!==F0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new p(`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===F0?[F0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(PK(J[W].segments,J[Y].segments))throw new p(`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 PK($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class F8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class B8{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class V8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}class zW{static __brand="McpRouter";routes={};scopes;param($){return new F8($.as,$.input,$.bind)}fromTool($,Z={}){return new V8($,Z)}fromApiRoute($,Z,J){return new B8($,Z,J)}}function B0($,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 O8 extends W0{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 M1{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 O8([B0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new O8($,Z)}}var XW=Symbol.for("gemi.HttpResponse");class U${kind;body;status;headers;[XW]=!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 TK(J),new U$("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 U$.json({error:Z},{...J,status:$})}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}}}function TK($){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.json: a ${$} response has no body.`)}function $Z($){return typeof $==="object"&&$!==null&&$[XW]===!0}function MK($,Z,J={}){return U$.error($,Z,J)}class GW{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 M1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function D8($,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",l3(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class QW{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=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function KW($,Z){if($Z($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class FW{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=KW(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=l0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class BW{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends N1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends N1{routes=J??{}}}else this.children=class extends N1{routes=Z},this.handler=()=>({})}async run($,Z){let J=KW(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=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class N1{middlewares=[];featureGates=[];routes={};view($,Z){return new FW($,Z)}file($){return new QW($)}redirect($){return new GW($)}layout($,Z,J){return new BW($,Z,J)}}function NK($){return $}function _K(){return{aliases:{},global:[],bodyLimit:null}}var Y1="redirect";function j1($,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 ZZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function xK($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(L(i).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function CK($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function r3($,Z){let J=Z||L(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=xK($,!W);if(W||!CK(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(Y1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class VW extends r{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let W=await s3(L(E),J);if(!W)throw new L$({redirectTo:r3(J,$)});return Z.setUser(W),{}}}var L8="gemi_same_site",U8="private, no-cache, no-store, max-age=0, must-revalidate";class t3 extends r{run(){let $=N.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(L8))return{};if(O$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(L8,"1"),new OW(`${W.pathname}${W.search}`)}}class OW extends W0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=SK($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":U8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":U8}},viewData:{status:200,data:{},headers:{"Cache-Control":U8},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 SK($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class DW extends r{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 UW={"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 LW extends r{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={...UW,...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={...UW,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var AK="Rate limit exceeded";class i1 extends W0{result;retryAfter;constructor($,Z=AK){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?H8($):{}};this.payload={api:{status:429,data:{error:{...l1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function H8($){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 z1{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(HW("window",W),HW("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 i1(W,typeof J==="function"?J(W):J);return W}}function HW($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}class MW extends r{async run($,Z){let J=EK();if(!J)return{};let W=await J.consume(this.key(),{limit:IW($)??this.config.limit,window:IW(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(H8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new i1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=PW(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${JZ(this.req)}:${this.req.routePath??"*"}`}}function EK(){try{let $=L();return $.bound(z1)?$.make(z1):null}catch{return null}}function JZ($){let Z=TW($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function IW($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class _W extends r{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new I8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new I8;return{}}}class I8 extends W0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:NW("csrf","Invalid CSRF token",403)}},view:{}}}class xW{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class CW{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 WZ:new e3}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 r{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 WZ:$ instanceof e3}}function fK($){return new P8($)}async function Z6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await uK($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return dK(z,Z,J,$.url)}async function dK($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:K}=await Y.read();if(Q)break;if(z+K.byteLength>Z){if(!J)throw new $6(W,Z);j.push(K.subarray(0,Z-z)),z=Z;break}j.push(K),z+=K.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 uK($){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 J6($){return new TextDecoder("utf-8").decode($)}var lK={"&":"&","<":"<",">":">",'"':""","'":"'"};function H$($){return $.replace(/[&<>"']/g,(Z)=>lK[Z])}var iK={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function T8($){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 iK[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 M8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function SW($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(T8($.slice(W)));return}if(Y>W)Z.text(T8($.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(M8($.slice(Y+2,j).trim())),W=j+1}else{let j=sK($,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=M8(z.slice(0,G));if(Q){if(Z.open(Q,nK(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function sK($,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 nK($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[M8(W[1])]=T8(W[2]??W[3]??"");return Z}class j0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var bW="http://www.sitemaps.org/schemas/sitemap/0.9",oK="http://www.w3.org/1999/xhtml",x8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
|
-
`,AW=`<urlset xmlns="${bW}" xmlns:xhtml="${oK}">
|
|
4
|
-
`,EW=`</urlset>
|
|
5
|
-
`,I$=50000,rZ=52428800,fW=2048,aK=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),rK=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,tK="application/xml; charset=utf-8",RW=new TextEncoder;function C8($,Z){let J;try{J=new URL($)}catch{throw new j0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new j0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>fW)throw new j0(`Sitemap: ${Z} is over ${fW} characters: "${W.slice(0,80)}\u2026".`);return W}function wW($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new j0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!rK.test($))throw new j0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function eK($){let Z=C8($.loc,"loc"),J=`<url><loc>${H$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${H$(wW($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!aK.has($.changefreq))throw new j0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);J+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let W=$.priority;if(!Number.isFinite(W)||W<0||W>1)throw new j0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let Y=W.hrefLang?.trim();if(!Y)throw new j0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=C8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${H$(Y)}" href="${H$(j)}"/>`}return`${J}</url>
|
|
6
|
-
`}function $F($){let Z=$.maxUrls??I$,J=$.maxBytes??rZ;if(!Number.isInteger(Z)||Z<1||Z>I$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${I$}.`);if(!Number.isInteger(J)||J<1||J>rZ)throw RangeError(`Sitemap: maxBytes must be an integer from 1 to ${rZ}.`);return{maxUrls:Z,maxBytes:J}}function kW($,Z={}){let{maxUrls:J,maxBytes:W}=$F(Z),Y=RW.encode(x8+AW+EW).byteLength,j=[],z=[],X=Y,G=()=>{j.push(x8+AW+z.join("")+EW),z=[],X=Y};for(let Q of $){let K=eK(Q),B=RW.encode(K).byteLength;if(Y+B>W)throw new j0(`Sitemap: the entry for ${Q.loc} alone is over maxBytes (${W}).`);if(z.length===J||X+B>W)G();z.push(K),X+=B}if(z.length>0||j.length===0)G();return j}function qW($){let Z="",J=0;for(let W of $){if(++J>I$)throw new j0(`Sitemap: an index can list at most ${I$} sitemaps.`);let Y=C8(W.loc,"sitemap loc");if(Z+=`<sitemap><loc>${H$(Y)}</loc>`,W.lastmod!=null)Z+=`<lastmod>${H$(wW(W.lastmod,Y))}</lastmod>`;Z+=`</sitemap>
|
|
7
|
-
`}return`${x8}<sitemapindex xmlns="${bW}">
|
|
8
|
-
${Z}</sitemapindex>
|
|
9
|
-
`}function N8($,Z,J){let W=new Headers(J);if(!W.has("content-type"))W.set("content-type",tK);return new Response($,{status:Z,headers:W})}function ZF($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function JF($,Z={}){let J=kW($,Z),W=ZF(Z.page);if(W!==null){let j=J[W-1];return j?N8(j,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(J.length===1)return N8(J[0],200,Z.headers);let Y=Z.pageUrl;if(!Y)throw new j0(`Sitemap: the entries need ${J.length} files, so Sitemap.response needs \`pageUrl\` to list them in an index.`);return N8(qW(J.map((j,z)=>({loc:Y(z+1)}))),200,Z.headers)}function _8($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function yW($,Z={}){let J=Z.maxUrls??1/0,W=$.replace(/^\uFEFF/,"").trimStart();if(!W.startsWith("<")){let F=[];for(let O of W.split(/\r?\n/)){if(F.length>=J)break;let V=O.trim()?_8(O):null;if(V)F.push({loc:V})}if(F.length===0&&W.length>0)throw new j0("Sitemap: the document is neither XML nor a list of URLs.");return{kind:"urlset",urls:F}}let Y=null,j=[],z=[],X=[],G=null,Q=null,K="",B=()=>Y==="index"?z.length:j.length;if(SW(W,{stopped:()=>B()>=J,open(F,O){let V=X[X.length-1];if(X.push(F),Y===null){if(F==="urlset")Y="urlset";else if(F==="sitemapindex")Y="index";return}if(Y==="urlset"&&F==="url"&&V==="urlset"||Y==="index"&&F==="sitemap"&&V==="sitemapindex")G={};else if(G&&(V==="url"||V==="sitemap")&&(F==="loc"||F==="lastmod"||F==="changefreq"||F==="priority"))Q=F,K="";else if(G&&Y==="urlset"&&V==="url"&&F==="link"){let D=O.href?_8(O.href):null;if(O.rel?.toLowerCase()==="alternate"&&O.hreflang&&D)(G.alternates??=[]).push({hrefLang:O.hreflang,href:D})}},close(F){let O=X.lastIndexOf(F);if(O===-1)return;if(X.length=O,Q&&F===Q&&G)G[Q]=K.trim(),Q=null;else if(G&&(F==="url"||F==="sitemap")){let V=G;G=null,Q=null;let D=V.loc?_8(V.loc):null;if(!D)return;if(Y==="index"){z.push(V.lastmod?{loc:D,lastmod:V.lastmod}:{loc:D});return}let U={loc:D};if(V.lastmod)U.lastmod=V.lastmod;if(V.changefreq)U.changefreq=V.changefreq;let H=V.priority?Number(V.priority):NaN;if(Number.isFinite(H))U.priority=H;if(V.alternates)U.alternates=V.alternates;j.push(U)}},text(F){if(Q)K+=F}}),Y===null)throw new j0("Sitemap: the document has no <urlset> or <sitemapindex>.");return Y==="index"?{kind:Y,sitemaps:z}:{kind:Y,urls:j}}async function*WF($,Z={}){let{maxUrls:J=I$,maxSitemaps:W=50,maxDepth:Y=3,maxSize:j=rZ,onError:z,...X}=Z,G=[{url:String($),depth:0}],Q=new Set,K=0,B=0;while(G.length>0&&B<J&&K<W){let F=G.shift(),O=F.url.replace(/#.*$/,"");if(Q.has(O))continue;Q.add(O),K++;let V;try{let D=await YZ(F.url,{...X,maxSize:j});if(!D.ok)throw D.body?.cancel().catch(()=>{}),new j0(`Sitemap: ${F.url} answered ${D.status}.`,F.url,D.status);let U=J6(await Z6(D,j));V=yW(U,{maxUrls:Math.max(J-B,W-K)})}catch(D){if(F.depth===0||!z||X.signal?.aborted)throw D;z(D,F.url);continue}if(V.kind==="index"){if(F.depth>=Y)continue;G=V.sitemaps.slice(0,W-K).map((U)=>({url:U.loc,depth:F.depth+1})).concat(G);continue}for(let D of V.urls)if(yield{...D,sitemap:F.url},++B>=J)return}}var vW={response:JF,chunk:kW,index:qW,parse:yW,read:WF,MAX_URLS:I$,MAX_BYTES:rZ};var YF=512000,jF=new TextEncoder;function gW($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function mW($){let Z="";for(let J=0;J<$.length;J++){let W=$[J];if(W==="%"&&/^[0-9a-fA-F]{2}$/.test($.slice(J+1,J+3)))Z+=`%${$.slice(J+1,J+3).toUpperCase()}`,J+=2;else if(W.charCodeAt(0)>126||W.charCodeAt(0)<=32){let Y=$.codePointAt(J);if(Y>65535)J++;for(let j of jF.encode(String.fromCodePoint(Y)))Z+=`%${j.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=W}return Z}function zF($,Z){let J=$.endsWith("$"),W=J?$.slice(0,-1):$,Y=0,j=0,z=-1,X=0;while(j<Z.length)if(Y<W.length&&W[Y]!=="*"&&W[Y]===Z[j])Y++,j++;else if(Y<W.length&&W[Y]==="*")z=Y++,X=j;else if(Y===W.length&&!J)return!0;else if(z!==-1)Y=z+1,j=++X;else return!1;while(Y<W.length&&W[Y]==="*")Y++;return Y===W.length}class jZ{groups;sitemaps;status;constructor($,Z,J="parsed"){this.groups=$;this.sitemaps=Z;this.status=J}groupsFor($){let Z=gW($)||"*";if(Z!=="*"){let J=this.groups.filter((W)=>W.userAgents.includes(Z));if(J.length>0)return J}return this.groups.filter((J)=>J.userAgents.includes("*"))}isAllowed($,Z="*"){let J;if($ instanceof URL||/^[a-z][a-z0-9+.-]*:/i.test($)){let Y=new URL(String($));J=Y.pathname+Y.search}else J=$.startsWith("/")?$:`/${$}`;if(J==="/robots.txt")return!0;if(this.status==="unavailable")return!0;if(this.status==="unreachable")return!1;J=mW(J);let W=null;for(let Y of this.groupsFor(Z))for(let j of Y.rules){if(!zF(j.path,J))continue;let z=j.path.length,X=j.type==="allow";if(!W||z>W.length||z===W.length&&X)W={length:z,allow:X}}return W?W.allow:!0}crawlDelay($="*"){for(let Z of this.groupsFor($))if(Z.crawlDelay!==void 0)return Z.crawlDelay;return null}}var XF={"user-agent":"user-agent",useragent:"user-agent","user agent":"user-agent",allow:"allow",disallow:"disallow",dissallow:"disallow",disalow:"disallow",sitemap:"sitemap","site-map":"sitemap","crawl-delay":"crawl-delay"};function hW($,Z={}){let J=[],W=[],Y=null,j=!1;for(let z of $.replace(/^\uFEFF/,"").split(/\r\n|\r|\n/)){let X=z.indexOf("#"),G=(X===-1?z:z.slice(0,X)).trim(),Q=G.indexOf(":");if(Q===-1)continue;let K=XF[G.slice(0,Q).trim().toLowerCase()],B=G.slice(Q+1).trim();if(!K)continue;if(K==="sitemap"){if(!B||/\s/.test(B))continue;try{let F=Z.url?new URL(B,Z.url):new URL(B);if(F.protocol==="http:"||F.protocol==="https:")W.push(F.href)}catch{}continue}if(K==="user-agent"){if(!j||!Y)Y={userAgents:[],rules:[]},J.push(Y),j=!0;let F=gW(B);if(F)Y.userAgents.push(F);continue}if(!Y)continue;if(j=!1,K==="crawl-delay"){let F=Number(B);if(Number.isFinite(F)&&F>=0)Y.crawlDelay=F;continue}if(!B)continue;Y.rules.push({type:K,path:mW(B)})}return new jZ(J,W)}async function GF($,Z={}){let{maxSize:J=YF,...W}=Z,Y=new URL("/robots.txt",$),j=await YZ(Y,{...W,maxSize:Number.MAX_SAFE_INTEGER}),z=j.status;if(z===429||z>=500)return j.body?.cancel().catch(()=>{}),new jZ([],[],"unreachable");if(z>=400)return j.body?.cancel().catch(()=>{}),new jZ([],[],"unavailable");let X=await Z6(j,J,!0),G=J6(X);if(X.byteLength>=J)G=G.slice(0,Math.max(0,G.lastIndexOf(`
|
|
10
|
-
`)));return hW(G,{url:j.url})}function S8($){return $===void 0?[]:typeof $==="string"?[$]:$}function W6($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
|
|
11
|
-
`}function pW($){let Z=[];for(let W of $.rules??[]){let Y=S8(W.userAgent);if(Y.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let j=Y.map((X)=>W6("User-agent",X)).join(""),z=[...S8(W.allow).map((X)=>["Allow",X]),...S8(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+=W6(X,G)}if(z.length===0)j+=`Disallow:
|
|
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+=W6("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 W6("Sitemap",Y.href)});if(J.length>0)Z.push(J.join(""));return Z.join(`
|
|
13
|
-
`)}function QF($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(pW($),{status:200,headers:J})}var cW={response:QF,text:pW,parse:hW,fetch:GF};import{createHmac as dW,randomBytes as KF}from"crypto";var E8="v2.";function f8($){return $.startsWith(E8)}function zZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function uW($){let Z=KF(16).toString("hex"),J=dW("sha256",zZ()).update(`${$}:${Z}`).digest("hex");return`${E8}${J}`}function Y6($,Z){let J=dW("sha256",zZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${E8}${J}`}import{createHash as VF,createHmac as OF,randomInt as DF,timingSafeEqual as sW}from"crypto";function lW($,Z){return Math.floor($/Z)*Z}function FF($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function R8($,Z,J,W){return Z*FF(J,W)+$}function BF($){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 K=Y*(1-(X-Z)/J);if(K<=Y)return Math.max(0,Math.ceil(K-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 iW($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:G}=$;if(Z){let K=R8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-K)),resetAt:Y-j+z,retryAfter:0}}let Q=BF({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 b8{}class w8 extends b8{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=lW(j,W),X=j-z,G=this.roll(Z,W,z);G.limit=J;let K=R8(G.current,G.previous,X,W)+Y<=J;if(K)G.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,G),this.buckets.size>this.maxKeys)this.evict(j);return iW({allowed:K,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 aW="h1.";function j6($,Z,J){let W=OF("sha256",zZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${aW}${W}`}function eZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(aW),X=j6($,Z,Y),G=Buffer.from(z?X:Y),Q=Buffer.from(j);if(G.length!==Q.length||Y===""||j==="")return sW(G,G),!1;return sW(G,Q)}function rW($){let Z="";for(let J=0;J<$;J++)Z+=String(DF(0,10));return Z}var tW=320;function $3($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>tW)return null;return Z.toLowerCase()}function z6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>tW)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var nW=null;function eW(){try{let $=L();if(typeof $?.bound==="function"&&$.bound(z1))return $.make(z1)}catch{}return nW??=new z1({driver:new w8,limit:1000,window:60}),nW}function oW($){return $.length<=64?$:`sha256:${VF("sha256").update($).digest("hex")}`}async function XZ($,Z,J,W){let Y=eW(),j=[[`auth:code-${$}:ip:${oW(JZ(J))}`,W.perIp]];if(Z!==null)j.push([`auth:code-${$}:email:${oW(Z)}`,W.perEmail]);for(let[z,X]of j){if(!X)continue;let[G,Q]=X,K=await Y.consume(z,{limit:G,window:Q});if(!K.allowed)throw new i1(K)}}async function $5($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await eW().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as q8}from"crypto";class k8 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"}}}function X6($,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 UF($={}){for(let Z of["password","magicLink"]){let J=$?.[Z];if(J!==void 0&&typeof J!=="boolean")throw Error(`auth.${Z} must be true or false, got ${JSON.stringify(J)}`)}}function y8($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5;return X6("length",Z,4,12),X6("expiresInMinutes",J,1),X6("linkExpiresInMinutes",W,1),X6("maxAttempts",Y,1),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:W,maxAttempts:Y,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:j,code:z})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${j}: ${z} (set auth.emailCode.send to deliver it)`)})}}async function LF($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function Z5($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:J}=$;return{provider:Z,...J!==void 0?{feature:J}:{}}}function J5($){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 } with an OAuthProvider.`);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 _I($){return $}function W5($={}){return UF($),{basePath:"/auth",verifyEmail:!0,password:!0,magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:k8,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:LF,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>q8(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return q8(32).toString("hex")},generateMagicLinkToken:()=>q8(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:y8($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}var HF=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),IF=new Set(["svg","math"]);function Y5($){return $===32||$===9||$===10||$===12||$===13}function j5($){return $>=65&&$<=90||$>=97&&$<=122}function G6($){return $>=65&&$<=90?$+32:$}function z5(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,G=0,Q=()=>$==="data"&&X===0&&G===0,K=()=>{if(!J&&HF.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(IF.has(Z)){if(J)G=Math.max(0,G-1);else if(!z)G+=1}Z=""},B=(F)=>{switch($){case"data":if(F===60)$="tagOpen";return;case"tagOpen":if(F===33)$="bang",j=0;else if(F===47)$="endTagOpen";else if(j5(F))$="tagName",J=!1,z=!1,Z=String.fromCharCode(G6(F));else if(F===63)$="bogus";else if(F===60)$="tagOpen";else $="data";return;case"endTagOpen":if(j5(F))$="tagName",J=!0,z=!1,Z=String.fromCharCode(G6(F));else if(F===62)$="data";else $="bogus";return;case"tagName":if(Y5(F)||F===47)$="inTag",z=F===47;else if(F===62)K();else Z+=String.fromCharCode(G6(F));return;case"inTag":if(F===62){K();return}if(z=F===47,F===34)$="attrDouble";else if(F===39)$="attrSingle";return;case"attrDouble":if(F===34)$="inTag";z=!1;return;case"attrSingle":if(F===39)$="inTag";z=!1;return;case"bang":if(F===45){if(j+=1,j===2)$="comment",j=0}else if(F===62)$="data";else $="bogus";return;case"bogus":if(F===62)$="data";return;case"comment":if(F===45)j=j<2?j+1:2;else if(F===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(Y<W.length){if(G6(F)===W.charCodeAt(Y))Y+=1;else Y=F===60?1:0;return}if(F===62)$="data",Z="";else if(Y5(F)||F===47)$="inTag",Z="";else Y=F===60?1:0;return}}};return{scanToInsertionPoint(F){for(let O=0;O<F.length;O++){if(Q())return O;B(F[O])}return F.length},write(F){for(let O=0;O<F.length;O++)B(F[O])},isSafe:Q}}function _1($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function PF($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${_1([$.path,$.variantKey,$.data])})</script>`}function TF($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${_1([$.id,$.locale,$.strings])})</script>`}function v8($,Z,J={},W){let Y=new TextEncoder,j=[],z=!1,X=!1,G=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((V)=>{if(V.status!=="resolved")return;j.push(PF(V))}),W?.onUse((V)=>{j.push(TF(V))});let Q=$.getReader(),K=z5(),B=(V,D)=>{V.enqueue(D),J.onChunk?.(D)},F=(V)=>{while(j.length>0){let D=Y.encode(j.shift());K.write(D),B(V,D)}},O=(V,D)=>{if(j.length===0){K.write(D),B(V,D);return}let U=K.scanToInsertionPoint(D);if(U>0)B(V,D.subarray(0,U));if(K.isSafe())F(V);let H=D.subarray(U);if(H.length>0)K.write(H),B(V,H)};return new ReadableStream({async pull(V){let D;try{D=await Q.read()}catch(T){throw G(),T}let{done:U,value:H}=D;if(U){F(V),V.close(),G();return}if(!z){if(z=!0,K.write(H),B(V,H),J.onShell?.(),K.isSafe())F(V);return}O(V,H)},cancel(V){return G(),Q.cancel(V)}})}var MF=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function Q6($){if(!$)return!1;return MF.test($)}async function G5($,Z=()=>{}){let J=N.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 NF($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:X5(),isBot:Q6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function Q5($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function NF($,Z){if(!$.context)return{};try{let J=N.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 K5($,Z){return`${$}:${Z}`}function g8($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function F5($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function B5($,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=xF($,Z,J,W.buckets);return F5(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function _F($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function xF($,Z,J,W){let Y=K5(Z.salt??$,_F(J));if(!W)return g8(Y);let j=W.get(Y);if(j!==void 0)return j;let z=g8(Y);return W.set(Y,z),z}class V5 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 m8{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 V5(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=CF(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 CF($){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 SF{}class AF 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 h8 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 O5 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 D5{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 s1{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new m8($.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{N.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new O5(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=EF(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new h8(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 D5(this,Q5($))}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=B5($,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 $=N.getStore();if($?.featureContext)return $.featureContext;let Z=await G5(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=N.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=N.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 EF($){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 U5($){if($===void 0)return!0;return await L(s1).enabled($)}async function GZ($,Z){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let J=Z5($[Z]);if(!J||!await U5(J.feature))return null;return J.provider}async function L5($){let Z=[];for(let J of Object.keys($))if(await GZ($,J))Z.push(J);return Z}function p8($){if($&&typeof $==="object")delete $.password;return $}function fF(){return new Proxy({},{get:($,Z)=>I5(Z)})}var H5=new WeakMap;function P5($){if($&&typeof $==="object"){for(let Z of Object.values($))P5(Z);Object.freeze($)}return $}var RF={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},bF=P5({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:RF});class c8{models;constructor($=fF()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return bF}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??x1(),W=L(C1).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await i0()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||i0())return Y();let z=(H5.get(W)??Promise.resolve()).then(Y,Y);return H5.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return p8(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return p8(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;try{return await this.run(()=>this.models.Session.findUnique({where:{token:$.token},select:this.sessionSelect()}))}catch(Z){return console.error("findSession failed:",Z),null}}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 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?p8(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 yO}from"crypto";function w0($,Z,J,W,Y){return s0(Z,y5($,Z),J,W,Y)}function s0($,Z,J,W,Y,j){let z=s8(Z,J,W);if(Y&&Z!==z)throw RangeError(Iz($,Z,J,W,j));return z}function y5($,Z){let J=$[Z];if(J===void 0)throw TypeError(M2(Z));return J}function O0($){return $!==null&&/object|function/.test(typeof $)}function y0($,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 ZJ($){return N$({name:$},1)}function N$($,Z){return r0((J)=>({value:J,configurable:1,writable:!Z}),$)}function v5($){return r0((Z)=>({get:Z,configurable:1}),$)}function x6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function DZ($,Z){let J={},W=$.length;for(let Y of Z)J[$[--W]]=Y;return J}function r0($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function Q3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function wF($,Z,J){let W={};for(let Y=0;Y<$.length;Y++)W[Z[Y]]=J[$[Y]];return W}function g0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function JJ($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function WJ($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function g5($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function m5($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function h5($,Z,J){let W={...J};for(let Y=0;Y<Z;Y++)W[$[Y]]=0;return W}function b($,...Z){return(...J)=>$(...Z,...J)}function T5($){return $[0].toUpperCase()+$.substring(1)}function K3($){return $.slice().sort()}function U6($,Z){return String(Z).padStart($,"0")}function n1($,Z){return Math.sign($-Z)}function s8($,Z,J){return Math.min(Math.max($,Z),J)}function A1($,Z){return[Math.floor($/Z),J3($,Z)]}function J3($,Z){return($%Z+Z)%Z}function r1($,Z){return[C6($,Z),YJ($,Z)]}function C6($,Z){return Math.trunc($/Z)||0}function YJ($,Z){return $%Z||0}function K6($){return Math.abs($%1)===0.5}function p5($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let G=$[J[X]],Q=G1[X],K=c/Q,[B,F]=r1(G,K);W+=F*Q,Y+=B}let[j,z]=r1(W,c);return[Y+j,z]}function S6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=G1[Y];W[J[Y]]=C6($,j),$=YJ($,j)}return W}function c5($){return $===w?X4:[]}function d5($){return $===w?P3:[]}function u5($){return $===w?["year","day"]:[]}function l5($){if($!==void 0)return t($)}function i5($){if($!==void 0)return t0($)}function jJ($){if($!==void 0)return F3($)}function t0($){return o5(F3($))}function F3($){return n5(_B($))}function zJ($){if($==null)throw TypeError("Cannot be null or undefined");return $}function s5($,Z){if(Z==null)throw RangeError(M2($));return Z}function f1($){if(!O0($))throw TypeError(Hz);return $}function A6($,Z,J=$){if(typeof Z!==$)throw TypeError(L3(J,Z));return Z}function n5($,Z="number"){if(!Number.isInteger($))throw RangeError(oF(Z,$));return $||0}function o5($,Z="number"){if($<=0)throw RangeError(aF(Z,$));return $}function XJ($){if(typeof $=="symbol")throw TypeError($B);return String($)}function L6($,Z){return O0($)?String($):t($,Z)}function E6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(eF($));return $}function a5($,Z="number"){if(typeof $=="bigint")throw TypeError(tF(Z));if($=Number($),!Number.isFinite($))throw RangeError(rF(Z,$));return $}function N0($,Z){return Math.trunc(a5($,Z))||0}function r5($,Z){return n5(a5($,Z),Z)}function M5($,Z){return o5(N0($,Z),Z)}function GJ($,Z){let[J,W]=r1(Z,c),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*c),[Y,W]}function KZ($,Z,J=1){return GJ($[0]+Z[0]*J,$[1]+Z[1]*J)}function FZ($,Z){return GJ($[0],$[1]+Z)}function c0($,Z){return KZ(Z,$,-1)}function x0($,Z){return n1($[0],Z[0])||n1($[1],Z[1])}function t5($,Z,J){return x0($,Z)===-1||x0($,J)===1}function f6($,Z=1){let J=BigInt(c/Z);return[Number($/J),Number($%J)*Z]}function BZ($,Z=1){let J=c/Z,[W,Y]=r1($,J);return[W,Y*Z]}function e5($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=c/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function d0($,Z=1,J){let[W,Y]=$,[j,z]=r1(Y,Z);return W*(c/Z)+(j+(J?z/Z:0))}function QJ($,Z,J=A1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(c/Z)+j,z]}function KJ($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function FJ($){return w0($,"isoYear",G3,X3,1),$.isoYear===G3?w0($,"isoMonth",4,12,1):$.isoYear===X3&&w0($,"isoMonth",1,9,1),$}function o1($){return R1({...$,...a0,isoHour:12}),$}function R1($){let Z=w0($,"isoYear",G3,X3,1),J=Z===G3?1:Z===X3?-1:0;return J&&u0(_0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function u0($){if(!$||t5($,RB,fB))throw RangeError(W4);return $}function t1($){return p5($,5,J1)[1]}function R6($){let[Z,J]=A1($,c);return[S6(J,5,J1),Z]}function $Y($){return ZY($)[0]}function ZY($){return QJ($,o0)}function C0($){return UZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function _0($){let Z=C0($);if(Z!==void 0){let[J,W]=r1(Z,q0);return[J,W*Q1+($.isoMicrosecond||0)*b$+($.isoNanosecond||0)]}}function BJ($,Z){let[J,W]=R6(t1($)-Z);return u0(_0({...$,isoDay:$.isoDay+W,...J}))}function H6(...$){return UZ(...$)/fz}function UZ(...$){let[Z,J]=JY(...$),W=Z.valueOf();if(!isNaN(W))return W-J*q0}function JY($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===G3?1:$===X3?-1:0,G=new Date;return G.setUTCHours(W,Y,j,z),G.setUTCFullYear($,Z-1,J+X),[G,X]}function $$($,Z){let[J,W]=FZ($,Z);W<0&&(W+=c,J-=1);let[Y,j]=A1(W,Q1),[z,X]=A1(j,b$);return b6(J*q0+Y,z,X)}function b6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-EB)/q0)*Math.sign($),Y=new Date($-W*q0);return DZ(Q4,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+W,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function WY($){return[$.isoYear,$.isoMonth,$.isoDay]}function YY(){return S1}function VJ($,Z){switch(Z){case 2:return OJ($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function jY($){return OJ($)?366:365}function OJ($){return $%4==0&&($%100!=0||$%400==0)}function zY($){let[Z,J]=JY($.isoYear,$.isoMonth,$.isoDay);return J3(Z.getUTCDay()-J,7)||7}function XY({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function kF($){let Z=C0($);if(Z<wB)return XY($);let J=KJ(h2(VZ),Z),{era:W,eraYear:Y}=Hj(J,VZ);return[W,Y]}function w6($){return _$($),k6($,1),$}function _$($){return GY($,1),$}function N5($){return m5(b2,$,GY($))}function GY($,Z){let{isoYear:J}=$,W=w0($,"isoMonth",1,YY(),Z);return{isoYear:J,isoMonth:W,isoDay:w0($,"isoDay",1,VJ(J,W),Z)}}function k6($,Z){return DZ(J1,[w0($,"isoHour",0,23,Z),w0($,"isoMinute",0,59,Z),w0($,"isoSecond",0,59,Z),w0($,"isoMillisecond",0,999,Z),w0($,"isoMicrosecond",0,999,Z),w0($,"isoNanosecond",0,999,Z)])}function y($){return $===void 0?0:sz(f1($))}function B3($,Z=0){$=e0($);let J=nz($),W=dB($,Z);return[sz($),W,J]}function DJ($){return nz(e0($))}function QY($){return $=e0($),q2($,9,6,1)}function LZ($,Z,J,W=9,Y=0,j=4){Z=e0(Z);let z=q2(Z,W,Y),X=HJ(Z),G=M3(Z,j),Q=T3(Z,W,Y,1);return z==null?z=Math.max(J,Q):VY(z,Q),X=IJ(X,Q,1),$&&(G=((K)=>K<4?(K+2)%4:K)(G)),[z,Q,X,G]}function q6($,Z=6,J){let W=HJ($=PJ($,_6)),Y=M3($,7),j=T3($,Z);return j=s5(_6,j),W=IJ(W,j,void 0,J),[j,W,Y]}function UJ($){return y2(e0($))}function KY($,Z){return LJ(e0($),Z)}function LJ($,Z=4){let J=BY($);return[M3($,4),...FY(T3($,Z),J)]}function FY($,Z){return $!=null?[G1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function HJ($){let Z=$[W3];return Z===void 0?1:N0(Z,W3)}function IJ($,Z,J,W){let Y=W?c:G1[Z+1];if(Y){let j=G1[Z];if(Y%(($=s0(W3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(L3(W3,$))}else $=s0(W3,$,1,J?1e9:1,1);return $}function BY($){let Z=$[i8];if(Z!==void 0){if(typeof Z!="number"){if(XJ(Z)==="auto")return;throw RangeError(L3(i8,Z))}Z=s0(i8,Math.floor(Z),0,9,1)}return Z}function e0($){return $===void 0?{}:f1($)}function PJ($,Z){return typeof $=="string"?{[Z]:$}:f1($)}function z0($){if($!==void 0){if(O0($))return Object.assign(Object.create(null),$);throw TypeError(Hz)}}function y6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:qB[Z]})}function TJ($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=XJ(j),j==="auto")return Y?W:null;let z=r8[j];if(z===void 0&&(z=SB[j]),z===void 0)throw RangeError(Mz($,j,r8));return s0($,z,W,J,1,I3),z}function x$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=XJ(Y),z=Z[j];if(z===void 0)throw RangeError(Mz($,j,Z));return z}function VY($,Z){if(Z>$)throw RangeError(IB)}function D0($){return{branding:F4,epochNanoseconds:$}}function I0($,Z,J){return{branding:q1,calendar:J,timeZone:Z,epochNanoseconds:$}}function X0($,Z=$.calendar){return{branding:k$,calendar:Z,...g0(dz,$)}}function G0($,Z=$.calendar){return{branding:w$,calendar:Z,...g0(w2,$)}}function T$($,Z=$.calendar){return{branding:xZ,calendar:Z,...g0(w2,$)}}function I6($,Z=$.calendar){return{branding:CZ,calendar:Z,...g0(w2,$)}}function $1($){return{branding:K4,...g0(cz,$)}}function s($){return{branding:B4,sign:Z$($),...g0(E2,$)}}function OY($){return $Y($.epochNanoseconds)}function v6($){return QJ($.epochNanoseconds,Q1)[0]}function DY($){return e5($.epochNanoseconds,b$)}function UY($){return e5($.epochNanoseconds)}function LY($){return $.epochNanoseconds}function L0($){return typeof $=="string"?$:t($.id)}function HZ($,Z){return $===Z||L0($)===L0(Z)}function HY($,Z,J,W,Y){let j=M$(W),[z,X]=((U,H)=>{let T=H((U=PJ(U,$J))[lz]),I=cB(U);return I=s5($J,I),[I,T]})(Y,$);if(j3(Math.max(z,j),X))return _5(W,z);if(!X)throw RangeError(Y4);let[G,Q,K]=d6(Z,J,X),B=lJ(K),F=u6(K),O=iJ(K),V=F(Q,G,W),D=O(Q,G,V,z);return j3(z,X)?_5(D,z):((U,H,T,I,x,A,f)=>{let S=Z$(U),[M,P]=MJ(I,R2(T,U),T,S,x,A,f),k=NJ(H,M,P);return U[g[T]]+k*S})(D,B(V),z,Q,G,B,F)}function _5($,Z){return d0(V0($),G1[Z],1)}function MJ($,Z,J,W,Y,j,z){let X=g[J],G={...Z,[X]:Z[X]+W},Q=z($,Y,Z),K=z($,Y,G);return[j(Q),j(K)]}function NJ($,Z,J){let W=d0(c0(Z,J));if(!W)throw RangeError(H3);return d0(c0(Z,$))/W}function IY($,Z){let[J,W,Y]=q6(Z,5,1);return D0(m6($.epochNanoseconds,J,W,Y,1))}function PY($,Z,J){let{epochNanoseconds:W,timeZone:Y,calendar:j}=Z,[z,X,G]=q6(J);if(z===0&&X===1)return Z;let Q=$(Y);if(z===6)W=((K,B,F,O)=>{let V=S0(F,B),[D,U]=K(V),H=F.epochNanoseconds,T=v0(B,D),I=v0(B,U);if(t5(H,T,I))throw RangeError(H3);return EY(NJ(H,T,I),O)?I:T})(SY,Q,Z,G);else{let K=Q.getOffsetNanosecondsFor(W);W=S$(Q,xY($$(W,K),z,X,G),K,2,0,1)}return I0(W,Y,j)}function TY($,Z){return X0(xY($,...q6(Z)),$.calendar)}function MY($,Z){let[J,W,Y]=q6(Z,5);var j;return $1((j=Y,_J($,V3(J,W),j)[0]))}function NY($,Z){let J=$(Z.timeZone),W=S0(Z,J),[Y,j]=SY(W),z=d0(c0(v0(J,Y),v0(J,j)),z4,1);if(z<=0)throw RangeError(H3);return z}function _Y($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>v0(z,j(S0(X,z))))(AY,$(J),Z);return I0(Y,J,W)}function xY($,Z,J,W){return CY($,V3(Z,J),W)}function CY($,Z,J){let[W,Y]=_J($,Z,J);return R1({...A$($,Y),...W})}function _J($,Z,J){return R6(e1(t1($),Z,J))}function P6($){return e1($,j4,7)}function V3($,Z){return G1[$]*Z}function SY($){let Z=AY($);return[Z,A$(Z,1)]}function AY($){return AB(6,$)}function qF($,Z,J){let W=Math.min(M$($),6);return PZ(h6(V0($,W),Z,J),W)}function g6($,Z,J,W,Y,j,z,X,G,Q){if(W===0&&Y===1)return $;let K=j3(W,X)?l6(X)&&W<6&&J>=6?vF:yF:gF,[B,F,O]=K($,Z,J,W,Y,j,z,X,G,Q);return O&&W!==7&&(B=((V,D,U,H,T,I,x,A)=>{let f=Z$(V);for(let S=H+1;S<=U;S++){if(S===7&&U!==7)continue;let M=R2(S,V);M[g[S]]+=f;let P=d0(c0(x(A(T,I,M)),D));if(P&&Math.sign(P)!==f)break;V=M}return V})(B,F,J,Math.max(6,W),z,X,G,Q)),B}function m6($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/c)($);return[e1(j,J,W),0]}return h6($,V3(Z,J),W,Y)}function h6($,Z,J,W){let[Y,j]=$;W&&j<0&&(j+=c,Y-=1);let[z,X]=A1(e1(j,Z,J),c);return GJ(Y+z,X)}function e1($,Z,J){return EY($/Z,J)*Z}function EY($,Z){return iB[Z]($)}function yF($,Z,J,W,Y,j){let z=Z$($),X=V0($),G=m6(X,W,Y,j),Q=c0(X,G),K=Math.sign(G[0]-X[0])===z,B=PZ(G,Math.min(J,6));return[{...$,...B},KZ(Z,Q),K]}function vF($,Z,J,W,Y,j,z,X,G,Q){let K=Z$($),B=d0(V0($,5)),F=V3(W,Y),O=e1(B,F,j),[V,D]=MJ(z,{...$,...f2},6,K,X,G,Q),U=O-d0(c0(V,D)),H=0;U&&Math.sign(U)!==K?Z=FZ(V,O):(H+=K,O=e1(U,F,j),Z=FZ(D,O));let T=s6(O);return[{...$,...T,days:$.days+H},Z,Boolean(H)]}function gF($,Z,J,W,Y,j,z,X,G,Q){let K=Z$($),B=g[W],F=R2(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let O=C6($[B],Y)*Y;F[B]=O;let[V,D]=MJ(z,F,W,Y*K,X,G,Q),U=O+NJ(Z,V,D)*K*Y,H=e1(U,Y,j),T=Math.sign(H-U)===K;return F[B]=H,[F,T?D:V,T]}function xJ($,Z,J,W){let[Y,j,z,X]=((Q)=>{let K=LJ(Q=e0(Q));return[Q.timeZone,...K]})(W),G=Y!==void 0;return((Q,K,B,F,O,V)=>{B=h6(B,O,F,1);let D=K.getOffsetNanosecondsFor(B);return bJ($$(B,D),V)+(Q?C$(P6(D)):"Z")})(G,Z(G?$(Y):q$),J.epochNanoseconds,j,z,X)}function CJ($,Z,J){let[W,Y,j,z,X,G]=((Q)=>{Q=e0(Q);let K=y2(Q),B=BY(Q),F=lB(Q),O=M3(Q,4),V=T3(Q,4);return[K,uB(Q),F,O,...FY(V,B)]})(J);return((Q,K,B,F,O,V,D,U,H,T)=>{F=h6(F,H,U,1);let I=Q(B).getOffsetNanosecondsFor(F);return bJ($$(F,I),T)+C$(P6(I),D)+((x,A)=>A!==1?"["+(A===2?"!":"")+L0(x)+"]":"")(B,V)+wJ(K,O)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,G)}function SJ($,Z){let[J,W,Y,j]=((Q)=>(Q=e0(Q),[y2(Q),...LJ(Q)]))(Z);return z=$.calendar,X=J,G=j,bJ(CY($,Y,W),G)+wJ(z,X);var z,X,G}function AJ($,Z){return J=$.calendar,W=$,Y=UJ(Z),T6(W)+wJ(J,Y);var J,W,Y}function EJ($,Z){return fY($.calendar,RY,$,UJ(Z))}function fJ($,Z){return fY($.calendar,mF,$,UJ(Z))}function RJ($,Z){let[J,W,Y]=KY(Z);return j=Y,bY(_J($,W,J)[0],j);var j}function p6($,Z){let[J,W,Y]=KY(Z,3);return W>1&&($={...$,...qF($,W,J)}),((j,z)=>{let{sign:X}=j,G=X===-1?A0(j):j,{hours:Q,minutes:K}=G,[B,F]=QJ(V0(G,3),o0,r1);hY(B);let O=kJ(F,z),V=z>=0||!X||O;return(X<0?"-":"")+"P"+x5({Y:P$(G.years),M:P$(G.months),W:P$(G.weeks),D:P$(G.days)})+(Q||K||B||V?"T"+x5({H:P$(Q),M:P$(K),S:P$(B,V)+O}):"")})($,Y)}function fY($,Z,J,W){let Y=L0($),j=W>1||W===0&&Y!==w;return W===1?Y===w?Z(J):T6(J):j?T6(J)+wY(Y,W===2):Z(J)}function x5($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function bJ($,Z){return T6($)+"T"+bY($,Z)}function T6($){return RY($)+"-"+n0($.isoDay)}function RY($){let{isoYear:Z}=$;return(Z<0||Z>9999?kY(Z)+U6(6,Math.abs(Z)):U6(4,Z))+"-"+n0($.isoMonth)}function mF($){return n0($.isoMonth)+"-"+n0($.isoDay)}function bY($,Z){let J=[n0($.isoHour),n0($.isoMinute)];return Z!==-1&&J.push(n0($.isoSecond)+((W,Y,j,z)=>kJ(W*Q1+Y*b$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function C$($,Z=0){if(Z===1)return"";let[J,W]=A1(Math.abs($),z4),[Y,j]=A1(W,j4),[z,X]=A1(j,o0);return kY($)+n0(J)+":"+n0(Y)+(z||X?":"+n0(z)+kJ(X):"")}function wJ($,Z){if(Z!==1){let J=L0($);if(Z>1||Z===0&&J!==w)return wY(J,Z===2)}return""}function wY($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function kJ($,Z){let J=U6(9,$);return J=Z===void 0?J.replace(oB,""):J.slice(0,Z),J?"."+J:""}function kY($){return $<0?"-":"+"}function P$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function hF($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=$$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function qY($,Z){let J=S0(Z,$);return{calendar:Z.calendar,...g0(dz,J),offset:C$(J.offsetNanoseconds),timeZone:Z.timeZone}}function S$($,Z,J,W=0,Y=0,j,z){if(J!==void 0&&W===1&&(W===1||z))return BJ(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let G=((Q,K,B,F)=>{let O=_0(K);F&&(B=P6(B));for(let V of Q){let D=d0(c0(V,O));if(F&&(D=P6(D)),D===B)return V}})(X,Z,J,j);if(G!==void 0)return G;if(W===0)throw RangeError(VB)}return z?_0(Z):v0($,Z,Y,X)}function v0($,Z,J=0,W=$.getPossibleInstantsFor(Z)){if(W.length===1)return W[0];if(J===1)throw RangeError(OB);if(W.length)return W[J===3?1:0];let Y=_0(Z),j=((X,G)=>{let Q=X.getOffsetNanosecondsFor(FZ(G,-c));return yJ(X.getOffsetNanosecondsFor(FZ(G,c))-Q)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor($$(Y,z)))[J===2?0:W.length-1]}function qJ($){if(Math.abs($)>=c)throw RangeError(FB);return $}function yJ($){if($>c)throw RangeError(BB);return $}function vJ($,Z,J){return D0(u0(KZ(Z.epochNanoseconds,((W)=>{if(pY(W))throw RangeError(LB);return V0(W,5)})($?A0(J):J))))}function gJ($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...dJ(z,X,W,J?A0(Y):Y,j)}}function mJ($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return X0(uJ($(j),J,Z?A0(W):W,Y),j)}function hJ($,Z,J,W,Y){let{calendar:j}=J;return G0(c6($(j),J,Z?A0(W):W,Y),j)}function pJ($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=Y3(z,J);Z&&(W=i6(W)),W.sign<0&&(X=z.dateAdd(X,{...H0,months:1}),X=A$(X,-1));let G=z.dateAdd(X,W,Y);return T$(Y3(z,G),j)}function cJ($,Z,J){return $1(yY(Z,$?A0(J):J)[0])}function dJ($,Z,J,W,Y){let j=V0(W,5),z=J.epochNanoseconds;if(pY(W)){let X=S0(J,$);z=KZ(v0($,{...c6(Z,X,{...W,...f2},Y),...g0(J1,X)}),j)}else z=KZ(z,j),y(Y);return{epochNanoseconds:u0(z)}}function uJ($,Z,J,W){let[Y,j]=yY(Z,J);return R1({...c6($,Z,{...J,...f2,days:J.days+j},W),...Y})}function c6($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);y(W);let Y=J.days+V0(J,5)[0];return Y?o1(A$(Z,Y)):Z}function Y3($,Z,J=1){return A$(Z,J-$.day(Z))}function yY($,Z){let[J,W]=V0(Z,5),[Y,j]=R6(t1($)+W);return[Y,J+j]}function A$($,Z){return Z?{...$,...b6(C0($)+Z*q0)}:$}function d6($,Z,J){let W=$(J.calendar);return l6(J)?[J,W,Z(J.timeZone)]:[{...J,...a0},W]}function lJ($){return $?LY:_0}function u6($){return $?b(dJ,$):uJ}function iJ($){return $?b(cF,$):dF}function l6($){return $&&$.epochNanoseconds}function j3($,Z){return $<=6-(l6(Z)?1:0)}function sJ($,Z,J,W,Y,j,z){let X=$(e0(z).relativeTo),G=Math.max(M$(Y),M$(j));if(j3(G,X))return s(IZ(((D,U,H,T)=>{let I=KZ(V0(D),V0(U),T?-1:1);if(!Number.isFinite(I[0]))throw RangeError(W4);return{...H0,...PZ(I,H)}})(Y,j,G,W)));if(!X)throw RangeError(Y4);W&&(j=A0(j));let[Q,K,B]=d6(Z,J,X),F=u6(B),O=iJ(B),V=F(K,Q,Y);return s(O(K,Q,F(K,V,j),G))}function vY($,Z,J,W,Y){let j=M$(W),[z,X,G,Q,K]=((f,S,M)=>{f=PJ(f,_6);let P=q2(f),k=M(f[lz]),m=HJ(f),h1=M3(f,7),Z0=T3(f);if(P===void 0&&Z0===void 0)throw RangeError(HB);return Z0==null&&(Z0=0),P==null&&(P=Math.max(Z0,S)),VY(P,Z0),m=IJ(m,Z0,1),[P,Z0,m,h1,k]})(Y,j,$),B=Math.max(j,z);if(!l6(K)&&B<=6)return s(IZ(((f,S,M,P,k)=>{let m=m6(V0(f),M,P,k);return{...H0,...PZ(m,S)}})(W,z,X,G,Q)));if(!K)throw RangeError(Y4);let[F,O,V]=d6(Z,J,K),D=lJ(V),U=u6(V),H=iJ(V),T=U(O,F,W),I=H(O,F,T,z),x=W.sign,A=Z$(I);if(x&&A&&x!==A)throw RangeError(H3);return A&&(I=g6(I,D(T),z,X,G,Q,O,F,D,U)),s(I)}function gY($){return $.sign===-1?i6($):$}function i6($){return s(A0($))}function A0($){let Z={};for(let J of g)Z[J]=-1*$[J]||0;return Z}function mY($){return!$.sign}function Z$($,Z=g){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(UB);J=Y}}return J}function IZ($){for(let Z of CB)s0(Z,$[Z],-b5,b5,1);return hY(d0(V0($),o0)),$}function hY($){if(!Number.isSafeInteger($))throw RangeError(DB)}function V0($,Z=6){return p5($,Z,g)}function PZ($,Z=6){let[J,W]=$,Y=S6(W,Z,g);if(Y[g[Z]]+=J*(c/G1[Z]),!Number.isFinite(Y[g[Z]]))throw RangeError(W4);return Y}function s6($,Z=5){return S6($,Z,g)}function pY($){return Boolean(Z$($,pz))}function M$($){let Z=9;for(;Z>0&&!$[g[Z]];Z--);return Z}function pF($,Z){return[$,Z]}function C5($){let Z=Math.floor($/O6)*O6;return[Z,Z+O6]}function cY($){let Z=J$($=L6($));if(!Z)throw RangeError(k0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(k0($));J=TZ(Z.offset)}return Z.timeZone&&rJ(Z.timeZone,1),D0(BJ(w6(Z),J))}function dY($){let Z=J$(t($));if(!Z)throw RangeError(k0($));if(Z.timeZone)return tY(Z,Z.offset?TZ(Z.offset):void 0);if(Z.m)throw RangeError(k0($));return $j(Z)}function uY($,Z){let J=J$(t($));if(!J||!J.timeZone)throw RangeError(k0($));let{offset:W}=J,Y=W?TZ(W):void 0,[,j,z]=B3(Z);return tY(J,Y,j,z)}function TZ($){let Z=rJ($);if(Z===void 0)throw RangeError(k0($));return Z}function lY($){let Z=J$(t($));if(!Z||Z.m)throw RangeError(k0($));return X0(eY(Z))}function n6($){let Z=J$(t($));if(!Z||Z.m)throw RangeError(k0($));return G0(Z.p?eY(Z):$j(Z))}function iY($,Z){let J=oJ(t(Z));if(J)return nJ(J),T$(FJ(_$(J)));let W=n6(Z);return T$(Y3($(W.calendar),W))}function nJ($){if($.calendar!==w)throw RangeError(E1($.calendar))}function sY($,Z){let J=aJ(t(Z));if(J)return nJ(J),I6(_$(J));let W=n6(Z),{calendar:Y}=W,j=$(Y),[z,X,G]=j.h(W),[Q,K]=j.I(z,X),[B,F]=j.N(Q,K,G);return I6(o1(j.P(B,F,G)),Y)}function nY($){let Z,J=((W)=>{let Y=$V.exec(W);return Y?(o6(Y[10]),Wj(Y)):void 0})(t($));if(!J){if(J=J$($),!J)throw RangeError(k0($));if(!J.p)throw RangeError(k0($));if(J.m)throw RangeError(E1("Z"));nJ(J)}if((Z=oJ($))&&N5(Z))throw RangeError(k0($));if((Z=aJ($))&&N5(Z))throw RangeError(k0($));return $1(k6(J,1))}function oY($){let Z=((J)=>{let W=WV.exec(J);return W?((Y)=>{function j(K,B,F){let O=0,V=0;if(F&&([O,G]=A1(G,G1[F])),K!==void 0){if(X)throw RangeError(E1(K));V=((D)=>{let U=parseInt(D);if(!Number.isFinite(U))throw RangeError(E1(D));return U})(K),z=1,B&&(G=tJ(B)*(G1[F]/o0),X=1)}return O+V}let z=0,X=0,G=0,Q={...DZ(g,[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)]),...S6(G,2,g)};if(!z)throw RangeError(Pz(g));return eJ(Y[1])<0&&(Q=A0(Q)),Q})(W):void 0})(t($));if(!Z)throw RangeError(k0($));return s(IZ(Z))}function aY($){let Z=J$($)||oJ($)||aJ($);return Z?Z.calendar:$}function rY($){let Z=J$($);return Z&&(Z.timeZone||Z.m&&q$||Z.offset)||$}function tY($,Z,J=0,W=0){let Y=a6($.timeZone),j=V4(Y);return I0(S$(j,w6($),Z,J,W,!j.v,$.m),Y,O3($.calendar))}function eY($){return Zj(R1(w6($)))}function $j($){return Zj(o1(_$($)))}function Zj($){return{...$,calendar:O3($.calendar)}}function J$($){let Z=eB.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:Jj(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...Wj(J.slice(5)),...o6(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function oJ($){let Z=rB.exec($);return Z?((J)=>({isoYear:Jj(J),isoMonth:parseInt(J[4]),isoDay:1,...o6(J[5])}))(Z):void 0}function aJ($){let Z=tB.exec($);return Z?((J)=>({isoYear:OZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...o6(J[3])}))(Z):void 0}function rJ($,Z){let J=ZV.exec($);return J?((W,Y)=>{let j=W[4]||W[5];if(Y&&j)throw RangeError(E1(j));return qJ((QZ(W[2])*z4+QZ(W[3])*j4+QZ(W[4])*o0+tJ(W[5]||""))*eJ(W[1]))})(J,Z):void 0}function Jj($){let Z=eJ($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(E1(-0));return Z*J}function Wj($){let Z=QZ($[3]);return{...R6(tJ($[4]||""))[0],isoHour:QZ($[1]),isoMinute:QZ($[2]),isoSecond:Z===60?59:Z}}function o6($){let Z,J,W=[];if($.replace(JV,(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(E1(Y))}else{if(J)throw RangeError(E1(Y));J=G}return""}),W.length>1&&Z)throw RangeError(E1($));return{timeZone:J,calendar:W[0]||w}}function tJ($){return parseInt($.padEnd(9,"0"))}function MZ($){return new RegExp(`^${$}$`,"i")}function eJ($){return $&&$!=="+"?-1:1}function QZ($){return $===void 0?0:parseInt($)}function Yj($){return a6(t($))}function a6($){let Z=$2($);return typeof Z=="number"?C$(Z):Z?((J)=>{if(jV.test(J))throw RangeError(KB);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?T5(j).replace(/island|noronha|murdo|rivadavia|urville/,T5):j)).join("/")})($):q$}function S5($){let Z=$2($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:q$}function $2($){let Z=rJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==q$?YV($):void 0}function Z2($,Z){return x0($.epochNanoseconds,Z.epochNanoseconds)}function J2($,Z){return x0($.epochNanoseconds,Z.epochNanoseconds)}function jj($,Z,J,W,Y,j){let z=$(e0(j).relativeTo),X=Math.max(M$(W),M$(Y));if(m5(g,W,Y))return 0;if(j3(X,z))return x0(V0(W),V0(Y));if(!z)throw RangeError(Y4);let[G,Q,K]=d6(Z,J,z),B=lJ(K),F=u6(K);return x0(B(F(Q,G,W)),B(F(Q,G,Y)))}function W2($,Z){return E$($,Z)||r6($,Z)}function E$($,Z){return n1(C0($),C0(Z))}function r6($,Z){return n1(t1($),t1(Z))}function zj($,Z){return!Z2($,Z)}function Xj($,Z){return!J2($,Z)&&!!t6($.timeZone,Z.timeZone)&&HZ($.calendar,Z.calendar)}function Gj($,Z){return!W2($,Z)&&HZ($.calendar,Z.calendar)}function Qj($,Z){return!E$($,Z)&&HZ($.calendar,Z.calendar)}function Kj($,Z){return!E$($,Z)&&HZ($.calendar,Z.calendar)}function Fj($,Z){return!E$($,Z)&&HZ($.calendar,Z.calendar)}function Bj($,Z){return!r6($,Z)}function t6($,Z){if($===Z)return 1;let J=L0($),W=L0(Z);if(J===W)return 1;try{return S5(J)===S5(W)}catch(Y){}}function Y2($,Z,J,W){let Y=LZ($,z0(W),3,5),j=e6(Z.epochNanoseconds,J.epochNanoseconds,...Y);return s($?A0(j):j)}function j2($,Z,J,W,Y,j){let z=Z4(W.calendar,Y.calendar),X=z0(j),[G,Q,K,B]=LZ(J,X,5),F=W.epochNanoseconds,O=Y.epochNanoseconds,V=x0(O,F),D;if(V)if(G<6)D=e6(F,O,G,Q,K,B);else{let U=Z(((T,I)=>{if(!t6(T,I))throw RangeError(Cz);return T})(W.timeZone,Y.timeZone)),H=$(z);D=Oj(H,U,W,Y,V,G,X),D=g6(D,O,G,Q,K,B,H,W,LY,b(dJ,U))}else D=H0;return s(J?A0(D):D)}function z2($,Z,J,W,Y){let j=Z4(J.calendar,W.calendar),z=z0(Y),[X,G,Q,K]=LZ(Z,z,6),B=_0(J),F=_0(W),O=x0(F,B),V;if(O)if(X<=6)V=e6(B,F,X,G,Q,K);else{let D=$(j);V=Dj(D,J,W,O,X,z),V=g6(V,F,X,G,Q,K,D,J,_0,uJ)}else V=H0;return s(Z?A0(V):V)}function X2($,Z,J,W,Y){let j=Z4(J.calendar,W.calendar),z=z0(Y);return Vj(Z,()=>$(j),J,W,...LZ(Z,z,6,9,6),z)}function G2($,Z,J,W,Y){let j=Z4(J.calendar,W.calendar),z=z0(Y),X=LZ(Z,z,9,9,8),G=$(j);return Vj(Z,()=>G,Y3(G,J),Y3(G,W),...X,z)}function Vj($,Z,J,W,Y,j,z,X,G){let Q=_0(J),K=_0(W),B;if(x0(K,Q))if(Y===6)B=e6(Q,K,Y,j,z,X);else{let F=Z();B=F.dateUntil(J,W,Y,G),j===6&&z===1||(B=g6(B,K,Y,j,z,X,F,J,_0,c6))}else B=H0;return s($?A0(B):B)}function Q2($,Z,J,W){let Y=z0(W),[j,z,X,G]=LZ($,Y,5,5),Q=e1(K2(Z,J),V3(z,X),G),K={...H0,...s6(Q,j)};return s($?A0(K):K)}function cF($,Z,J,W,Y,j){let z=x0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?Uj(J.epochNanoseconds,W.epochNanoseconds,Y):Oj(Z,$,J,W,z,Y,j):H0}function dF($,Z,J,W,Y){let j=_0(Z),z=_0(J),X=x0(z,j);return X?W<=6?Uj(j,z,W):Dj($,Z,J,X,W,Y):H0}function Oj($,Z,J,W,Y,j,z){let[X,G,Q]=((F,O,V,D)=>{function U(){return S={...A$(I,A++*-D),...T},M=v0(F,S),x0(x,M)===-D}let H=S0(O,F),T=g0(J1,H),I=S0(V,F),x=V.epochNanoseconds,A=0,f=K2(H,I),S,M;if(Math.sign(f)===-D&&A++,U()&&(D===-1||U()))throw RangeError(H3);let P=d0(c0(M,x));return[H,S,P]})(Z,J,W,Y);var K,B;return{...j===6?(K=X,B=G,{...H0,days:Lj(K,B)}):$.dateUntil(X,G,j,z),...s6(Q)}}function Dj($,Z,J,W,Y,j){let[z,X,G]=((Q,K,B)=>{let F=K,O=K2(Q,K);return Math.sign(O)===-B&&(F=A$(K,-B),O+=c*B),[Q,F,O]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...s6(G)}}function e6($,Z,J,W,Y,j){return{...H0,...PZ(m6(c0($,Z),W,Y,j),J)}}function Uj($,Z,J){return{...H0,...PZ(c0($,Z),J)}}function Lj($,Z){return $4(C0($),C0(Z))}function $4($,Z){return Math.trunc((Z-$)/q0)}function K2($,Z){return t1(Z)-t1($)}function Z4($,Z){if(!HZ($,Z))throw RangeError(x2);return $}function uF($){function Z(Y){return((j,z)=>({...Hj(j,z),F:j.month,day:parseInt(j.day)}))(KJ(J,Y),W)}let J=h2($),W=M6($);return{id:$,O:lF(Z),B:iF(Z)}}function lF($){return y0((Z)=>{let J=C0(Z);return $(J)},WeakMap)}function iF($){let Z=$(0).year-bB;return y0((J)=>{let W,Y=UZ(J-Z),j=[],z=[];do Y+=400*q0;while((W=$(Y)).year<=J);do Y+=(1-W.day)*q0,W.year===J&&(j.push(Y),z.push(W.F)),Y-=q0;while((W=$(Y)).year>=J);return{k:j.reverse(),C:Ez(z.reverse())}})}function Hj($,Z){let J,W,Y=Ij($);if($.era){let j=gz[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=_j(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function Ij($){return parseInt($.relatedYear||$.year)}function n8($){let{year:Z,F:J,day:W}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,W]}function z3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*q0}function F6($){let Z=E5(this,$),J=E5(this,$-1),W=Z.length;if(W>J.length){let Y=xj(this);if(Y<0)return-Y;for(let j=0;j<W;j++)if(Z[j]!==J[j])return j+1}}function B6($){return $4(z3.call(this,$),z3.call(this,$+1))}function A5($,Z){let{k:J}=this.B($),W=Z+1,Y=J;return W>J.length&&(W=1,Y=this.B($+1).k),$4(J[Z-1],Y[W-1])}function V6($){return this.B($).k.length}function E5($,Z){return Object.keys($.B(Z).C)}function Pj($){return O3(t($))}function O3($){if(($=$.toLowerCase())!==w&&$!==G4&&M6($)!==M6(h2($).resolvedOptions().calendar))throw RangeError(QB($));return $}function M6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function Tj($){return this.R($)[0]}function Mj($){return this.R($)[1]}function F2($){let[Z]=this.h($);return $4(this.q(Z),C0($))+1}function Nj($){let Z=XV.exec($);if(!Z)throw RangeError(XB($));return[parseInt(Z[1]),Boolean(Z[2])]}function N6($,Z,J){return $+(Z||J&&$>=J?1:0)}function o8($,Z){return $-(Z&&$>=Z?1:0)}function _j($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function a8($){return gz[Cj($)]}function xj($){return NB[Cj($)]}function Cj($){return M6($.id||w)}function Sj($,Z,J,W){let Y=W$(J,W,Z1,[],kz);if(Y.timeZone!==void 0){let j=J.dateFromFields(Y),z=f$(Y),X=$(Y.timeZone);return{epochNanoseconds:S$(Z(X),{...j,...z},Y.offset!==void 0?TZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...a0}}function Aj($,Z,J,W,Y,j){let z=W$(J,Y,Z1,bz,kz),X=$(z.timeZone),[G,Q,K]=B3(j),B=J.dateFromFields(z,y6(j,G)),F=f$(z,G);return I0(S$(Z(X),{...B,...F},z.offset!==void 0?TZ(z.offset):void 0,Q,K),X,W)}function Ej($,Z,J){let W=W$($,Z,Z1,[],k1),Y=y(J);return X0(R1({...$.dateFromFields(W,y6(J,Y)),...f$(W,Y)}))}function B2($,Z,J,W=[]){let Y=W$($,Z,Z1,W);return $.dateFromFields(Y,J)}function V2($,Z,J,W){let Y=W$($,Z,A2,W);return $.yearMonthFromFields(Y,J)}function O2($,Z,J,W,Y=[]){let j=W$($,J,Z1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=OZ),$.monthDayFromFields(j,W)}function fj($,Z){let J=y(Z);return $1(f$(X1($,t8,[],1),J))}function Rj($){let Z=X1($,E2);return s(IZ({...H0,...Z}))}function W$($,Z,J,W=[],Y=[]){return X1(Z,[...$.fields(J),...Y].sort(),W)}function X1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(ZB(X));if(X==="constructor"||X==="__proto__")throw RangeError(N2(X));let G=$[X];if(G!==void 0)z=1,w5[X]&&(G=w5[X](G,X)),Y[X]=G;else if(J){if(J.includes(X))throw TypeError(M2(X));Y[X]=vz[X]}j=X}if(W&&!z)throw TypeError(Pz(Z));return Y}function f$($,Z){return k6(FV({...vz,...$}),Z)}function bj($,Z,J,W,Y,j){let z=z0(j),{calendar:X,timeZone:G}=J;return I0(((Q,K,B,F,O)=>{let V=D3(Q,B,F,Z1,wz,Rz),[D,U,H]=B3(O,2);return S$(K,{...Q.dateFromFields(V,y6(O,D)),...f$(V,D)},TZ(V.offset),U,H)})($(X),Z(G),W,Y,z),G,X)}function wj($,Z,J,W,Y){let j=z0(Y);return X0(((z,X,G,Q)=>{let K=D3(z,X,G,Z1,k1),B=y(Q);return R1({...z.dateFromFields(K,y6(Q,B)),...f$(K,B)})})($(Z.calendar),J,W,j))}function kj($,Z,J,W,Y){let j=z0(Y);return((z,X,G,Q)=>{let K=D3(z,X,G,Z1);return z.dateFromFields(K,Q)})($(Z.calendar),J,W,j)}function qj($,Z,J,W,Y){let j=z0(Y);return T$(((z,X,G,Q)=>{let K=D3(z,X,G,A2);return z.yearMonthFromFields(K,Q)})($(Z.calendar),J,W,j))}function yj($,Z,J,W,Y){let j=z0(Y);return((z,X,G,Q)=>{let K=D3(z,X,G,Z1);return z.monthDayFromFields(K,Q)})($(Z.calendar),J,W,j)}function vj($,Z,J){return $1(((W,Y,j)=>{let z=y(j);return f$({...g0(t8,W),...X1(Y,t8)},z)})($,Z,J))}function gj($,Z){return s((J=$,W=Z,IZ({...J,...X1(W,E2)})));var J,W}function D3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=X1(Z,z,j),G=X1(J,z);return X=$.mergeFields(X,G),X1(X,z,[])}function D2($,Z){let J=W$($,Z,yz);return $.monthDayFromFields(J)}function U2($,Z,J){let W=W$($,Z,qz);return $.yearMonthFromFields(W,J)}function mj($,Z,J,W,Y){Z=g0(J=$.fields(J),Z),W=X1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=X1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function d8($,Z){let{era:J,eraYear:W,year:Y}=Z,j=a8($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(WB);if(!j)throw RangeError(JB);let z=j[J];if(z===void 0)throw RangeError(jB(J));let X=_j(W,z);if(Y!==void 0&&Y!==X)throw RangeError(YB);Y=X}else if(Y===void 0)throw TypeError(zB(j));return Y}function u8($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,G,Q,K)=>{let B=X.U(Q),[F,O]=Nj(G),V=N6(F,O,B);if(O){let D=xj(X);if(D===void 0)throw RangeError(Z3);if(D>0){if(V>D)throw RangeError(Z3);if(B===void 0){if(K===1)throw RangeError(Z3);V--}}else{if(V!==-D)throw RangeError(Z3);if(B===void 0&&K===1)throw RangeError(Z3)}}return V})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(_z);Y=z,W=1}else if(Y===void 0)throw TypeError(GB);return s0("month",Y,1,$.L(J),W)}function f5($,Z,J,W,Y){return w0(Z,"day",1,$.j(W,J),Y)}function l8($,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 hj($){return D0(u0(f6(E6($))))}function pj($,Z,J,W,Y=w){return I0(u0(f6(E6(J))),Z(W),$(Y))}function cj($,Z,J,W,Y=0,j=0,z=0,X=0,G=0,Q=0,K=w){return X0(R1(w6(r0(N0,DZ(Q4,[Z,J,W,Y,j,z,X,G,Q])))),$(K))}function dj($,Z,J,W,Y=w){return G0(o1(_$(r0(N0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function uj($,Z,J,W=w,Y=1){let j=N0(Z),z=N0(J),X=$(W);return T$(FJ(_$({isoYear:j,isoMonth:z,isoDay:N0(Y)})),X)}function lj($,Z,J,W=w,Y=OZ){let j=N0(Z),z=N0(J),X=$(W);return I6(o1(_$({isoYear:N0(Y),isoMonth:j,isoDay:z})),X)}function ij($=0,Z=0,J=0,W=0,Y=0,j=0){return $1(k6(r0(N0,DZ(J1,[$,Z,J,W,Y,j])),1))}function sj($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,G=0,Q=0){return s(IZ(r0(r5,DZ(g,[$,Z,J,W,Y,j,z,X,G,Q]))))}function L2($,Z,J=w){return I0($.epochNanoseconds,Z,J)}function nj($){return D0($.epochNanoseconds)}function H2($,Z){return X0(S0(Z,$))}function I2($,Z){return G0(S0(Z,$))}function oj($,Z,J){return U2($(Z.calendar),J)}function aj($,Z,J){return D2($(Z.calendar),J)}function P2($,Z){return $1(S0(Z,$))}function rj($,Z,J,W){let Y=((j,z,X,G)=>{let Q=DJ(G);return v0(j(z),X,Q)})($,J,Z,W);return I0(u0(Y),J,Z.calendar)}function tj($,Z,J){let W=$(Z.calendar);return T$({...Z,...U2(W,J)})}function ej($,Z,J){return D2($(Z.calendar),J)}function $z($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):a0;return I0(v0(J(j),{...W,...X}),j,W.calendar)}function Zz($,Z=a0){return X0(R1({...$,...Z}))}function Jz($,Z,J){return U2($(Z.calendar),J)}function Wz($,Z,J){return D2($(Z.calendar),J)}function Yz($,Z,J,W){return((Y,j,z)=>mj(Y,j,qz,f1(z),P3))($(Z.calendar),J,W)}function jz($,Z,J,W){return((Y,j,z)=>mj(Y,j,yz,f1(z),X4))($(Z.calendar),J,W)}function zz($,Z,J,W,Y){let j=f1(Y),z=Z(j.plainDate),X=$(j.timeZone);return I0(v0(J(X),{...z,...W}),X,z.calendar)}function Xz($,Z){return X0(R1({...$,...Z}))}function Gz($){return D0(u0(BZ($,o0)))}function Qz($){return D0(u0(BZ($,Q1)))}function Kz($){return D0(u0(f6(E6($),b$)))}function Fz($){return D0(u0(f6(E6($))))}function Bz($,Z,J=a0){let W=Z.timeZone,Y=$(W),j={...S0(Z,Y),...J};return I0(S$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function Vz($,Z,J){let W=Z.timeZone,Y=$(W),j={...S0(Z,Y),...J},z=Lz(Z.calendar,J.calendar);return I0(S$(Y,j,j.offsetNanoseconds,2),W,z)}function Oz($,Z=a0){return X0({...$,...Z})}function Dz($,Z){return X0({...$,...Z},Lz($.calendar,Z.calendar))}function J4($,Z){return{...$,calendar:Z}}function Uz($,Z){return{...$,timeZone:Z}}function Lz($,Z){if($===Z)return $;let J=L0($),W=L0(Z);if(J===W||J===w)return Z;if(W===w)return $;throw RangeError(x2)}function sF($,Z){return(J)=>J===w?$:J===G4||J===VZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),zV(J))}function R$($,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=JJ(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=q$,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function b1($,Z=T2){let[J,,,W]=$;return(Y,j=SV,...z)=>{let X=Z(W&&W(...z),Y,j,J),G=X.resolvedOptions();return[X,...nF($,G,z)]}}function T2($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(PB);J.timeZone=$}return new Y$(Z,J)}function nF($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,G)=>{if((G||z!==w)&&z!==X)throw RangeError(x2)})(L0(j.calendar),Z.calendar,Y),W(j,Z)))}function NZ($){let Z=U3();return $$(Z,$.getOffsetNanosecondsFor(Z))}function U3(){return BZ(Date.now(),Q1)}function w1(){return q5||(q5=new Y$().resolvedOptions().timeZone)}var oF=($,Z)=>`Non-integer ${$}: ${Z}`,aF=($,Z)=>`Non-positive ${$}: ${Z}`,rF=($,Z)=>`Non-finite ${$}: ${Z}`,tF=($)=>`Cannot convert bigint to ${$}`,eF=($)=>`Invalid bigint: ${$}`,$B="Cannot convert Symbol to string",Hz="Invalid object",Iz=($,Z,J,W,Y)=>Y?Iz($,Y[Z],Y[J],Y[W]):L3($,Z)+`; must be between ${J}-${W}`,L3=($,Z)=>`Invalid ${$}: ${Z}`,M2=($)=>`Missing ${$}`,N2=($)=>`Invalid field ${$}`,ZB=($)=>`Duplicate field ${$}`,Pz=($)=>"No valid fields: "+$.join(),Tz="Invalid bag",Mz=($,Z,J)=>L3($,Z)+"; must be "+Object.keys(J).join(),Nz="Cannot use valueOf",_2="Invalid calling context",JB="Forbidden era/eraYear",WB="Mismatching era/eraYear",YB="Mismatching year/eraYear",jB=($)=>`Invalid era: ${$}`,zB=($)=>"Missing year"+($?"/era/eraYear":""),XB=($)=>`Invalid monthCode: ${$}`,_z="Mismatching month/monthCode",GB="Missing month/monthCode",R5="Cannot guess year",Z3="Invalid leap month",xz="Invalid protocol",H3="Invalid protocol results",x2="Mismatching Calendars",QB=($)=>`Invalid Calendar: ${$}`,Cz="Mismatching TimeZones",KB="Forbidden ICU TimeZone",FB="Out-of-bounds offset",BB="Out-of-bounds TimeZone gap",VB="Invalid TimeZone offset",OB="Ambiguous offset",W4="Out-of-bounds date",DB="Out-of-bounds duration",UB="Cannot mix duration signs",Y4="Missing relativeTo",LB="Cannot use large units",HB="Required smallestUnit or largestUnit",IB="smallestUnit > largestUnit",k0=($)=>`Cannot parse: ${$}`,E1=($)=>`Invalid substring: ${$}`,Sz=($)=>`Cannot format ${$}`,Az="Mismatching types for formatting",PB="Cannot specify TimeZone",Ez=b(Q3,($,Z)=>Z),_Z=b(Q3,($,Z,J)=>J),n0=b(U6,2),r8={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},I3=Object.keys(r8),q0=86400000,fz=1000,b$=1000,Q1=1e6,o0=1e9,j4=60000000000,z4=3600000000000,c=86400000000000,G1=[1,b$,Q1,o0,j4,z4,c],k1=I3.slice(0,6),t8=K3(k1),Rz=["offset"],bz=["timeZone"],wz=k1.concat(Rz),kz=wz.concat(bz),e8=["era","eraYear"],TB=e8.concat(["year"]),X4=["year"],C2=["monthCode"],S2=["month"].concat(C2),P3=["day"],A2=S2.concat(X4),qz=C2.concat(X4),Z1=P3.concat(A2),MB=P3.concat(S2),yz=P3.concat(C2),vz=_Z(k1,0),w="iso8601",G4="gregory",VZ="japanese",gz={[G4]:{bce:-1,ce:0},[VZ]:{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}},NB={chinese:13,dangi:13,hebrew:-6},t=b(A6,"string"),mz=b(A6,"boolean"),_B=b(A6,"number"),hz=b(A6,"function"),g=I3.map(($)=>$+"s"),E2=K3(g),xB=g.slice(0,6),pz=g.slice(6),CB=pz.slice(1),SB=Ez(g),H0=_Z(g,0),f2=_Z(xB,0),R2=b(h5,g),J1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],b2=["isoDay","isoMonth","isoYear"],Q4=J1.concat(b2),w2=K3(b2),cz=K3(J1),dz=K3(Q4),a0=_Z(cz,0),AB=b(h5,Q4),Y$=Intl.DateTimeFormat,uz="en-GB",k2=1e8,EB=k2*q0,fB=[k2,0],RB=[-k2,0],X3=275760,G3=-271821,bB=1970,OZ=1972,S1=12,wB=UZ(1868,9,8),kB=y0(kF,WeakMap),_6="smallestUnit",$J="unit",W3="roundingIncrement",i8="fractionalSecondDigits",lz="relativeTo",iz={constrain:0,reject:1},qB=Object.keys(iz),yB={compatible:0,reject:1,earlier:2,later:3},vB={reject:0,use:1,prefer:2,ignore:3},gB={auto:0,never:1,critical:2,always:3},mB={auto:0,never:1,critical:2},hB={auto:0,never:1},pB={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},T3=b(TJ,_6),q2=b(TJ,"largestUnit"),cB=b(TJ,$J),sz=b(x$,"overflow",iz),nz=b(x$,"disambiguation",yB),dB=b(x$,"offset",vB),y2=b(x$,"calendarName",gB),uB=b(x$,"timeZoneName",mB),lB=b(x$,"offset",hB),M3=b(x$,"roundingMode",pB),xZ="PlainYearMonth",CZ="PlainMonthDay",w$="PlainDate",k$="PlainDateTime",K4="PlainTime",q1="ZonedDateTime",F4="Instant",B4="Duration",iB=[Math.floor,($)=>K6($)?Math.floor($):Math.round($),Math.ceil,($)=>K6($)?Math.ceil($):Math.round($),Math.trunc,($)=>K6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>K6($)?($=Math.trunc($)||0)+$%2:Math.round($)],q$="UTC",O6=5184000,sB=H6(1847),nB=H6(new Date().getUTCFullYear()+10),oB=/0+$/,S0=y0(hF,WeakMap),b5=4294967295,V4=y0(($)=>{let Z=$2($);return typeof Z=="object"?new az(Z):new oz(Z||0)});class oz{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[BJ($,this.v)]}l(){}}class az{constructor($){this.$=((Z)=>{function J(G){let Q=s8(G,z,X),[K,B]=C5(Q),F=Y(K),O=Y(B);return F===O?F:W(j(K,B),F,O,G)}function W(G,Q,K,B){let F,O;for(;(B===void 0||(F=B<G[0]?Q:B>=G[1]?K:void 0)===void 0)&&(O=G[1]-G[0]);){let V=G[0]+Math.floor(O/2);Z(V)===K?G[1]=V:G[0]=V+1}return F}let Y=y0(Z),j=y0(pF),z=sB,X=nB;return{G(G){let Q=J(G-86400),K=J(G+86400),B=G-Q,F=G-K;if(Q===K)return[B];let O=J(B);return O===J(F)?[G-O]:Q>K?[B,F]:[]},V:J,l(G,Q){let K=s8(G,z,X),[B,F]=C5(K),O=O6*Q,V=Q<0?()=>F>z||(z=K,0):()=>B<X||(X=K,0);for(;V();){let D=Y(B),U=Y(F);if(D!==U){let H=j(B,F);W(H,D,U);let T=H[0];if((n1(T,G)||1)===Q)return T}B+=O,F+=O}}}})(((Z)=>(J)=>{let W=KJ(Z,J*fz);return H6(Ij(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V($Y($))*o0}getPossibleInstantsFor($){let[Z,J]=[H6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*Q1+W.isoMicrosecond*b$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>u0(FZ(BZ(Y,o0),J)))}l($,Z){let[J,W]=ZY($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return BZ(Y,o0)}}var v2="([+\u2212-])",D6="(?:[.,](\\d{1,9}))?",rz=`(?:(?:${v2}(\\d{6}))|(\\d{4}))-?(\\d{2})`,g2="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+D6+")?)?",m2=v2+g2,aB=rz+"-?(\\d{2})(?:[T ]"+g2+"(Z|"+m2+")?)?",tz="\\[(!?)([^\\]]*)\\]",O4=`((?:${tz}){0,9})`,rB=MZ(rz+O4),tB=MZ("(?:--)?(\\d{2})-?(\\d{2})"+O4),eB=MZ(aB+O4),$V=MZ("T?"+g2+"(?:"+m2+")?"+O4),ZV=MZ(m2),JV=new RegExp(tz,"g"),WV=MZ(`${v2}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${D6}H)?(?:(\\d+)${D6}M)?(?:(\\d+)${D6}S)?)?`),YV=y0(($)=>new Y$(uz,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),jV=/^(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$/,zV=y0(uF),h2=y0(($)=>new Y$(uz,{calendar:$,timeZone:q$,era:"short",year:"numeric",month:"short",day:"numeric"})),XV=/^M(\d{2})(L?)$/,GV={era:L6,eraYear:N0,year:N0,month:M5,monthCode:L6,day:M5},QV=_Z(k1,N0),KV=_Z(g,r5),w5=Object.assign({},GV,QV,KV,{offset:L6}),FV=b(wF,k1,J1),k5={dateAdd($,Z,J){let W=y(J),Y,{years:j,months:z,weeks:X,days:G}=Z;if(G+=V0(Z,5)[0],j||z)Y=((Q,K,B,F,O)=>{let[V,D,U]=Q.h(K);if(B){let[H,T]=Q.I(V,D);V+=B,D=N6(H,T,Q.U(V)),D=s0("month",D,1,Q.L(V),O)}return F&&([V,D]=Q._(V,D,F)),U=s0("day",U,1,Q.j(V,D),O),Q.q(V,D,U)})(this,$,j,z,W);else{if(!X&&!G)return $;Y=C0($)}return Y+=(7*X+G)*q0,o1(b6(Y))},dateUntil($,Z,J){if(J<=7){let G=0,Q=Lj({...$,...a0},{...Z,...a0});return J===7&&([G,Q]=r1(Q,7)),{...H0,weeks:G,days:Q}}let W=this.h($),Y=this.h(Z),[j,z,X]=((G,Q,K,B,F,O,V)=>{let D=F-Q,U=O-K,H=V-B;if(D||U){let T=Math.sign(D||U),I=G.j(F,O),x=0;if(Math.sign(H)===-T){let A=I;[F,O]=G._(F,O,-T),D=F-Q,U=O-K,I=G.j(F,O),x=T<0?-A:I}if(H=V-Math.min(B,I)+x,D){let[A,f]=G.I(Q,K),[S,M]=G.I(F,O);if(U=S-A||Number(M)-Number(f),Math.sign(U)===-T){let P=T<0&&-G.L(F);D=(F-=T)-Q,U=O-N6(A,f,G.U(F))+(P||G.L(F))}}}return[D,U,H]})(this,...W,...Y);return J===8&&(z+=this.J(j,W[0]),j=0),{...H0,years:j,months:z,days:X}},dateFromFields($,Z){let J=y(Z),W=d8(this,$),Y=u8(this,$,W,J),j=f5(this,$,Y,W,J);return G0(o1(this.P(W,Y,j)),this.id||w)},yearMonthFromFields($,Z){let J=y(Z),W=d8(this,$),Y=u8(this,$,W,J);return T$(FJ(this.P(W,Y,1)),this.id||w)},monthDayFromFields($,Z){let J=y(Z),W=!this.id,{monthCode:Y,year:j,month:z}=$,X,G,Q,K,B;if(Y!==void 0){[X,G]=Nj(Y),B=y5($,"day");let F=this.N(X,G,B);if(!F)throw RangeError(R5);if([Q,K]=F,z!==void 0&&z!==K)throw RangeError(_z);W&&(K=s0("month",K,1,S1,1),B=s0("day",B,1,VJ(j!==void 0?j:Q,K),J))}else{Q=j===void 0&&W?OZ:d8(this,$),K=u8(this,$,Q,J),B=f5(this,$,K,Q,J);let F=this.U(Q);G=K===F,X=o8(K,F);let O=this.N(X,G,B);if(!O)throw RangeError(R5);[Q,K]=O}return I6(o1(this.P(Q,K,B)),this.id||w)},fields($){return a8(this)&&$.includes("year")?[...$,...e8]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return l8(J,Z,S2),a8(this)&&(l8(J,Z,TB),this.id===VZ&&l8(J,Z,MB,e8)),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:F2,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"+n0(j)+(z?"L":""))(W,Y)},dayOfWeek:zY,daysInWeek(){return 7}},BV={dayOfYear:F2,h:WY,q:UZ},VV=Object.assign({},BV,{weekOfYear:Tj,yearOfWeek:Mj,R($){function Z(O){return(7-O<W?7:0)-O}function J(O){let V=jY(F+O),D=O||1,U=Z(J3(G+V*D,7));return K=(V+(U-Q)*D)/7}let W=this.id?1:4,Y=zY($),j=this.dayOfYear($),z=J3(Y-1,7),X=j-1,G=J3(z-X,7),Q=Z(G),K,B=Math.floor((X-Q)/7)+1,F=$.isoYear;return B?B>J(0)&&(B=1,F++):(B=J(-1),F--),[B,F,K]}}),OV={dayOfYear:F2,h:n8,q:z3,weekOfYear:Tj,yearOfWeek:Mj,R(){return[]}},SZ=sF(Object.assign({},k5,VV,{h:WY,ee($){return this.id===G4?XY($):this.id===VZ?kB($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[OZ,$]},K:OJ,U(){},L:YY,J:($)=>$*S1,j:VJ,X:jY,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:UZ,_:($,Z,J)=>($+=C6(J,S1),(Z+=YJ(J,S1))<1?($--,Z+=S1):Z>S1&&($++,Z-=S1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},k5,OV,{h:n8,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=F6.call(this,$);return[o8(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=n8.call(this,{isoYear:OZ,isoMonth:S1,isoDay:31}),z=F6.call(this,W),X=Y===z;(n1($,o8(Y,z))||n1(Number(Z),Number(X))||n1(J,j))===1&&W--;for(let G=0;G<100;G++){let Q=W-G,K=F6.call(this,Q),B=N6($,Z,K);if(Z===(B===K)&&J<=A5.call(this,Q,B))return[Q,B]}},K($){let Z=B6.call(this,$);return Z>B6.call(this,$-1)&&Z>B6.call(this,$+1)},U:F6,L:V6,J($,Z){let J=Z+$,W=Math.sign($),Y=W<0?-1:0,j=0;for(let z=Z;z!==J;z+=W)j+=V6.call(this,z+Y);return j},j:A5,X:B6,P($,Z,J){return b6(z3.call(this,$,Z,J))},q:z3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(W4);if(J<0)for(;Z<1;)Z+=V6.call(this,--$);else{let W;for(;Z>(W=V6.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}})),a1="numeric",AZ=["timeZoneName"],ez={month:a1,day:a1},p2={year:a1,month:a1},c2=Object.assign({},p2,{day:a1}),d2={hour:a1,minute:a1,second:a1},u2=Object.assign({},c2,d2),DV=Object.assign({},u2,{timeZoneName:"short"}),UV=Object.keys(p2),LV=Object.keys(ez),HV=Object.keys(c2),IV=Object.keys(d2),l2=["dateStyle"],PV=UV.concat(l2),TV=LV.concat(l2),i2=HV.concat(l2,["weekday"]),N3=IV.concat(["dayPeriod","timeStyle"]),s2=i2.concat(N3),MV=s2.concat(AZ),NV=AZ.concat(N3),_V=AZ.concat(i2),xV=AZ.concat(["day","weekday"],N3),CV=AZ.concat(["year","weekday"],N3),SV={},n2=[R$(s2,u2),v6],$X=[R$(MV,DV),v6,0,($,Z)=>{let J=L0($.timeZone);if(Z&&L0(Z.timeZone)!==J)throw RangeError(Cz);return J}],o2=[R$(s2,u2,AZ),C0],a2=[R$(i2,c2,NV),C0],r2=[R$(N3,d2,_V),($)=>t1($)/Q1],t2=[R$(PV,p2,xV),C0,1],e2=[R$(TV,ez,CV),C0,1],q5;function B1($,Z,J,W,Y){function j(...G){if(!(this instanceof j))throw TypeError(_2);YX(this,Z(...G))}function z(G,Q){return Object.defineProperties(function(...K){return G.call(this,X(this),...K)},ZJ(Q))}function X(G){let Q=M0(G);if(!Q||Q.branding!==$)throw TypeError(_2);return Q}return Object.defineProperties(j.prototype,{...v5(r0(z,J)),...N$(r0(z,W)),...x6("Temporal."+$)}),Object.defineProperties(j,{...N$(Y),...ZJ($)}),[j,(G)=>{let Q=Object.create(j.prototype);return YX(Q,G),Q},X]}function XX($){return $=$.concat("id").sort(),(Z)=>{if(!g5(Z,$))throw TypeError(xz);return Z}}function bZ($){if(M0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(Tz);return $}function D4($,Z){let J={};for(let W in $)J[W]=({o:Y},j)=>{let z=M0(j)||{},{branding:X}=z,G=X===w$||Z.includes(X)?z:f0(j);return Y[W](G)};return J}function J7($){let Z={};for(let J in $)Z[J]=(W)=>{let{calendar:Y}=W;return(j=Y,typeof j=="string"?SZ(j):(z=j,Object.assign(Object.create(dV),{i:z})))[J](W);var j,z};return Z}function Q$(){throw TypeError(Nz)}function x3({calendar:$}){return typeof $=="string"?new F7($):$}function ZX($,Z){if(Z=z0(Z),O0($)){let W=M0($);if(W&&W.branding===CZ)return y(Z),W;let Y=KX($);return O2(M4(Y||w),!Y,$,Z)}let J=sY(SZ,$);return y(Z),J}function GX($,Z,J){return W=Z.call($,E0(D0(J))),qJ(F3(W));var W}function U4($,Z=OX){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=b(Z[Y],$,hz($[Y]));return W}function d($,Z){return typeof $=="string"?V4($):U4($,Z)}function K0($){return d($,Z7)}function K1($){if(O0($)){let Z=M0($);if(Z)switch(Z.branding){case F4:return Z;case q1:return D0(Z.epochNanoseconds)}}return cY($)}function JX($,Z,J){let W=Z.l(K1(J).epochNanoseconds,$);return W?E0(D0(W)):null}function l($){return O0($)?(M0($)||{}).timeZone||oV($):((Z)=>a6(rY(t(Z))))($)}function j$($,Z){if(O0($)){let J=M0($)||{};switch(J.branding){case K4:return y(Z),J;case k$:return y(Z),$1(J);case q1:return y(Z),P2(K0,J)}return fj($,Z)}return y(Z),nY($)}function W7($){return $===void 0?void 0:j$($)}function EZ($,Z){if(Z=z0(Z),O0($)){let W=M0($);return W&&W.branding===xZ?(y(Z),W):V2(P4(C3($)),$,Z)}let J=iY(SZ,$);return y(Z),J}function z$($,Z){if(Z=z0(Z),O0($)){let W=M0($)||{};switch(W.branding){case k$:return y(Z),W;case w$:return y(Z),X0({...W,...a0});case q1:return y(Z),H2(K0,W)}return Ej(T4(C3($)),$,Z)}let J=lY($);return y(Z),J}function f0($,Z){if(Z=z0(Z),O0($)){let W=M0($)||{};switch(W.branding){case w$:return y(Z),W;case k$:return y(Z),G0(W);case q1:return y(Z),I2(K0,W)}return B2(T4(C3($)),$,Z)}let J=n6($);return y(Z),J}function QX($,Z,J){return t0(Z.call($,$0(G0(J,$))))}function V1($){return(Z)=>typeof Z=="string"?SZ(Z):((J,W)=>{let Y=Object.keys(W).sort(),j={};for(let z of Y)j[z]=b(W[z],J,J[z]);return j})(Z,$)}function e($){if(O0($)){let Z=M0($);return Z&&Z.branding===B4?Z:Rj($)}return oY($)}function _3($){if($!==void 0){if(O0($)){let Z=M0($)||{};switch(Z.branding){case q1:case w$:return Z;case k$:return G0(Z)}let J=C3($);return{...Sj(l,d,T4(J),$),calendar:J}}return dY($)}}function C3($){return KX($)||w}function KX($){let{calendar:Z}=$;if(Z!==void 0)return T0(Z)}function T0($){return O0($)?(M0($)||{}).calendar||KO($):((Z)=>O3(aY(t(Z))))($)}function fZ($,Z){if(Z=z0(Z),O0($)){let J=M0($);if(J&&J.branding===q1)return B3(Z),J;let W=C3($);return Aj(l,d,T4(W),W,$,Z)}return uY($,Z)}function WX($){return r0((Z)=>(J)=>Z($7(J)),$)}function $7($){return S0($,K0)}function AV(){let $=Y$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(Y$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);B7.set(this,((z,X={})=>{let G=new Y$(z,X),Q=G.resolvedOptions(),K=Q.locale,B=g0(Object.keys(X),Q),F=y0(RV),O=(...V)=>{let D,U=V.map((H,T)=>{let I=M0(H),x=(I||{}).branding;if(T&&D&&D!==x)throw TypeError(Az);return D=x,I});return D?F(D)(K,B,...U):[G,...V]};return O.u=G,O})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&EV(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||fV(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function EV($){return function(...Z){let J=B7.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function fV($){return function(...Z){return B7.get(this).u[$](...Z)}}function RV($){let Z=bV[$];if(!Z)throw TypeError(Sz($));return b1(Z,y0(T2))}var bV={Instant:n2,PlainDateTime:o2,PlainDate:a2,PlainTime:r2,PlainYearMonth:t2,PlainMonthDay:e2},wV=b1(n2),kV=b1($X),qV=b1(o2),yV=b1(a2),vV=b1(r2),gV=b1(t2),mV=b1(e2),Y7={era:l5,eraYear:jJ,year:F3,month:t0,daysInMonth:t0,daysInYear:t0,inLeapYear:mz,monthsInYear:t0},H4={monthCode:t},j7={day:t0},FX={dayOfWeek:t0,dayOfYear:t0,weekOfYear:i5,yearOfWeek:jJ,daysInWeek:t0},BX=Object.assign({},Y7,H4,j7,FX),L4=new WeakMap,M0=L4.get.bind(L4),YX=L4.set.bind(L4),hV={...D4(Y7,[xZ]),...D4(FX,[]),...D4(H4,[xZ,CZ]),...D4(j7,[CZ])},z7=J7(BX),pV=J7({...Y7,...H4}),cV=J7({...H4,...j7}),S3={calendarId:($)=>L0($.calendar)},dV=r0(($,Z)=>function(J){let{i:W}=this;return $(W[Z]($0(G0(J,W))))},BX),uV=Q3(($)=>(Z)=>Z[$],g.concat("sign")),X7=Q3(($,Z)=>(J)=>J[J1[Z]],k1),VX={epochSeconds:OY,epochMilliseconds:v6,epochMicroseconds:DY,epochNanoseconds:UY},A3=b(JJ,new Set(["branding"])),[lV,RZ,iV]=B1(CZ,b(lj,T0),{...S3,...cV},{getISOFields:A3,getCalendar:x3,with($,Z,J){return RZ(yj(XO,$,this,bZ(Z),J))},equals:($,Z)=>Fj($,ZX(Z)),toPlainDate($,Z){return $0(jz(E3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=mV(Z,J,$);return W.format(Y)},toString:fJ,toJSON:($)=>fJ($),valueOf:Q$},{from:($,Z)=>RZ(ZX($,Z))}),OX={getOffsetNanosecondsFor:GX,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,P0(X0(J,w)))].map((j)=>nV(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(x0),yJ(d0(c0(W[0],W[Y-1])))),W}},Z7={getOffsetNanosecondsFor:GX},[sV,E0,nV]=B1(F4,hj,VX,{add:($,Z)=>E0(vJ(0,$,e(Z))),subtract:($,Z)=>E0(vJ(1,$,e(Z))),until:($,Z,J)=>u(Y2(0,$,K1(Z),J)),since:($,Z,J)=>u(Y2(1,$,K1(Z),J)),round:($,Z)=>E0(IY($,Z)),equals:($,Z)=>zj($,K1(Z)),toZonedDateTime($,Z){let J=f1(Z);return Q0(L2($,l(J.timeZone),T0(J.calendar)))},toZonedDateTimeISO:($,Z)=>Q0(L2($,l(Z))),toLocaleString($,Z,J){let[W,Y]=wV(Z,J,$);return W.format(Y)},toString:($,Z)=>xJ(l,K0,$,Z),toJSON:($)=>xJ(l,K0,$),valueOf:Q$},{from:($)=>E0(K1($)),fromEpochSeconds:($)=>E0(Gz($)),fromEpochMilliseconds:($)=>E0(Qz($)),fromEpochMicroseconds:($)=>E0(Kz($)),fromEpochNanoseconds:($)=>E0(Fz($)),compare:($,Z)=>Z2(K1($),K1(Z))}),[I4,JP]=B1("TimeZone",($)=>{let Z=Yj($);return{branding:"TimeZone",id:Z,o:V4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(z$(Z)).map((J)=>E0(D0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(K1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=K1(Z).epochNanoseconds,W=U4(this,Z7).getOffsetNanosecondsFor(J);return C$(W)},getPlainDateTimeFor($,Z,J=w){let W=K1(Z).epochNanoseconds,Y=U4(this,Z7).getOffsetNanosecondsFor(W);return P0(X0($$(W,Y),T0(J)))},getInstantFor($,Z,J){let W=z$(Z),Y=DJ(J),j=U4(this);return E0(D0(v0(j,W,Y)))},getNextTransition:({o:$},Z)=>JX(1,$,Z),getPreviousTransition:({o:$},Z)=>JX(-1,$,Z),equals($,Z){return!!t6(this,l(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=l($);return typeof Z=="string"?new I4(Z):Z}}),oV=XX(Object.keys(OX)),[aV,X$]=B1(K4,ij,X7,{getISOFields:A3,with($,Z,J){return X$(vj(this,bZ(Z),J))},add:($,Z)=>X$(cJ(0,$,e(Z))),subtract:($,Z)=>X$(cJ(1,$,e(Z))),until:($,Z,J)=>u(Q2(0,$,j$(Z),J)),since:($,Z,J)=>u(Q2(1,$,j$(Z),J)),round:($,Z)=>X$(MY($,Z)),equals:($,Z)=>Bj($,j$(Z)),toZonedDateTime:($,Z)=>Q0(zz(l,f0,d,$,Z)),toPlainDateTime:($,Z)=>P0(Xz($,f0(Z))),toLocaleString($,Z,J){let[W,Y]=vV(Z,J,$);return W.format(Y)},toString:RJ,toJSON:($)=>RJ($),valueOf:Q$},{from:($,Z)=>X$(j$($,Z)),compare:($,Z)=>r6(j$($),j$(Z))}),[rV,G$,tV]=B1(xZ,b(uj,T0),{...S3,...pV},{getISOFields:A3,getCalendar:x3,with($,Z,J){return G$(qj(zO,$,this,bZ(Z),J))},add:($,Z,J)=>G$(pJ(jX,0,$,e(Z),J)),subtract:($,Z,J)=>G$(pJ(jX,1,$,e(Z),J)),until:($,Z,J)=>u(G2(zX,0,$,EZ(Z),J)),since:($,Z,J)=>u(G2(zX,1,$,EZ(Z),J)),equals:($,Z)=>Kj($,EZ(Z)),toPlainDate($,Z){return $0(Yz(E3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=gV(Z,J,$);return W.format(Y)},toString:EJ,toJSON:($)=>EJ($),valueOf:Q$},{from:($,Z)=>G$(EZ($,Z)),compare:($,Z)=>E$(EZ($),EZ(Z))}),[eV,P0]=B1(k$,b(cj,T0),{...S3,...z7,...X7},{getISOFields:A3,getCalendar:x3,with($,Z,J){return P0(wj(E3,$,this,bZ(Z),J))},withCalendar:($,Z)=>P0(J4($,T0(Z))),withPlainDate:($,Z)=>P0(Dz($,f0(Z))),withPlainTime:($,Z)=>P0(Oz($,W7(Z))),add:($,Z,J)=>P0(mJ(y$,0,$,e(Z),J)),subtract:($,Z,J)=>P0(mJ(y$,1,$,e(Z),J)),until:($,Z,J)=>u(z2(F1,0,$,z$(Z),J)),since:($,Z,J)=>u(z2(F1,1,$,z$(Z),J)),round:($,Z)=>P0(TY($,Z)),equals:($,Z)=>Gj($,z$(Z)),toZonedDateTime:($,Z,J)=>Q0(rj(d,$,l(Z),J)),toPlainDate:($)=>$0(G0($)),toPlainTime:($)=>X$($1($)),toPlainYearMonth($){return G$(tj(P4,$,this))},toPlainMonthDay($){return RZ(ej(M4,$,this))},toLocaleString($,Z,J){let[W,Y]=qV(Z,J,$);return W.format(Y)},toString:SJ,toJSON:($)=>SJ($),valueOf:Q$},{from:($,Z)=>P0(z$($,Z)),compare:($,Z)=>W2(z$($),z$(Z))}),[$O,$0,DX]=B1(w$,b(dj,T0),{...S3,...z7},{getISOFields:A3,getCalendar:x3,with($,Z,J){return $0(kj(E3,$,this,bZ(Z),J))},withCalendar:($,Z)=>$0(J4($,T0(Z))),add:($,Z,J)=>$0(hJ(y$,0,$,e(Z),J)),subtract:($,Z,J)=>$0(hJ(y$,1,$,e(Z),J)),until:($,Z,J)=>u(X2(F1,0,$,f0(Z),J)),since:($,Z,J)=>u(X2(F1,1,$,f0(Z),J)),equals:($,Z)=>Qj($,f0(Z)),toZonedDateTime($,Z){let J=!O0(Z)||Z instanceof I4?{timeZone:Z}:Z;return Q0($z(l,j$,d,$,J))},toPlainDateTime:($,Z)=>P0(Zz($,W7(Z))),toPlainYearMonth($){return G$(Jz(P4,$,this))},toPlainMonthDay($){return RZ(Wz(M4,$,this))},toLocaleString($,Z,J){let[W,Y]=yV(Z,J,$);return W.format(Y)},toString:AJ,toJSON:($)=>AJ($),valueOf:Q$},{from:($,Z)=>$0(f0($,Z)),compare:($,Z)=>E$(f0($),f0(Z))}),G7={fields($,Z,J){return[...Z.call($,J)]}},UX=Object.assign({dateFromFields($,Z,J,W){return DX(Z.call($,Object.assign(Object.create(null),J),W))}},G7),LX=Object.assign({yearMonthFromFields($,Z,J,W){return tV(Z.call($,Object.assign(Object.create(null),J),W))}},G7),HX=Object.assign({monthDayFromFields($,Z,J,W){return iV(Z.call($,Object.assign(Object.create(null),J),W))}},G7),Q7={mergeFields($,Z,J,W){return f1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},ZO=Object.assign({},UX,Q7),JO=Object.assign({},LX,Q7),WO=Object.assign({},HX,Q7),K7={dateAdd($,Z,J,W,Y){return DX(Z.call($,$0(G0(J,$)),u(s(W)),Y))}},IX=Object.assign({},K7,{dateUntil($,Z,J,W,Y,j){return QO(Z.call($,$0(G0(J,$)),$0(G0(W,$)),Object.assign(Object.create(null),j,{largestUnit:I3[Y]})))}}),YO=Object.assign({},K7,{day:QX}),jO=Object.assign({},IX,{day:QX}),P4=V1(LX),T4=V1(UX),M4=V1(HX),zO=V1(JO),E3=V1(ZO),XO=V1(WO),y$=V1(K7),F1=V1(IX),jX=V1(YO),zX=V1(jO),[GO,u,QO]=B1(B4,sj,{...uV,blank:mY},{with:($,Z)=>u(gj($,Z)),negated:($)=>u(i6($)),abs:($)=>u(gY($)),add:($,Z,J)=>u(sJ(_3,F1,d,0,$,e(Z),J)),subtract:($,Z,J)=>u(sJ(_3,F1,d,1,$,e(Z),J)),round:($,Z)=>u(vY(_3,F1,d,$,Z)),total:($,Z)=>HY(_3,F1,d,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):p6($)},toString:p6,toJSON:($)=>p6($),valueOf:Q$},{from:($)=>u(e($)),compare:($,Z,J)=>jj(_3,y$,d,e($),e(Z),J)}),PX={toString:($)=>$.id,toJSON:($)=>$.id,...hV,dateAdd:({id:$,o:Z},J,W,Y)=>$0(G0(Z.dateAdd(f0(J),e(W),Y),$)),dateUntil:({o:$},Z,J,W)=>u(s($.dateUntil(f0(Z),f0(J),QY(W)))),dateFromFields:({id:$,o:Z},J,W)=>$0(B2(Z,J,W,u5($))),yearMonthFromFields:({id:$,o:Z},J,W)=>G$(V2(Z,J,W,c5($))),monthDayFromFields:({id:$,o:Z},J,W)=>RZ(O2(Z,0,J,W,d5($))),fields({o:$},Z){let J=new Set(Z1),W=[];for(let Y of Z){if(t(Y),!J.has(Y))throw RangeError(N2(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(WJ(zJ(Z)),WJ(zJ(J)))},[F7]=B1("Calendar",($)=>{let Z=Pj($);return{branding:"Calendar",id:Z,o:SZ(Z)}},{id:($)=>$.id},PX,{from($){let Z=T0($);return typeof Z=="string"?new F7(Z):Z}}),KO=XX(Object.keys(PX).slice(4)),[FO,Q0]=B1(q1,b(pj,T0,l),{...VX,...S3,...WX(z7),...WX(X7),offset:($)=>C$($7($).offsetNanoseconds),offsetNanoseconds:($)=>$7($).offsetNanoseconds,timeZoneId:($)=>L0($.timeZone),hoursInDay:($)=>NY(d,$)},{getISOFields:($)=>qY(K0,$),getCalendar:x3,getTimeZone:({timeZone:$})=>typeof $=="string"?new I4($):$,with($,Z,J){return Q0(bj(E3,d,$,this,bZ(Z),J))},withCalendar:($,Z)=>Q0(J4($,T0(Z))),withTimeZone:($,Z)=>Q0(Uz($,l(Z))),withPlainDate:($,Z)=>Q0(Vz(d,$,f0(Z))),withPlainTime:($,Z)=>Q0(Bz(d,$,W7(Z))),add:($,Z,J)=>Q0(gJ(y$,d,0,$,e(Z),J)),subtract:($,Z,J)=>Q0(gJ(y$,d,1,$,e(Z),J)),until:($,Z,J)=>u(s(j2(F1,d,0,$,fZ(Z),J))),since:($,Z,J)=>u(s(j2(F1,d,1,$,fZ(Z),J))),round:($,Z)=>Q0(PY(d,$,Z)),startOfDay:($)=>Q0(_Y(d,$)),equals:($,Z)=>Xj($,fZ(Z)),toInstant:($)=>E0(nj($)),toPlainDateTime:($)=>P0(H2(K0,$)),toPlainDate:($)=>$0(I2(K0,$)),toPlainTime:($)=>X$(P2(K0,$)),toPlainYearMonth($){return G$(oj(P4,$,this))},toPlainMonthDay($){return RZ(aj(M4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=kV(Z,J,$);return W.format(Y)},toString:($,Z)=>CJ(K0,$,Z),toJSON:($)=>CJ(K0,$),valueOf:Q$},{from:($,Z)=>Q0(fZ($,Z)),compare:($,Z)=>J2(fZ($),fZ(Z))}),BO=Object.defineProperties({},{...x6("Temporal.Now"),...N$({timeZoneId:()=>w1(),instant:()=>E0(D0(U3())),zonedDateTime:($,Z=w1())=>Q0(I0(U3(),l(Z),T0($))),zonedDateTimeISO:($=w1())=>Q0(I0(U3(),l($),w)),plainDateTime:($,Z=w1())=>P0(X0(NZ(K0(l(Z))),T0($))),plainDateTimeISO:($=w1())=>P0(X0(NZ(K0(l($))),w)),plainDate:($,Z=w1())=>$0(G0(NZ(K0(l(Z))),T0($))),plainDateISO:($=w1())=>$0(G0(NZ(K0(l($))),w)),plainTimeISO:($=w1())=>X$($1(NZ(K0(l($)))))})}),wZ=Object.defineProperties({},{...x6("Temporal"),...N$({PlainYearMonth:rV,PlainMonthDay:lV,PlainDate:$O,PlainTime:aV,PlainDateTime:eV,ZonedDateTime:FO,Instant:sV,Calendar:F7,TimeZone:I4,Duration:GO,Now:BO})}),VO=AV(),B7=new WeakMap,OO=Object.defineProperties(Object.create(Intl),N$({DateTimeFormat:VO}));var N4="x-gemi-socket";var GP="gemi.v1",TX="/__gemi/socket",QP=/^[A-Za-z0-9_-]{1,32}$/,KP={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function OP($){return $}function MX(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:TX,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 DO,randomBytes as UO}from"crypto";function LO($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(DO("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var HO="__control",V7=250,IO=1e4,PO=15000;class O7{config;prefix;controlChannel;instanceId=UO(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??LO(),this.controlChannel=this.prefix+HO,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=f3((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 $})(),PO,"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 (${NX(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(IO,V7*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(V7,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;f3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${NX(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??TO(Math.min(Z,V7));await f3(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 f3(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 f3(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 f3($,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 TO($){return new Promise((Z)=>setTimeout(Z,$))}function NX($){return $ instanceof Error?$.message:String($)}import{createHmac as MO,hkdfSync as NO,randomBytes as _X}from"crypto";function xX($){return MO("sha256",_O()).update($).digest("base64url").slice(0,22)}var _4=null;function _O(){let $=process.env.SECRET||void 0;if(_4&&_4.secret===$)return _4.key;let Z=$?Buffer.from(NO("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):_X(32);return _4={secret:$,key:Z},Z}function IP(){return _X(16).toString("base64url")}var xO=/^[A-Za-z0-9_-]{8,64}$/;function D7($){return typeof $==="string"&&xO.test($)}function CX($,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 AX 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 m0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=O1(MX(),$),this.driver=AO(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 R3(this,x4($,Z[0]),null)}toUser($){return new R3(this,{topic:e$($),pattern:F0},null)}toOthers($){return new EX(this,SO($))}broadcastEvent($){let Z=$.broadcastOn(),J=Array.isArray(Z)?Z:[Z],W=$.broadcastAs(),Y=$.broadcastWith(),j=J.map((z)=>this.prepare(x4(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){r9(Z);let Y;try{Y=CX($.topic,Z,J,W?xX(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){kZ(()=>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=CO($);kZ(()=>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 AX(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 R3{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 EX{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new R3(this.manager,x4($,Z[0]),this.except)}toUser($){return new R3(this.manager,{topic:e$($),pattern:F0},this.except)}}function x4($,Z){if(a9($))return{topic:K8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:aZ($,Z??{}),pattern:$};if($===F0)throw new p('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:K8($)}}function CO($){if($&&typeof $==="object"&&"user"in $)return{user:e$($.user).slice(F0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:x4($.channel,$.params).topic};throw new p("Broadcast.revoke takes { user } or { channel }.")}function SO($){if($===null||$===void 0)return null;if(typeof $==="string")return D7($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(N4);return D7(J)?J:null}function AO($,Z){let J=$.driver;if(J===void 0||J==="memory")return new SX;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new O7({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 U7 extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class EO{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1}import{createHash as L7,createHmac as fO,randomBytes as fX,timingSafeEqual as wX}from"crypto";var w3=600,C4="gemi_oauth",RO=`__Host-${C4}`;function qZ($,Z=C4){if(Z===C4)return $?RO:C4;return $?`__Host-${Z}`:Z}function b3($){return $.toString("base64url")}function kX($){return fO("sha256",zZ()).update(`gemi-oauth-state:${$}`).digest()}function RX($,Z){let J=L7("sha256").update($).digest(),W=L7("sha256").update(Z).digest();return wX(J,W)&&$.length===Z.length}function S4($,Z=Date.now(),J={}){let W=b3(fX(32)),Y=b3(fX(32)),j=bO(Y),z={provider:$,state:W,codeVerifier:Y,expiresAt:Z+w3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{}};return{state:W,codeVerifier:Y,codeChallenge:j,cookieValue:wO(z)}}function bO($){return b3(L7("sha256").update($).digest())}function wO($){let Z=b3(Buffer.from(JSON.stringify($)));return`${Z}.${b3(kX(Z))}`}function kO($){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=kX(J);if(W.length!==Y.length||!wX(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")return null;return j}catch{return null}}var K$=new Map,bX=1e4;function qO($,Z,J){if(K$.size>=bX){for(let[W,Y]of K$)if(Y<=J)K$.delete(W);while(K$.size>=bX){let W=K$.keys().next().value;if(W===void 0)break;K$.delete(W)}}K$.set($,Z)}function A4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=kO($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=RX(J.state,$.returnedState),Y=RX(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(K$.has(J.state))return{ok:!1,reason:"invalid_state"};return qO(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var H7=new WeakMap;function vO($){let Z=H7.get($);if(!Z)Z=$(yO(32).toString("hex")),H7.set($,Z),Z.catch(()=>H7.delete($));return Z}async function I7($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await vO($.hashPassword))}catch{}return!1}async function v$($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class T7 extends Error{}function P7($){return typeof $==="string"&&$!==""?$:null}function qX($){return $3($)}var gO=256;function yX($){return typeof $==="string"&&$!==""&&$.length<=gO?$:null}var E4="intended_url";function gX($){if($.cookies.get(E4))$.ctx().setCookie(E4,"",{maxAge:-1})}function vX($){let Z=$.cookies.get(E4);if(!Z)return null;gX($);try{return j1(decodeURIComponent(Z),"")||null}catch{return null}}class M7 extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class mX extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class hX extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}function y1($){if(L(E).config[$]===!1)throw new W0("Not found",{status:404})}class n extends tZ{async me(){let $=await b0.user();if(!$)throw new A8;return $}async verifyEmail($=new C){y1("password");let Z=await $.input(),{userProvider:J}=L(E),W=P7(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=L(E),{userProvider:J}=Z,W=P7($.search.get("token")),Y=null;try{Y=$3(decodeURIComponent($.search.get("email")??""))}catch{}if(await XZ("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp}),!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,L(E).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await v$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){y1("magicLink");let Z=L(E),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=$3(W),z=yX(Y);if(await XZ("verify",j,$,Z.config.emailCode.verifyLimit),!j||!z)throw new h({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new h({pin:["Too many attempts"]});if(X.status!=="ok")throw new h({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new C){let Z=L(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,L(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await v$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new C){let Z=L(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,L(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await v$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new M7){y1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=L(E),z=await j.userProvider.findUserByEmailAddress(Y,j.config.verifyEmail),X=typeof W==="string"&&await I7(j.config,W,z?.password);if(!z||!X)throw new h({invalid_credentials:["Invalid credentials"]});let G=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,L(E).accessTokenCookieOptions($,G.expiresAt)),await j.config.onSignIn(z,$.search.toJSON()),await v$(j.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...K}=z;return K}async signIn($=new M7){y1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=L(E),z=await j.userProvider.findUserByEmailAddress(Y,j.config.verifyEmail),X=typeof W==="string"&&await I7(j.config,W,z?.password);if(!z||!X)throw new h({invalid_credentials:["Invalid credentials"]});let G=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,L(E).accessTokenCookieOptions($,G.expiresAt)),await j.config.onSignIn(z,$.search.toJSON()),await v$(j.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...K}=z;return K}async signUp(){y1("password");let $=L(E),{userProvider:Z,config:J}=$,W=new J.signUpRequest,Y=await W.input(),{email:j,password:z,name:X,invitationId:G}=Y.toJSON(),Q=qX(j);if(!Q)throw new h({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new h({password:["Invalid password"]});if(G!=null&&typeof G!=="string")throw new h({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(Q,!1))throw new h({email:["Email address already exists"]});let B=await J.hashPassword(z),F=L(i).detectLocale(W),O;if(G)O=await Z.findInvitation(G,Q);let V,D="";if(O)V=await Z.transaction(async()=>{await Z.deleteInvitationById(G);let U=await Z.createUser({email:Q,name:X,password:B,emailVerifiedAt:new Date,locale:F});return await Z.createAccount({organizationId:O.organizationId,userId:U.id,organizationRole:O.role}),await J.onUserCreated(U),U});else D=await J.generateEmailVerificationToken(Q),V=await Z.transaction(async()=>{let U=await Z.createUser({email:Q,name:X,password:B,verificationToken:D,locale:F});return await J.onUserCreated(U),U});return await J.onSignUp(V,D,W.search.toJSON()),V}async signOut($=new C){let Z=O$($),J=L(E),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",L(E).accessTokenCookieOptions($,new Date(0))),L(E).cookieDomain($))$.ctx().setCookie("access_token","",{...L(E).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)mO(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user);return{}}async forgotPassword($=new mX){y1("password");let Z=await $.input(),J=qX(Z.get("email"));if(!J)return{};let{userProvider:W,config:Y}=L(E),j=await W.findUserByEmailAddress(J,Y.verifyEmail);if(!j)return{};let z=await Y.generateForgotPasswordToken(j);return await W.createPasswordResetToken({user:j,token:z}),await Y.onForgotPassword(j,z),{}}async resetPassword($=new hX){y1("password");let{userProvider:Z,config:J}=L(E),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=P7(j),X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new h({token:["Invalid token"]});if(wZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(wZ.Now.instant()).sign>=0)throw new h({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let Q=await Z.findUserByEmailAddress(X.user.email,J.verifyEmail);if(!Q)throw new h({email:["User not found"]});let K=await J.hashPassword(Y);return await Z.updateUserPassword({id:Q.id,password:K}),await Z.deleteAllUserSessions(Q.id),await J.onResetPassword(Q),{}}async changePassword($=new C){y1("password");let{userProvider:Z,config:J}=L(E),W=await b0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(typeof z!=="string")throw new h({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,J.verifyEmail);if(!(typeof j==="string"&&await I7(J,j,X?.password)))throw new h({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=L(E).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await GZ(J,Z);if(!Y){if(W)throw new W0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=ZZ($.rawRequest),z=j1($.search.get(Y1),"");if(z)$.ctx().setCookie(E4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else gX($);let{state:X,codeChallenge:G,cookieValue:Q}=S4(Z);return $.ctx().setCookie(qZ(j),Q,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:w3}),{destination:await Y.getRedirectUrl($,{state:X,codeChallenge:G,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,J=L(E),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await GZ(Y.oauthProviders,Z);if(j&&!z)throw new W0("Not found",{status:404});let X=ZZ($.rawRequest),G=qZ(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 K=$.search.get("error");if(K)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(K)?K:"provider_error");let B=A4({provider:Z,cookieValue:Q,returnedState:$.search.get("state")});if("reason"in B)return console.error(`Authentication error: OAuth callback refused (${B.reason})`),this.oauthFailure($,B.reason);if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let F;try{F=await z.onCallback($,{state:B.payload.state,codeVerifier:B.payload.codeVerifier})}catch(P){if(P instanceof U7)return this.oauthFailure($,P.code);return console.error("Authentication error: OAuth provider callback failed",P),this.oauthFailure($,"provider_error")}let{name:O,username:V,providerId:D,emailVerified:U}=F??{},H=typeof F?.email==="string"?F.email:void 0,T=H?z6(H):null,I=D?await W.findUserBySocialAccount(Z,D):null,x="signin",A=!I&&!T&&!H&&!!D&&z.createUsersWithoutEmail===!0;if(!I&&A){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{I=await this.createOAuthUserWithoutEmail({provider:Z,providerId:D,name:O,username:V,locale:L(i).detectLocale($)}),x="signup"}catch(P){let k=await W.findUserBySocialAccount(Z,D);if(!k)throw P;I=k}}if(!I){if(!T)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,H?"invalid_email":D?"missing_email":"no_identity");if(U===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let P=L(i).detectLocale($);try{let k=await this.linkOAuthAccount({provider:Z,providerId:D,email:T,rawEmail:H,name:O,username:V,locale:P,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(k==="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(k==="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(k)I=k.user,x=k.action}catch(k){let m=D?await W.findUserBySocialAccount(Z,D):null;if(!m)throw k;I=m}if(!I)return this.oauthFailure($,"account_conflict")}let f=await J.createOrUpdateSessionV2({email:I.email,id:I.id});if($.ctx().setCookie("access_token",f.token,L(E).accessTokenCookieOptions($,f.expiresAt)),x==="signup")await Y.onSignUp(I,"",$.search.toJSON());else await Y.onSignIn(I,$.search.toJSON());await v$(J.config,{session:f,user:I,isNewUser:x==="signup",method:"oauth",req:$});let S=vX($)??Y.redirectPath,M=Y.oauthCompleteProfilePath?j1(Y.oauthCompleteProfilePath,""):"";if(M&&!I.email){let P=new URL(M,"http://gemi.invalid");P.searchParams.set(Y1,S),S=`${P.pathname}${P.search}${P.hash}`}return{session:f,redirectTo:S}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=L(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),W})}oauthFailure($,Z){let J=vX($),W=L(E).config.oauthFailurePath;if(W){let Y=j1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(Y1,J);M1.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}=L(E),K=(V)=>({provider:Z,userId:V,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),B=await G.findUserByEmailAddress(W,!1),F=Y?.trim();if(!B&&F&&F!==W)B=await G.findUserByEmailAddress(F,!1);if(B){if($.linkExisting===!1)return"account_exists";if(!J)return{user:B,action:"signin"};let V=await G.findSocialAccounts(B.id,Z);if(V.some((U)=>U.providerId===J))return{user:B,action:"signin"};if(V.some((U)=>U.providerId))return console.error(`Authentication error: user ${B.id} is already linked to a different ${Z} account`),null;let D=V[0];if(D){if(!await G.claimSocialAccount(D,J))throw Error(`${Z} account link changed concurrently`)}else await G.createSocialAccount(K(B.id));return{user:B,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await G.transaction(async()=>{let V=await G.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await G.createSocialAccount(K(V.id));return await Q.onUserCreated(V),V}),action:"signup"}}async createMagicLinkToken($=new C){y1("magicLink");let Z=await $.input(),J=$3(Z.get("email")),W=L(E),{uniformMagicLinkResponse:Y,requestLimit:j}=W.config.emailCode;if(await XZ("request",J,$,j),!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}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new C){let Z=L(E),J=Z.config.emailCode;if(!J.enabled)throw new W0("Not found",{status:404});let W=await $.input(),Y=z6(W.get("email"));if(await XZ("request",Y,$,J.requestLimit),!Y)throw new h({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=L(E),{userProvider:J,config:W}=Z;if(!W.emailCode.enabled)throw new W0("Not found",{status:404});let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),G=z6(j),Q=yX(z);if(await XZ("verify",G,$,W.emailCode.verifyLimit),!G||!Q)throw new h({code:["invalid_code"]});let K=await Z.verifyOneTimeCode(G,Q,{claim:!1});if(K.status==="too_many_attempts")throw new h({code:["too_many_attempts"]});if(K.status!=="ok")throw new h({code:["invalid_code"]});let B=K.row,F=await J.findUserByEmailAddress(G,!1),O=!1;if(F){if(!await J.claimMagicLinkToken(B.id))throw new h({code:["invalid_code"]});await J.verifyUser(G)}else if(W.emailCode.createUser){let D=L(i).detectLocale($);try{F=await J.transaction(async()=>{if(!await J.claimMagicLinkToken(B.id))throw new T7;let U=await J.createUser({email:G,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:D});return await W.onUserCreated(U),U}),O=!0}catch(U){if(U instanceof T7)throw new h({code:["invalid_code"]});throw U}}else throw await J.claimMagicLinkToken(B.id),new h({code:["invalid_code"]});let V=await Z.createOrUpdateSessionV2({email:G,id:F.id});return $.ctx().setCookie("access_token",V.token,L(E).accessTokenCookieOptions($,V.expiresAt)),await W.onSignIn(V,$.search.toJSON()),await v$(Z.config,{session:V,isNewUser:O,method:"email-code",req:$}),{session:V,isNewUser:O}}}function mO($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=L();if(typeof J?.bound!=="function"||!J.bound(m0))return;J.make(m0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var pX="gemi_oauth_connection";class f4 extends tZ{async connect($=new C){let Z=String($.params.provider??""),W=L(k3).providers[Z],Y=await b0.user(),j=j1($.search.get(Y1),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=ZZ($.rawRequest),{state:X,codeChallenge:G,cookieValue:Q}=S4(cX(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(qZ(z,pX),Q,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:w3}),M1.external(W.authorizationUrl({state:X,codeChallenge:G,redirectUri:dX($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),J=L(k3),W=await b0.user(),Y=ZZ($.rawRequest),j=qZ(Y,pX),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=A4({provider:cX(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 K=$.search.get("error");if(K)return this.finish(G,Z,/^[a-z0-9_]{1,64}$/.test(K)?K:"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 B=$.search.get("code");if(!B)return this.finish(G,Z,"missing_code");try{let F=await Q.exchangeCode({code:B,codeVerifier:X.payload.codeVerifier,redirectUri:dX($,Z,Q.config.redirectUri)}),O=await J.save(W,Z,F);await L(E).config.onConnected({user:W,provider:Z,connection:O,profile:F.profile??null,req:$})}catch(F){if(F instanceof uX)return console.error(`OAuth connection to ${Z} failed: ${F.message}`),this.finish(G,Z,F.providerError??F.code);throw F}return this.finish(G,Z)}finish($,Z,J){let W=$||j1(L(E).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw M1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function cX($){return`connection:${$}`}function dX($,Z,J){if(J)return J;return`${q3()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}class lX extends N1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[n,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[n,"oauthCallback"])}}class iX extends N1{middlewares=["cache:private"];routes={"/:provider":this.redirect([f4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([f4,"callback"]).middleware([t3,"auth"])}}class N7 extends N1{middlewares=["cache:private"];routes={"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[n,"signInWithMagicLink"]),"/oauth":lX,"/connections":iX}}class _7 extends R0{middlewares=["cache:private"];routes={"/sign-in":this.post(n,"signIn"),"/sign-in-v2":this.post(n,"signInV2"),"/sign-up":this.post(n,"signUp"),"/sign-out":this.post(n,"signOut"),"/forgot-password":this.post(n,"forgotPassword"),"/reset-password":this.post(n,"resetPassword"),"/change-password":this.post(n,"changePassword"),"/verify-email":this.post(n,"verifyEmail"),"/me":this.get(n,"me").middleware(["auth"]),"/magic-link":this.post(n,"createMagicLinkToken"),"/sign-in-with-pin":this.post(n,"signInWithPin"),"/sign-in-with-pin-v2":this.post(n,"signInWithPinV2"),"/email-code":this.post(n,"requestEmailCode"),"/email-code/verify":this.post(n,"verifyEmailCode")}}class x7 extends R0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new C().params.locale;return await L(i).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new C,Z=`/${$.params.scope??""}`,J=$.params.locale,W=L(i),Y=J??W.detectLocale($),j=W.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:j}})}}class C7{}class S7 extends C7{async resize($,Z){let{height:J,width:W,quality:Y,fit:j}=Z;return await(await R4("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 ET($){return $}function sX(){return{driver:new S7}}class A7 extends R0{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 new Response(JSON.stringify({error:"url query parameter is required"}),{headers:{"Content-Type":"application/json"},status:404});let G=`${J.startsWith("http")?"":`http://localhost:${process.env.PORT||5173}`}${J}`,Q=await fetch(G);if(!Q.ok)return new Response(JSON.stringify({error:"Image not found",info:G}),{headers:{"Content-Type":"application/json"},status:404});let K=Buffer.from(await Q.arrayBuffer()),B=await L(nX).resize(K,{height:Y,width:W,fit:j,quality:z});Q.headers.delete("Content-Type"),Q.headers.delete("Content-Length");let F=new Headers(Q.headers);return F.set("Content-Type","image/webp"),F.set("Content-Length",`${B.byteLength}`),new Response(new Uint8Array(B),{headers:F})})}}class nX{static token="image";driver;constructor($={}){this.driver=$.driver??sX().driver}resize($,Z){return this.driver.resize($,Z)}}class E7 extends R0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(L(oX).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function mT($){return $}function aX(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function rX(){return{partialRendering:!0,localeRouting:"prefix",onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function hO($){return"run"in $}function pO($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function cO($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function dO($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function uO($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function tX($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function f7($,Z="",J=[]){let W={};function Y(j,z,X,G,Q){let K=j==="/"?"":j,B=Z==="/"?"":Z,F=(`${B}${K}`===""?"/":`${B}${K}`).replaceAll("//","/");if(!W[F])W[F]={};W[F][z.toUpperCase()]={exec:X,middleware:[...J,...G],...Q?{source:Q}:{}},W[F].OPTIONS={exec:()=>{let V=new C().ctx().headers;return new Response(null,{headers:V,status:204})},middleware:[]}}for(let[j,z]of Object.entries($)){if(uO(z)){let X=z;for(let G of["GET","POST","PUT","DELETE"])Y(j,G,X.run.bind(X),X.middlewares);continue}if(hO(z)){let X=z,G=X.method,Q=X.middlewares,K=X.run.bind(X);if(Y(j,G,K,Q,X.source),tX(z))Y(j,"HEAD",K,Q,X.source)}if(pO(z))for(let[X,G]of Object.entries(z)){let Q=G,K=Q.middlewares,B=Q.run.bind(Q);if(Y(j,X,B,K,Q.source),X==="get"&&tX(Q))Y(j,"HEAD",B,K,Q.source)}if(dO(z)){let X=new z,G=f7(X.routes,`${Z}${j}`,X.middlewares);for(let[Q,K]of Object.entries(G))W[Q.replaceAll("//","/")]=K}if(cO(z)){let{first:X,second:G}=z;for(let[Q,K]of Object.entries(X)){let B=K.middlewares,F=K.run.bind(K),[O,...V]=j.split("/").reverse();if(!O.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(V.reverse().join("/"),Q,F,B,K.source)}for(let[Q,K]of Object.entries(G)){let B=K.middlewares,F=K.run.bind(K);Y(j,Q,F,B,K.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 b4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function R7($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function b7($){let Z=b4($);return Z.length>1?Z.replace(/\/$/,""):Z}function eX($,Z){return Z.map((J)=>({...J,path:b7(R7($,J.path))}))}function w4($){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=w4(j.routes);for(let[X,{exec:G,middleware:Q,segments:K,features:B,static:F}]of Object.entries(z)){let O=R7(J,X),V=(D)=>Y.run.call(Y,D,J);Z[b4(O)]={exec:[V,...G],middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...B],viewPath:Y.viewPath,segments:[{path:b7(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...eX(J,K)],...F?{static:F}:{}}}}else{let j=(z)=>Y.run.call(Y,z,J);Z[b4(J)]={exec:[j],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:b7(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new W,j=w4(Y.routes);for(let[z,{exec:X,middleware:G,viewPath:Q,segments:K,features:B,static:F}]of Object.entries(j)){let O=R7(J,z);Z[b4(O)]={exec:X,middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...B],viewPath:Q,segments:eX(J,K),...F?{static:F}:{}}}}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 lO=Object.defineProperty,_=($,Z)=>lO($,"name",{value:Z,configurable:!0}),gZ=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,J,W,Y,j){this.type=$,this.name=Z,this.prefix=J,this.value=W,this.suffix=Y,this.modifier=j}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};_(gZ,"Part");var iO=/[$_\p{ID_Start}]/u,sO=/[$_\u200C\u200D\p{ID_Continue}]/u,k7=".*";function $G($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}_($G,"isASCII");function v7($,Z=!1){let J=[],W=0;for(;W<$.length;){let Y=$[W],j=_(function(z){if(!Z)throw TypeError(z);J.push({type:"INVALID_CHAR",index:W,value:$[W++]})},"ErrorOrInvalid");if(Y==="*"){J.push({type:"ASTERISK",index:W,value:$[W++]});continue}if(Y==="+"||Y==="?"){J.push({type:"OTHER_MODIFIER",index:W,value:$[W++]});continue}if(Y==="\\"){J.push({type:"ESCAPED_CHAR",index:W++,value:$[W++]});continue}if(Y==="{"){J.push({type:"OPEN",index:W,value:$[W++]});continue}if(Y==="}"){J.push({type:"CLOSE",index:W,value:$[W++]});continue}if(Y===":"){let z="",X=W+1;for(;X<$.length;){let G=$.substr(X,1);if(X===W+1&&iO.test(G)||X!==W+1&&sO.test(G)){z+=$[X++];continue}break}if(!z){j(`Missing parameter name at ${W}`);continue}J.push({type:"NAME",index:W,value:z}),W=X;continue}if(Y==="("){let z=1,X="",G=W+1,Q=!1;if($[G]==="?"){j(`Pattern cannot start with "?" at ${G}`);continue}for(;G<$.length;){if(!$G($[G],!1)){j(`Invalid character '${$[G]}' at ${G}.`),Q=!0;break}if($[G]==="\\"){X+=$[G++]+$[G++];continue}if($[G]===")"){if(z--,z===0){G++;break}}else if($[G]==="("&&(z++,$[G+1]!=="?")){j(`Capturing groups are not allowed at ${G}`),Q=!0;break}X+=$[G++]}if(Q)continue;if(z){j(`Unbalanced pattern at ${W}`);continue}if(!X){j(`Missing pattern at ${W}`);continue}J.push({type:"REGEX",index:W,value:X}),W=G;continue}J.push({type:"CHAR",index:W,value:$[W++]})}return J.push({type:"END",index:W,value:""}),J}_(v7,"lexer");function g7($,Z={}){let J=v7($);Z.delimiter??="/#?",Z.prefixes??="./";let W=`[^${h0(Z.delimiter)}]+?`,Y=[],j=0,z=0,X="",G=new Set,Q=_((I)=>{if(z<J.length&&J[z].type===I)return J[z++].value},"tryConsume"),K=_(()=>Q("OTHER_MODIFIER")??Q("ASTERISK"),"tryConsumeModifier"),B=_((I)=>{let x=Q(I);if(x!==void 0)return x;let{type:A,index:f}=J[z];throw TypeError(`Unexpected ${A} at ${f}, expected ${I}`)},"mustConsume"),F=_(()=>{let I="",x;for(;x=Q("CHAR")??Q("ESCAPED_CHAR");)I+=x;return I},"consumeText"),O=_((I)=>I,"DefaultEncodePart"),V=Z.encodePart||O,D="",U=_((I)=>{D+=I},"appendToPendingFixedValue"),H=_(()=>{D.length&&(Y.push(new gZ(3,"","",V(D),"",3)),D="")},"maybeAddPartFromPendingFixedValue"),T=_((I,x,A,f,S)=>{let M=3;switch(S){case"?":M=1;break;case"*":M=0;break;case"+":M=2;break}if(!x&&!A&&M===3){U(I);return}if(H(),!x&&!A){if(!I)return;Y.push(new gZ(3,"","",V(I),"",M));return}let P;A?A==="*"?P=k7:P=A:P=W;let k=2;P===W?(k=1,P=""):P===k7&&(k=0,P="");let m;if(x?m=x:A&&(m=j++),G.has(m))throw TypeError(`Duplicate name '${m}'.`);G.add(m),Y.push(new gZ(k,m,V(I),P,V(f),M))},"addPart");for(;z<J.length;){let I=Q("CHAR"),x=Q("NAME"),A=Q("REGEX");if(!x&&!A&&(A=Q("ASTERISK")),x||A){let S=I??"";Z.prefixes.indexOf(S)===-1&&(U(S),S=""),H();let M=K();T(S,x,A,"",M);continue}let f=I??Q("ESCAPED_CHAR");if(f){U(f);continue}if(Q("OPEN")){let S=F(),M=Q("NAME"),P=Q("REGEX");!M&&!P&&(P=Q("ASTERISK"));let k=F();B("CLOSE");let m=K();T(S,M,P,k,m);continue}H(),B("END")}return Y}_(g7,"parse");function h0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}_(h0,"escapeString");function q7($){return $&&$.ignoreCase?"ui":"u"}_(q7,"flags");function ZG($,Z,J){return m7(g7($,J),Z,J)}_(ZG,"stringToRegexp");function g$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}_(g$,"modifierToString");function m7($,Z,J={}){J.delimiter??="/#?",J.prefixes??="./",J.sensitive??=!1,J.strict??=!1,J.end??=!0,J.start??=!0,J.endsWith="";let W=J.start?"^":"";for(let X of $){if(X.type===3){X.modifier===3?W+=h0(X.value):W+=`(?:${h0(X.value)})${g$(X.modifier)}`;continue}Z&&Z.push(X.name);let G=`[^${h0(J.delimiter)}]+?`,Q=X.value;if(X.type===1?Q=G:X.type===0&&(Q=k7),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?W+=`(${Q})${g$(X.modifier)}`:W+=`((?:${Q})${g$(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){W+=`(?:${h0(X.prefix)}(${Q})${h0(X.suffix)})`,W+=g$(X.modifier);continue}W+=`(?:${h0(X.prefix)}`,W+=`((?:${Q})(?:`,W+=h0(X.suffix),W+=h0(X.prefix),W+=`(?:${Q}))*)${h0(X.suffix)})`,X.modifier===0&&(W+="?")}let Y=`[${h0(J.endsWith)}]|$`,j=`[${h0(J.delimiter)}]`;if(J.end)return J.strict||(W+=`${j}?`),J.endsWith.length?W+=`(?=${Y})`:W+="$",new RegExp(W,q7(J));J.strict||(W+=`(?:${j}(?=${Y}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=J.delimiter.indexOf(X)>-1)}return z||(W+=`(?=${j}|${Y})`),new RegExp(W,q7(J))}_(m7,"partsToRegexp");var B$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},nO={delimiter:".",prefixes:"",sensitive:!0,strict:!0},oO={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function JG($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}_(JG,"isAbsolutePathname");function h7($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}_(h7,"maybeStripPrefix");function WG($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}_(WG,"maybeStripSuffix");function p7($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}_(p7,"treatAsIPv6Hostname");var YG=["ftp","file","http","https","ws","wss"];function c7($){if(!$)return!0;for(let Z of YG)if($.test(Z))return!0;return!1}_(c7,"isSpecialScheme");function jG($,Z){if($=h7($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}_(jG,"canonicalizeHash");function zG($,Z){if($=h7($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}_(zG,"canonicalizeSearch");function XG($,Z){return Z||$===""?$:p7($)?l7($):u7($)}_(XG,"canonicalizeHostname");function GG($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}_(GG,"canonicalizePassword");function QG($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}_(QG,"canonicalizeUsername");function KG($,Z,J){if(J||$==="")return $;if(Z&&!YG.includes(Z))return new URL(`${Z}:${$}`).pathname;let W=$[0]=="/";return $=new URL(W?$:"/-"+$,"https://example.com").pathname,W||($=$.substring(2,$.length)),$}_(KG,"canonicalizePathname");function FG($,Z,J){return d7(Z)===$&&($=""),J||$===""?$:i7($)}_(FG,"canonicalizePort");function BG($,Z){return $=WG($,":"),Z||$===""?$:k4($)}_(BG,"canonicalizeProtocol");function d7($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}_(d7,"defaultPortForProtocol");function k4($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}_(k4,"protocolEncodeCallback");function VG($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}_(VG,"usernameEncodeCallback");function OG($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}_(OG,"passwordEncodeCallback");function u7($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}_(u7,"hostnameEncodeCallback");function l7($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}_(l7,"ipv6HostnameEncodeCallback");function i7($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}_(i7,"portEncodeCallback");function DG($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}_(DG,"standardURLPathnameEncodeCallback");function UG($){return $===""?$:new URL(`data:${$}`).pathname}_(UG,"pathURLPathnameEncodeCallback");function LG($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}_(LG,"searchEncodeCallback");function HG($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}_(HG,"hashEncodeCallback");var IG=class{#j;#W=[];#Z={};#$=0;#Y=1;#Q=0;#X=0;#V=0;#O=0;#D=!1;constructor($){this.#j=$}get result(){return this.#Z}parse(){for(this.#W=v7(this.#j,!0);this.#$<this.#W.length;this.#$+=this.#Y){if(this.#Y=1,this.#W[this.#$].type==="END"){if(this.#X===0){this.#I(),this.#K()?this.#J(9,1):this.#F()?this.#J(8,1):this.#J(7,0);continue}else if(this.#X===2){this.#B(5);continue}this.#J(10,0);break}if(this.#V>0)if(this.#C())this.#V-=1;else continue;if(this.#x()){this.#V+=1;continue}switch(this.#X){case 0:this.#P()&&this.#B(1);break;case 1:if(this.#P()){this.#E();let $=7,Z=1;this.#M()?($=2,Z=3):this.#D&&($=2),this.#J($,Z)}break;case 2:this.#L()?this.#B(3):(this.#H()||this.#F()||this.#K())&&this.#B(5);break;case 3:this.#N()?this.#J(4,1):this.#L()&&this.#J(5,1);break;case 4:this.#L()&&this.#J(5,1);break;case 5:this.#S()?this.#O+=1:this.#A()&&(this.#O-=1),this.#_()&&!this.#O?this.#J(6,1):this.#H()?this.#J(7,0):this.#F()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 6:this.#H()?this.#J(7,0):this.#F()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 7:this.#F()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 8:this.#K()&&this.#J(9,1);break;case 9:break;case 10:break}}this.#Z.hostname!==void 0&&this.#Z.port===void 0&&(this.#Z.port="")}#J($,Z){switch(this.#X){case 0:break;case 1:this.#Z.protocol=this.#G();break;case 2:break;case 3:this.#Z.username=this.#G();break;case 4:this.#Z.password=this.#G();break;case 5:this.#Z.hostname=this.#G();break;case 6:this.#Z.port=this.#G();break;case 7:this.#Z.pathname=this.#G();break;case 8:this.#Z.search=this.#G();break;case 9:this.#Z.hash=this.#G();break;case 10:break}this.#X!==0&&$!==10&&([1,2,3,4].includes(this.#X)&&[6,7,8,9].includes($)&&(this.#Z.hostname??=""),[1,2,3,4,5,6].includes(this.#X)&&[8,9].includes($)&&(this.#Z.pathname??=this.#D?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#T($,Z)}#T($,Z){this.#X=$,this.#Q=this.#$+Z,this.#$+=Z,this.#Y=0}#I(){this.#$=this.#Q,this.#Y=0}#B($){this.#I(),this.#X=$}#U($){return $<0&&($=this.#W.length-$),$<this.#W.length?this.#W[$]:this.#W[this.#W.length-1]}#z($,Z){let J=this.#U($);return J.value===Z&&(J.type==="CHAR"||J.type==="ESCAPED_CHAR"||J.type==="INVALID_CHAR")}#P(){return this.#z(this.#$,":")}#M(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#L(){return this.#z(this.#$,"@")}#N(){return this.#z(this.#$,":")}#_(){return this.#z(this.#$,":")}#H(){return this.#z(this.#$,"/")}#F(){if(this.#z(this.#$,"?"))return!0;if(this.#W[this.#$].value!=="?")return!1;let $=this.#U(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#K(){return this.#z(this.#$,"#")}#x(){return this.#W[this.#$].type=="OPEN"}#C(){return this.#W[this.#$].type=="CLOSE"}#S(){return this.#z(this.#$,"[")}#A(){return this.#z(this.#$,"]")}#G(){let $=this.#W[this.#$],Z=this.#U(this.#Q).index;return this.#j.substring(Z,$.index)}#E(){let $={};Object.assign($,B$),$.encodePart=k4;let Z=ZG(this.#G(),void 0,$);this.#D=c7(Z)}};_(IG,"Parser");var w7=["protocol","username","password","hostname","port","pathname","search","hash"],F$="*";function y7($,Z){if(typeof $!="string")throw TypeError("parameter 1 is not of type 'string'.");let J=new URL($,Z);return{protocol:J.protocol.substring(0,J.protocol.length-1),username:J.username,password:J.password,hostname:J.hostname,port:J.port,pathname:J.pathname,search:J.search!==""?J.search.substring(1,J.search.length):void 0,hash:J.hash!==""?J.hash.substring(1,J.hash.length):void 0}}_(y7,"extractValues");function D1($,Z){return Z?vZ($):$}_(D1,"processBaseURLString");function yZ($,Z,J){let W;if(typeof Z.baseURL=="string")try{W=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=D1(W.protocol.substring(0,W.protocol.length-1),J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=D1(W.username,J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=D1(W.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=D1(W.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=D1(W.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=D1(W.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=D1(W.search.substring(1,W.search.length),J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&Z.hash===void 0&&($.hash=D1(W.hash.substring(1,W.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=BG(Z.protocol,J)),typeof Z.username=="string"&&($.username=QG(Z.username,J)),typeof Z.password=="string"&&($.password=GG(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=XG(Z.hostname,J)),typeof Z.port=="string"&&($.port=FG(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,W&&!JG($.pathname,J)){let Y=W.pathname.lastIndexOf("/");Y>=0&&($.pathname=D1(W.pathname.substring(0,Y+1),J)+$.pathname)}$.pathname=KG($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=zG(Z.search,J)),typeof Z.hash=="string"&&($.hash=jG(Z.hash,J)),$}_(yZ,"applyInit");function vZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}_(vZ,"escapePatternString");function PG($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}_(PG,"escapeRegexpString");function TG($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",W=`[^${PG(Z.delimiter)}]+?`,Y=/[$_\u200C\u200D\p{ID_Continue}]/u,j="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){j+=vZ(X.value);continue}j+=`{${vZ(X.value)}}${g$(X.modifier)}`;continue}let G=X.hasCustomName(),Q=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),K=z>0?$[z-1]:null,B=z<$.length-1?$[z+1]:null;if(!Q&&G&&X.type===1&&X.modifier===3&&B&&!B.prefix.length&&!B.suffix.length)if(B.type===3){let F=B.value.length>0?B.value[0]:"";Q=Y.test(F)}else Q=!B.hasCustomName();if(!Q&&!X.prefix.length&&K&&K.type===3){let F=K.value[K.value.length-1];Q=Z.prefixes.includes(F)}Q&&(j+="{"),j+=vZ(X.prefix),G&&(j+=`:${X.name}`),X.type===2?j+=`(${X.value})`:X.type===1?G||(j+=`(${W})`):X.type===0&&(!G&&(!K||K.type===3||K.modifier!==3||Q||X.prefix!=="")?j+="*":j+=`(${J})`),X.type===1&&G&&X.suffix.length&&Y.test(X.suffix[0])&&(j+="\\"),j+=vZ(X.suffix),Q&&(j+="}"),X.modifier!==3&&(j+=g$(X.modifier))}return j}_(TG,"partsToPattern");var s7=class{#j;#W={};#Z={};#$={};#Y={};#Q=!1;constructor($={},Z,J){try{let W;if(typeof Z=="string"?W=Z:J=Z,typeof $=="string"){let X=new IG($);if(X.parse(),$=X.result,W===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=W}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(W)throw TypeError("parameter 1 is not of type 'string'.")}typeof J>"u"&&(J={ignoreCase:!1});let Y={ignoreCase:J.ignoreCase===!0},j={pathname:F$,protocol:F$,username:F$,password:F$,hostname:F$,port:F$,search:F$,hash:F$};this.#j=yZ(j,$,!0),d7(this.#j.protocol)===this.#j.port&&(this.#j.port="");let z;for(z of w7){if(!(z in this.#j))continue;let X={},G=this.#j[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,B$),X.encodePart=k4;break;case"username":Object.assign(X,B$),X.encodePart=VG;break;case"password":Object.assign(X,B$),X.encodePart=OG;break;case"hostname":Object.assign(X,nO),p7(G)?X.encodePart=l7:X.encodePart=u7;break;case"port":Object.assign(X,B$),X.encodePart=i7;break;case"pathname":c7(this.#W.protocol)?(Object.assign(X,oO,Y),X.encodePart=DG):(Object.assign(X,B$,Y),X.encodePart=UG);break;case"search":Object.assign(X,B$,Y),X.encodePart=LG;break;case"hash":Object.assign(X,B$,Y),X.encodePart=HG;break}try{this.#Y[z]=g7(G,X),this.#W[z]=m7(this.#Y[z],this.#Z[z],X),this.#$[z]=TG(this.#Y[z],X),this.#Q=this.#Q||this.#Y[z].some((Q)=>Q.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#j[z]}'.`)}}}catch(W){throw TypeError(`Failed to construct 'URLPattern': ${W.message}`)}}get[Symbol.toStringTag](){return"URLPattern"}test($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return!1;try{typeof $=="object"?J=yZ(J,$,!1):J=yZ(J,y7($,Z),!1)}catch{return!1}let W;for(W of w7)if(!this.#W[W].exec(J[W]))return!1;return!0}exec($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return;try{typeof $=="object"?J=yZ(J,$,!1):J=yZ(J,y7($,Z),!1)}catch{return null}let W={};Z?W.inputs=[$,Z]:W.inputs=[$];let Y;for(Y of w7){let j=this.#W[Y].exec(J[Y]);if(!j)return null;let z={};for(let[X,G]of this.#Z[Y].entries())if(typeof G=="string"||typeof G=="number"){let Q=j[X+1];z[G]=Q}W[Y]={input:J[Y]??"",groups:z}}return W}static compareComponent($,Z,J){let W=_((X,G)=>{for(let Q of["type","modifier","prefix","value","suffix"]){if(X[Q]<G[Q])return-1;if(X[Q]===G[Q])continue;return 1}return 0},"comparePart"),Y=new gZ(3,"","","","",3),j=new gZ(0,"","","","",3),z=_((X,G)=>{let Q=0;for(;Q<Math.min(X.length,G.length);++Q){let K=W(X[Q],G[Q]);if(K)return K}return X.length===G.length?0:W(X[Q]??Y,G[Q]??Y)},"comparePartList");return!Z.#$[$]&&!J.#$[$]?0:Z.#$[$]&&!J.#$[$]?z(Z.#Y[$],[j]):!Z.#$[$]&&J.#$[$]?z([j],J.#Y[$]):z(Z.#Y[$],J.#Y[$])}get protocol(){return this.#$.protocol}get username(){return this.#$.username}get password(){return this.#$.password}get hostname(){return this.#$.hostname}get port(){return this.#$.port}get pathname(){return this.#$.pathname}get search(){return this.#$.search}get hash(){return this.#$.hash}get hasRegExpGroups(){return this.#Q}};_(s7,"URLPattern");function y3($,Z){for(let[J,W]of Object.entries($)){let Y=new s7({pathname:J});if(Y.test({pathname:Z}))return{routePath:J,params:Y.exec({pathname:Z})?.pathname.groups??{},route:W}}return null}var m$={startIndex:0,carriedViews:[]};function MG($,Z){let J=B0($.path,Z);return J.includes("*")?null:J}function aO($,Z){if(!$)return m$;if($.search!==Z.search)return m$;let J=Math.min($.segments.length,Z.segments.length-1),W=0;while(W<J){let Y=$.segments[W],j=Z.segments[W];if(j.alwaysRun)break;if(Y.viewPath!==j.viewPath)break;let z=MG(Y,$.params),X=MG(j,Z.params);if(z===null||X===null||z!==X)break;W++}if(W===0)return m$;return{startIndex:W,carriedViews:Z.segments.slice(0,W).map(({viewPath:Y})=>Y)}}function rO($,Z){let[,J,...W]=$.split("/");if(!Z.includes(J))return $;let Y=`/${W.join("/")}`;return Y==="/"?"/":Y.replace(/\/$/,"")}function NG($){let{flatViewRoutes:Z,supportedLocales:J,from:W,origin:Y,to:j}=$;if(!W)return m$;let z;try{z=new URL(W,Y)}catch{return m$}if(z.origin!==Y)return m$;let X=y3(Z,rO(z.pathname,J));if(!X)return m$;return aO({segments:X.route.segments,params:X.params,search:z.search},j)}var n7="x-gemi-from";import{createElement as g1,Fragment as cG}from"react";function tO($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function q4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if("children"in W){Z[J]=[Y];let j=new W.children,z=q4(j.routes);for(let[X,G]of Object.entries(z)){let Q=J==="/"?X:`${J}${X}`,K=X==="/"&&J!=="/"?J:Q;Z[K]=[Y,...G]}if(Z[J].length===1)delete Z[J]}else Z[J]=[Y]}else{let Y=new W,j=q4(Y.routes);for(let[z,X]of Object.entries(j)){let G=J==="/"?z:`${J}${z}`,Q=z==="/"&&J!=="/"?J:G;Z[Q]=X}}return Object.fromEntries(Object.entries(Z).map(([J,W])=>[tO(J),W]))}function y4($,Z){let[J,W]=Z,Y=$.find(([j])=>j===J);if(!Y){$.push([J,[...W]]);return}for(let j of W)y4(Y[1],j)}function v4($){let Z=[];for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if(Y==="__")continue;if(Y==="REDIRECT")continue;if(Y==="FILE")continue;if("children"in W){let j=new W.children,z=v4(j.routes);y4(Z,[Y,z])}else y4(Z,[Y,[]])}else{let Y=new W,j=v4(Y.routes);for(let z of j)y4(Z,z)}return Z}function o7($){let Z=[];for(let[J,W]of $)Z.push(J,...o7(W).flat());return Array.from(new Set(Z))}class V$ extends v{static getFacadeAccessor(){return i}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=N.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(N.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??V$.locale(),$.timeZone??V$.timeZone())}static setLocale($=V$.locale(),Z={}){let J=this.getFacadeRoot(),W=$;if(!J.supportedLocales.includes($))W=J.defaultLocale;let Y=N.getStore();if(Z.cookie!==!1)Y.setCookie("i18n-locale",W,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return Y.setLocale(W),W}}class a7{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function _G($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var eO=50;class mZ{fetcher;entries=new Map;settleListener=null;failListener=null;shellAt=null;settledBacklog=[];shipped=new Set;requestStartedAt=performance.now();renderStartedAt=null;discoveryHintsMuted=!1;constructor($){this.fetcher=$}elapsed(){return Math.round(performance.now()-this.requestStartedAt)}keyFor($,Z){return[$,Z].filter((J)=>J.length>0).join("?")}markRenderStart(){if(this.renderStartedAt===null)this.renderStartedAt=performance.now()}markShell(){if(this.shellAt===null)this.shellAt=this.elapsed()}summarize($){let Z=this.elapsed();return{shellAt:this.shellAt??Z,settledAt:Z,aborted:$,queries:Array.from(this.entries.values(),(J)=>({path:J.path,variantKey:J.variantKey,startedAt:J.startedAt,settledAt:J.settledAt,status:J.status,source:J.source}))}}onQueryFail($){this.failListener=$}muteDiscoveryHints(){this.discoveryHintsMuted=!0}maybeLogLateDiscovery($){if(!$.lateBy||this.discoveryHintsMuted)return;if($.status!=="resolved")return;if(Bun.env.NODE_ENV==="production")return;let Z="";try{let Y=JSON.stringify($.data)?.length??0;Z=Y>=1024?`${(Y/1024).toFixed(1)} kB`:`${Y} B`}catch{Z="an unserializable payload"}let J=($.settledAt??0)-$.startedAt,W=$.variantKey?`, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams($.variantKey)))} }`:"";console.warn(`[gemi] useQuery("${$.patternPath}") was discovered ${$.lateBy}ms into the `+`server render \u2014 under a suspended segment, so its fetch (${J}ms, resolved ${Z}) could not overlap the others. It still streamed. If the query belongs on this route, \`Query.prefetch("${$.patternPath}"${W})\` in the view `+"handler starts it at request time \u2014 but note prefetched data is also re-fetched and "+`streamed into every client-side navigation payload for the route, even when the client already holds it, so weigh that bandwidth against the ${Z}. If the data is only needed conditionally (a closed popover, a hidden tab), \`{ lazy: true }\` + \`trigger()\` avoids running it here at all. \`Query.noPrefetch()\` in the handler marks the omission intentional and silences this hint for the route.`)}read($,Z){return this.entries.get(this.keyFor($,Z))}ensure($,Z={},J="render"){let W=Z.params??{},Y=new URLSearchParams(_G(Z.search??{}));Y.delete("json"),Y.sort();let j=B0($,W),z=Y.toString(),X=this.keyFor(j,z),G=this.entries.get(X);if(G)return G;let Q;if(J==="render"&&this.renderStartedAt!==null){let O=Math.round(performance.now()-this.renderStartedAt);if(O>eO)Q=O}let K,B=new Promise((O)=>{K=O}),F={path:j,patternPath:$,variantKey:z,lateBy:Q,status:"pending",promise:B,source:J,startedAt:this.elapsed()};return this.entries.set(X,F),this.fetcher($,W,Y).then((O)=>{F.status="resolved",F.data=O},(O)=>{F.status="rejected",F.error=O}).then(()=>{if(F.settledAt=this.elapsed(),this.maybeLogLateDiscovery(F),F.status==="rejected"&&this.failListener)this.failListener(F);if(this.settleListener)this.settleListener(F);else this.settledBacklog.push(F);K()}),F}async allSettled(){let $=0;while($!==this.entries.size)$=this.entries.size,await Promise.all(Array.from(this.entries.values(),(Z)=>Z.promise))}snapshotResolved(){let $={};for(let[Z,J]of this.entries){if(J.status!=="resolved")continue;this.shipped.add(Z),$[J.path]??={},$[J.path][J.variantKey]=J.data}return $}onSettle($){this.settleListener=(J)=>{if(this.shipped.has(this.keyFor(J.path,J.variantKey)))return;$(J)};let Z=this.settledBacklog;this.settledBacklog=[];for(let J of Z)this.settleListener(J)}}class v1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,J,W,Y){super(typeof W?.message==="string"?W.message:`Request to /api${$} failed with status ${J}`);this.path=$;this.variantKey=Z;this.status=J;this.body=W;this.retryAfter=Y;this.name="QueryError"}}function hZ(){let $=JSON.stringify({error:l1("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function r7(){return{status:403,error:{message:"Forbidden"}}}function v3($){let Z=pZ.getStore();return(J,W,Y)=>{let j=new URL($.url).origin,z=[B0(J,W),Y.toString()].filter((K)=>K.length>0).join("?"),X=new Request(`${j}/${z}`,{headers:$.headers,signal:$.signal}),G=xG($);if(G)cZ(X,G);let Q=new C(X,W);return pZ.run(Z,()=>N.run(Q,async()=>{try{let K=await L(W1).dispatchers(G).api.getRouteData(J);if($Z(K)){if(!K.ok)throw new v1(B0(J,W),Y.toString(),K.status,K.body);return K.body}if(K instanceof Response){let B=await K.json().catch(()=>null);if(!K.ok)throw new v1(B0(J,W),Y.toString(),K.status,B);return B}return K}catch(K){if(K instanceof v1)throw K;let B=new v1(B0(J,W),Y.toString(),500,{message:K instanceof Error?K.message:String(K)});throw B.cause=K,B}}))}}var $D=new Set(["script","style","template","title"]),ZD=/\shidden([\s=/]|$)/i,JD=/"[^"]*"|'[^']*'/g;function WD($){let Z=0,J=0,W=0,Y=0;while(Y<$.length){let j=$.indexOf("<",Y),z=j===-1?$.length:j;if(z>Y){let B=$.slice(Y,z).replace(/\s+/g,"").length;if(W>0)J+=B;else Z+=B}if(j===-1)break;if($.startsWith("<!--",j)){let B=$.indexOf("-->",j+4);Y=B===-1?$.length:B+3;continue}let X=$.indexOf(">",j);if(X===-1)break;let G=$.slice(j+1,X);Y=X+1;let Q=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(G)?.[1]?.toLowerCase();if(!Q)continue;let K=G.startsWith("/");if(!K&&$D.has(Q)&&!G.endsWith("/")){let B=$.indexOf(`</${Q}`,Y);Y=B===-1?$.length:B;continue}if(Q!=="div")continue;if(K){if(W>0)W-=1}else if(W>0)W+=1;else if(ZD.test(G.replace(JD,'""')))W=1}return{shellChars:Z,deferredChars:J}}var YD=1000,jD=64;function zD($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function XD($,Z){if(Z.deferredChars<YD)return null;if(Z.shellChars>=jD)return null;return`[gemi] GET ${$} streams ${zD(Z.deferredChars)} of its `+`content behind reveal scripts \u2014 a no-JS visitor sees ~${Z.shellChars} chars. If this is a public/content route, add "no-stream" to its middleware.`}function CG($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,W){if(Z.has(J))return;let Y=XD(J,W);if(!Y)return;Z.add(J),$(Y)}}}function SG(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),WD(Z)}}}function AG($,Z,J=1e4,W){let Y=new TextEncoder,j=()=>{};return new ReadableStream({start(z){let X=!1,G=(K)=>{if(X)return;X=!0,clearTimeout(Q);try{z.close()}catch{}W?.({aborted:K})};j=G,z.enqueue(Y.encode(`${JSON.stringify($)}
|
|
14
|
-
`)),Z.onSettle((K)=>{if(X||K.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([K.path,K.variantKey,K.data])}
|
|
15
|
-
`))});let Q=setTimeout(()=>G(!0),J);Z.allSettled().then(()=>G(!1),()=>G(!1))},cancel(){j(!1)}})}import{Fragment as EM,createContext as GD,createElement as fM,lazy as RM,use as bM,useContext as wM}from"react";function EG($){return{islands:[],render:$,instances:new WeakMap,count:0}}var g3="gemi-slot",fG="data-slot",RG="data-gemi-slot";var QD=Symbol.for("gemi.staticRender"),bG=globalThis[QD]??=GD(null);import{createHash as vG}from"crypto";var t7='var r=document,i=window,a=history;i.__gemi_nav?.d();var L=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:L.signal,...s}),q=i.__gemi_nav={d:()=>L.abort()},v=(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))},D=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},R=(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")v(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>v(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),v(n,s)});for(let m of n.children)l.observe(m)}}},O=\'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(O)?.content,C=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],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},y={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,N=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},Y=(t)=>{let e=r.body,n=t.body,s=D(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),R(e,s)},H=async(t,e)=>{let n=++b,s=!e&&y[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)||C(d)!=C(r))throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),Y(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)N(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(),y[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=y[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&&(y[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(O)?.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();R(r,D(r));_(!0);';import{createHash as KD}from"crypto";import{existsSync as kG,readFileSync as FD}from"fs";import{join as J9}from"path";var qG=".script",BD=[".ts",".js"],VD="document-scripts.json",yG="data-gemi-script",OD=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function DD($){if(typeof $!=="string"||!OD.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 UD($,Z){for(let J of BD){let W=J9($,"views",`${Z}${qG}${J}`);if(kG(W))return W}return null}async function wG($){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(`
|
|
16
|
-
`);throw Error(`The document script ${$} does not bundle.
|
|
17
|
-
${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 LD($){return`'sha256-${KD("sha256").update($).digest("base64")}'`}var e7,$9=new Map;function HD(){if(e7===void 0){let $=J9(Z9(),"dist","server",VD);e7=kG($)?JSON.parse(FD($,"utf8")):null}return e7??null}async function W9($){DD($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=HD()?.[$];if(j!==void 0)return j;let z=$9.get($);if(z)return z}let J=J9(Z9(),"app"),W=UD(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${qG}.ts (or .js).`);if(!Z)return wG(W);let Y=wG(W);return $9.set($,Y),Y.catch(()=>$9.delete($)),Y}async function hM($){return LD(await W9($))}var ID="gemi-islands",nM=`'sha256-${vG("sha256").update(z9).digest("base64")}'`;function Y9($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var j9=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),oM=`'sha256-${vG("sha256").update(t7).digest("base64")}'`,PD='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',TD="gemi-static";function gG($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((V)=>{let D=V.module?J(V.module):void 0;if(!D)return console.error(`[gemi] island ${V.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(V.load==="eager")for(let U of D.preload)z.add(U);return{s:D.src,e:V.export,l:V.load}});let G=X.some((V)=>V!==null),Q=j?`<script type="module" ${yG}="${j9(j.name)}">${j.source}</script>`:"";if(!G&&!Y)return Y9($,"</head>",Q,!1);let B=(Y?`<meta name="${TD}" content="${j9(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((V)=>`<link rel="modulepreload" href="${j9(V)}"/>`).join("")+Q,F=Y?t7:z9,O=(G?`<script type="application/json" id="${ID}">${_1({i:X})}</script>`:"")+`<script type="module">${W?PD+F:F}</script>`;return Y9(Y9($,"</head>",B,!1),"</body>",O,!0)}function MD($,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 mG($){let Z=`<template ${RG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=MD($,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=`<${g3} ${fG}="${j}" style="display:contents"></${g3}>`;$=$.split(G).join(`<${g3} style="display:contents">${X}</${g3}>`)}return $}function hG($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function pG($,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)}var ND=async()=>(await import("./chunk-jbd723h1.js")).default,X9,m3=async(...$)=>{return X9??=import("react-dom/server.browser").catch((Z)=>{throw X9=void 0,Z}),(await X9).renderToReadableStream(...$)},dG=1e4,uG="no-locale",_D=`
|
|
18
|
-
!function(){try{var d=document.documentElement,c=d.classList;
|
|
19
|
-
c.remove('light','dark');
|
|
20
|
-
var e=localStorage.getItem('theme');
|
|
21
|
-
if('system'===e||(!e&&'system'===defaultTheme)){
|
|
22
|
-
var t='(prefers-color-scheme: dark)',m=window.matchMedia(t);
|
|
23
|
-
if(m.media!==t||m.matches){d.style.colorScheme='dark';c.add('dark')}
|
|
24
|
-
else{d.style.colorScheme='light';c.add('light')}
|
|
25
|
-
}else if(e){
|
|
26
|
-
c.add(e||'')
|
|
27
|
-
}}catch(e){}}()
|
|
28
|
-
`;async function xD($,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 K9="/assets";function CD($){return $===K9||$.startsWith(`${K9}/`)}function SD($){let Z=$.filter(CD);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 "${K9}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function AD($){let Z=L(W1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function G9($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function ED($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class h3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];staticRoutes=[];root=null;shellReporter=CG();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;constructor($){let Z=rX();this.partialRendering=$.partialRendering??Z.partialRendering,this.localeRouting=$.localeRouting??Z.localeRouting,this.hooks={onRequestStart:$.onRequestStart??Z.onRequestStart,onRequestEnd:$.onRequestEnd??Z.onRequestEnd,onRequestFail:$.onRequestFail??Z.onRequestFail,onStreamComplete:$.onStreamComplete??Z.onStreamComplete};let J={"/":$.rootRouter,"/auth":N7};this.flatViewRoutes=w4(J),SD(Object.keys(this.flatViewRoutes)),this.routeManifest=q4(J),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,W])=>W.at(-1)!=="FILE")),this.componentTree=v4(J),this.flatComponentTree=o7(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,W])=>W.static).map(([W])=>W);for(let W of this.staticRoutes){let Y=this.flatViewRoutes[W].static?.layout;if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=L(s1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)g4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{h$.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 K of J?.[Q]??[])G.add(K);return[...G].map((Q)=>g1("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 K=Q9(),B=new AbortController,F=setTimeout(()=>B.abort(),dG),O=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},V=EG(async(D,U)=>{let H=await m3(D,{signal:B.signal,identifierPrefix:U,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:O});return await H.allReady.catch(()=>{}),await new Response(H).text()});try{let D,U=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(U)D={name:U,source:await W9(U)};let H;if(W.navigation){let x=W.navigation===!0?{}:W.navigation,A=x.version?String(await J(()=>x.version(Z))):"";H={identity:[W.layout??"",$.buildId??"",D?.name??"",A].join("|"),prefetch:x.prefetch==="none"?"none":"intent"}}let T=await m3(g1(bG.Provider,{value:V,children:g1(cG,{children:[...Q,g1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:K,rootLayout:G,key:"root"})]})}),{signal:B.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:O});await T.allReady.catch(()=>{});let I=mG(await new Response(T).text());return new Response(gG(I,V,$.resolveIsland,Bun.env.NODE_ENV!=="production",H,D),{status:200,headers:X})}finally{clearTimeout(F),J(()=>this.completeStream(Z,z.summarize(B.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:K,noStream:B,url:F,user:O,viewData:V,breadcrumbs:D,urlLocaleSegment:U,meta:H,isOgRequest:T,appId:I,features:x,staticView:A}=$,f=G.replace(`/${U}`,""),S={kind:"view",data:{meta:H,pageData:{[f]:V},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:O},routeManifest:this.clientRouteManifest,breadcrumbs:D,router:{urlLocaleSegment:U,pathname:Y,params:X,currentPath:G,searchParams:F.search,is404:!Y?!0:!1,domain:Z.domain?AD(Z):null},appId:I,features:x,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},M=this.root,P=this.routeManifest[Y];return async(k)=>{let{bootstrapModules:m=[],loaders:h1,getStyles:Z0,viewImportMap:o,cssManifest:q,ogMap:U0,viewModules:d$,clientEntry:u$,modulePreloadManifest:lZ,assetBase:I1,resolveIsland:l$,buildId:i$}=k,a=u$?[]:m,c3=(J0)=>[J0,`window.loaders=${h1}`,...u$?[`import(${JSON.stringify(u$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(T){let J0=null,n$=null;for(let o$ of P??[])if(typeof U0[o$]==="function")n$=o$,J0=U0[o$];if(!J0)return new Response("Not found",{status:404});let nQ=Object.values(S.data.pageData)[0];try{await m3(g1(J0,nQ[n$]),{onError:()=>{}})}catch(o$){let{fonts:oQ,...aQ}=o$.satoriOptions,rQ=await Promise.all(oQ.map((d3)=>{return xD(d3.name,d3.weight,d3.style).then((JK)=>({...d3,data:JK}))})),q9=new Headers(j);q9.set("Content-Type","image/png");let[tQ,eQ]=await Promise.all([ND(),R4("Rendering an OG image")]),$K=await tQ(o$.jsx,{...aQ,fonts:rQ}),ZK=await eQ(Buffer.from($K)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(ZK),{headers:q9})}return new Response("data")}if(A&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:A,currentViews:P,data:S.data,serverQueries:Q,headers:j,getStyles:Z0,viewImportMap:o,viewModules:d$,resolveIsland:l$,buildId:i$});if(S.data.cssManifest=q,S.data.modulePreloadManifest=lZ??{},I1&&I1!=="/")S.data.assetBase=I1;let Z8=this.modulePreloadLinks({clientEntry:u$,modulePreloadManifest:lZ,views:P??["404"],routeKey:Y??"404"}),s$=await Z0(P);S.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let P1=new AbortController,iZ=setTimeout(()=>P1.abort(),dG),T1=Q6(K)||B,R=Bun.env.NODE_ENV!=="production"&&!T1&&Y&&this.shellReporter.shouldObserve(Y)?SG():null,p0=Q9();try{let J0=await m3(g1(cG,{children:[...Z8,...s$,g1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:_D}}),g1(M,{data:S.data,viewImportMap:o,viewModules:d$,serverQueries:Q,dictionarySink:p0,key:"root"})]}),{bootstrapScriptContent:c3(`window.__GEMI_DATA__ = ${_1(S.data)}`),bootstrapModules:a,signal:P1.signal,...T1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(n$){if(Bun.env.NODE_ENV!=="production")console.error(n$)}});if(J0.allReady.catch(()=>{}).finally(()=>clearTimeout(iZ)),T1)await J0.allReady.catch(()=>{});return new Response(v8(J0,Q,{onShell:T1?void 0:()=>Q.markShell(),onChunk:R?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(P1.signal.aborted)),R)this.shellReporter.report(Y,R.measure())})},p0),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(J0){if(clearTimeout(iZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(P1.signal.aborted))),J0;let n$=await m3(g1("div"),{bootstrapScriptContent:c3(`window.error= ${_1(J0.message)}; window.stack_trace=${_1(J0.stack)};window.__GEMI_DATA__ = ${_1(S.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...a]:a});return new Response(v8(n$,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(P1.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(D$(Z))return 404;if(Z?.kind===d1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(u1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof v1&&(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,K=null,B=L(i),F=y3(this.flatViewRoutes,j),O=B.isLocaleAware&&this.localeRouting==="prefix"&&!F?.route.middleware.includes(uG);if(O&&B.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,K=z;if(O&&!Y&&K===null&&!(K===null&&F!==null)){let M=lG(z,B.supportedLocales,B.defaultLocale);if(M){let P=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${M}${P}${W?".json":""}${J.search}`}})}}if(O&&!Y){let M=L(i).detectLocale(new C($,{},"view",G));if(K===null&&M!==B.defaultLocale){let P=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${M}${P}${J.search}`}})}}G=G.replace("//","/");let D=[],U=[],H=null,T={},I=null,x=!1,A=[],f;try{let M=y3(this.flatViewRoutes,G);if(K&&M?.route.middleware.includes(uG))M=null;if(M){if(H=M.routePath,T=M.params,D=M.route.exec,U=M.route.middleware,A=M.route.features,x=U.includes("no-stream"),f=M.route.static,W&&this.partialRendering){let P=$.headers.get(n7),k=NG({flatViewRoutes:this.flatViewRoutes,supportedLocales:L(i).supportedLocales,from:P,origin:J.origin,to:{segments:M.route.segments,params:T,search:J.search}});if(k.startIndex>0)D=D.slice(k.startIndex),I={from:P,carriedViews:k.carriedViews}}}}catch(M){throw M}if(f&&W)return new Response("Not found",{status:404});let S=new C($,T,"view",H);return this.hooks.onRequestStart(S),await N.run(S,async()=>{let M=null,P=N.getStore(),k=pZ.getStore(),m=(q)=>pZ.run(k,()=>N.runWith(P,q));P.serverQueries=new mZ(v3($));let h1=new Set;P.serverQueries.onQueryFail((q)=>{h1.add(q.error);try{m(()=>Promise.resolve(this.hooks.onRequestFail(o,q.error)).catch(()=>{}))}catch{}});let Z0=hG(f);if(K){let q=K.replaceAll("/","");V$.setLocale(q,{cookie:Z0.locale})}else if(B.isLocaleAware&&!O)P.setLocale(B.defaultLocale);else V$.setLocale(void 0,{cookie:Z0.locale});let o=P.req;if(Z0.session)g4();try{let q=null;try{await L(c1).runMiddleware(U)}catch(R){if(q=this.viewRefusalStatus(o,R,h1),q===null)throw R}if(q!==null||A.length>0&&!await this.passesFeatureGates(A))H=null,D=[],o.routePath="";let U0=L(i),d$=U0.isEnabled,u$=U0.isLocaleAware,lZ=new C($,o.params),I1={defaultLocale:U0.defaultLocale,timeZone:U0.detectTimeZone(lZ)};if(u$){let R=null;if(K)R=K.replaceAll("/",""),P.setLocale(R);else if(!O)R=P.locale??U0.defaultLocale;else R=U0.detectLocale(lZ),P.setLocale(R);let p0=d$?U0.getPageTranslations(R,o.routePath):{};I1={...I1,supportedLocales:U0.supportedLocales,currentLocale:R,dictionary:{[R]:p0},defaultLocale:U0.defaultLocale,...O?{}:{localeRouting:"off"}}}await iG(I1.currentLocale??"");let l$;try{l$=await Promise.all(D.map((R)=>R(o)))}catch(R){if(q=this.viewRefusalStatus(o,R,h1),q===null)throw R;H=null,D=[],o.routePath="",l$=[]}let{cookies:i$,headers:a}=P;if(q!==null)a.set("Cache-Control","no-store");M={data:l$,cookies:i$,headers:a,user:P.user,prefetchedData:P.serverQueries.snapshotResolved(),currentPathName:H,params:o.params,urlLocaleSegment:Q,meta:P.renderMeta(),appId:L(a7).id,features:await L(s1).forClient()};let{params:c3,user:Z8}=M,s$={},P1={};for(let R of l$??[]){let[p0,J0]=Object.entries(R)?.[0]??[];if(!p0||!J0)continue;P1[`${p0}:${H}`]=J0.breadcrumb,s$[p0]=J0}let iZ=s$.FILE;if(iZ){for(let R of i$)a.append("Set-Cookie",R.toString());try{await this.onRequestEnd(o)}catch(R){h$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}return await D8(iZ,a)}if(W){a.set("Content-Type","application/x-ndjson; charset=utf-8"),a.append("Vary",n7),i$.forEach((p0)=>a.append("Set-Cookie",p0.toString())),await this.hooks.onRequestEnd(o);let R={meta:I&&!P.metadata.touched?null:M.meta,data:{[G]:s$},breadcrumbs:P1,prefetchedData:P.serverQueries.snapshotResolved(),i18n:I1,features:M.features,is404:!H,appId:M.appId,partial:I};return new Response(AG(R,P.serverQueries,void 0,({aborted:p0})=>m(()=>this.completeStream(o,P.serverQueries.summarize(p0)))),{headers:a})}if(a.set("Content-Type","text/html; charset=utf-8"),!x&&!(f&&H))a.append("Vary","User-Agent");let T1=Boolean(f&&H);if(!T1||Z0.session)g4();for(let R of i$)a.append("Set-Cookie",R.toString());if(!T1||Z0.csrf){let R=Bun.CSRF.generate(process.env.SECRET);a.append("Set-Cookie",`csrf_token=${R}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(o,{mintSession:!T1||Z0.session})}catch(R){h$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}if(T1)pG(a,f);return await this.render({req:o,runInRequestScope:m,csrfTokenHMAC:Buffer.from(""),currentPathName:H,headers:a,i18n:I1,params:c3,pathname:J.pathname,serverQueries:P.serverQueries,userAgent:$.headers.get("user-agent"),noStream:x,url:J,user:Z8,viewData:s$,breadcrumbs:P1,urlLocaleSegment:Q,meta:M.meta,appId:M.appId,features:M.features,isOgRequest:Y,staticView:H?f:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===d1){let U0=W?ED(q.payload.viewData??q.payload.api):G9(q.payload.view);for(let d$ of P.cookies)U0.headers.append("Set-Cookie",d$.toString());return U0}if(!h1.has(q))this.hooks.onRequestFail(o,q);if(u1(q))return console.error(q),W?hZ():G9(r7());if(q instanceof v1&&q.status===403)return W?hZ():G9(r7());throw q}},Z)}}function F9(){let $=JSON.stringify({error:l1("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 rG extends R0{routes={"/api-routes":this.get(()=>{let $=L(h4).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 $=L(h3).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 fD=new Set([p1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),RD=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,bD=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function wD($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(fD.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===p1)throw Error(`dispatchAs: credentials may not set the "${p1}" cookie. The access token stays the initiator's.`);if(!RD.test(Y)||!bD.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function kD($,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 sG($){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 nG($,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})}}class h4{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=aX();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=f7({"/":$.rootRouter,"/auth":_7,"/__gemi__/services/i18n":x7,"/__gemi__/services/logs":E7,"/__gemi__/services/image":A7,"/__gemi__/debug":rG})}getRouteHandlerAndParams($){let Z=new URL($.url),J=aG(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 L(c1).runMiddleware(W)}catch(Y){if(Y.kind===d1)return sG(Y.payload.api);else{if(D$(Y))return F9();if(this.onRequestFail(Z,Y),console.error(Y),u1(Y))return hZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=N.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===d1)return sG(j.payload.api);if(D$(j))return F9();if(this.onRequestFail(J.req,j),console.error(j),u1(j))return hZ();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){h$.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:l1("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await N.run(j,async()=>{let z=N.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,W)};try{let Q=L(i);if(Q.isEnabled){let D=Q.detectLocale(j);z.setLocale(D)}z.setRequest(j),L(c1).applyDefaultBodyLimit($);let K=await this.runRouteMiddleware(W,j);if(K instanceof Response){let D=nG(K,z.headers,z.cookies);return await G(),D}let B=await this.getRouteData(W),F=z.headers,O=z.cookies;if(B instanceof Response){let D=nG(B,F,O);if(this.isOpenEndedBody($,D)){let U=kD(D,()=>this.endRequest(z,j,W));return X=!0,U}return await G(),D}let V=($Z(B)?B:U$.json(B)).toResponse(F,O);return await G(),V}catch(Q){if(!X)try{await G()}catch(K){console.error(K)}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,K=[],B=G?null:$.cookies.get(p1);if(B)K.push(`${p1}=${B}`);if(Y?.credentials)wD(Q,K,Y.credentials,G!==void 0);if(K.length>0)Q.set("Cookie",K.join("; "));let F=G?null:$.headers.get(p1);if(F)Q.set(p1,F);let O=$.headers.get("User-Agent");if(O)Q.set("User-Agent",O);let V;if(W instanceof FormData)V=W;else if(W!==void 0)Q.set("Content-Type","application/json"),V=JSON.stringify(W);let D=new Request(z,{method:Z,headers:Q,body:V,...Y?.signal?{signal:Y.signal}:{}});if(oG(D,JZ($),G?.grant,Y?.progress),$.domain)cZ(D,$.domain);let U=G?{user:G.user}:void 0;return N.exit(()=>a3.exit(()=>this.handleApiRequest(D,U)))}}import{timingSafeEqual as qD}from"crypto";import{isIP as yD}from"net";var u4="",O9="*",vD=60000,gD=1e4,V9=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,p4=16,B9=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,c4="x-forwarded-host";function tG($){return $.startsWith(":")}function d4($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&qD(J,W)}function mD($){if(!$)return null;if($===!0)return{header:c4,clientIpHeader:null,secret:null};return{header:($.hostHeader??c4).toLowerCase(),clientIpHeader:$.clientIpHeader?.toLowerCase()??null,secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function hD($){if(!$||$===!0)return;let{hostHeader:Z,clientIpHeader:J,secret:W}=$;if(Z!==void 0&&(typeof Z!=="string"||!B9.test(Z)))throw Error(`\`route.domains.trustProxy.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(Z)}.`);if(J!==void 0){if(typeof J!=="string"||!B9.test(J))throw Error(`\`route.domains.trustProxy.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(J)}.`);if(!W)throw Error("`route.domains.trustProxy.clientIpHeader` needs `secret`: without proof the proxy sent it, any client that reaches the app directly picks its own address.");if(J.toLowerCase()===(Z??c4).toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `hostHeader`.");if(typeof W.header==="string"&&J.toLowerCase()===W.header.toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `secret.header`.")}if(!W)return;if(typeof W.header!=="string"||!B9.test(W.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${W.header}".`);if(W.header.toLowerCase()===(Z??c4).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof W.value!=="string"||W.value.length<p4)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${p4} characters. A guessable one lets any client name its own host.`)}function U1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function pD($){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 cD($){let Z=U1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>V9.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<p4)throw Error(`\`route.domains.ask.secret\` must be at least ${p4} characters. A guessable one is worse than leaving \`ask\` out.`);hD($.trustProxy);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),tG(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)=>V9.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 D9{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){cD($),this.root=U1($.root),this.hostTrust=mD($.trustProxy);for(let Z of $.groups??[])if(tG(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??vD,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!d4($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.hostTrust;if(!Z?.clientIpHeader||!Z.secret)return null;if(!d4($.headers.get(Z.secret.header),Z.secret.value))return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0]?.trim();return J&&yD(J)?J:null}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return U1(this.forwardedHost($))??U1(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&&U1(Y)?pD(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:O9,params:{},custom:!0};return null}async allows($,Z){let J=U1($);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:u4,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&&V9.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>=gD)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=U1($);if(Z)this.cache.delete(Z)}}}var dD="/__gemi__/domains/ask";class W1{static token="router.domains";resolver;acceptsCustomDomains;groups=new Map;constructor($,Z){this.groups.set(u4,$);let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new D9(J);let W=(Y)=>({api:Y.api?new h4({...Z.api,...Y.api}):$.api,view:Y.view?new h3({...Z.view,...Y.view}):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(O9,W(J.custom.fallback))}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)eG($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return cZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==dD)return null;if(!d4(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??u4)}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 l4($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var $Q=600000;function ZQ($,Z){return[Y6($,Z),Y6($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new c8){J5($.oauthProviders),this.config={...O1(W5($),$),emailCode:y8($.emailCode)},this.provider=Z}async oauthProvider($){return await GZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await L5(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=L().bound(W1)?L(W1).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"?L(W1).resolver?.root:U1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??U1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!f8($))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=l4(J.expiresAt),j=l4(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=N.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/$Q),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=Y6($,j),K=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:K,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of ZQ($,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(f8($)||!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()/$Q),W=ZQ($,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=N.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 L$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=uW(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:Y,userAgent:W??""});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){await this.userProvider.deleteMagicLinkToken($);let J=await this.config.generateMagicLinkToken($),W=await this.config.generateCode($),Y=typeof W==="string"&&W!==""?W:rW(Z);return await this.userProvider.createMagicLinkToken({email:$,token:j6("link",$,J),pin:j6("pin",$,Y)}),{email:$,pin:Y,token:J}}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.userProvider.findMagicLinkTokenByEmail($);if(!j)return eZ("pin",$,null,Z),{status:"invalid"};let z=l4(j.createdAt);if(z+W*60000<=Date.now())return eZ("pin",$,null,Z),{status:"expired"};if(!await $5(j.id,z,Y,W))return await this.userProvider.claimMagicLinkToken(j.id),{status:"too_many_attempts"};if(!eZ("pin",$,j.pin,Z))return{status:"invalid"};if(J.claim!==!1&&!await this.userProvider.claimMagicLinkToken(j.id))return{status:"invalid"};return{status:"ok",row:j}}async verifyMagicLinkToken($,Z){let J=await this.userProvider.findMagicLinkTokenByEmail($),W=eZ("link",$,J?.token,Z);if(!J||!W)return!1;if(l4(J.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(J.id)}}class b0 extends v{static getFacadeAccessor(){return E}static async user(){let $=await b0.userOrNull();if($)return $;throw new L$({redirectTo:r3(N.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=N.getStore();if($?.user)return $.user;let Z=await s3(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=N.getStore()?.req;return j1(Z?.search.get(Y1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await b0.user();if(!await $(Z))throw new WZ}static async guardSafe($){let Z=await b0.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 i4{static ensure($,Z={}){let J=N.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new mZ(v3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=i4.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){i4.ensure($,Z[0])}static noPrefetch(){let $=N.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new mZ(v3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function JQ($,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=uD(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 uD($){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 YQ{static origin($){return WQ($)}static absolute($,...Z){return`${q3()}${B0(String($),Z[0]??{})}`}static relative($,...Z){return B0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=L(W1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=N.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):q3();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return JQ({root:W.root,origin:j},$,B0(String(Z),J[0]??{}))}}class jQ{name="Meta";static description($){N.getStore().metadata.description($)}static title($){N.getStore().metadata.title($)}static openGraph($){N.getStore().metadata.openGraph($)}static htmlAttributes($){N.getStore().metadata.htmlAttributes($)}static canonical($){N.getStore().metadata.canonical($)}static alternates($){N.getStore().metadata.alternates($)}static fonts($){N.getStore().metadata.fonts($)}}var lD={set($,Z,J){N.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(N.getStore().req.cookies.has($))return!1;return N.getStore().setCookie($,Z,J),!0},delete($,Z){N.getStore().deleteCookie($,Z)}};class m1 extends v{static getFacadeAccessor(){return p$}static get client(){return this.getFacadeRoot().client}static get($){return m1.client.get($)}static set($,Z){return m1.client.set($,Z)}static del(...$){return m1.client.del(...$)}static exists($){return m1.client.exists($)}static incr($){return m1.client.incr($)}static expire($,Z){return m1.client.expire($,Z)}static ttl($){return m1.client.ttl($)}}function jx($){return $}function zQ(){return{store:"memory",ttl:null}}class U9{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 iD="500";class L9{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=`${sD(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",iD]),[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 $=L(),Z=$.bound(p$)?$.make(p$).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 sD($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var nD="k:",XQ="tag:",oD="t:";class H9{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 I9 extends H9{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=O1(zQ(),$),this.config.ttl!==null&&this.config.ttl!==void 0)c$(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 QQ(this,Z)}async flush(){await this.store.flush()}async storeKey($){return nD+KQ($)}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=XQ+Z,W=await this.store.get(J);if(W!==null)return W;let Y=GQ();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(XQ+Z,GQ(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:c$(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new U9(this.config.memory);if($==="redis"){let Z=this.options.application;return new L9({...this.config.redis,client:Z?{send:(J,W)=>Z.make(p$).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 QQ extends H9{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){KQ($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${oD}${Z.join(",")}:${$}`}}function KQ($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function GQ(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class FQ extends v{static getFacadeAccessor(){return I9}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 BQ extends v{static getFacadeAccessor(){return z1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class OQ extends v{static getFacadeAccessor(){return VQ}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class UQ extends v{static getFacadeAccessor(){return DQ}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class LQ extends v{static getFacadeAccessor(){return k3}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 wx($){return $}function HQ(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function s4($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function P9($){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:aD}=globalThis.Bun;function rD(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var tD=async($)=>{let Z=new aD($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},eD=async($)=>{let Z;try{Z=(await import("./chunk-b00z33zg.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(()=>{})}},IQ=($)=>rD()?tD($):eD($);var $U=/^[A-Za-z_][A-Za-z0-9_]*$/;class T9{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(!$U.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??IQ}async createTable(){for(let $ of ZU(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 PQ(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
|
|
29
|
-
INSERT INTO ${W} (channel, seq) VALUES (${Z}, 1)
|
|
30
|
-
ON CONFLICT (channel) DO UPDATE SET seq = ${W}.seq + 1
|
|
31
|
-
RETURNING seq
|
|
32
|
-
`,z=Number(j.seq);if(await $`
|
|
33
|
-
INSERT INTO ${Y} (channel, seq, data, created_at)
|
|
34
|
-
VALUES (${Z}, ${z}, ${JSON.stringify(J??null)}, ${Date.now()})
|
|
35
|
-
`,z>this.retain)await $`DELETE FROM ${Y} WHERE channel = ${Z} AND seq <= ${z-this.retain}`;if(this.dialect==="postgres")await $`SELECT pg_notify(${this.notifyChannel}, ${`${z} ${Z}`})`;return z}async heads($){let Z=new Map($.map((Y)=>[Y,0]));if($.length===0)return Z;let J=this.sql,W=await J`
|
|
36
|
-
SELECT channel, seq FROM ${J.unsafe(`"${this.headsTable}"`)}
|
|
37
|
-
WHERE channel IN ${J([...$])}
|
|
38
|
-
`;for(let Y of W)Z.set(Y.channel,Number(Y.seq));return Z}async read($,Z,J){let W=this.sql,[Y]=await W`
|
|
39
|
-
SELECT seq FROM ${W.unsafe(`"${this.headsTable}"`)} WHERE channel = ${$}
|
|
40
|
-
`,j=Y?Number(Y.seq):0;if(Z>j)return{entries:[],head:j,gap:!0};if(Z===j)return{entries:[],head:j,gap:!1};let z=await W`
|
|
41
|
-
SELECT seq, data FROM ${W.unsafe(`"${this.entriesTable}"`)}
|
|
42
|
-
WHERE channel = ${$} AND seq > ${Z}
|
|
43
|
-
ORDER BY seq
|
|
44
|
-
LIMIT ${J}
|
|
45
|
-
`;if(z.length===0||Number(z[0].seq)!==Z+1)return{entries:[],head:j,gap:!0};return{entries:z.map((X)=>({seq:Number(X.seq),data:JSON.parse(X.data)})),head:j,gap:!1}}async listen($,Z){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let J=await this.listener(this.url);try{await J.listen(this.notifyChannel,(W)=>{let Y=W.indexOf(" "),j=Number(W.slice(0,Y));if(Y>0&&Number.isInteger(j))$(W.slice(Y+1),j)},Z)}catch(W){throw await J.close(),W}return{close:()=>J.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let $=i0();if($===void 0||x1()!==this.connection)return;return $}}function ZU($,Z){return[`CREATE TABLE IF NOT EXISTS "${$}" (
|
|
46
|
-
"channel" TEXT NOT NULL PRIMARY KEY,
|
|
47
|
-
"seq" BIGINT NOT NULL
|
|
48
|
-
)`,`CREATE TABLE IF NOT EXISTS "${Z}" (
|
|
49
|
-
"channel" TEXT NOT NULL,
|
|
50
|
-
"seq" BIGINT NOT NULL,
|
|
51
|
-
"data" TEXT NOT NULL,
|
|
52
|
-
"created_at" BIGINT NOT NULL,
|
|
53
|
-
PRIMARY KEY ("channel", "seq")
|
|
54
|
-
)`]}class M9{logs=new Map;retain;constructor($={}){let Z=$.retain??1000;if(!Number.isInteger(Z)||Z<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Z}.`);this.retain=Z}async publish($,Z){let J=this.logs.get($);if(!J)J={head:0,entries:[]},this.logs.set($,J);let W=++J.head;if(J.entries.push({seq:W,data:Z===void 0?null:structuredClone(Z)}),J.entries.length>this.retain)J.entries.splice(0,J.entries.length-this.retain);return W}async heads($){return new Map($.map((Z)=>[Z,this.logs.get(Z)?.head??0]))}async read($,Z,J){let W=this.logs.get($),Y=W?.head??0;if(Z>Y)return{entries:[],head:Y,gap:!0};if(!W||Z===Y)return{entries:[],head:Y,gap:!1};let j=W.entries[0]?.seq??Y+1;if(j>Z+1)return{entries:[],head:Y,gap:!0};let z=Z+1-j;return{entries:W.entries.slice(z,z+J),head:Y,gap:!1}}}var xQ=new TextEncoder;function TQ($,Z){return xQ.encode(`id: ${$}
|
|
55
|
-
data: ${JSON.stringify(Z)}
|
|
56
|
-
|
|
57
|
-
`)}function CQ($,Z,J,W){let Y=Z instanceof Request?Z:Z.rawRequest,j=W.cursor??Y.headers.get("Last-Event-ID")??new URL(Y.url).searchParams.get("cursor"),z;try{z=$.subscribe(J,{cursor:j,signal:Y.signal})}catch(F){if(!(F instanceof n4))throw F;return new Response(JSON.stringify({error:"The change feed is at capacity."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":String(W.retryAfter??5)}})}let X=null,G=!1,Q=!1,K=(F)=>{if(X)clearInterval(X);if(X=null,z.close(),Q)return;Q=!0;try{F.close()}catch{}},B=new ReadableStream({start(F){X=setInterval(()=>{if(_Q())return K(F);try{F.enqueue(xQ.encode(MQ))}catch{K(F)}},$.config.keepaliveInterval)},async pull(F){try{if(!G){if(await z.ready(),G=!0,!Q)F.enqueue(TQ(z.cursor,{type:"ready"}));return}let O=await z.next();if(O.done||Q)return K(F);F.enqueue(TQ(z.cursor,O.value))}catch(O){if(!Q)console.error("[gemi] A change feed stream failed.",O);K(F)}},cancel(){if(Q=!0,X)clearInterval(X);X=null,z.close()}});return new Response(B,{headers:NQ()})}var SQ=255,AQ=500,JU=30000;class n4 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class dZ{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=AQ;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=O1(HQ(),$),this.driver=YU(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){_9($);let J=Z===void 0?null:Z;if(i0()!==void 0&&!this.driver.joinsTransaction?.())return kZ(async()=>{this.wake($,await this.driver.publish($,J))}),null;let W=await this.driver.publish($,J);return kZ(()=>this.wake($,W)),W}async head($){return _9($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=N9($);return s4(await this.driver.heads(Z))}subscribe($,Z={}){let J=N9($);if(this.all.size>=this.config.maxSubscriptions)throw new n4(this.config.maxSubscriptions);let W=new EQ(this,J,WU(Z.cursor),this.config,Z.signal);this.all.add(W);for(let Y of J){let j=this.followers.get(Y);if(!j)this.followers.set(Y,j=new Set);j.add(W)}return this.startListening(),this.startPolling(),W}stream($,Z,J={}){return CQ(this,$,N9(Z),J)}async close(){if(this.listenState="closed",this.retryTimer)clearTimeout(this.retryTimer);this.retryTimer=null,this.stopPolling();for(let Z of this.all)Z.close();let $=this.listening;this.listening=null,await $?.close(),await this.driver.close?.()}forget($){if(!this.all.delete($))return;for(let Z of $.channels){let J=this.followers.get(Z);if(J?.delete($),J?.size===0)this.followers.delete(Z)}if(this.all.size===0)this.stopPolling()}poll(){return this.polling??=(async()=>{try{let $=[...this.followers.keys()];for(let Z=0;Z<$.length;Z+=500){let J=await this.driver.heads($.slice(Z,Z+500));for(let[W,Y]of J)this.wake(W,Y)}}catch($){console.error("[gemi] The change feed could not read its channels' heads.",$)}finally{this.polling=null}})(),this.polling}startPolling(){if(this.pollTimer)return;this.pollTimer=setInterval(()=>void this.poll(),this.config.pollInterval),this.pollTimer.unref?.()}stopPolling(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null}wake($,Z){for(let J of this.followers.get($)??[])J.moved($,Z)}resync(){this.poll()}startListening(){if(this.listenState!=="off"||!this.driver.listen)return;this.connect()}async connect(){this.listenState="connecting",this.retryTimer=null;try{let $=await this.driver.listen((Z,J)=>this.wake(Z,J),()=>this.resync());if(this.listenState!=="connecting"){await $.close();return}this.listening=$,this.listenState="listening",this.backoffMs=AQ,this.resync()}catch($){if(this.listenState!=="connecting")return;console.error(`[gemi] The change feed could not listen for other instances' changes; retrying in ${this.backoffMs}ms.`,$),this.listenState="retrying",this.retryTimer=setTimeout(()=>void this.connect(),this.backoffMs),this.retryTimer.unref?.(),this.backoffMs=Math.min(this.backoffMs*2,JU)}}}class EQ{manager;config;signal;channels;positions=new Map;readTo=new Map;dirty=new Set;pending=[];started=null;wakeUp=null;closed=!1;onAbort=()=>this.close();constructor($,Z,J,W,Y){this.manager=$;this.config=W;this.signal=Y;this.channels=Z;for(let j of Z){let z=J.get(j);if(z!==void 0)this.positions.set(j,z),this.readTo.set(j,z),this.dirty.add(j)}if(Y?.aborted)this.close();else Y?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return s4(this.positions)}get isClosed(){return this.closed}ready(){return this.started??=(async()=>{let $=this.channels.filter((J)=>!this.positions.has(J));if($.length===0)return;let Z=await this.manager.driver.heads($);for(let J of $){let W=Z.get(J)??0;this.positions.set(J,W),this.readTo.set(J,W)}})(),this.started}async next(){await this.ready();for(;;){if(this.closed)return{done:!0,value:void 0};let $=this.pending.shift();if($)return this.positions.set($.channel,$.seq),{done:!1,value:$};let Z=this.dirty.values().next().value;if(Z!==void 0){await this.read(Z);continue}await this.idle()}}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}close(){if(this.closed)return;this.closed=!0,this.pending.length=0,this.signal?.removeEventListener("abort",this.onAbort),this.manager.forget(this),this.wake()}moved($,Z){let J=this.readTo.get($);if(J!==void 0&&Z===J)return;this.dirty.add($),this.wake()}async read($){let Z=this.readTo.get($)??0;this.dirty.delete($);let{batchSize:J}=this.config,{entries:W,head:Y,gap:j}=await this.manager.driver.read($,Z,J);if(this.closed)return;if(j){this.readTo.set($,Y),this.pending.push({type:"reset",channel:$,seq:Y});return}for(let z of W)this.readTo.set($,z.seq),this.pending.push({type:"change",channel:$,seq:z.seq,data:z.data});if(W.length===J)this.dirty.add($)}idle(){return new Promise(($)=>{this.wakeUp=$})}wake(){let $=this.wakeUp;this.wakeUp=null,$?.()}}function _9($){if(typeof $!=="string"||$===""||$.length>SQ)throw Error(`A change feed channel is a string of 1 to ${SQ} characters; got ${JSON.stringify($)}.`)}function N9($){let Z=[...new Set(typeof $==="string"?[$]:$)];if(Z.length===0)throw Error("A change feed subscription needs at least one channel.");for(let J of Z)_9(J);return Z}function WU($){if($===void 0||$===null)return new Map;if(typeof $==="string")return P9($);let Z=$ instanceof Map?[...$]:Object.entries($);return P9(s4(new Map(Z)))}function YU($,Z){if($==="memory")return new M9;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The change feed driver needs the application it belongs to, and this ChangeFeedManager was built without one. Pass { application }.");if($==="database")return new T9(Z.make(C1));return $(Z)}if(typeof $==="string")throw Error(`Unknown change feed driver "${$}". The changeFeed slice's driver is "memory", "database", a ChangeFeedDriver, or a function returning one.`);return $}class fQ extends v{static getFacadeAccessor(){return dZ}static publish($,Z){return this.getFacadeRoot().publish($,Z)}static head($){return this.getFacadeRoot().head($)}static cursor($){return this.getFacadeRoot().cursor($)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}}class p3 extends m0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(m0)?$.make(m0):void 0;if(Z instanceof p3)return Z;let J=new p3($,Z);return $.instance(m0,J),J}constructor($,Z){super({driver:"memory",maxEventBytes:Z?.config.maxEventBytes,warnEventBytes:Z?.config.warnEventBytes},{application:$});this.application=$;this.previous=Z;this.channelsFrom=Z}channelsFrom;get channels(){return this.channelsFrom?.channels??null}publish($){this.sent.push($)}sendRevocation($){this.revoked.push($)}restore(){if(this.previous){this.application.instance(m0,this.previous);return}this.application.forget(m0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${x9($,Z,J)} to have been broadcast. ${this.summary()}`)}assertNotSent($,Z,J){let W=this.matching($,Z,J);if(W.length===0)return;throw Error(`Expected ${x9($,Z,J)} not to have been broadcast, but it was broadcast ${C9(W.length)}: ${S9(W)}.`)}assertSentTimes($,Z,J,W){let Y=this.matching($,J,W);if(Y.length===Z)return;throw Error(`Expected ${x9($,J,W)} to have been broadcast ${C9(Z)}, but it was broadcast ${C9(Y.length)}. `+this.summary())}assertNothingSent(){if(this.sent.length===0)return;throw Error(`Expected nothing to have been broadcast, but ${this.sent.length} ${this.sent.length===1?"emit was":"emits were"}: ${S9(this.sent)}.`)}matching($,Z,J){return t$($),this.sent.filter((W)=>(W.pattern===$||t9($,W.topic))&&(Z===void 0||W.event===Z)&&(J===void 0||J(W.data,W)))}summary(){if(this.sent.length===0)return"Nothing was broadcast.";return`Broadcast: ${S9(this.sent)}.`}}function x9($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function C9($){return`${$} ${$===1?"time":"times"}`}function S9($){return $.map((Z)=>`${Z.topic} ${Z.event}(${jU(Z.data)})`).join(", ")}function jU($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class RQ extends v{static getFacadeAccessor(){return m0}static to($,...Z){return this.getFacadeRoot().to($,...Z)}static toUser($){return this.getFacadeRoot().toUser($)}static toOthers($){return this.getFacadeRoot().toOthers($)}static revoke($){this.getFacadeRoot().revoke($)}static fake(){return p3.install(L())}}function BC($){return $}function bQ(){return{store:"memory",sweepLimit:500}}var A9=["completed","failed","cancelled","timed_out"],L1=["pending","running"];function H1($){return A9.includes($)}class E9{runs=new Map;clock=0;get size(){return this.runs.size}async create($){if(this.runs.has($.id))throw Error(`A run with the id ${$.id} already exists.`);let Z=this.tick(),J={id:$.id,kind:$.kind,subject:$.subject,owner:$.owner,status:$.status,meta:structuredClone($.meta??null),progress:null,result:null,error:null,version:1,createdAt:Z,startedAt:$.status==="running"?Z:null,updatedAt:Z,finishedAt:null,deadlineAt:$.deadlineMs===null?null:Z+$.deadlineMs};return this.runs.set(J.id,J),structuredClone(J)}async get($){let Z=this.runs.get($);return Z?structuredClone(Z):null}async list($){let Z=[];for(let J of this.runs.values()){if($.kind!==void 0&&J.kind!==$.kind)continue;if($.subject!==void 0&&J.subject!==$.subject)continue;if($.owner!==void 0&&J.owner!==$.owner)continue;if($.statuses&&!$.statuses.includes(J.status))continue;Z.push(J)}return Z.reverse().sort((J,W)=>W.createdAt-J.createdAt),Z.slice(0,f9($.limit)).map((J)=>structuredClone(J))}async transition($,Z,J){let W=this.runs.get($);if(!W||!Z.includes(W.status))return null;let Y=structuredClone(J),j=this.tick();if(Y.status!==void 0){if(W.startedAt===null&&Y.status!=="pending")W.startedAt=j;if(H1(Y.status))W.finishedAt=j;W.status=Y.status}if("progress"in Y)W.progress=Y.progress??null;if("result"in Y)W.result=Y.result??null;if("error"in Y)W.error=Y.error??null;return W.version+=1,W.updatedAt=j,structuredClone(W)}async overdue($,Z){let J=[];for(let W of this.runs.values())if(L1.includes(W.status)&&W.deadlineAt!==null&&W.deadlineAt<=$)J.push(W);return J.sort((W,Y)=>W.deadlineAt-Y.deadlineAt),J.slice(0,Math.max(0,Z)).map((W)=>structuredClone(W))}async now(){return this.tick()}async prune($){let Z=this.tick()-$,J=0;for(let[W,Y]of this.runs)if(Y.finishedAt!==null&&Y.finishedAt<=Z)this.runs.delete(W),J++;return J}tick(){return this.clock=Math.max(this.clock,Date.now()),this.clock}}function f9($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class w9{table;sql;dialect;connection;constructor($,Z={}){let J=Z.table??"gemi_runs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The runs table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);this.table=J,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of zU(this.dialect,this.table))await this.sql.unsafe($)}async create($){let Z=this.q(),J=this.clock(Z),W=$.deadlineMs===null?Z`NULL`:Z`${J} + ${this.ms(Z,$.deadlineMs)}`,Y=$.status==="running"?J:Z`NULL`;await Z`
|
|
58
|
-
INSERT INTO ${this.name(Z)}
|
|
59
|
-
(id, kind, subject, owner, status, meta, version,
|
|
60
|
-
created_at, started_at, updated_at, deadline_at)
|
|
61
|
-
VALUES
|
|
62
|
-
(${$.id}, ${$.kind}, ${$.subject}, ${$.owner}, ${$.status},
|
|
63
|
-
${a4($.meta)}, 1, ${J}, ${Y}, ${J}, ${W})
|
|
64
|
-
`;let j=await this.get($.id);if(!j)throw Error(`The run ${$.id} was not found after it was written.`);return j}async get($){let Z=this.q(),J=await Z`SELECT * FROM ${this.name(Z)} WHERE id = ${$}`;return J[0]?b9(J[0]):null}async list($){let Z=this.q(),J=[Z`1 = 1`];if($.kind!==void 0)J.push(Z`kind = ${$.kind}`);if($.subject!==void 0)J.push(Z`subject = ${$.subject}`);if($.owner!==void 0)J.push(Z`owner = ${$.owner}`);if($.statuses!==void 0)J.push($.statuses.length===0?Z`1 = 0`:Z`status IN (${o4(Z,$.statuses)})`);let W=J.reduce((j,z)=>Z`${j} AND ${z}`);return(await Z`
|
|
65
|
-
SELECT * FROM ${this.name(Z)}
|
|
66
|
-
WHERE ${W}
|
|
67
|
-
ORDER BY created_at DESC, id DESC
|
|
68
|
-
LIMIT ${f9($.limit)}
|
|
69
|
-
`).map(b9)}async transition($,Z,J){if(Z.length===0)return null;let W=this.q(),Y=this.clock(W),j=[W`updated_at = ${Y}`,W`version = version + 1`];if(J.status!==void 0){if(j.push(W`status = ${J.status}`),J.status!=="pending")j.push(W`started_at = COALESCE(started_at, ${Y})`);if(H1(J.status))j.push(W`finished_at = ${Y}`)}if("progress"in J)j.push(W`progress = ${a4(J.progress)}`);if("result"in J)j.push(W`result = ${a4(J.result)}`);if("error"in J)j.push(W`error = ${a4(J.error)}`);let z=j.reduce((G,Q)=>W`${G}, ${Q}`),X=await W`
|
|
70
|
-
UPDATE ${this.name(W)} SET ${z}
|
|
71
|
-
WHERE id = ${$} AND status IN (${o4(W,Z)})
|
|
72
|
-
`;if(kQ(X)===0)return null;return this.get($)}async overdue($,Z){let J=this.q();return(await J`
|
|
73
|
-
SELECT * FROM ${this.name(J)}
|
|
74
|
-
WHERE status IN (${o4(J,L1)})
|
|
75
|
-
AND deadline_at IS NOT NULL AND deadline_at <= ${this.ms(J,$)}
|
|
76
|
-
ORDER BY deadline_at, id
|
|
77
|
-
LIMIT ${Math.max(0,Math.floor(Z))}
|
|
78
|
-
`).map(b9)}async now(){let $=this.q(),[Z]=await $`SELECT ${this.clock($)} AS now`;return Number(Z.now)}async prune($){let Z=this.q(),J=await Z`
|
|
79
|
-
DELETE FROM ${this.name(Z)}
|
|
80
|
-
WHERE status IN (${o4(Z,A9)})
|
|
81
|
-
AND finished_at <= ${this.clock(Z)} - ${this.ms(Z,$)}
|
|
82
|
-
`;return kQ(J)}joinable(){if(this.connection===void 0)return;let $=i0();if($===void 0||x1()!==this.connection)return;return $}q(){return this.joinable()??this.sql}name($){let Z=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Z?`\`${this.table}\``:`"${this.table}"`)}clock($){switch(this.dialect){case"postgres":return $`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return $`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return $`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms($,Z){let J=Math.max(0,Math.round(Z));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${J} AS SIGNED)`:$`CAST(${J} AS BIGINT)`}}function o4($,Z){return Z.map((J)=>$`${J}`).reduce((J,W)=>$`${J}, ${W}`)}function a4($){return $===void 0||$===null?null:JSON.stringify($)}function r4($){if($===null||$===void 0)return null;return JSON.parse(String($))}function R9($){return $===null||$===void 0?null:Number($)}function wQ($){return $===null||$===void 0?null:String($)}function b9($){return{id:String($.id),kind:String($.kind),subject:wQ($.subject),owner:wQ($.owner),status:String($.status),meta:r4($.meta),progress:r4($.progress),result:r4($.result),error:r4($.error),version:Number($.version),createdAt:Number($.created_at),startedAt:R9($.started_at),updatedAt:Number($.updated_at),finishedAt:R9($.finished_at),deadlineAt:R9($.deadline_at)}}function kQ($){let Z=$;return Math.max(Number(Z.count??0),Number(Z.affectedRows??0))}function zU($,Z){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
|
|
83
|
-
\`id\` VARCHAR(191) NOT NULL,
|
|
84
|
-
\`kind\` VARCHAR(191) NOT NULL,
|
|
85
|
-
\`subject\` VARCHAR(191) NULL,
|
|
86
|
-
\`owner\` VARCHAR(191) NULL,
|
|
87
|
-
\`status\` VARCHAR(191) NOT NULL,
|
|
88
|
-
\`meta\` LONGTEXT NULL,
|
|
89
|
-
\`progress\` LONGTEXT NULL,
|
|
90
|
-
\`result\` LONGTEXT NULL,
|
|
91
|
-
\`error\` LONGTEXT NULL,
|
|
92
|
-
\`version\` INTEGER NOT NULL DEFAULT 1,
|
|
93
|
-
\`created_at\` BIGINT NOT NULL,
|
|
94
|
-
\`started_at\` BIGINT NULL,
|
|
95
|
-
\`updated_at\` BIGINT NOT NULL,
|
|
96
|
-
\`finished_at\` BIGINT NULL,
|
|
97
|
-
\`deadline_at\` BIGINT NULL,
|
|
98
|
-
|
|
99
|
-
INDEX \`${Z}_subject_created_at_idx\`(\`subject\`, \`created_at\`),
|
|
100
|
-
INDEX \`${Z}_status_deadline_at_idx\`(\`status\`, \`deadline_at\`),
|
|
101
|
-
PRIMARY KEY (\`id\`)
|
|
102
|
-
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let J=$==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',W=$==="sqlite"?"":`,
|
|
103
|
-
|
|
104
|
-
CONSTRAINT "${Z}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${Z}" (
|
|
105
|
-
${J}
|
|
106
|
-
"kind" TEXT NOT NULL,
|
|
107
|
-
"subject" TEXT,
|
|
108
|
-
"owner" TEXT,
|
|
109
|
-
"status" TEXT NOT NULL,
|
|
110
|
-
"meta" TEXT,
|
|
111
|
-
"progress" TEXT,
|
|
112
|
-
"result" TEXT,
|
|
113
|
-
"error" TEXT,
|
|
114
|
-
"version" INTEGER NOT NULL DEFAULT 1,
|
|
115
|
-
"created_at" BIGINT NOT NULL,
|
|
116
|
-
"started_at" BIGINT,
|
|
117
|
-
"updated_at" BIGINT NOT NULL,
|
|
118
|
-
"finished_at" BIGINT,
|
|
119
|
-
"deadline_at" BIGINT${W}
|
|
120
|
-
)`,`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 qQ=191,yQ=30000;class t4 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class e4 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 k9{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=O1(bQ(),$),this.store=QU(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(dZ);return this.ownFeed??=new dZ,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){mQ("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;mQ("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:c$($.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 GU(Z),this.change($,L1,{status:"running",progress:Z})}complete($,Z){return this.change($,L1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,L1,{status:"failed",error:gQ(Z)})}cancel($,Z){return this.change($,L1,{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 t4($);if(H1(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 e4)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,L1,{status:"failed",error:G instanceof e4?gQ(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()+c$(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new t4($);let z=null;for(;;){if(H1(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 vQ(z,Math.min(G,X??1/0,yQ),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 t4($);if(yield W,H1(W.status))return;for await(let Y of J){let j=XU(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,H1(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=c$($);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||H1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,L1,{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(H1(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,vQ(j,Math.min(z??1/0,yQ))]);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 vQ($,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 XU($,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 gQ($){if(typeof $==="string")return{message:$};if($ instanceof e4)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function mQ($,Z){if(typeof Z!=="string"||Z===""||Z.length>qQ)throw TypeError(`A run's ${$} is a string of 1 to ${qQ} characters; got ${JSON.stringify(Z)}.`)}function GU($){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 QU($,Z){if($==="memory")return new E9;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(C1).connection();return new w9(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 hQ extends v{static getFacadeAccessor(){return k9}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 pQ extends v{static getFacadeAccessor(){return s1}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 $8{bound;constructor($){this.bound=$}get name(){return this.bound??x1()}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 uQ(J.sql,(W)=>cQ(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-dxm5gxqk.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=iQ($,lQ(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=i0();if($===void 0)return;return x1()===this.name?$:void 0}connection($=this.name){return dQ($),L(C1).connection($)}}var uZ=new $8;class sQ extends v{static getFacadeAccessor(){return C1}static connection($){return new $8($)}static get sql(){return uZ.sql}static get dialect(){return uZ.dialect}static query($){return uZ.query($)}static execute($){return uZ.execute($)}static transaction($){return uZ.transaction($)}static schema(){return uZ.schema()}static close(){return this.getFacadeRoot().close()}}export{l0 as Od,sZ as Pd,j8 as Qd,r$ as Rd,oZ as Sd,R0 as Td,s3 as Ud,E8 as Vd,f8 as Wd,uW as Xd,i1 as Yd,z1 as Zd,r as _d,MW as $d,JZ as ae,lW as be,iW as ce,b8 as de,w8 as ee,j6 as fe,eZ as ge,UF as he,_I as ie,W5 as je,K5 as ke,g8 as le,F5 as me,B5 as ne,_F as oe,V5 as pe,m8 as qe,SF as re,AF as se,h8 as te,O5 as ue,D5 as ve,s1 as we,U5 as xe,bF as ye,c8 as ze,L8 as Ae,t3 as Be,M1 as Ce,U$ as De,MK as Ee,D8 as Fe,N1 as Ge,V$ as He,i4 as Ie,YQ as Je,jQ as Ke,lD as Le,m1 as Me,jx as Ne,zQ as Oe,U9 as Pe,L9 as Qe,I9 as Re,QQ as Se,FQ as Te,BQ as Ue,OQ as Ve,UQ as We,LQ as Xe,wx as Ye,HQ as Ze,s4 as _e,P9 as $e,T9 as af,M9 as bf,n4 as cf,dZ as df,EQ as ef,fQ as ff,p as gf,aZ as hf,N4 as if,GP as jf,QP as kf,KP as lf,OP as mf,MX as nf,O7 as of,xX as pf,IP as qf,AX as rf,m0 as sf,R3 as tf,EX as uf,RQ as vf,BC as wf,A9 as xf,L1 as yf,H1 as zf,E9 as Af,w9 as Bf,zU as Cf,t4 as Df,e4 as Ef,k9 as Ff,hQ as Gf,pQ as Hf,$8 as If,sQ as Jf,U7 as Kf,EO as Lf,C7 as Mf,S7 as Nf,ET as Of,sX as Pf,nX as Qf,n3 as Rf,c1 as Sf,mT as Tf,aX as Uf,rX as Vf,a7 as Wf,hZ as Xf,r7 as Yf,hM as Zf,nM as _f,oM as $f,K9 as ag,CD as bg,G9 as cg,ED as dg,h3 as eg,F9 as fg,sG as gg,nG as hg,h4 as ig,W1 as jg,E as kg,b0 as lg,o3 as mg,WW as ng,UK as og,$W as pg,jW as qg,F8 as rg,B8 as sg,V8 as tg,zW as ug,NK as vg,_K as wg,VW as xg,DW as yg,LW as zg,_W as Ag,xW as Bg,CW as Cg,P8 as Dg,fK as Eg,j0 as Fg,vW as Gg,jZ as Hg,cW as Ig};
|
|
121
|
-
|
|
122
|
-
//# debugId=4113CAFC7D18321F64756E2164756E21
|