gemi 0.244.0 → 0.245.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/ai/testing/index.js +2 -2
- package/dist/ai/testing/index.js.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-t77xnb8k.js → chunk-11fc5nve.js} +3 -3
- package/dist/{chunk-t77xnb8k.js.map → chunk-11fc5nve.js.map} +1 -1
- package/dist/{chunk-7mxwstm2.js → chunk-1gptecxr.js} +2 -2
- package/dist/{chunk-7mxwstm2.js.map → chunk-1gptecxr.js.map} +1 -1
- package/dist/{chunk-n537kc55.js → chunk-1v7qcmr7.js} +2 -2
- package/dist/{chunk-n537kc55.js.map → chunk-1v7qcmr7.js.map} +1 -1
- package/dist/{chunk-632nqkza.js → chunk-2kt5kgaq.js} +2 -2
- package/dist/{chunk-632nqkza.js.map → chunk-2kt5kgaq.js.map} +1 -1
- package/dist/{chunk-s0azv6dd.js → chunk-31fgprsv.js} +2 -2
- package/dist/{chunk-s0azv6dd.js.map → chunk-31fgprsv.js.map} +1 -1
- package/dist/{chunk-wac3gv1t.js → chunk-3n7rmrd1.js} +2 -2
- package/dist/{chunk-wac3gv1t.js.map → chunk-3n7rmrd1.js.map} +1 -1
- package/dist/{chunk-vqtzwnwr.js → chunk-4md5qxe1.js} +2 -2
- package/dist/{chunk-vqtzwnwr.js.map → chunk-4md5qxe1.js.map} +1 -1
- package/dist/{chunk-tws22txn.js → chunk-5961jw1h.js} +2 -2
- package/dist/{chunk-7ztbpqed.js.map → chunk-5961jw1h.js.map} +1 -1
- package/dist/{chunk-65m459jb.js → chunk-5npzvdh9.js} +2 -2
- package/dist/{chunk-65m459jb.js.map → chunk-5npzvdh9.js.map} +1 -1
- package/dist/{chunk-4y0j6c56.js → chunk-71ap56wq.js} +4 -4
- package/dist/{chunk-4y0j6c56.js.map → chunk-71ap56wq.js.map} +1 -1
- package/dist/{chunk-7ztbpqed.js → chunk-748evey0.js} +2 -2
- package/dist/{chunk-tws22txn.js.map → chunk-748evey0.js.map} +1 -1
- package/dist/{chunk-bbhrs7s3.js → chunk-7gf0hjth.js} +2 -2
- package/dist/{chunk-bbhrs7s3.js.map → chunk-7gf0hjth.js.map} +1 -1
- package/dist/{chunk-xvnjahea.js → chunk-7jpfvs5v.js} +2 -2
- package/dist/{chunk-xvnjahea.js.map → chunk-7jpfvs5v.js.map} +1 -1
- package/dist/chunk-8fb7gey2.js +5 -0
- package/dist/{chunk-8dga75cv.js.map → chunk-8fb7gey2.js.map} +1 -1
- package/dist/{chunk-e0e43wvq.js → chunk-8vzxnjp4.js} +2 -2
- package/dist/{chunk-e0e43wvq.js.map → chunk-8vzxnjp4.js.map} +1 -1
- package/dist/{chunk-p03jdwc1.js → chunk-akvv3mvx.js} +2 -2
- package/dist/{chunk-p03jdwc1.js.map → chunk-akvv3mvx.js.map} +1 -1
- package/dist/{chunk-dfat5nmk.js → chunk-b0hjrnn6.js} +3 -3
- package/dist/{chunk-dfat5nmk.js.map → chunk-b0hjrnn6.js.map} +1 -1
- package/dist/{chunk-sew755q5.js → chunk-b1dxjd33.js} +1 -1
- package/dist/{chunk-e4a6smfv.js → chunk-b1gt8s41.js} +1 -1
- package/dist/{chunk-3tpj5t10.js → chunk-b5g6ch5p.js} +2 -2
- package/dist/{chunk-3tpj5t10.js.map → chunk-b5g6ch5p.js.map} +1 -1
- package/dist/{chunk-ed64ynex.js → chunk-ba2yfwv1.js} +2 -2
- package/dist/{chunk-ed64ynex.js.map → chunk-ba2yfwv1.js.map} +1 -1
- package/dist/{chunk-ac135mmf.js → chunk-bcpxyv8m.js} +2 -2
- package/dist/{chunk-ac135mmf.js.map → chunk-bcpxyv8m.js.map} +1 -1
- package/dist/{chunk-h6dzn5j6.js → chunk-be0r4rgs.js} +2 -2
- package/dist/{chunk-h6dzn5j6.js.map → chunk-be0r4rgs.js.map} +1 -1
- package/dist/{chunk-57n0m9fv.js → chunk-bv76ypa6.js} +2 -2
- package/dist/{chunk-57n0m9fv.js.map → chunk-bv76ypa6.js.map} +1 -1
- package/dist/{chunk-9xm5z33t.js → chunk-c2cdf01r.js} +2 -2
- package/dist/{chunk-9xm5z33t.js.map → chunk-c2cdf01r.js.map} +1 -1
- package/dist/{chunk-26pfh03x.js → chunk-cyxsmd4q.js} +3 -3
- package/dist/{chunk-26pfh03x.js.map → chunk-cyxsmd4q.js.map} +1 -1
- package/dist/{chunk-5pfbqc1c.js → chunk-d8ekdvsw.js} +2 -2
- package/dist/{chunk-5pfbqc1c.js.map → chunk-d8ekdvsw.js.map} +1 -1
- package/dist/{chunk-093j5rh8.js → chunk-dapd4vkd.js} +3 -3
- package/dist/{chunk-093j5rh8.js.map → chunk-dapd4vkd.js.map} +1 -1
- package/dist/{chunk-gqw25apr.js → chunk-dx4h7rap.js} +2 -2
- package/dist/{chunk-gqw25apr.js.map → chunk-dx4h7rap.js.map} +1 -1
- package/dist/{chunk-fwmzms6e.js → chunk-e71g3wf3.js} +2 -2
- package/dist/{chunk-fwmzms6e.js.map → chunk-e71g3wf3.js.map} +1 -1
- package/dist/{chunk-7c48nxqb.js → chunk-exw8wa9c.js} +3 -3
- package/dist/{chunk-7c48nxqb.js.map → chunk-exw8wa9c.js.map} +1 -1
- package/dist/{chunk-fs2cdxry.js → chunk-fe7f6jbc.js} +2 -2
- package/dist/{chunk-fs2cdxry.js.map → chunk-fe7f6jbc.js.map} +1 -1
- package/dist/{chunk-fb3qkmwh.js → chunk-fesg4q4p.js} +2 -2
- package/dist/{chunk-fb3qkmwh.js.map → chunk-fesg4q4p.js.map} +1 -1
- package/dist/{chunk-0jmh2271.js → chunk-ffb2mytk.js} +2 -2
- package/dist/{chunk-0jmh2271.js.map → chunk-ffb2mytk.js.map} +1 -1
- package/dist/{chunk-t67dbfqs.js → chunk-fgmd1hn7.js} +3 -3
- package/dist/{chunk-t67dbfqs.js.map → chunk-fgmd1hn7.js.map} +1 -1
- package/dist/{chunk-kjz6jh54.js → chunk-gm14dthh.js} +3 -3
- package/dist/{chunk-kjz6jh54.js.map → chunk-gm14dthh.js.map} +1 -1
- package/dist/{chunk-d39h1mrz.js → chunk-gmkzq212.js} +3 -3
- package/dist/{chunk-d39h1mrz.js.map → chunk-gmkzq212.js.map} +1 -1
- package/dist/{chunk-54v3y7mg.js → chunk-gx5yhz2m.js} +3 -3
- package/dist/{chunk-54v3y7mg.js.map → chunk-gx5yhz2m.js.map} +1 -1
- package/dist/{chunk-ge5m9qdt.js → chunk-h02cqzar.js} +2 -2
- package/dist/{chunk-ge5m9qdt.js.map → chunk-h02cqzar.js.map} +1 -1
- package/dist/{chunk-hvw25pe3.js → chunk-h2ar54x8.js} +1 -1
- package/dist/{chunk-kejexfsg.js → chunk-h6yse9wf.js} +2 -2
- package/dist/{chunk-kejexfsg.js.map → chunk-h6yse9wf.js.map} +1 -1
- package/dist/{chunk-n8cm2sw6.js → chunk-hh3m9be7.js} +2 -2
- package/dist/{chunk-n8cm2sw6.js.map → chunk-hh3m9be7.js.map} +1 -1
- package/dist/{chunk-11hmhyk5.js → chunk-hhka8j31.js} +3 -3
- package/dist/{chunk-11hmhyk5.js.map → chunk-hhka8j31.js.map} +1 -1
- package/dist/{chunk-xy5evkaz.js → chunk-hmdpf21x.js} +1 -1
- package/dist/{chunk-ss0gk90s.js → chunk-jv7n3p61.js} +2 -2
- package/dist/{chunk-ss0gk90s.js.map → chunk-jv7n3p61.js.map} +1 -1
- package/dist/{chunk-2yvzc5tq.js → chunk-jzg9zdtj.js} +2 -2
- package/dist/{chunk-2yvzc5tq.js.map → chunk-jzg9zdtj.js.map} +1 -1
- package/dist/{chunk-zpnxr23b.js → chunk-k5vt2kz6.js} +2 -2
- package/dist/{chunk-zpnxr23b.js.map → chunk-k5vt2kz6.js.map} +1 -1
- package/dist/{chunk-yqsnrp2b.js → chunk-kck2q09f.js} +2 -2
- package/dist/{chunk-yqsnrp2b.js.map → chunk-kck2q09f.js.map} +1 -1
- package/dist/{chunk-9cxs1q57.js → chunk-ket76475.js} +2 -2
- package/dist/{chunk-9cxs1q57.js.map → chunk-ket76475.js.map} +1 -1
- package/dist/{chunk-2mtm1yt6.js → chunk-kjtx99jj.js} +2 -2
- package/dist/{chunk-2mtm1yt6.js.map → chunk-kjtx99jj.js.map} +1 -1
- package/dist/{chunk-ye1kbxkx.js → chunk-kjzvrx2p.js} +3 -3
- package/dist/{chunk-ye1kbxkx.js.map → chunk-kjzvrx2p.js.map} +1 -1
- package/dist/{chunk-v3ddktnq.js → chunk-kss2kkmm.js} +3 -3
- package/dist/{chunk-v3ddktnq.js.map → chunk-kss2kkmm.js.map} +1 -1
- package/dist/{chunk-jr53em8y.js → chunk-mbfjxyq0.js} +2 -2
- package/dist/{chunk-jr53em8y.js.map → chunk-mbfjxyq0.js.map} +1 -1
- package/dist/{chunk-w9v8bbp8.js → chunk-mc7p37d0.js} +2 -2
- package/dist/{chunk-w9v8bbp8.js.map → chunk-mc7p37d0.js.map} +1 -1
- package/dist/{chunk-rffa9x3d.js → chunk-n26d4z3t.js} +2 -2
- package/dist/{chunk-rffa9x3d.js.map → chunk-n26d4z3t.js.map} +1 -1
- package/dist/{chunk-646bqwp8.js → chunk-n8kke112.js} +2 -2
- package/dist/{chunk-646bqwp8.js.map → chunk-n8kke112.js.map} +1 -1
- package/dist/{chunk-vh6vc4h1.js → chunk-nbdjbde4.js} +3 -3
- package/dist/{chunk-vh6vc4h1.js.map → chunk-nbdjbde4.js.map} +1 -1
- package/dist/{chunk-fy4142fv.js → chunk-ptm1d4vp.js} +2 -2
- package/dist/{chunk-fy4142fv.js.map → chunk-ptm1d4vp.js.map} +1 -1
- package/dist/chunk-q0k1j5a4.js +10 -0
- package/dist/{chunk-q94v5skw.js.map → chunk-q0k1j5a4.js.map} +4 -6
- package/dist/{chunk-t4eeg7j1.js → chunk-qbm49b1t.js} +3 -3
- package/dist/{chunk-t4eeg7j1.js.map → chunk-qbm49b1t.js.map} +1 -1
- package/dist/{chunk-eb4mx34p.js → chunk-r9266nax.js} +3 -3
- package/dist/{chunk-eb4mx34p.js.map → chunk-r9266nax.js.map} +1 -1
- package/dist/{chunk-e3m0anq1.js → chunk-rqknf5k0.js} +3 -3
- package/dist/{chunk-e3m0anq1.js.map → chunk-rqknf5k0.js.map} +1 -1
- package/dist/{chunk-4f8qpzsw.js → chunk-rtmz9yvj.js} +1 -1
- package/dist/{chunk-bsmy8vqs.js → chunk-rxtec0qr.js} +2 -2
- package/dist/{chunk-bsmy8vqs.js.map → chunk-rxtec0qr.js.map} +1 -1
- package/dist/{chunk-7qt9pxm6.js → chunk-s4xekxsk.js} +1 -1
- package/dist/{chunk-sp79baph.js → chunk-se0tnb9x.js} +2 -2
- package/dist/{chunk-sp79baph.js.map → chunk-se0tnb9x.js.map} +1 -1
- package/dist/chunk-t56z2zec.js +88 -0
- package/dist/{chunk-v040m0k2.js.map → chunk-t56z2zec.js.map} +15 -12
- package/dist/{chunk-fjh3xaq7.js → chunk-thdhm39v.js} +2 -2
- package/dist/{chunk-fjh3xaq7.js.map → chunk-thdhm39v.js.map} +1 -1
- package/dist/{chunk-zrqqnfrs.js → chunk-vg0yj29r.js} +2 -2
- package/dist/{chunk-zrqqnfrs.js.map → chunk-vg0yj29r.js.map} +1 -1
- package/dist/{chunk-110ecy3e.js → chunk-vq0gcvcy.js} +2 -2
- package/dist/{chunk-110ecy3e.js.map → chunk-vq0gcvcy.js.map} +1 -1
- package/dist/{chunk-3ywtqcxt.js → chunk-w31afsrx.js} +2 -2
- package/dist/{chunk-3ywtqcxt.js.map → chunk-w31afsrx.js.map} +1 -1
- package/dist/{chunk-27f9z8yk.js → chunk-wr7xq82n.js} +3 -3
- package/dist/{chunk-27f9z8yk.js.map → chunk-wr7xq82n.js.map} +1 -1
- package/dist/{chunk-2g6cmkrn.js → chunk-xac2vwtq.js} +3 -3
- package/dist/{chunk-2g6cmkrn.js.map → chunk-xac2vwtq.js.map} +1 -1
- package/dist/{chunk-mjfnv2r9.js → chunk-y1qmedgq.js} +2 -2
- package/dist/{chunk-mjfnv2r9.js.map → chunk-y1qmedgq.js.map} +1 -1
- package/dist/{chunk-mbstaydx.js → chunk-z0nx5nkb.js} +2 -2
- package/dist/{chunk-mbstaydx.js.map → chunk-z0nx5nkb.js.map} +1 -1
- package/dist/{chunk-c0hxmw3a.js → chunk-z5ha9z3m.js} +2 -2
- package/dist/{chunk-c0hxmw3a.js.map → chunk-z5ha9z3m.js.map} +1 -1
- package/dist/{chunk-yrna0ajq.js → chunk-z5wwhgsg.js} +3 -3
- package/dist/{chunk-yrna0ajq.js.map → chunk-z5wwhgsg.js.map} +1 -1
- package/dist/{chunk-0tsnmrf9.js → chunk-zc42brkr.js} +2 -2
- package/dist/{chunk-0tsnmrf9.js.map → chunk-zc42brkr.js.map} +1 -1
- package/dist/{chunk-hhaxacwh.js → chunk-zez3fjnf.js} +2 -2
- package/dist/{chunk-hhaxacwh.js.map → chunk-zez3fjnf.js.map} +1 -1
- package/dist/{chunk-rwyn40p1.js → chunk-ztg4pgqe.js} +2 -2
- package/dist/{chunk-rwyn40p1.js.map → chunk-ztg4pgqe.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 +11 -0
- package/dist/http/ApiRouter.d.ts.map +1 -1
- package/dist/http/McpEndpoint.d.ts +228 -0
- package/dist/http/McpEndpoint.d.ts.map +1 -0
- package/dist/http/RateLimitMiddleware.d.ts +7 -0
- package/dist/http/RateLimitMiddleware.d.ts.map +1 -1
- package/dist/http/index.d.ts +1 -0
- package/dist/http/index.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/mcp/http/McpHttpServer.d.ts +0 -1
- package/dist/services/mcp/http/McpHttpServer.d.ts.map +1 -1
- package/dist/services/mcp/http/protocol.d.ts +6 -0
- package/dist/services/mcp/http/protocol.d.ts.map +1 -1
- package/dist/services/middleware/MiddlewareRegistry.d.ts +12 -0
- package/dist/services/middleware/MiddlewareRegistry.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/DomainResolver.d.ts +22 -5
- package/dist/services/router/DomainResolver.d.ts.map +1 -1
- package/dist/services/router/DomainRouter.d.ts +1 -1
- package/dist/services/router/DomainRouter.d.ts.map +1 -1
- package/dist/services/router/config.d.ts +42 -4
- package/dist/services/router/config.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/stats/route-table.js.map +1 -1
- package/dist/stats/routeTable.d.ts +1 -1
- package/dist/stats/routeTable.d.ts.map +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-8dga75cv.js +0 -5
- package/dist/chunk-q94v5skw.js +0 -10
- package/dist/chunk-v040m0k2.js +0 -88
- /package/dist/{chunk-sew755q5.js.map → chunk-b1dxjd33.js.map} +0 -0
- /package/dist/{chunk-e4a6smfv.js.map → chunk-b1gt8s41.js.map} +0 -0
- /package/dist/{chunk-hvw25pe3.js.map → chunk-h2ar54x8.js.map} +0 -0
- /package/dist/{chunk-xy5evkaz.js.map → chunk-hmdpf21x.js.map} +0 -0
- /package/dist/{chunk-4f8qpzsw.js.map → chunk-rtmz9yvj.js.map} +0 -0
- /package/dist/{chunk-7qt9pxm6.js.map → chunk-s4xekxsk.js.map} +0 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{pi as sF}from"./chunk-kjzvrx2p.js";import{Ji as iF}from"./chunk-gmkzq212.js";import{$i as V8,Bj as x6,Hj as A6,Ki as H3,Oi as ZF,Pi as PY,Pj as v1,Qi as NY,Ri as v8,Si as R8,Tj as OZ,Vi as k8,Wi as w8,Xi as tB,Yi as e9,_i as z3,aj as D2,bj as l2,cj as u,ej as g8,fj as f$,gj as jY,hj as i2,ij as s2,jj as U6,kj as S,lj as q9,mj as j5,nj as NZ,oj as y8,pj as C6,rj as g$,sj as j8}from"./chunk-dapd4vkd.js";import{Vj as Z$,Wj as y0,Xj as Y$,Yj as hY}from"./chunk-2kt5kgaq.js";import{bk as h,ek as CQ,fk as DZ}from"./chunk-gx5yhz2m.js";import{gk as QZ,hk as L2,lk as bJ,mk as U8,nk as P}from"./chunk-vq0gcvcy.js";import{qk as DQ,tk as $6}from"./chunk-cyxsmd4q.js";import{Ak as xF,xk as pJ}from"./chunk-qbm49b1t.js";import{Sk as q$,Xk as W$}from"./chunk-k5vt2kz6.js";import{jl as oG}from"./chunk-8vzxnjp4.js";import{kl as LZ,nl as IF,zl as z6}from"./chunk-z5wwhgsg.js";import{Bl as N$}from"./chunk-mbfjxyq0.js";import{Cl as L6,Dl as c$,El as d$,Fl as x8,Gl as pF,Il as aW,Jl as cF,Tl as A8,Vl as dF,Wl as uF,Xl as lF}from"./chunk-kss2kkmm.js";import{nm as u$}from"./chunk-n26d4z3t.js";import{sm as Z2,xm as W2}from"./chunk-5npzvdh9.js";import{Em as $2,Jm as l}from"./chunk-zez3fjnf.js";import{Km as j3,Nm as H}from"./chunk-xac2vwtq.js";import{Vm as s9}from"./chunk-dx4h7rap.js";import{in as p9}from"./chunk-ket76475.js";import{jn as O8,ln as WF}from"./chunk-jzg9zdtj.js";import{qn as J2}from"./chunk-748evey0.js";function V3($){return typeof $==="function"&&$.prototype!==void 0}var f2=Symbol.for("gemi.HttpResponse"),$V=new Set([301,302,303,307,308]);class L1{kind;body;status;headers;[f2]=!0;constructor($,Z,W,Y){this.kind=$;this.body=Z;this.status=W;this.headers=Y}static json($,Z={}){let W=Z.status??200;return w2(W,"json"),new L1("json",$,W,new Headers(Z.headers))}static error($,Z,W={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return L1.json({error:Z},{...W,status:$})}static redirect($,Z={}){let W=Z.status??303;if(!$V.has(W))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${W}.`);let Y=String($);if(Y==="")throw TypeError("HttpResponse.redirect: url is empty.");let J=new Headers(Z.headers);return J.set("Location",Y),new L1("empty",void 0,W,J)}static noContent($={}){return new L1("empty",null,204,new Headers($.headers))}static text($,Z={}){let W=Z.status??200;return w2(W,"text"),new L1("text",$,W,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let W=$,Y=this.serialize(W);for(let J of Z)W.append("Set-Cookie",J);this.headers.forEach((J,j)=>{if(j.toLowerCase()!=="set-cookie")W.set(j,J)});for(let J of this.headers.getSetCookie())W.append("Set-Cookie",J);if(this.status>=400&&!this.headers.has("Cache-Control"))W.set("Cache-Control","no-store");return new Response(Y,{status:this.status,headers:W})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function w2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function r1($){return typeof $==="object"&&$!==null&&$[f2]===!0}function ZV($,Z,W={}){return L1.error($,Z,W)}function v0($){return typeof $==="string"?[$]:$}function F6($,Z){let W=$.split(/[\\/]/).pop()??"",Y=Z?"attachment":"inline",J=W.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${Y}; filename="${J}"; filename*=UTF-8''${encodeURIComponent(W)}`}function WV($){return"total"in $&&"partial"in $&&"body"in $}function q2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function U3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":w8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function YV($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(WV($))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,W=Z instanceof Blob?Z:null,Y=$.total??W?.size??-1;return{body:Z,start:$.start??0,end:$.end??Y-1,total:Y,partial:$.partial??!1,type:$.type??W?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function f8($,Z){if($ instanceof Response)return $;if(!$)return q2();let W=await YV($),{body:Y,start:J,end:j,total:z,partial:X}=W;if(!X&&Y instanceof Blob&&"exists"in Y&&typeof Y.exists==="function"){if(!await Y.exists())return q2()}let{range:G}=Z;if(G){if(z<=0)return U3(Math.max(z,0));if(!X){if(Y instanceof Blob){let B=R8(G,z);if(!B)return U3(z);Y=Y.slice(B.start,B.end+1),J=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,F=Q?206:W.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",W.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),Q)V.set("Content-Range",k8(J,j,z)),V.set("Content-Length",String(j-J+1));else if(z>=0)V.set("Content-Length",String(z));if(W.name)V.set("Content-Disposition",F6(W.name,W.download));if(W.etag)V.set("ETag",W.etag);if(W.lastModified)V.set("Last-Modified",W.lastModified.toUTCString());for(let[B,U]of Object.entries(W.extraHeaders))V.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(Y&&"cancel"in Y&&typeof Y.cancel==="function")await Y.cancel();return new Response(null,{status:F,headers:V})}return new Response(Y,{status:F,headers:V})}var JV=["content-type"];var v2=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function jV($){try{let Z=new URL($);return Z.origin!=="null"&&Z.origin===$}catch{return!1}}function D3($,Z){let W=(J)=>{throw Error(`CORS policy on ${Z}: ${J}`)};if($===null||typeof $!=="object")W('expected an object such as { origins: "*" } or `false`.');let Y=$.origins==="*"?"*":typeof $.origins==="string"?[$.origins]:$.origins;if(Y!=="*"){if(!Array.isArray(Y)||Y.length===0)W('`origins` must be "*", an origin or a non-empty list of origins.');for(let J of Y){if(J==="*")W('"*" goes on its own (`origins: "*"`), not in a list.');if(J!=="null"&&!jV(J))W(`"${J}" is not an origin. Write scheme, host and port only, e.g. "https://shop.example".`)}}if($.credentials){if(Y==="*")W("`credentials: true` needs a list of exact origins: browsers refuse credentials with `*`, and echoing any origin with credentials lets every site read the answer as the user.");if(Y.includes("null"))W('`credentials: true` cannot admit "null": any site can send `Origin: null` (a sandboxed frame), so credentials for it are credentials for everyone. Authenticate such callers with a token instead.')}for(let J of $.methods??[])if(!v2.test(J))W(`"${J}" is not a method.`);for(let J of[...$.headers??[],...$.exposeHeaders??[]])if(!v2.test(J))W(`"${J}" is not a header name.`);if($.maxAge!==void 0&&!(Number.isInteger($.maxAge)&&$.maxAge>=0))W("`maxAge` must be a whole number of seconds.");return{...$,origins:Y}}function y2($,Z){return $.origins==="*"||$.origins.includes(Z)}function zV($,Z){return $.credentials===!0&&$.origins!=="*"&&Z!=="null"}function m2($,Z,W){if($.set("Access-Control-Allow-Origin",Z.origins==="*"?"*":W),zV(Z,W))$.set("Access-Control-Allow-Credentials","true");else $.delete("Access-Control-Allow-Credentials")}function h2($,Z){let W=($.get("Vary")??"").split(",").map((J)=>J.trim()).filter(Boolean);if(W.includes("*"))return;let Y=W.map((J)=>J.toLowerCase());for(let J of Z)if(!Y.includes(J.toLowerCase()))W.push(J);$.set("Vary",W.join(", "))}function g2($,Z,W){if(Z.origins!=="*")h2($,["Origin"]);if(!W||!y2(Z,W))return;if(m2($,Z,W),Z.exposeHeaders?.length)$.set("Access-Control-Expose-Headers",Z.exposeHeaders.join(", "))}function p2($,Z,W){let Y=W.headers.get("Origin");try{return g2($.headers,Z,Y),$}catch{let J=new Headers($.headers);return g2(J,Z,Y),new Response($.body,{status:$.status,statusText:$.statusText,headers:J})}}function c2($){return $.method==="OPTIONS"&&$.headers.has("Access-Control-Request-Method")}function d2($,Z){let W=new Headers,Y=$.headers.get("Origin"),J=$.headers.get("Access-Control-Request-Method").trim().toUpperCase(),j=Z[J];if(h2(W,["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]),!j||!Y||!y2(j,Y))return new Response(null,{status:204,headers:W});let z=Object.keys(Z).filter((F)=>Z[F]===j),X=j.methods?j.methods.map((F)=>F.toUpperCase()).filter((F)=>z.includes(F)):z;if(!X.includes(J))return new Response(null,{status:204,headers:W});let G=(j.headers??JV).map((F)=>F.toLowerCase());if(($.headers.get("Access-Control-Request-Headers")??"").split(",").map((F)=>F.trim().toLowerCase()).filter(Boolean).some((F)=>!G.includes(F)))return new Response(null,{status:204,headers:W});if(m2(W,j,Y),W.set("Access-Control-Allow-Methods",X.join(", ")),G.length)W.set("Access-Control-Allow-Headers",G.join(", "));return W.set("Access-Control-Max-Age",String(j.maxAge??600)),new Response(null,{status:204,headers:W})}function XV($){return V3($)}function u2($,Z){if($.length===0)return $();return $(Z??new S)}class d{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];__internal_bodyLimitDefault;constructor($,Z,W){this.method=$;this.handler=Z;this.methodName=W;this.handler=Z,this.methodName=W,this.method=$}get source(){if(!XV(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return u2(Z[this.methodName].bind(Z),$)}return u2(this.handler,$)}middleware($){return this.middlewares=v0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:D3($,`a ${this.method} route`),this}}class n2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=v0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:D3($,"a proxy route"),this}async run(){let $=new S,Z=$.headers.toJSON();for(let W of l2($.rawRequest))delete Z[W];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(W){if(s2($.rawRequest))throw new g8(i2($.rawRequest));throw W}}}class o2{constructor(...$){return new d(...$)}}class a2 extends d{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),W=Z?.req?.rawRequest,Y=v8(W?.headers.get("Range"));if(Z)Z.rangeRequest=Y;try{let J=await super.run($);if(r1(J))return J;return await f8(J,{range:Y,method:W?.method})}catch(J){if(J instanceof y8)return U3(J.total);throw J}finally{if(Z)Z.rangeRequest=null}}}class t2{constructor(...$){return new a2(...$)}}class r2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new d("GET",$,"list"),post:new d("POST",$,"store")},this.second={get:new d("GET",$,"show"),put:new d("PUT",$,"update"),delete:new d("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 A0{static __brand="ApiRouter";routes={};middlewares=[];cors;middleware($){}get($,Z){return new d("GET",$,Z)}post($,Z){return new d("POST",$,Z)}put($,Z){return new d("PUT",$,Z)}patch($,Z){return new d("PATCH",$,Z)}delete($,Z){return new d("DELETE",$,Z)}resource($){return new r2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${q8($)}.`);return GV($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${q8($)}.`);return QV($)}file($,Z){return new o2("GET",$,Z)}stream($,Z){return new t2("GET",$,Z)}proxy($,Z={}){return new n2($,Z)}mcp($){let Z=$.__routes;if($.__brand!=="McpEndpoint"||typeof Z!=="function")throw TypeError(`this.mcp() takes an McpEndpoint class, and got ${q8($)}.`);return Z.call($)}}function q8($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function GV($){let Z={stream:new d("POST",$,"stream"),attach:new d("POST",$,"attach"),watch:new d("POST",$,"watch"),stop:new d("POST",$,"stop"),upload:new d("POST",$,"upload")};return Z.stream.__internal_bodyLimitDefault="none",Z.upload.__internal_bodyLimitDefault="upload",class extends A0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(Y){if(Y.stream)Z.stream.middleware(Y.stream);if(Y.attach)Z.attach.middleware(Y.attach),Z.watch.middleware(Y.attach);if(Y.stop)Z.stop.middleware(Y.stop);if(Y.upload)Z.upload.middleware(Y.upload);return this}}}function QV($){let Z={start:new d("POST",$,"voiceStart"),update:new d("PATCH",$,"voiceUpdate"),end:new d("DELETE",$,"voiceEnd")};return class extends A0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(Y){if(Y.start)Z.start.middleware(Y.start);if(Y.update)Z.update.middleware(Y.update);if(Y.end)Z.end.middleware(Y.end);return this}}}var e1="access_token";function w$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function V6($,Z){let W=w$(Z);if(!W)return null;return(await $.getSession(W,Z.headers.get("User-Agent")))?.user??null}var BV=/^[A-Za-z0-9_-]+$/,FV=/^:[A-Za-z_][A-Za-z0-9_]*$/,e2=/^[A-Za-z0-9_-]{1,128}$/,VV=/^[A-Za-z0-9_.:-]+$/;class s extends Error{constructor($){super($);this.name="InvalidChannelError"}}function $Y($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function TZ($){if(typeof $!=="string"||$.length===0)throw new s("A channel pattern must be a non-empty string.");if($.length>255)throw new s(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),W=new Set;for(let Y of Z){if(FV.test(Y)){let J=Y.slice(1);if(W.has(J))throw new s(`The channel pattern "${$}" names the param "${J}" twice.`);W.add(J);continue}if(Y.startsWith("__"))throw new s(`The channel "${$}" has the segment "${Y}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!BV.test(Y))throw new s(`The channel pattern "${$}" has an invalid segment "${Y}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function O3($,Z={}){let W=TZ($),Y=new Set,J=W.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);Y.add(z);let X=Z[z];if(X===void 0||X===null)throw new s(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!e2.test(G))throw new s(`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(!Y.has(j))throw new s(`The channel "${$}" has no param "${j}".`);if(J.length>255)throw new s(`The topic built from "${$}" is longer than 255 characters.`);return J}function m8($){if(TZ($).some((W)=>W.startsWith(":")))throw new s(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function ZY($){if(typeof $!=="string"||$.length===0||$.length>64||!VV.test($))throw new s(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function WY($,Z){if($===Z)return!0;if($===O0)return Z.startsWith(`${O0}.`)&&Z.split(".").length===2;let W=$.split("."),Y=Z.split(".");if(W.length!==Y.length)return!1;return W.every((J,j)=>J===Y[j]||J.startsWith(":")&&e2.test(Y[j]))}var O0="user";function KZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return O3(`${O0}.:id`,{id:Z})}class W0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class D6 extends W0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');let W=Z==="upload"?this.config.uploadLimit??f$("50mb"):f$(Z);return U6(this.req.rawRequest,W),{}}}function YY($){let Z=new Map;for(let W of $)if(typeof W==="string"){let[Y,J=""]=W.split(":");if(Y.startsWith("-")){if(Z.has(Y.replace("-","")))Z.delete(Y.replace("-",""))}else Z.set(Y,J.split(",").filter(Boolean))}else Z.set(W,[]);return Z}function UV($){return{"body-limit":D6.configure({uploadLimit:$})}}class $${config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:f$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=f$($.uploadBodyLimit??"50mb"),this.builtinAliases=UV(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||jY($))return;let W=Z==="upload"?Math.max(this.defaultBodyLimit,this.uploadBodyLimit):this.defaultBodyLimit;U6($,W,{checkDeclared:!1,uploadLimit:this.uploadBodyLimit})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}resolve($){let Z=this.aliases,W=[];for(let[Y,J]of YY($).entries())if(typeof Y==="string"){if(Z[Y])W.push({Middleware:Z[Y],params:J})}else if(V3(Y))W.push({Middleware:Y,params:[]});return W}runMiddleware($){let Z=new S,W=this.aliases,Y=[];for(let[J,j]of YY($).entries())if(typeof J==="string"){let z=W[J];if(z){let X=new z(Z);Y.push({run:()=>X.run.call(X,...j),runsOnRefusal:JY(z)})}}else if(V3(J)){let z=new J(Z);Y.push({run:z.run.bind(z),runsOnRefusal:JY(J)})}else Y.push({run:J,runsOnRefusal:!1});return(async()=>{let J={};for(let j=0;j<Y.length;j++)try{J={...J,...await Y[j].run()}}catch(z){throw await DV(Y.slice(j+1)),z}return J})()}}function JY($){return $?.runsOnRefusal===!0}async function DV($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(W){console.error(W)}}}class O6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...v0($)],this}events(...$){return this}}class QY{static __brand="ChannelRouter";channels={};public(){return new O6("public")}private($){return new O6("private",$)}async authorize($,Z,W={},Y={}){try{HV(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let J=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!BY(J))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===O0){if(Object.keys(W??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=O3(Z,W??{})}catch(G){if(G instanceof s)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(W??{}).map(([G,Q])=>[G,String(Q)])),X=new S($,z,"api",Z);return P.exit(()=>L6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(J.middlewares.length>0)await H($$).runMiddleware(J.middlewares);if(Z===O0){let Q=await zY(X);if(!Q)return{ok:!1,code:"denied"};if(j=KZ(Q),J.visibility==="private"&&J.authorizer){if(await XY(J.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(J.visibility==="private"){if((J.authorizer?await XY(J.authorizer,X,z):await zY(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(MV(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()}},Y.carried)))}}async function OV($,Z,W={},Y={}){let J=typeof $==="function"?new $:$;FY(J);let j=Y.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 J.authorize(z,Z,W,{carried:X})).ok}function BY($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function zY($){if(!P.getStore().user&&w$($)===null)return null;try{return await g0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function XY($,Z,W){if(LV($))return new $().authorize(Z,W);return $(Z,W)}function LV($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function MV($){return $?.kind===Z$||W$($)||q$($)}var GY=new WeakSet;function HV($){if(GY.has($))return;FY($),GY.add($)}function FY($){let Z=Object.entries($.channels),W=[];for(let[Y,J]of Z){if(!BY(J))throw new s(`The channel "${Y}" is not declared with this.public() or this.private().`);let j=TZ(Y);if(j[0].startsWith(":"))throw new s(`The channel pattern "${Y}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(Y!==O0&&j.length===2&&j[0]===O0)throw new s(`The channel pattern "${Y}" 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(Y!==O0&&J.visibility==="private"&&!J.authorizer&&j.some((z)=>z.startsWith(":")))throw new s(`The private channel "${Y}" 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) => ...).`);W.push({pattern:Y,segments:Y===O0?[O0,":id"]:j})}for(let Y=0;Y<W.length;Y++)for(let J=Y+1;J<W.length;J++)if(TV(W[Y].segments,W[J].segments))throw new s(`The channel patterns "${W[Y].pattern}" and "${W[J].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 TV($,Z){if($.length!==Z.length)return!1;return $.every((W,Y)=>W===Z[Y]||W.startsWith(":")||Z[Y].startsWith(":"))}class h8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,W){this.as=$;this.input=Z;this.bind=W}}class M6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,W){this.method=$;this.url=Z;this.meta=W}}class p8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function KV($){let Z=[],W="";for(let Y of $)if(Y==="_"||Y==="-"||Y===" "){if(W)Z.push(W);W=""}else if(Y===Y.toLowerCase())W+=Y;else{if(W)Z.push(W);W=Y.toLowerCase()}if(W)Z.push(W);return Z}function PV($,Z){let W=KV($);if(Z==="snake")return W.join("_");if(Z==="kebab")return W.join("-");return W.map((Y,J)=>J===0?Y:Y[0].toUpperCase()+Y.slice(1)).join("")}class VY{static __brand="McpRouter";routes={};scopes;param($){return new h8($.as,$.input,$.bind)}fromTool($,Z={}){return new p8($,Z)}fromApiRoute($,Z,W){return new M6($,Z,W)}fromApiRouteFor($,Z,W){let{name:Y,audiences:J,description:j,params:z,files:X,...G}=W,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,F=Object.keys(J??{});if(F.length===0)throw Error(`${Q}: declare at least one audience.`);let V={},B=new Map;for(let U of F){let{name:O,casing:D,description:L,params:M,files:T,...K}=J[U],N=O??(D?PV(Y,D):Y);if(B.has(N))throw Error(`${Q}: the audiences "${B.get(N)}" and "${U}" are both named "${N}". Give one its own name or casing.`);B.set(N,U);let _=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof _!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let x={...G,...K,description:_};if(z||M)x.params={...z,...M};if(X||T)x.files={...X,...T};V[N]=new M6($,Z,x)}return V}}var NV="Rate limit exceeded";class M1 extends y0{result;retryAfter;constructor($,Z=NV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let W={"Content-Type":"application/json",...$?c8($):{}};this.payload={api:{status:429,data:{error:{...Y$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:W},view:{error:{message:Z},status:429,headers:W}}}}function c8($){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 m0{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let W=Z.limit??this.config.limit,Y=Z.window??this.config.window,J=Z.cost??1;if(UY("window",Y),UY("limit",W),!Number.isFinite(J)||J<0)throw Error(`Rate limiter cost must be zero or greater, got ${J}`);return await this.config.driver.consume({key:$,limit:W,window:Y*1000,cost:J})}async enforce($,Z={},W){let Y=await this.consume($,Z);if(!Y.allowed)throw new M1(Y,typeof W==="function"?W(Y):W);return Y}}function UY($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}async function d8($,Z){let W=_V();if(!W)return null;let Y=await W.consume($,Z);return Y.allowed?null:Math.max(1,Math.ceil(Y.retryAfter/1000))}function _V(){try{let $=H();return $.bound(m0)?$.make(m0):null}catch{return null}}var DY=["2026-07-28"],H6=["2025-11-25","2025-06-18","2025-03-26"],T6=[...DY,...H6],OY="io.modelcontextprotocol/protocolVersion",eT="io.modelcontextprotocol/clientCapabilities";var LY="io.modelcontextprotocol/serverInfo",z0={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class o extends Error{code;data;status;constructor($,Z,W,Y=200){super(Z);this.code=$;this.data=W;this.status=Y;this.name="JsonRpcError"}}function k1($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function MY($){if(Array.isArray($))throw new o(z0.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new o(z0.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,W=Z.id,Y=typeof W==="string"||typeof W==="number"&&Number.isFinite(W);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new o(z0.InvalidRequest,"params must be an object.",void 0,400);if(W===void 0)return{kind:"notification",message:Z};if(!Y)throw new o(z0.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(Y&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new o(z0.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function $K($,Z){let W=$.outputSchema?.toJSONSchema(),Y={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...W&&(Z||W.type==="object")?{outputSchema:W}:{},...Object.keys(Y).length>0?{annotations:Y}:{}}}function o0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function IV($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let W=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(W)}catch{return null}}function HY($,Z,W){if(!DY.includes(W))throw new o(z0.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:T6,requested:W},400);let Y=(z)=>new o(z0.HeaderMismatch,`Header mismatch: ${z}`,void 0,400);if($.headers.get("mcp-protocol-version")!==W)throw Y("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw Y("Mcp-Method does not match the method.");let J=Z.params??{},j=Z.method==="tools/call"||Z.method==="prompts/get"?J.name:Z.method==="resources/read"?J.uri:void 0;if(j!==void 0){let z=$.headers.get("mcp-name");if(z===null||IV(z)!==j)throw Y("Mcp-Name does not match the request's name.")}}import{isIP as K6}from"net";function J$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let Y=Z.indexOf("]");if(Y<0)return null;let J=Z.slice(Y+1);if(J!==""&&!/^:\d{1,5}$/.test(J))return null;let j=Z.slice(1,Y);return K6(j)===6?j:null}if(K6(Z))return Z;let W=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return W&&K6(W[1])===4?W[1]:null}function TY($,{ipv6Prefix:Z=64}={}){if(!Number.isInteger(Z)||Z<0||Z>128)throw RangeError(`ipv6Prefix must be a whole number from 0 to 128, not ${Z}.`);let W=J$($);if(W===null||K6(W)===4)return W??$;let Y=CV(W);if(Y===null)return $;if(Y.slice(0,5).every((z)=>z===0)&&Y[5]===65535)return`${Y[6]>>8}.${Y[6]&255}.${Y[7]>>8}.${Y[7]&255}`;let J=Y.map((z,X)=>{let G=Math.min(Math.max(Z-X*16,0),16);return z&(65535<<16-G&65535)}),j=xV(J);return Z===128?j:`${j}/${Z}`}function CV($){let Z=$.split("%")[0].toLowerCase(),W=/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(Z);if(W){let[Q,F,V,B]=W.slice(1).map(Number);Z=`${Z.slice(0,W.index)}${(Q<<8|F).toString(16)}:${(V<<8|B).toString(16)}`}let[Y,J]=Z.split("::"),j=(Q)=>Q===""?[]:Q.split(":").map((F)=>parseInt(F,16)),z=j(Y),X=J===void 0?[]:j(J),G=J===void 0?z:[...z,...Array.from({length:8-z.length-X.length},()=>0),...X];return G.length===8&&G.every((Q)=>Q>=0&&Q<=65535)?G:null}function xV($){let Z=-1,W=0;for(let J=0;J<8;J++){if($[J]!==0)continue;let j=J;while(j<8&&$[j]===0)j++;if(j-J>W)Z=J,W=j-J;J=j}let Y=$.map((J)=>J.toString(16));if(W<2)return Y.join(":");return`${Y.slice(0,Z).join(":")}::${Y.slice(Z+W).join(":")}`}class _Y extends W0{static isRateLimit=!0;async run($,Z){let W=AV();if(!W)return{};let Y=await W.consume(this.key(),{limit:KY($)??this.config.limit,window:KY(Z)??this.config.window});if(this.config.headers!==!1){let J=this.req.ctx?.();if(J)for(let[j,z]of Object.entries(c8(Y)))J.setHeaders(j,z)}if(!Y.allowed)throw new M1(Y);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=PY(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${v$(this.req)}:${this.req.routePath??"*"}`}}function AV(){try{let $=H();return $.bound(m0)?$.make(m0):null}catch{return null}}function P6($){let Z=NY($.rawRequest);if(Z!==void 0)return Z;let W=$.headers.get("x-forwarded-for");if(W){let[Y]=W.split(",");if(Y?.trim())return J$(Y)??Y.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function v$($,Z){return TY(P6($),Z)}function KY($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}var SV={token:"router.domains"},bV={token:"middleware"},EV={limit:600,window:60},RV=1048576,IY=/^(GET|POST|PUT|PATCH|DELETE) (\/\S*)$/,kV=/^[A-Za-z0-9_.-]{1,128}$/;class L3 extends Error{code;status;data;headers;constructor($,Z,W={}){super(Z);this.code=$;this.name="McpEndpointError",this.status=W.status??200,this.data=W.data,this.headers=W.headers}}var AY=Symbol("McpEndpoint.result");class SY{static __brand="McpEndpoint";server;rateLimit;maxBodyBytes;tool($){return $}static result($,Z={}){return{[AY]:!0,body:$,isError:Z.isError===!0,text:Z.text}}static __routes(){let $=new this;return $.check(this.name||"McpEndpoint"),new u8($)}checked;check($){if(this.checked=$,this.caller!=="anonymous")throw Error(`${$}: set \`caller = "anonymous" as const\` to serve this endpoint to anyone. It is required: an endpoint that names no caller would be open without anybody having said so.`);if(!o0(this.tools))throw Error(`${$}: tools must be an object of tools, by name.`);for(let[Z,W]of Object.entries(this.tools)){let Y=`${$}: tool "${Z}"`;if(!kV.test(Z))throw Error(`${Y}: a tool name is 1 to 128 letters, digits, "_", "-" or ".".`);if(!o0(W)||typeof W.run!=="function"||typeof W.description!=="string")throw Error(`${Y} needs a description and a run().`);if(!o0(W.inputSchema))throw Error(`${Y}: inputSchema must be an s schema or a JSON Schema object.`);if(W.offered!==void 0&&typeof W.offered!=="function")throw Error(`${Y}: offered must be a function.`);let J=W.rateLimit;if(typeof J==="string"){if(!IY.test(J))throw Error(`${Y}: rateLimit "${J}" is not "METHOD /path", like "POST /orders".`)}else if(J!==void 0&&!xY(J))throw Error(`${Y}: rateLimit must be "METHOD /path" or { limit, window } in positive numbers.`)}if(this.rateLimit!==void 0&&this.rateLimit!==!1&&!xY(this.rateLimit))throw Error(`${$}: rateLimit must be { limit, window } in positive numbers, or false.`)}async __post($){let Z=$.rawRequest,W=this.rateLimit===!1?null:this.rateLimit??EV;if(W){let G=await d8(`mcp-endpoint:${v$($)}:${$.routePath??"*"}`,W);if(G!==null)return w1(k1(null,new o(z0.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String(G)})}if(!/^application\/json\s*(;|$)/i.test(Z.headers.get("content-type")??""))return new Response("Content-Type must be application/json.",{status:415,headers:{"Cache-Control":"no-store"}});let Y=Z.headers.get("mcp-protocol-version");if(Y!==null&&!T6.includes(Y))return w1(k1(null,new o(z0.InvalidRequest,`Unsupported MCP-Protocol-Version: ${Y.slice(0,40)}`)),400);let J=this.context?await this.context($):void 0;if(J instanceof Response)return J;if(J===null||this.context&&J===void 0)return w1(k1(null,new o(z0.InvalidRequest,"Not found.")),404);let j,z=this.maxBodyBytes??RV;try{j=JSON.parse(await qV(Z,z))}catch(G){if(G instanceof N6)return w1(k1(null,new o(z0.InvalidRequest,`The request is larger than ${z} bytes.`)),413);return w1(k1(null,new o(z0.ParseError,"Parse error.")),400)}let X=o0(j)&&(typeof j.id==="string"||typeof j.id==="number")?j.id:null;try{return await this.dispatch($,J,j)}catch(G){if(G instanceof L3)return w1(k1(X,new o(G.code,G.message,G.data)),G.status,G.headers);if(G instanceof o)return w1(k1(X,G),G.status);return console.error(`[gemi/mcp] ${this.checked} failed:`,G),w1(k1(X,new o(z0.InternalError,"Internal error.")),500)}}async dispatch($,Z,W){let Y=MY(W);if(Y.kind!=="request")return new Response(null,{status:202});let{message:J}=Y,j=J.params??{},z=o0(j._meta)?j._meta:{},X=z[OY],G=typeof X==="string";if(G)HY($.rawRequest,J,X);let Q=await this.answer($,Z,J.method,j,z,G);return w1({jsonrpc:"2.0",id:J.id,result:G?this.complete(Q):Q},200)}async answer($,Z,W,Y,J,j){switch(W){case"initialize":{if(j)break;let z=Y.protocolVersion;return{protocolVersion:H6.includes(z)?z:H6[0],capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo(),...this.server?.instructions?{instructions:this.server.instructions}:{}}}case"server/discover":if(!j)break;return{supportedVersions:T6,capabilities:{tools:{}},...this.server?.instructions?{instructions:this.server.instructions}:{}};case"ping":return{};case"tools/list":{let z=[];for(let[X,G]of Object.entries(this.tools))if(await this.offers(G,Z,$))z.push(wV(X,G));return j?{tools:z,ttlMs:60000,cacheScope:"private"}:{tools:z}}case"tools/call":return await this.call($,Z,Y,J)}throw new o(z0.MethodNotFound,`Method not found: ${W.slice(0,100)}`)}async call($,Z,W,Y){let J=W.name,j=typeof J==="string"&&Object.hasOwn(this.tools,J)?this.tools[J]:void 0;if(!j||!await this.offers(j,Z,$))throw new o(z0.InvalidParams,`Unknown tool: ${String(J).slice(0,100)}`);let z=await this.spend($,J,j);if(z!==null)throw new L3(-32000,"Rate limit exceeded",{status:429,data:{retry_after:z},headers:{"Retry-After":String(z)}});let X=W.arguments===void 0?{}:W.arguments;if(!o0(X))throw new o(z0.InvalidParams,"arguments must be an object.");if(bY(j.inputSchema)){let Q=j.inputSchema.safeParse(X);if(Q.ok===!1)return{content:[{type:"text",text:`Invalid arguments for "${J}": ${Q.errors.join(", ")}`}],isError:!0};X=Q.value}let G;try{G=await j.run(X,{context:Z,req:$,tool:J,meta:Y,signal:$.rawRequest.signal})}catch(Q){if(Q instanceof L3||Q instanceof o)throw Q;return console.error(`[gemi/mcp] ${this.checked}: "${J}" failed:`,Q),{content:[{type:"text",text:`"${J}" failed on the server.`}],isError:!0}}return fV(G)}async offers($,Z,W){return $.offered?await $.offered(Z,W)===!0:!0}async spend($,Z,W){let Y=W.rateLimit;if(Y===void 0)return null;if(typeof Y!=="string")return await d8(`mcp-endpoint-tool:${v$($)}:${$.routePath??"*"}:${Z}`,Y);let[,J,j]=IY.exec(Y),z=this.twinLimits($,Z,J,j);if(z.length===0)return null;let X=new S($.rawRequest,{},"api",j);try{await P.run(X,async()=>{for(let{Middleware:G,params:Q}of z)await new G(X).run(...Q)})}catch(G){if(G instanceof M1||G?.name==="RateLimitExceededError"){let Q=G.retryAfter??1000;return Math.max(1,Math.ceil(Q/1000))}throw G}return null}twinLimits($,Z,W,Y){let j=H(SV).dispatchers($.domain).api.flatRoutes[Y]?.[W];if(!j)throw Error(`${this.checked}: tool "${Z}" spends the rate limits of ${W} ${Y}, and this host's api has no such route. Name the route by its full path, without /api.`);return H(bV).resolve(j.middleware).filter(({Middleware:z})=>z.isRateLimit===!0)}serverInfo(){return{name:this.server?.name??"gemi",version:this.server?.version??"1.0.0"}}complete($){return{resultType:"complete",...$,_meta:{[LY]:this.serverInfo()}}}}class u8{post;get;delete;constructor($){this.post=new d("POST",(W)=>$.__post(W));let Z=(W)=>new Response(null,{status:405,headers:{Allow:"POST","Cache-Control":"no-store"}});this.get=new d("GET",Z),this.delete=new d("DELETE",Z)}middleware($){let Z=v0($);for(let W of[this.post,this.get,this.delete])W.middleware(Z);return this}cors($){for(let Z of[this.post,this.get,this.delete])Z.cors($);return this}}function wV($,Z){return{name:$,...Z.title?{title:Z.title}:{},description:Z.description,inputSchema:bY(Z.inputSchema)?Z.inputSchema.toJSONSchema():Z.inputSchema,...Z.outputSchema?{outputSchema:Z.outputSchema}:{},...Z.annotations||Z.title?{annotations:{...Z.title?{title:Z.title}:{},...Z.annotations}}:{}}}function fV($){if(o0($)&&$[AY]===!0){let Z=$;return{content:[{type:"text",text:Z.text??CY(Z.body)}],...o0(Z.body)?{structuredContent:Z.body}:{},isError:Z.isError}}if(typeof $==="string")return{content:[{type:"text",text:$}],isError:!1};return{content:[{type:"text",text:CY($)}],...o0($)?{structuredContent:$}:{},isError:!1}}function CY($){return typeof $==="string"?$:JSON.stringify($??null)}function bY($){return o0($)&&typeof $.safeParse==="function"&&typeof $.toJSONSchema==="function"}function xY($){return o0($)&&typeof $.limit==="number"&&$.limit>0&&Number.isFinite($.limit)&&typeof $.window==="number"&&$.window>0&&Number.isFinite($.window)}class N6 extends Error{}async function qV($,Z){let W=Number($.headers.get("content-length"));if(Number.isFinite(W)&&W>Z)throw new N6;if(!$.body)return"";let Y=$.body.getReader(),J=[],j=0;for(;;){let{done:z,value:X}=await Y.read();if(z)break;if(j+=X.byteLength,j>Z)throw await Y.cancel(),new N6;J.push(X)}return Buffer.concat(J).toString("utf8")}function w1($,Z,W={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...W}})}function L0($,Z){return $.replace(/:([^/]+[*?]?)/g,(W,Y)=>{let J=Y.endsWith("?")||Y.endsWith("*"),j=J?Y.slice(0,-1):Y,z=Z[j];if(z===void 0){if(J)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 l8 extends y0{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 f1{static to($,...Z){let[W={}]=Z,{search:Y={},params:J={},permanent:j,status:z}={params:{},status:307,permanent:!1,...W},X=new URLSearchParams(Y).toString();throw new l8([L0($,J)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new l8($,Z)}}class EY{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,W]=$;this.handler=(Y)=>{return new Z()[W](Y)}}}async run($,Z){let{destination:W,permanent:Y=!1,status:J=307}=await this.handler($);if(!W)throw Error(`Redirect destination is required see ${Z}`);return f1.to(W,{permanent:Y,status:J}),{}}middleware($){return this.middlewares=v0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function i8($,Z){if($ instanceof Response)return $;let W=$ instanceof Blob,Y=W?$:$.file,J=W?$.name:$.name??$.file?.name,j=(W?$.type:$.type??$.file?.type)||"",z=W?!1:$.download??!1,X=W?200:$.status??200;if(!W)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(Y instanceof Blob&&"exists"in Y&&typeof Y.exists==="function"){if(!await Y.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),Y instanceof Blob)Z.set("Content-Length",String(Y.size));if(J)Z.set("Content-Disposition",F6(J,z));return new Response(Y instanceof Blob?Y.stream():Y,{status:X,headers:Z})}class RY{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,W]=$;this.handler=(Y)=>{return new Z()[W](Y)}}}async run($,Z){let W=await this.handler($);if(!W)throw Error(`File route handler must return a file see ${Z}`);return{FILE:W}}middleware($){return this.middlewares=v0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function kY($,Z){if(r1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class wY{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[W,Y]=Z;this.handler=(J)=>{return new W()[Y](J)}}}async run($,Z){let W=kY(await this.handler($),this.viewPath);return{[this.viewPath]:{...W,breadcrumb:{label:W?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=v0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class fY{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,W){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends q1{routes=W??{}};else if(Array.isArray(Z)){let[Y,J]=Z;this.handler=(j)=>{return new Y()[J](j)},this.children=class extends q1{routes=W??{}}}else this.children=class extends q1{routes=Z},this.handler=()=>({})}async run($,Z){let W=kY(await this.handler($),this.viewPath);return{[this.viewPath]:{...W,breadcrumb:{label:W?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=v0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class q1{middlewares=[];featureGates=[];routes={};view($,Z){return new wY($,Z)}file($){return new RY($)}redirect($){return new EY($)}layout($,Z,W){return new fY($,Z,W)}}function vV($){return $}function gV(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var a0="redirect";function H1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let W=new URL($,"http://gemi.invalid");if(W.origin!=="http://gemi.invalid")return Z;let Y=`${W.search}${W.hash}`.replaceAll("/","%2F"),J=`${W.pathname}${Y}`.replaceAll(":","%3A");return J.startsWith("//")?Z:J}catch{return Z}}function PZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function s8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function yV($,Z=!0){let W=new URL($.rawRequest.url),Y=W.pathname.replace(/\.(json|og)$/,""),[,J,...j]=Y.split("/");if(H(l).supportedLocales.includes(J))Y=`/${j.join("/")}`;return Z?`${Y}${W.search}`:Y}function mV($,Z){let W=(Y)=>Y.replace(/\/+$/,"")||"/";return W($)===W(Z)}function _6($,Z){let W=Z||H(R).config.signInPath,Y=/^[a-z][a-z\d+.-]*:/i.test(W);if(Y?!/^https?:\/\//i.test(W):!W.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${W}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let J=new URL(W,"http://gemi.invalid");if($?.kind==="view"){let j=yV($,!Y);if(Y||!mV(new URL(j,J).pathname,J.pathname))J.searchParams.set(a0,j)}return Y?J.href:`${J.pathname}${J.search}`}class qY extends W0{async run($){let Z=P.getStore(),W=Z.req;if(Z.user)return{};let Y=await V6(H(R),W);if(!Y)throw new g$({redirectTo:_6(W,$)});return Z.setUser(Y),{}}}var o8="gemi_same_site",n8="private, no-cache, no-store, max-age=0, must-revalidate";class I6 extends W0{run(){let $=P.getStore(),Z=$?.req;if(!Z||$.user)return{};let W=Z.rawRequest;if(Z.kind!=="view"||W.method!=="GET"&&W.method!=="HEAD")return{};let Y=new URL(W.url);if(/\.(json|og)$/.test(Y.pathname))return{};if(Y.searchParams.has(o8))return{};if(w$(Z))return{};let J=W.headers.get("Sec-Fetch-Site");if(J&&J!=="cross-site")return{};throw Y.searchParams.set(o8,"1"),new vY(`${Y.pathname}${Y.search}`)}}class vY extends y0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=hV($),W={"Content-Type":"text/html; charset=utf-8","Cache-Control":n8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":n8}},viewData:{status:200,data:{},headers:{"Cache-Control":n8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:W,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 hV($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class gY extends W0{async run(...$){let[Z="public",W="864000",...Y]=$,J=`${Z}, max-age=${W}${Y.length>0?", ":""}${Y.join(", ")}`;if($.length===0)J="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")J="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")J="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",J);return{}}}var yY={"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 mY extends W0{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 W={...yY,...this.config.origins[Z]};if(Z==="null")delete W["Access-Control-Allow-Credentials"];for(let[Y,J]of Object.entries(W))$.ctx().setHeaders(Y,J)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let W={...yY,...this.config.origins["*"]};delete W["Access-Control-Allow-Credentials"];for(let[Y,J]of Object.entries(W))$.ctx().setHeaders(Y,J)}return{}}}class pY extends W0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new a8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new a8;return{}}}class a8 extends y0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:hY("csrf","Invalid CSRF token",403)}},view:{}}}class cY{policiesList={};constructor(){let $=this.register();for(let Z of $){let W=new Z;this.policiesList[Z.name]=W}}register(){return[]}}class dY{all($,Z){return!0}}class t8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new NZ:new C6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let W=this.answers.get($.rawRequest);if(!W)W=new Map,this.answers.set($.rawRequest,W);let Y=W.get(Z);if(!Y)Y=this.decide($,Z),W.set(Z,Y);return Y}async allows($,Z){try{return await this.authorize($,Z),!0}catch(W){if(this.isRefusal(W))return!1;throw W}}fromRoute($=new S,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,W)=>this.fromRoute(Z,W||void 0);this.middlewareClass=class extends W0{async run(W){await $(this.req,W)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:W,body:Y})=>{let J;if(W!==void 0){if(J=$.thread?await $.thread(W,Z):null,J===null||J===void 0)throw this.refusal()}if(Y!==void 0){let j=await $.body(Y,Z);if(await this.authorize(Z,j),W!==void 0&&String(J)!==String(j))throw this.refusal();return}if(W!==void 0)await this.authorize(Z,J)}}}async decide($,Z){let W=await this.options.load(Z,$);if(W===null||W===void 0||!await this.options.allow(W,$))throw this.refusal();return W}isRefusal($){return this.refuse==="forbidden"?$ instanceof NZ:$ instanceof C6}}function pV($){return new t8($)}async function S6($,Z,W=!1){if(!$.body)return new Uint8Array;let[Y,J]=await $U($.body),z=Y.length>=2&&Y[0]===31&&Y[1]===139?J.pipeThrough(new DecompressionStream("gzip")):J;return eV(z,Z,W,$.url)}async function eV($,Z,W,Y){let J=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:F}=await J.read();if(Q)break;if(z+F.byteLength>Z){if(!W)throw new A6(Y,Z);j.push(F.subarray(0,Z-z)),z=Z;break}j.push(F),z+=F.byteLength}}finally{J.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 $U($){let Z=$.getReader(),W=await Z.read(),Y=W.done?new Uint8Array:W.value,J=new ReadableStream({start(j){if(W.done)j.close();else j.enqueue(Y)},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[Y,J]}function b6($){return new TextDecoder("utf-8").decode($)}var ZU={"&":"&","<":"<",">":">",'"':""","'":"'"};function y$($){return $.replace(/[&<>"']/g,(Z)=>ZU[Z])}var WU={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function r8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,W)=>{if(W[0]!=="#")return WU[W]??Z;let Y=W[1]==="x"?parseInt(W.slice(2),16):parseInt(W.slice(1),10);return Y>0&&Y<=1114111?String.fromCodePoint(Y):Z})}function e8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function uY($,Z){let W=$.length,Y=0;while(Y<W){if(Z.stopped?.())return;let J=$.indexOf("<",Y);if(J===-1){Z.text(r8($.slice(Y)));return}if(J>Y)Z.text(r8($.slice(Y,J)));if($.startsWith("<!--",J)){let j=$.indexOf("-->",J+4);if(j===-1)return;Y=j+3}else if($.startsWith("<![CDATA[",J)){let j=$.indexOf("]]>",J+9);if(j===-1)return;Z.text($.slice(J+9,j)),Y=j+3}else if($.startsWith("<?",J)){let j=$.indexOf("?>",J+2);if(j===-1)return;Y=j+2}else if($.startsWith("<!",J)){let j=$.indexOf(">",J+2);if(j===-1)return;let z=$.indexOf("[",J+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;Y=G+1}else Y=j+1}else if($[J+1]==="/"){let j=$.indexOf(">",J+2);if(j===-1)return;Z.close(e8($.slice(J+2,j).trim())),Y=j+1}else{let j=YU($,J+1);if(j===-1)return;let z=$.slice(J+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=e8(z.slice(0,G));if(Q){if(Z.open(Q,JU(z.slice(G)),X),X)Z.close(Q)}Y=j+1}}}function YU($,Z){let W=null;for(let Y=Z;Y<$.length;Y++){let J=$[Y];if(W){if(J===W)W=null}else if(J==='"'||J==="'")W=J;else if(J===">")return Y}return-1}function JU($){let Z={},W=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let Y of $.matchAll(W))Z[e8(Y[1])]=r8(Y[2]??Y[3]??"");return Z}class X0 extends Error{url;status;constructor($,Z=null,W=null){super($);this.url=Z;this.status=W;this.name="SitemapError"}}var oY="http://www.sitemaps.org/schemas/sitemap/0.9",jU="http://www.w3.org/1999/xhtml",W5=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
|
+
`,lY=`<urlset xmlns="${oY}" xmlns:xhtml="${jU}">
|
|
4
|
+
`,iY=`</urlset>
|
|
5
|
+
`,m$=50000,M3=52428800,sY=2048,zU=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),XU=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,GU="application/xml; charset=utf-8",nY=new TextEncoder;function Y5($,Z){let W;try{W=new URL($)}catch{throw new X0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(W.protocol!=="http:"&&W.protocol!=="https:")throw new X0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let Y=W.href;if(Y.length>sY)throw new X0(`Sitemap: ${Z} is over ${sY} characters: "${Y.slice(0,80)}\u2026".`);return Y}function aY($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new X0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!XU.test($))throw new X0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function QU($){let Z=Y5($.loc,"loc"),W=`<url><loc>${y$(Z)}</loc>`;if($.lastmod!=null)W+=`<lastmod>${y$(aY($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!zU.has($.changefreq))throw new X0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);W+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let Y=$.priority;if(!Number.isFinite(Y)||Y<0||Y>1)throw new X0(`Sitemap: priority ${Y} of ${Z} is not between 0 and 1.`);W+=`<priority>${Number(Y.toFixed(4))}</priority>`}for(let Y of $.alternates??[]){let J=Y.hrefLang?.trim();if(!J)throw new X0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=Y5(Y.href,`alternate href of ${Z}`);W+=`<xhtml:link rel="alternate" hreflang="${y$(J)}" href="${y$(j)}"/>`}return`${W}</url>
|
|
6
|
+
`}function BU($){let Z=$.maxUrls??m$,W=$.maxBytes??M3;if(!Number.isInteger(Z)||Z<1||Z>m$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${m$}.`);if(!Number.isInteger(W)||W<1||W>M3)throw RangeError(`Sitemap: maxBytes must be an integer from 1 to ${M3}.`);return{maxUrls:Z,maxBytes:W}}function tY($,Z={}){let{maxUrls:W,maxBytes:Y}=BU(Z),J=nY.encode(W5+lY+iY).byteLength,j=[],z=[],X=J,G=()=>{j.push(W5+lY+z.join("")+iY),z=[],X=J};for(let Q of $){let F=QU(Q),V=nY.encode(F).byteLength;if(J+V>Y)throw new X0(`Sitemap: the entry for ${Q.loc} alone is over maxBytes (${Y}).`);if(z.length===W||X+V>Y)G();z.push(F),X+=V}if(z.length>0||j.length===0)G();return j}function rY($){let Z="",W=0;for(let Y of $){if(++W>m$)throw new X0(`Sitemap: an index can list at most ${m$} sitemaps.`);let J=Y5(Y.loc,"sitemap loc");if(Z+=`<sitemap><loc>${y$(J)}</loc>`,Y.lastmod!=null)Z+=`<lastmod>${y$(aY(Y.lastmod,J))}</lastmod>`;Z+=`</sitemap>
|
|
7
|
+
`}return`${W5}<sitemapindex xmlns="${oY}">
|
|
8
|
+
${Z}</sitemapindex>
|
|
9
|
+
`}function $5($,Z,W){let Y=new Headers(W);if(!Y.has("content-type"))Y.set("content-type",GU);return new Response($,{status:Z,headers:Y})}function FU($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function VU($,Z={}){let W=tY($,Z),Y=FU(Z.page);if(Y!==null){let j=W[Y-1];return j?$5(j,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(W.length===1)return $5(W[0],200,Z.headers);let J=Z.pageUrl;if(!J)throw new X0(`Sitemap: the entries need ${W.length} files, so Sitemap.response needs \`pageUrl\` to list them in an index.`);return $5(rY(W.map((j,z)=>({loc:J(z+1)}))),200,Z.headers)}function Z5($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function eY($,Z={}){let W=Z.maxUrls??1/0,Y=$.replace(/^\uFEFF/,"").trimStart();if(!Y.startsWith("<")){let B=[];for(let U of Y.split(/\r?\n/)){if(B.length>=W)break;let O=U.trim()?Z5(U):null;if(O)B.push({loc:O})}if(B.length===0&&Y.length>0)throw new X0("Sitemap: the document is neither XML nor a list of URLs.");return{kind:"urlset",urls:B}}let J=null,j=[],z=[],X=[],G=null,Q=null,F="",V=()=>J==="index"?z.length:j.length;if(uY(Y,{stopped:()=>V()>=W,open(B,U){let O=X[X.length-1];if(X.push(B),J===null){if(B==="urlset")J="urlset";else if(B==="sitemapindex")J="index";return}if(J==="urlset"&&B==="url"&&O==="urlset"||J==="index"&&B==="sitemap"&&O==="sitemapindex")G={};else if(G&&(O==="url"||O==="sitemap")&&(B==="loc"||B==="lastmod"||B==="changefreq"||B==="priority"))Q=B,F="";else if(G&&J==="urlset"&&O==="url"&&B==="link"){let D=U.href?Z5(U.href):null;if(U.rel?.toLowerCase()==="alternate"&&U.hreflang&&D)(G.alternates??=[]).push({hrefLang:U.hreflang,href:D})}},close(B){let U=X.lastIndexOf(B);if(U===-1)return;if(X.length=U,Q&&B===Q&&G)G[Q]=F.trim(),Q=null;else if(G&&(B==="url"||B==="sitemap")){let O=G;G=null,Q=null;let D=O.loc?Z5(O.loc):null;if(!D)return;if(J==="index"){z.push(O.lastmod?{loc:D,lastmod:O.lastmod}:{loc:D});return}let L={loc:D};if(O.lastmod)L.lastmod=O.lastmod;if(O.changefreq)L.changefreq=O.changefreq;let M=O.priority?Number(O.priority):NaN;if(Number.isFinite(M))L.priority=M;if(O.alternates)L.alternates=O.alternates;j.push(L)}},text(B){if(Q)F+=B}}),J===null)throw new X0("Sitemap: the document has no <urlset> or <sitemapindex>.");return J==="index"?{kind:J,sitemaps:z}:{kind:J,urls:j}}async function*UU($,Z={}){let{maxUrls:W=m$,maxSitemaps:Y=50,maxDepth:J=3,maxSize:j=M3,onError:z,...X}=Z,G=[{url:String($),depth:0}],Q=new Set,F=0,V=0;while(G.length>0&&V<W&&F<Y){let B=G.shift(),U=B.url.replace(/#.*$/,"");if(Q.has(U))continue;Q.add(U),F++;let O;try{let D=await v1(B.url,{...X,maxSize:j});if(!D.ok)throw D.body?.cancel().catch(()=>{}),new X0(`Sitemap: ${B.url} answered ${D.status}.`,B.url,D.status);let L=b6(await S6(D,j));O=eY(L,{maxUrls:Math.max(W-V,Y-F)})}catch(D){if(B.depth===0||!z||X.signal?.aborted)throw D;z(D,B.url);continue}if(O.kind==="index"){if(B.depth>=J)continue;G=O.sitemaps.slice(0,Y-F).map((L)=>({url:L.loc,depth:B.depth+1})).concat(G);continue}for(let D of O.urls)if(yield{...D,sitemap:B.url},++V>=W)return}}var $J={response:VU,chunk:tY,index:rY,parse:eY,read:UU,MAX_URLS:m$,MAX_BYTES:M3};var DU=512000,OU=new TextEncoder;function ZJ($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function WJ($){let Z="";for(let W=0;W<$.length;W++){let Y=$[W];if(Y==="%"&&/^[0-9a-fA-F]{2}$/.test($.slice(W+1,W+3)))Z+=`%${$.slice(W+1,W+3).toUpperCase()}`,W+=2;else if(Y.charCodeAt(0)>126||Y.charCodeAt(0)<=32){let J=$.codePointAt(W);if(J>65535)W++;for(let j of OU.encode(String.fromCodePoint(J)))Z+=`%${j.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=Y}return Z}function LU($,Z){let W=$.endsWith("$"),Y=W?$.slice(0,-1):$,J=0,j=0,z=-1,X=0;while(j<Z.length)if(J<Y.length&&Y[J]!=="*"&&Y[J]===Z[j])J++,j++;else if(J<Y.length&&Y[J]==="*")z=J++,X=j;else if(J===Y.length&&!W)return!0;else if(z!==-1)J=z+1,j=++X;else return!1;while(J<Y.length&&Y[J]==="*")J++;return J===Y.length}class _Z{groups;sitemaps;status;constructor($,Z,W="parsed"){this.groups=$;this.sitemaps=Z;this.status=W}groupsFor($){let Z=ZJ($)||"*";if(Z!=="*"){let W=this.groups.filter((Y)=>Y.userAgents.includes(Z));if(W.length>0)return W}return this.groups.filter((W)=>W.userAgents.includes("*"))}isAllowed($,Z="*"){let W;if($ instanceof URL||/^[a-z][a-z0-9+.-]*:/i.test($)){let J=new URL(String($));W=J.pathname+J.search}else W=$.startsWith("/")?$:`/${$}`;if(W==="/robots.txt")return!0;if(this.status==="unavailable")return!0;if(this.status==="unreachable")return!1;W=WJ(W);let Y=null;for(let J of this.groupsFor(Z))for(let j of J.rules){if(!LU(j.path,W))continue;let z=j.path.length,X=j.type==="allow";if(!Y||z>Y.length||z===Y.length&&X)Y={length:z,allow:X}}return Y?Y.allow:!0}crawlDelay($="*"){for(let Z of this.groupsFor($))if(Z.crawlDelay!==void 0)return Z.crawlDelay;return null}}var MU={"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 YJ($,Z={}){let W=[],Y=[],J=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 F=MU[G.slice(0,Q).trim().toLowerCase()],V=G.slice(Q+1).trim();if(!F)continue;if(F==="sitemap"){if(!V||/\s/.test(V))continue;try{let B=Z.url?new URL(V,Z.url):new URL(V);if(B.protocol==="http:"||B.protocol==="https:")Y.push(B.href)}catch{}continue}if(F==="user-agent"){if(!j||!J)J={userAgents:[],rules:[]},W.push(J),j=!0;let B=ZJ(V);if(B)J.userAgents.push(B);continue}if(!J)continue;if(j=!1,F==="crawl-delay"){let B=Number(V);if(Number.isFinite(B)&&B>=0)J.crawlDelay=B;continue}if(!V)continue;J.rules.push({type:F,path:WJ(V)})}return new _Z(W,Y)}async function HU($,Z={}){let{maxSize:W=DU,...Y}=Z,J=new URL("/robots.txt",$),j=await v1(J,{...Y,maxSize:Number.MAX_SAFE_INTEGER}),z=j.status;if(z===429||z>=500)return j.body?.cancel().catch(()=>{}),new _Z([],[],"unreachable");if(z>=400)return j.body?.cancel().catch(()=>{}),new _Z([],[],"unavailable");let X=await S6(j,W,!0),G=b6(X);if(X.byteLength>=W)G=G.slice(0,Math.max(0,G.lastIndexOf(`
|
|
10
|
+
`)));return YJ(G,{url:j.url})}function J5($){return $===void 0?[]:typeof $==="string"?[$]:$}function E6($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
|
|
11
|
+
`}function JJ($){let Z=[];for(let Y of $.rules??[]){let J=J5(Y.userAgent);if(J.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let j=J.map((X)=>E6("User-agent",X)).join(""),z=[...J5(Y.allow).map((X)=>["Allow",X]),...J5(Y.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+=E6(X,G)}if(z.length===0)j+=`Disallow:
|
|
12
|
+
`;if(Y.crawlDelay!==void 0){if(!Number.isFinite(Y.crawlDelay)||Y.crawlDelay<0)throw TypeError(`Robots: crawlDelay ${Y.crawlDelay} is not a number of seconds.`);j+=E6("Crawl-delay",String(Y.crawlDelay))}Z.push(j)}let W=($.sitemaps??[]).map((Y)=>{let J;try{J=new URL(Y)}catch{throw TypeError(`Robots: sitemap "${Y}" is not an absolute URL.`)}return E6("Sitemap",J.href)});if(W.length>0)Z.push(W.join(""));return Z.join(`
|
|
13
|
+
`)}function TU($,Z={}){let W=new Headers(Z.headers);if(!W.has("content-type"))W.set("content-type","text/plain; charset=utf-8");return new Response(JJ($),{status:200,headers:W})}var jJ={response:TU,text:JJ,parse:YJ,fetch:HU};import{createHmac as zJ,randomBytes as KU}from"crypto";var z5="v2.";function X5($){return $.startsWith(z5)}function IZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function XJ($){let Z=KU(16).toString("hex"),W=zJ("sha256",IZ()).update(`${$}:${Z}`).digest("hex");return`${z5}${W}`}function R6($,Z){let W=zJ("sha256",IZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${z5}${W}`}import{createHash as _U,createHmac as IU,randomInt as CU,timingSafeEqual as BJ}from"crypto";function GJ($,Z){return Math.floor($/Z)*Z}function PU($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function G5($,Z,W,Y){return Z*PU(W,Y)+$}function NU($){let{current:Z,previous:W,elapsed:Y,window:J,limit:j,cost:z}=$,X=j-z;if(X<0)return J;let G=Math.max(0,J-Y);if(W>0){let F=J*(1-(X-Z)/W);if(F<=J)return Math.max(0,Math.ceil(F-Y))}if(Z<=X)return G;if(Z<=0)return G;let Q=J*(1-X/Z);return G+Math.max(0,Math.ceil(Q))}function QJ($){let{allowed:Z,current:W,previous:Y,now:J,elapsed:j,window:z,limit:X,cost:G}=$;if(Z){let F=G5(W,Y,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-F)),resetAt:J-j+z,retryAfter:0}}let Q=NU({current:W,previous:Y,elapsed:j,window:z,limit:X,cost:G});return{allowed:!1,limit:X,remaining:0,resetAt:J+Q,retryAfter:Q}}class Q5{}class B5 extends Q5{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:W,window:Y}=$,J=$.cost??1,j=Date.now(),z=GJ(j,Y),X=j-z,G=this.roll(Z,Y,z);G.limit=W;let F=G5(G.current,G.previous,X,Y)+J<=W;if(F)G.current+=J;if(this.buckets.delete(Z),this.buckets.set(Z,G),this.buckets.size>this.maxKeys)this.evict(j);return QJ({allowed:F,current:G.current,previous:G.previous,now:j,elapsed:X,window:Y,limit:W,cost:J})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,W){let Y=this.buckets.get($);if(!Y||Y.window!==Z)return{window:Z,limit:0,windowStart:W,current:0,previous:0};if(Y.windowStart===W)return Y;if(Y.windowStart+Z===W)return Y.previous=Y.current,Y.current=0,Y.windowStart=W,Y;return Y.previous=0,Y.current=0,Y.windowStart=W,Y}evict($){for(let[Y,J]of this.buckets)if($-J.windowStart>=J.window*2)this.buckets.delete(Y);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let W=[...this.buckets].map(([Y,J],j)=>({key:Y,order:j,spent:J.limit>0?(J.current+J.previous)/J.limit:0}));W.sort((Y,J)=>Y.spent-J.spent||Y.order-J.order);for(let{key:Y}of W){if(this.buckets.size<=Z)break;this.buckets.delete(Y)}}}var VJ="h1.";function k6($,Z,W){let Y=IU("sha256",IZ()).update(`gemi:one-time:${$}:${Z}:${W}`).digest("hex");return`${VJ}${Y}`}function CZ($,Z,W,Y){let J=typeof Y==="string"?Y:"",j=typeof W==="string"?W:"",z=j.startsWith(VJ),X=k6($,Z,J),G=Buffer.from(z?X:J),Q=Buffer.from(j);if(G.length!==Q.length||J===""||j==="")return BJ(G,G),!1;return BJ(G,Q)}function UJ($){let Z="";for(let W=0;W<$;W++)Z+=String(CU(0,10));return Z}var DJ=320;function h$($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>DJ)return null;return Z.toLowerCase()}function w6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>DJ)return null;let W=Z.toLowerCase();if(W.length<3||W.length>254||!/^[^\s@]+@[^\s@]+$/.test(W))return null;return W}var FJ=null;function OJ(){try{let $=H();if(typeof $?.bound==="function"&&$.bound(m0))return $.make(m0)}catch{}return FJ??=new m0({driver:new B5,limit:1000,window:60}),FJ}function F5($){return $.length<=64?$:`sha256:${_U("sha256").update($).digest("hex")}`}function xU($){return $==="request"||$==="verify"||$==="link"?`auth:code-${$}`:`auth:${$}`}async function p$($,Z,W,Y,J,j){let z=OJ(),X=[["perIp",`ip:${F5(v$(W))}`,Y.perIp]];if(Z!==null)X.push(["perEmail",`email:${F5(Z)}`,Y.perEmail]);for(let[G,Q,F]of X){if(!F)continue;let V=J?await J({req:W,scope:$,limit:G}):void 0,B=xU($),U=V?`${B}:p:${F5(String(V))}:${Q}`:`${B}:${Q}`,[O,D]=F,L=await z.consume(U,{limit:O,window:D});if(!L.allowed)throw await j?.(G),new M1(L)}}async function LJ($,Z,W,Y=10){let J=Math.max(86400,Math.ceil(Y*60*(W+1)));return(await OJ().consume(`auth:code-attempt:${$}:${Z}`,{limit:W,window:J})).allowed}import{randomBytes as U5}from"crypto";class V5 extends S{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"}}}import{createHash as AU,timingSafeEqual as SU}from"crypto";function HJ($){let Z=$??process.env.AUTH_FIXED_CODE;return typeof Z==="string"&&Z!==""?Z:null}function TJ($){if($!==void 0&&$!==null)return $===!0;return process.env.AUTH_FIXED_CODE_ALLOW_PRODUCTION==="1"}var bU="[gemi] WARNING: a fixed sign-in code is enabled in production (AUTH_FIXED_CODE / auth.emailCode.fixedCode, opted in with AUTH_FIXED_CODE_ALLOW_PRODUCTION=1 / auth.emailCode.allowFixedCodeInProduction). Anyone who knows the code can sign in as any user. This is meant for local test servers only; never set it on a real deployment.";function KJ($={},{warn:Z=!1}={}){let{fixedCode:W,allowFixedCodeInProduction:Y}=$??{};if(W!==void 0&&W!==null&&typeof W!=="string")throw Error(`auth.emailCode.fixedCode must be a string, got ${JSON.stringify(W)}`);if(Y!==void 0&&Y!==null&&typeof Y!=="boolean")throw Error(`auth.emailCode.allowFixedCodeInProduction must be a boolean, got ${JSON.stringify(Y)}`);let J=HJ(W);if(J===null)return;let j=W?"auth.emailCode.fixedCode":"AUTH_FIXED_CODE",z=Bun.env.NODE_ENV==="production";if(z&&!TJ(Y))throw Error(`${j} is set, but a fixed sign-in code is for development and tests only and is refused when NODE_ENV=production. Unset it in this environment (a local production-build test server can opt in with AUTH_FIXED_CODE_ALLOW_PRODUCTION=1).`);if(J.trim()!==J||J.length>256)throw Error(`${j} must have no surrounding whitespace and at most 256 characters`);if(z&&Z)console.warn(bU)}function EU($={}){if(Bun.env.NODE_ENV==="production"&&!TJ($.allowFixedCodeInProduction))return null;return HJ($.fixedCode)}function MJ($){return AU("sha256").update($).digest()}function PJ($,Z={}){let W=EU(Z);if(W===null||typeof $!=="string"||$==="")return!1;return SU(MJ($),MJ(W))}async function g1($,Z){if(typeof $==="function")return await $({req:Z})===!0;return Boolean($)}function D5($){return $===!0||typeof $==="function"}function O5($={}){return{signIn:{perEmail:$.signIn?.perEmail??[10,900],perIp:$.signIn?.perIp??[50,900]},signUp:{perEmail:$.signUp?.perEmail??!1,perIp:$.signUp?.perIp??[10,3600]},forgot:{perEmail:$.forgot?.perEmail??[5,900],perIp:$.forgot?.perIp??[20,900]},reset:{perEmail:$.reset?.perEmail??!1,perIp:$.reset?.perIp??[20,900]}}}function T3($,Z,W,Y=1/0){if(!Number.isInteger(Z)||Z<W||Z>Y){let J=Y===1/0?`an integer of at least ${W}`:`an integer from ${W} to ${Y}`;throw Error(`auth.emailCode.${$} must be ${J}, got ${Z}`)}}function RU($={}){let Z=[["password",$?.password],["magicLink",$?.magicLink],["verifyEmail",$?.verifyEmail],["emailCode.enabled",$?.emailCode?.enabled]];for(let[W,Y]of Z)if(Y!==void 0&&typeof Y!=="boolean"&&typeof Y!=="function")throw Error(`auth.${W} must be true, false or a function of the request, got ${JSON.stringify(Y)}`)}function L5($={}){let Z=$.length??6,W=$.expiresInMinutes??10,Y=$.linkExpiresInMinutes??10080,J=$.maxAttempts??5,j=$.activeCodes??1;return T3("length",Z,4,12),T3("expiresInMinutes",W,1),T3("linkExpiresInMinutes",Y,1),T3("maxAttempts",J,1),T3("activeCodes",j,1,5),KJ($),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:W,linkExpiresInMinutes:Y,maxAttempts:J,activeCodes:j,requestLimit:{perEmail:$.requestLimit?.perEmail??[5,900],perIp:$.requestLimit?.perIp??[20,900]},verifyLimit:{perEmail:$.verifyLimit?.perEmail??[10,900],perIp:$.verifyLimit?.perIp??[50,900]},uniformMagicLinkResponse:$.uniformMagicLinkResponse??!1,send:$.send??(({email:z,code:X})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${z}: ${X} (set auth.emailCode.send to deliver it)`)}),fixedCode:$.fixedCode??null,allowFixedCodeInProduction:$.allowFixedCodeInProduction??null}}async function kU($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function NJ($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:W,enabled:Y}=$;return{provider:Z,...W!==void 0?{feature:W}:{},...Y!==void 0?{enabled:Y}:{}}}function _J($){for(let[Z,W]of Object.entries($??{})){if(typeof W?.getRedirectUrl==="function")continue;let Y=W;if(typeof Y?.provider?.getRedirectUrl!=="function")throw Error(`auth.oauthProviders.${Z} must be an OAuthProvider, or { provider, feature, enabled } with an OAuthProvider.`);if(Y.enabled!==void 0&&typeof Y.enabled!=="boolean"&&typeof Y.enabled!=="function")throw Error(`auth.oauthProviders.${Z}.enabled must be true, false or a function of the request.`);if(Y.feature!==void 0&&(typeof Y.feature!=="string"||Y.feature===""))throw Error(`auth.oauthProviders.${Z}.feature must be a feature key from app/features.`)}}function hN($){return $}function IJ($={}){return RU($),{basePath:"/auth",verifyEmail:!0,password:!0,passwordLimits:O5($.passwordLimits),magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:V5,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:kU,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>U5(32).toString("hex"),generateEmailVerificationToken:()=>{if($.verifyEmail===!1)return"";return U5(32).toString("hex")},generateMagicLinkToken:()=>U5(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:L5($.emailCode),generateCode:()=>{return},rateLimitKey:()=>{return},onAuthenticated:()=>{}}}var wU=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),fU=new Set(["svg","math"]);function CJ($){return $===32||$===9||$===10||$===12||$===13}function xJ($){return $>=65&&$<=90||$>=97&&$<=122}function f6($){return $>=65&&$<=90?$+32:$}function AJ(){let $="data",Z="",W=!1,Y="",J=0,j=0,z=!1,X=0,G=0,Q=()=>$==="data"&&X===0&&G===0,F=()=>{if(!W&&wU.has(Z)){$="rawText",Y=`</${Z}`,J=0,Z="";return}if($="data",Z==="template")if(W)X=Math.max(0,X-1);else X+=1;else if(fU.has(Z)){if(W)G=Math.max(0,G-1);else if(!z)G+=1}Z=""},V=(B)=>{switch($){case"data":if(B===60)$="tagOpen";return;case"tagOpen":if(B===33)$="bang",j=0;else if(B===47)$="endTagOpen";else if(xJ(B))$="tagName",W=!1,z=!1,Z=String.fromCharCode(f6(B));else if(B===63)$="bogus";else if(B===60)$="tagOpen";else $="data";return;case"endTagOpen":if(xJ(B))$="tagName",W=!0,z=!1,Z=String.fromCharCode(f6(B));else if(B===62)$="data";else $="bogus";return;case"tagName":if(CJ(B)||B===47)$="inTag",z=B===47;else if(B===62)F();else Z+=String.fromCharCode(f6(B));return;case"inTag":if(B===62){F();return}if(z=B===47,B===34)$="attrDouble";else if(B===39)$="attrSingle";return;case"attrDouble":if(B===34)$="inTag";z=!1;return;case"attrSingle":if(B===39)$="inTag";z=!1;return;case"bang":if(B===45){if(j+=1,j===2)$="comment",j=0}else if(B===62)$="data";else $="bogus";return;case"bogus":if(B===62)$="data";return;case"comment":if(B===45)j=j<2?j+1:2;else if(B===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(J<Y.length){if(f6(B)===Y.charCodeAt(J))J+=1;else J=B===60?1:0;return}if(B===62)$="data",Z="";else if(CJ(B)||B===47)$="inTag",Z="";else J=B===60?1:0;return}}};return{scanToInsertionPoint(B){for(let U=0;U<B.length;U++){if(Q())return U;V(B[U])}return B.length},write(B){for(let U=0;U<B.length;U++)V(B[U])},isSafe:Q}}function t0($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function SJ($){return $?`<script nonce="${$}">`:"<script>"}function qU($,Z){let W=t0([$.path,$.variantKey,$.data]);return`${SJ(Z)}(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${W})</script>`}function vU($,Z){let W=t0([$.id,$.locale,$.strings]);return`${SJ(Z)}(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${W})</script>`}function M5($,Z,W={},Y,J){let j=new TextEncoder,z=[],X=!1,G=!1,Q=()=>{if(G)return;G=!0,W.onClose?.()};Z.onSettle((D)=>{if(D.status!=="resolved")return;z.push(qU(D,J))}),Y?.onUse((D)=>{z.push(vU(D,J))});let F=$.getReader(),V=AJ(),B=(D,L)=>{D.enqueue(L),W.onChunk?.(L)},U=(D)=>{while(z.length>0){let L=j.encode(z.shift());V.write(L),B(D,L)}},O=(D,L)=>{if(z.length===0){V.write(L),B(D,L);return}let M=V.scanToInsertionPoint(L);if(M>0)B(D,L.subarray(0,M));if(V.isSafe())U(D);let T=L.subarray(M);if(T.length>0)V.write(T),B(D,T)};return new ReadableStream({async pull(D){let L;try{L=await F.read()}catch(K){throw Q(),K}let{done:M,value:T}=L;if(M){U(D),D.close(),Q();return}if(!X){if(X=!0,V.write(T),B(D,T),W.onShell?.(),V.isSafe())U(D);return}O(D,T)},cancel(D){return Q(),F.cancel(D)}})}var gU=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function q6($){if(!$)return!1;return gU.test($)}async function EJ($,Z=()=>{}){let W=P.getStore(),Y=W?.req??null,J=null;if(Y?.rawRequest?.url)try{J=new URL(Y.rawRequest.url).pathname}catch{J=null}return{user:W?.user??null,attributes:await yU($,Z),request:{path:J,routePath:Y?.routePath??null,locale:W?.locale??null},anonymousId:bJ(),isBot:q6(Y?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function RJ($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function yU($,Z){if(!$.context)return{};try{let W=P.getStore();return await $.context(W?.req??null)??{}}catch(W){return Z(`The \`context\` hook in app/config/features.ts threw; evaluating with no attributes. ${W instanceof Error?W.message:String(W)}`),{}}}function kJ($,Z){return`${$}:${Z}`}function H5($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),W=Number.parseInt(Z.slice(0,8),16);return Math.floor(W/4294967296*1e4)}function wJ($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function fJ($,Z,W,Y){if(Y.unavailable)return{value:!1,reason:"unavailable"};if(Y.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let j;try{j=Z.when(W)}catch(z){return Y.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(W.isBot)return{value:!1,reason:"bot"};let J=hU($,Z,W,Y.buckets);return wJ(J,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function mU($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function hU($,Z,W,Y){let J=kJ(Z.salt??$,mU(W));if(!Y)return H5(J);let j=Y.get(J);if(j!==void 0)return j;let z=H5(J);return Y.set(J,z),z}class qJ 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 T5{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,W,Y=()=>{}){this.source=$;this.declared=Z;this.ttlMs=W;this.warn=Y}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 qJ(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:W}=this.readRows($);return this.snapshot={active:Z,audit:W,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,W=new Map;for(let Y of $??[]){let J=typeof Y?.key==="string"?Y.key:null;if(!J){this.warn("Ignoring a feature row with no `key`.");continue}if(!(J in this.declared)){this.warn(`Feature row "${J}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(J,Y.active===!0);let j=pU(Y);if(j)W.set(J,j)}return{active:Z,audit:W}}handleFailure($){let Z=$ instanceof Error?$.message:String($),W=Date.now();if(this.lastError=$,this.retryAfter=W+this.ttlMs,W-this.lastFailureLoggedAt>=this.ttlMs)this.lastFailureLoggedAt=W,this.warn(`Could not load feature switches: ${Z}`);if(this.snapshot)return this.snapshot;return this.snapshot={active:new Map,audit:new Map,loadedAt:W,unavailable:!0},this.snapshot}}function pU($){let Z={},W=$.updatedBy;if(typeof W==="string")Z.updatedBy=W;else if(W===null)Z.updatedBy=null;let Y=$.updatedAt;if(Y instanceof Date||typeof Y==="string"||typeof Y==="number"){let J=Y instanceof Date?Y:new Date(Y);if(!Number.isNaN(J.getTime()))Z.updatedAt=J}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class cU{}class dU 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 K5 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 vJ 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 gJ{manager;ctx;constructor($,Z){this.manager=$;this.ctx=Z}async enabled($){return(await this.explain($)).value}async explain($){return await this.manager.evaluateIn($,this.ctx,new Map)}async all(){return await this.manager.evaluateAllIn(this.ctx,new Map,{clientOnly:!1})}}class j${config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new T5($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:W}=await this.switches();return{unavailable:W,features:Object.entries(this.declared).map(([Y,J])=>({key:Y,describe:J.describe,rollout:J.rollout,targeted:J.when!==void 0,serverOnly:J.serverOnly,salt:J.salt,active:$.get(Y),...Z.get(Y)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{P.getStore()?.featureEvaluations?.clear()}}async set($,Z,W={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new vJ(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let Y=uU(W.actor),J=this.config.source;if(typeof J.write!=="function")throw new K5(J.constructor?.name||"an anonymous source");let{actorRecorded:j}=await J.write($,Z,{actor:Y});if(Y!==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 gJ(this,RJ($))}async evaluateIn($,Z,W){let Y=this.memoFor(Z),J=Y?.get($);if(J)return J;let j=this.declared[$];if(!j)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),G=fJ($,j,Z,{active:z,unavailable:X,buckets:W,warn:this.log});return Y?.set($,G),this.notify($,G,Z),G}async evaluateAllIn($,Z,W){let Y={};for(let[J,j]of Object.entries(this.declared)){if(W.clientOnly&&j.serverOnly)continue;Y[J]=(await this.evaluateIn(J,$,Z)).value}return Y}async switches(){if(!this.config.enabled||Object.keys(this.declared).length===0)return{active:new Map,audit:new Map,unavailable:!1};let $=await this.store.get();return{active:$.active,audit:$.audit,unavailable:$.unavailable}}async switchFor($){if(!this.config.enabled)return{active:!1,unavailable:!1};let Z=await this.store.get();return{active:Z.active.get($),unavailable:Z.unavailable}}async requestContext(){let $=P.getStore();if($?.featureContext)return $.featureContext;let Z=await EJ(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=P.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=P.getStore();if(!$)return new Map;return $.featureBuckets??=new Map,$.featureBuckets}notify($,Z,W){if(!this.config.onEvaluate)return;try{this.config.onEvaluate($,Z,W)}catch(Y){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${Y instanceof Error?Y.message:String(Y)}`)}}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 uU($){if($===void 0||$===null)return null;if(typeof $==="string"){if($.length>0)return $}else if(typeof $==="object"){let{publicId:Z,id:W}=$;if(typeof Z==="string"&&Z.length>0)return Z;if(typeof W==="string"&&W.length>0||typeof W==="number")return String(W)}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 yJ($){if($===void 0)return!0;return await H(j$).enabled($)}function mJ(){try{return P.getStore()?.req??null}catch{return null}}async function xZ($,Z,W=mJ()){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let Y=NJ($[Z]);if(!Y||!await yJ(Y.feature))return null;if(Y.enabled!==void 0&&Y.enabled!==!0){if(typeof Y.enabled==="function"&&!W)return null;if(!await g1(Y.enabled,W))return null}let J=Y.provider;if(typeof J.isAvailable==="function"&&!await J.isAvailable(W))return null;return J}async function hJ($,Z=mJ()){let W=[];for(let Y of Object.keys($))if(await xZ($,Y,Z))W.push(Y);return W}function P5($){if($&&typeof $==="object")delete $.password;return $}function lU(){return new Proxy({},{get:($,Z)=>pJ(Z)})}function cJ($){if($&&typeof $==="object"){for(let Z of Object.values($))cJ(Z);Object.freeze($)}return $}var iU={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},sU=cJ({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:iU});class N5{models;constructor($=lU()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return sU}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let W=this.models.User.$connection??d$(),Y=H(u$).connection(W);return this.models.User.transaction(async()=>{if(Y.dialect==="postgres"){let J=`gemi:legacy-session:${$}`;await c$()`SELECT pg_advisory_xact_lock(hashtextextended(${J}, 0))`}return Z()})}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return P5(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return P5(Z)}async findUserByEmailAddress($,Z){return await this.run(()=>this.models.User.findUnique({where:Z?{email:$,emailVerifiedAt:{not:null}}:{email:$}}))}async findUserByVerificationToken($){if(typeof $!=="string"||$==="")return null;return await this.run(()=>this.models.User.findFirst({where:{verificationToken:$}}))}async verifyUser($){return await this.run(()=>this.models.User.update({where:{email:$},data:{emailVerifiedAt:new Date}}))}async createSession($){return await this.run(()=>this.models.Session.create({data:$,include:{user:!0}}))}async createSessionV2($){return await this.run(()=>this.models.Session.create({data:$,select:this.sessionSelect()}))}async findSession($){if(!$.token)return null;return await this.run(()=>this.models.Session.findUnique({where:{token:$.token},select:this.sessionSelect()}))}async updateSession($){return await this.run(()=>this.models.Session.update({where:{token:$.token},data:{expiresAt:$.expiresAt},select:this.sessionSelect()}))}async deleteSession($){if(!$.token)return;await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}))}async claimLegacySession($){if(!$.token)return!1;let{count:Z}=await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}));return Z>0}async deleteAllUserSessions($){await this.run(()=>this.models.Session.deleteMany({where:{userId:$}}))}async createPasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.create({data:{token:$.token,user:{connect:{id:$.user.id}}}}))}async findPasswordResetToken($){if(typeof $.token!=="string"||$.token==="")return null;return await this.run(()=>this.models.PasswordResetToken.findUnique({where:{token:$.token},include:{user:!0}}))}async deletePasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.delete({where:{token:$.token}}))}async findInvitation($,Z){if(typeof $!=="string"||typeof Z!=="string")return null;return await this.run(()=>this.models.OrganizationInvitation.findFirst({where:{publicId:$,email:Z}}))}async deleteInvitationById($){await this.run(()=>this.models.OrganizationInvitation.delete({where:{publicId:$}}))}async createAccount($){return await this.run(()=>this.models.Account.create({data:{userId:$.userId,organizationId:$.organizationId,organizationRole:$.organizationRole}}))}async createMagicLinkToken($){return await this.run(()=>this.models.MagicLinkToken.create({data:{email:$.email,token:$.token,pin:$.pin}}))}async findUserMagicLinkToken($){let Z=(W)=>typeof W==="string"&&W!=="";if(!Z($.email))return null;if($.token!==void 0&&!Z($.token))return null;if($.token===void 0&&!Z($.pin))return null;return await this.run(()=>$.token?this.models.MagicLinkToken.findUnique({where:{token_email:{token:$.token,email:$.email}}}):this.models.MagicLinkToken.findUnique({where:{pin_email:{pin:$.pin,email:$.email}}}))}async findMagicLinkTokenByEmail($){return await this.run(()=>this.models.MagicLinkToken.findFirst({where:{email:$},orderBy:{id:"desc"}}))}async listMagicLinkTokensByEmail($,Z){return await this.run(()=>this.models.MagicLinkToken.findMany({where:{email:$},orderBy:{id:"desc"},take:Z}))}async deleteMagicLinkTokensExcept($,Z){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$,id:{notIn:Z}}}))}async claimMagicLinkToken($){let{count:Z}=await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{id:$}}));return Z===1}async deleteMagicLinkToken($){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$}}))}async createSocialAccount($){return await this.run(()=>this.models.SocialAccount.create({data:$}))}async findUserBySocialAccount($,Z){if(!Z)return null;let W=await this.run(()=>this.models.SocialAccount.findFirst({where:{provider:$,providerId:Z},include:{user:!0}}));return W?P5(W.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:W}=await this.run(()=>this.models.SocialAccount.updateMany({where:{id:$.id,providerId:$.providerId},data:{providerId:Z}}));return W===1}}import{randomBytes as tL}from"crypto";function h0($,Z,W,Y,J){return Y1(Z,Jj($,Z),W,Y,J)}function Y1($,Z,W,Y,J,j){let z=A5(Z,W,Y);if(J&&Z!==z)throw RangeError(pX($,Z,W,Y,j));return z}function Jj($,Z){let W=$[Z];if(W===void 0)throw TypeError(WW(Z));return W}function H0($){return $!==null&&/object|function/.test(typeof $)}function d0($,Z=Map){let W=new Z;return(Y,...J)=>{if(W.has(Y))return W.get(Y);let j=$(Y,...J);return W.set(Y,j),j}}function q5($){return n$({name:$},1)}function n$($,Z){return X1((W)=>({value:W,configurable:1,writable:!Z}),$)}function jj($){return X1((Z)=>({get:Z,configurable:1}),$)}function t6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function wZ($,Z){let W={},Y=$.length;for(let J of Z)W[$[--Y]]=J;return W}function X1($,Z,W){let Y={};for(let J in Z)Y[J]=$(Z[J],J,W);return Y}function S3($,Z,W){let Y={};for(let J=0;J<Z.length;J++){let j=Z[J];Y[j]=$(j,J,W)}return Y}function nU($,Z,W){let Y={};for(let J=0;J<$.length;J++)Y[Z[J]]=W[$[J]];return Y}function l0($,Z){let W={};for(let Y of $)W[Y]=Z[Y];return W}function v5($,Z){let W={};for(let Y in Z)$.has(Y)||(W[Y]=Z[Y]);return W}function g5($){$={...$};let Z=Object.keys($);for(let W of Z)$[W]===void 0&&delete $[W];return $}function zj($,Z){for(let W of Z)if(!(W in $))return 0;return 1}function Xj($,Z,W){for(let Y of $)if(Z[Y]!==W[Y])return 0;return 1}function Gj($,Z,W){let Y={...W};for(let J=0;J<Z;J++)Y[$[J]]=0;return Y}function q($,...Z){return(...W)=>$(...Z,...W)}function dJ($){return $[0].toUpperCase()+$.substring(1)}function b3($){return $.slice().sort()}function c6($,Z){return String(Z).padStart($,"0")}function z$($,Z){return Math.sign($-Z)}function A5($,Z,W){return Math.min(Math.max($,Z),W)}function m1($,Z){return[Math.floor($/Z),P3($,Z)]}function P3($,Z){return($%Z+Z)%Z}function Q$($,Z){return[r6($,Z),y5($,Z)]}function r6($,Z){return Math.trunc($/Z)||0}function y5($,Z){return $%Z||0}function v6($){return Math.abs($%1)===0.5}function Qj($,Z,W){let Y=0,J=0;for(let X=0;X<=Z;X++){let G=$[W[X]],Q=K1[X],F=n/Q,[V,B]=Q$(G,F);Y+=B*Q,J+=V}let[j,z]=Q$(Y,n);return[J+j,z]}function e6($,Z,W){let Y={};for(let J=Z;J>=0;J--){let j=K1[J];Y[W[J]]=r6($,j),$=y5($,j)}return Y}function Bj($){return $===v?w4:[]}function Fj($){return $===v?m3:[]}function Vj($){return $===v?["year","day"]:[]}function Uj($){if($!==void 0)return Y0($)}function Dj($){if($!==void 0)return G1($)}function m5($){if($!==void 0)return E3($)}function G1($){return Mj(E3($))}function E3($){return Lj(mD($))}function h5($){if($==null)throw TypeError("Cannot be null or undefined");return $}function Oj($,Z){if(Z==null)throw RangeError(WW($));return Z}function p1($){if(!H0($))throw TypeError(hX);return $}function $4($,Z,W=$){if(typeof Z!==$)throw TypeError(v3(W,Z));return Z}function Lj($,Z="number"){if(!Number.isInteger($))throw RangeError(BD(Z,$));return $||0}function Mj($,Z="number"){if($<=0)throw RangeError(FD(Z,$));return $}function p5($){if(typeof $=="symbol")throw TypeError(OD);return String($)}function d6($,Z){return H0($)?String($):Y0($,Z)}function Z4($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(DD($));return $}function Hj($,Z="number"){if(typeof $=="bigint")throw TypeError(UD(Z));if($=Number($),!Number.isFinite($))throw RangeError(VD(Z,$));return $}function S0($,Z){return Math.trunc(Hj($,Z))||0}function Tj($,Z){return Lj(Hj($,Z),Z)}function uJ($,Z){return Mj(S0($,Z),Z)}function c5($,Z){let[W,Y]=Q$(Z,n),J=$+W,j=Math.sign(J);return j&&j===-Math.sign(Y)&&(J-=j,Y+=j*n),[J,Y]}function SZ($,Z,W=1){return c5($[0]+Z[0]*W,$[1]+Z[1]*W)}function bZ($,Z){return c5($[0],$[1]+Z)}function r0($,Z){return SZ(Z,$,-1)}function E0($,Z){return z$($[0],Z[0])||z$($[1],Z[1])}function Kj($,Z,W){return E0($,Z)===-1||E0($,W)===1}function W4($,Z=1){let W=BigInt(n/Z);return[Number($/W),Number($%W)*Z]}function EZ($,Z=1){let W=n/Z,[Y,J]=Q$($,W);return[Y,J*Z]}function Pj($,Z=1){let[W,Y]=$,J=Math.floor(Y/Z),j=n/Z;return BigInt(W)*BigInt(j)+BigInt(J)}function e0($,Z=1,W){let[Y,J]=$,[j,z]=Q$(J,Z);return Y*(n/Z)+(j+(W?z/Z:0))}function d5($,Z,W=m1){let[Y,J]=$,[j,z]=W(J,Z);return[Y*(n/Z)+j,z]}function u5($,Z){let W=$.formatToParts(Z),Y={};for(let J of W)Y[J.type]=J.value;return Y}function l5($){return h0($,"isoYear",A3,x3,1),$.isoYear===A3?h0($,"isoMonth",4,12,1):$.isoYear===x3&&h0($,"isoMonth",1,9,1),$}function X$($){return c1({...$,...z1,isoHour:12}),$}function c1($){let Z=h0($,"isoYear",A3,x3,1),W=Z===A3?1:Z===x3?-1:0;return W&&$1(b0({...$,isoDay:$.isoDay+W,isoNanosecond:$.isoNanosecond-W})),$}function $1($){if(!$||Kj($,iD,lD))throw RangeError(b4);return $}function B$($){return Qj($,5,V1)[1]}function Y4($){let[Z,W]=m1($,n);return[e6(W,5,V1),Z]}function Nj($){return _j($)[0]}function _j($){return d5($,j1)}function R0($){return fZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function b0($){let Z=R0($);if(Z!==void 0){let[W,Y]=Q$(Z,c0);return[W,Y*P1+($.isoMicrosecond||0)*YZ+($.isoNanosecond||0)]}}function i5($,Z){let[W,Y]=Y4(B$($)-Z);return $1(b0({...$,isoDay:$.isoDay+Y,...W}))}function u6(...$){return fZ(...$)/rX}function fZ(...$){let[Z,W]=Ij(...$),Y=Z.valueOf();if(!isNaN(Y))return Y-W*c0}function Ij($,Z=1,W=1,Y=0,J=0,j=0,z=0){let X=$===A3?1:$===x3?-1:0,G=new Date;return G.setUTCHours(Y,J,j,z),G.setUTCFullYear($,Z-1,W+X),[G,X]}function V$($,Z){let[W,Y]=bZ($,Z);Y<0&&(Y+=n,W-=1);let[J,j]=m1(Y,P1),[z,X]=m1(j,YZ);return J4(W*c0+J,z,X)}function J4($,Z=0,W=0){let Y=Math.ceil(Math.max(0,Math.abs($)-uD)/c0)*Math.sign($),J=new Date($-Y*c0);return wZ(q4,[J.getUTCFullYear(),J.getUTCMonth()+1,J.getUTCDate()+Y,J.getUTCHours(),J.getUTCMinutes(),J.getUTCSeconds(),J.getUTCMilliseconds(),Z,W])}function Cj($){return[$.isoYear,$.isoMonth,$.isoDay]}function xj(){return y1}function s5($,Z){switch(Z){case 2:return n5($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function Aj($){return n5($)?366:365}function n5($){return $%4==0&&($%100!=0||$%400==0)}function Sj($){let[Z,W]=Ij($.isoYear,$.isoMonth,$.isoDay);return P3(Z.getUTCDay()-W,7)||7}function bj({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function oU($){let Z=R0($);if(Z<nD)return bj($);let W=u5(KW(RZ),Z),{era:Y,eraYear:J}=hz(W,RZ);return[Y,J]}function j4($){return o$($),z4($,1),$}function o$($){return Ej($,1),$}function lJ($){return Xj(VW,$,Ej($))}function Ej($,Z){let{isoYear:W}=$,Y=h0($,"isoMonth",1,xj(),Z);return{isoYear:W,isoMonth:Y,isoDay:h0($,"isoDay",1,s5(W,Y),Z)}}function z4($,Z){return wZ(V1,[h0($,"isoHour",0,23,Z),h0($,"isoMinute",0,59,Z),h0($,"isoSecond",0,59,Z),h0($,"isoMillisecond",0,999,Z),h0($,"isoMicrosecond",0,999,Z),h0($,"isoNanosecond",0,999,Z)])}function m($){return $===void 0?0:OG(p1($))}function R3($,Z=0){$=Q1($);let W=LG($),Y=JO($,Z);return[OG($),Y,W]}function o5($){return LG(Q1($))}function Rj($){return $=Q1($),OW($,9,6,1)}function qZ($,Z,W,Y=9,J=0,j=4){Z=Q1(Z);let z=OW(Z,Y,J),X=r5(Z),G=p3(Z,j),Q=h3(Z,Y,J,1);return z==null?z=Math.max(W,Q):qj(z,Q),X=e5(X,Q,1),$&&(G=((F)=>F<4?(F+2)%4:F)(G)),[z,Q,X,G]}function X4($,Z=6,W){let Y=r5($=$7($,a6)),J=p3($,7),j=h3($,Z);return j=Oj(a6,j),Y=e5(Y,j,void 0,W),[j,Y,J]}function a5($){return LW(Q1($))}function kj($,Z){return t5(Q1($),Z)}function t5($,Z=4){let W=fj($);return[p3($,4),...wj(h3($,Z),W)]}function wj($,Z){return $!=null?[K1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function r5($){let Z=$[N3];return Z===void 0?1:S0(Z,N3)}function e5($,Z,W,Y){let J=Y?n:K1[Z+1];if(J){let j=K1[Z];if(J%(($=Y1(N3,$,1,J/j-(Y?0:1),1))*j))throw RangeError(v3(N3,$))}else $=Y1(N3,$,1,W?1e9:1,1);return $}function fj($){let Z=$[x5];if(Z!==void 0){if(typeof Z!="number"){if(p5(Z)==="auto")return;throw RangeError(v3(x5,Z))}Z=Y1(x5,Math.floor(Z),0,9,1)}return Z}function Q1($){return $===void 0?{}:p1($)}function $7($,Z){return typeof $=="string"?{[Z]:$}:p1($)}function G0($){if($!==void 0){if(H0($))return Object.assign(Object.create(null),$);throw TypeError(hX)}}function G4($,Z){return $&&Object.assign(Object.create(null),$,{overflow:aD[Z]})}function Z7($,Z,W=9,Y=0,J){let j=Z[$];if(j===void 0)return J?Y:void 0;if(j=p5(j),j==="auto")return J?Y:null;let z=R5[j];if(z===void 0&&(z=cD[j]),z===void 0)throw RangeError(uX($,j,R5));return Y1($,z,Y,W,1,y3),z}function a$($,Z,W,Y=0){let J=W[$];if(J===void 0)return Y;let j=p5(J),z=Z[j];if(z===void 0)throw RangeError(uX($,j,Z));return z}function qj($,Z){if(Z>$)throw RangeError(fD)}function T0($){return{branding:g4,epochNanoseconds:$}}function _0($,Z,W){return{branding:i1,calendar:W,timeZone:Z,epochNanoseconds:$}}function Q0($,Z=$.calendar){return{branding:jZ,calendar:Z,...l0(FG,$)}}function B0($,Z=$.calendar){return{branding:JZ,calendar:Z,...l0(UW,$)}}function i$($,Z=$.calendar){return{branding:dZ,calendar:Z,...l0(UW,$)}}function l6($,Z=$.calendar){return{branding:uZ,calendar:Z,...l0(UW,$)}}function B1($){return{branding:v4,...l0(BG,$)}}function $0($){return{branding:y4,sign:U$($),...l0(QW,$)}}function vj($){return Nj($.epochNanoseconds)}function Q4($){return d5($.epochNanoseconds,P1)[0]}function gj($){return Pj($.epochNanoseconds,YZ)}function yj($){return Pj($.epochNanoseconds)}function mj($){return $.epochNanoseconds}function P0($){return typeof $=="string"?$:Y0($.id)}function vZ($,Z){return $===Z||P0($)===P0(Z)}function hj($,Z,W,Y,J){let j=s$(Y),[z,X]=((L,M)=>{let T=M((L=$7(L,f5))[UG]),K=YO(L);return K=Oj(f5,K),[K,T]})(J,$);if(I3(Math.max(z,j),X))return iJ(Y,z);if(!X)throw RangeError(E4);let[G,Q,F]=O4(Z,W,X),V=C7(F),B=L4(F),U=x7(F),O=B(Q,G,Y),D=U(Q,G,O,z);return I3(z,X)?iJ(D,z):((L,M,T,K,N,_,x)=>{let b=U$(L),[w,A]=W7(K,FW(T,L),T,b,N,_,x),f=Y7(M,w,A);return L[p[T]]+f*b})(D,V(O),z,Q,G,V,B)}function iJ($,Z){return e0(M0($),K1[Z],1)}function W7($,Z,W,Y,J,j,z){let X=p[W],G={...Z,[X]:Z[X]+Y},Q=z($,J,Z),F=z($,J,G);return[j(Q),j(F)]}function Y7($,Z,W){let Y=e0(r0(Z,W));if(!Y)throw RangeError(g3);return e0(r0(Z,$))/Y}function pj($,Z){let[W,Y,J]=X4(Z,5,1);return T0(F4($.epochNanoseconds,W,Y,J,1))}function cj($,Z,W){let{epochNanoseconds:Y,timeZone:J,calendar:j}=Z,[z,X,G]=X4(W);if(z===0&&X===1)return Z;let Q=$(J);if(z===6)Y=((F,V,B,U)=>{let O=k0(B,V),[D,L]=F(O),M=B.epochNanoseconds,T=u0(V,D),K=u0(V,L);if(Kj(M,T,K))throw RangeError(g3);return tj(Y7(M,T,K),U)?K:T})(oj,Q,Z,G);else{let F=Q.getOffsetNanosecondsFor(Y);Y=r$(Q,sj(V$(Y,F),z,X,G),F,2,0,1)}return _0(Y,J,j)}function dj($,Z){return Q0(sj($,...X4(Z)),$.calendar)}function uj($,Z){let[W,Y,J]=X4(Z,5);var j;return B1((j=J,J7($,k3(W,Y),j)[0]))}function lj($,Z){let W=$(Z.timeZone),Y=k0(Z,W),[J,j]=oj(Y),z=e0(r0(u0(W,J),u0(W,j)),k4,1);if(z<=0)throw RangeError(g3);return z}function ij($,Z){let{timeZone:W,calendar:Y}=Z,J=((j,z,X)=>u0(z,j(k0(X,z))))(aj,$(W),Z);return _0(J,W,Y)}function sj($,Z,W,Y){return nj($,k3(Z,W),Y)}function nj($,Z,W){let[Y,J]=J7($,Z,W);return c1({...e$($,J),...Y})}function J7($,Z,W){return Y4(F$(B$($),Z,W))}function i6($){return F$($,R4,7)}function k3($,Z){return K1[$]*Z}function oj($){let Z=aj($);return[Z,e$(Z,1)]}function aj($){return dD(6,$)}function aU($,Z,W){let Y=Math.min(s$($),6);return yZ(V4(M0($,Y),Z,W),Y)}function B4($,Z,W,Y,J,j,z,X,G,Q){if(Y===0&&J===1)return $;let F=I3(Y,X)?M4(X)&&Y<6&&W>=6?rU:tU:eU,[V,B,U]=F($,Z,W,Y,J,j,z,X,G,Q);return U&&Y!==7&&(V=((O,D,L,M,T,K,N,_)=>{let x=U$(O);for(let b=M+1;b<=L;b++){if(b===7&&L!==7)continue;let w=FW(b,O);w[p[b]]+=x;let A=e0(r0(N(_(T,K,w)),D));if(A&&Math.sign(A)!==x)break;O=w}return O})(V,B,W,Math.max(6,Y),z,X,G,Q)),V}function F4($,Z,W,Y,J){if(Z===6){let j=((z)=>z[0]+z[1]/n)($);return[F$(j,W,Y),0]}return V4($,k3(Z,W),Y,J)}function V4($,Z,W,Y){let[J,j]=$;Y&&j<0&&(j+=n,J-=1);let[z,X]=m1(F$(j,Z,W),n);return c5(J+z,X)}function F$($,Z,W){return tj($/Z,W)*Z}function tj($,Z){return XO[Z]($)}function tU($,Z,W,Y,J,j){let z=U$($),X=M0($),G=F4(X,Y,J,j),Q=r0(X,G),F=Math.sign(G[0]-X[0])===z,V=yZ(G,Math.min(W,6));return[{...$,...V},SZ(Z,Q),F]}function rU($,Z,W,Y,J,j,z,X,G,Q){let F=U$($),V=e0(M0($,5)),B=k3(Y,J),U=F$(V,B,j),[O,D]=W7(z,{...$,...BW},6,F,X,G,Q),L=U-e0(r0(O,D)),M=0;L&&Math.sign(L)!==F?Z=bZ(O,U):(M+=F,U=F$(L,B,j),Z=bZ(D,U));let T=T4(U);return[{...$,...T,days:$.days+M},Z,Boolean(M)]}function eU($,Z,W,Y,J,j,z,X,G,Q){let F=U$($),V=p[Y],B=FW(Y,$);Y===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let U=r6($[V],J)*J;B[V]=U;let[O,D]=W7(z,B,Y,J*F,X,G,Q),L=U+Y7(Z,O,D)*F*J,M=F$(L,J,j),T=Math.sign(M-L)===F;return B[V]=M,[B,T?D:O,T]}function j7($,Z,W,Y){let[J,j,z,X]=((Q)=>{let F=t5(Q=Q1(Q));return[Q.timeZone,...F]})(Y),G=J!==void 0;return((Q,F,V,B,U,O)=>{V=V4(V,U,B,1);let D=F.getOffsetNanosecondsFor(V);return V7(V$(V,D),O)+(Q?t$(i6(D)):"Z")})(G,Z(G?$(J):zZ),W.epochNanoseconds,j,z,X)}function z7($,Z,W){let[Y,J,j,z,X,G]=((Q)=>{Q=Q1(Q);let F=LW(Q),V=fj(Q),B=zO(Q),U=p3(Q,4),O=h3(Q,4);return[F,jO(Q),B,U,...wj(O,V)]})(W);return((Q,F,V,B,U,O,D,L,M,T)=>{B=V4(B,M,L,1);let K=Q(V).getOffsetNanosecondsFor(B);return V7(V$(B,K),T)+t$(i6(K),D)+((N,_)=>_!==1?"["+(_===2?"!":"")+P0(N)+"]":"")(V,O)+U7(F,U)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,Y,J,j,z,X,G)}function X7($,Z){let[W,Y,J,j]=((Q)=>(Q=Q1(Q),[LW(Q),...t5(Q)]))(Z);return z=$.calendar,X=W,G=j,V7(nj($,J,Y),G)+U7(z,X);var z,X,G}function G7($,Z){return W=$.calendar,Y=$,J=a5(Z),s6(Y)+U7(W,J);var W,Y,J}function Q7($,Z){return rj($.calendar,ej,$,a5(Z))}function B7($,Z){return rj($.calendar,$D,$,a5(Z))}function F7($,Z){let[W,Y,J]=kj(Z);return j=J,$z(J7($,Y,W)[0],j);var j}function U4($,Z){let[W,Y,J]=kj(Z,3);return Y>1&&($={...$,...aU($,Y,W)}),((j,z)=>{let{sign:X}=j,G=X===-1?w0(j):j,{hours:Q,minutes:F}=G,[V,B]=d5(M0(G,3),j1,Q$);Gz(V);let U=D7(B,z),O=z>=0||!X||U;return(X<0?"-":"")+"P"+sJ({Y:l$(G.years),M:l$(G.months),W:l$(G.weeks),D:l$(G.days)})+(Q||F||V||O?"T"+sJ({H:l$(Q),M:l$(F),S:l$(V,O)+U}):"")})($,J)}function rj($,Z,W,Y){let J=P0($),j=Y>1||Y===0&&J!==v;return Y===1?J===v?Z(W):s6(W):j?s6(W)+Zz(J,Y===2):Z(W)}function sJ($){let Z=[];for(let W in $){let Y=$[W];Y&&Z.push(Y,W)}return Z.join("")}function V7($,Z){return s6($)+"T"+$z($,Z)}function s6($){return ej($)+"-"+J1($.isoDay)}function ej($){let{isoYear:Z}=$;return(Z<0||Z>9999?Wz(Z)+c6(6,Math.abs(Z)):c6(4,Z))+"-"+J1($.isoMonth)}function $D($){return J1($.isoMonth)+"-"+J1($.isoDay)}function $z($,Z){let W=[J1($.isoHour),J1($.isoMinute)];return Z!==-1&&W.push(J1($.isoSecond)+((Y,J,j,z)=>D7(Y*P1+J*YZ+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),W.join(":")}function t$($,Z=0){if(Z===1)return"";let[W,Y]=m1(Math.abs($),k4),[J,j]=m1(Y,R4),[z,X]=m1(j,j1);return Wz($)+J1(W)+":"+J1(J)+(z||X?":"+J1(z)+D7(X):"")}function U7($,Z){if(Z!==1){let W=P0($);if(Z>1||Z===0&&W!==v)return Zz(W,Z===2)}return""}function Zz($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function D7($,Z){let W=c6(9,$);return W=Z===void 0?W.replace(BO,""):W.slice(0,Z),W?"."+W:""}function Wz($){return $<0?"-":"+"}function l$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function ZD($,Z){let{epochNanoseconds:W}=$,Y=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(W),J=V$(W,Y);return{calendar:$.calendar,...J,offsetNanoseconds:Y}}function Yz($,Z){let W=k0(Z,$);return{calendar:Z.calendar,...l0(FG,W),offset:t$(W.offsetNanoseconds),timeZone:Z.timeZone}}function r$($,Z,W,Y=0,J=0,j,z){if(W!==void 0&&Y===1&&(Y===1||z))return i5(Z,W);let X=$.getPossibleInstantsFor(Z);if(W!==void 0&&Y!==3){let G=((Q,F,V,B)=>{let U=b0(F);B&&(V=i6(V));for(let O of Q){let D=e0(r0(O,U));if(B&&(D=i6(D)),D===V)return O}})(X,Z,W,j);if(G!==void 0)return G;if(Y===0)throw RangeError(SD)}return z?b0(Z):u0($,Z,J,X)}function u0($,Z,W=0,Y=$.getPossibleInstantsFor(Z)){if(Y.length===1)return Y[0];if(W===1)throw RangeError(bD);if(Y.length)return Y[W===3?1:0];let J=b0(Z),j=((X,G)=>{let Q=X.getOffsetNanosecondsFor(bZ(G,-n));return L7(X.getOffsetNanosecondsFor(bZ(G,n))-Q)})($,J),z=j*(W===2?-1:1);return(Y=$.getPossibleInstantsFor(V$(J,z)))[W===2?0:Y.length-1]}function O7($){if(Math.abs($)>=n)throw RangeError(xD);return $}function L7($){if($>n)throw RangeError(AD);return $}function M7($,Z,W){return T0($1(SZ(Z.epochNanoseconds,((Y)=>{if(Qz(Y))throw RangeError(kD);return M0(Y,5)})($?w0(W):W))))}function H7($,Z,W,Y,J,j=Object.create(null)){let z=Z(Y.timeZone),X=$(Y.calendar);return{...Y,..._7(z,X,Y,W?w0(J):J,j)}}function T7($,Z,W,Y,J=Object.create(null)){let{calendar:j}=W;return Q0(I7($(j),W,Z?w0(Y):Y,J),j)}function K7($,Z,W,Y,J){let{calendar:j}=W;return B0(D4($(j),W,Z?w0(Y):Y,J),j)}function P7($,Z,W,Y,J=Object.create(null)){let j=W.calendar,z=$(j),X=_3(z,W);Z&&(Y=H4(Y)),Y.sign<0&&(X=z.dateAdd(X,{...N0,months:1}),X=e$(X,-1));let G=z.dateAdd(X,Y,J);return i$(_3(z,G),j)}function N7($,Z,W){return B1(Jz(Z,$?w0(W):W)[0])}function _7($,Z,W,Y,J){let j=M0(Y,5),z=W.epochNanoseconds;if(Qz(Y)){let X=k0(W,$);z=SZ(u0($,{...D4(Z,X,{...Y,...BW},J),...l0(V1,X)}),j)}else z=SZ(z,j),m(J);return{epochNanoseconds:$1(z)}}function I7($,Z,W,Y){let[J,j]=Jz(Z,W);return c1({...D4($,Z,{...W,...BW,days:W.days+j},Y),...J})}function D4($,Z,W,Y){if(W.years||W.months||W.weeks)return $.dateAdd(Z,W,Y);m(Y);let J=W.days+M0(W,5)[0];return J?X$(e$(Z,J)):Z}function _3($,Z,W=1){return e$(Z,W-$.day(Z))}function Jz($,Z){let[W,Y]=M0(Z,5),[J,j]=Y4(B$($)+Y);return[J,W+j]}function e$($,Z){return Z?{...$,...J4(R0($)+Z*c0)}:$}function O4($,Z,W){let Y=$(W.calendar);return M4(W)?[W,Y,Z(W.timeZone)]:[{...W,...z1},Y]}function C7($){return $?mj:b0}function L4($){return $?q(_7,$):I7}function x7($){return $?q(YD,$):JD}function M4($){return $&&$.epochNanoseconds}function I3($,Z){return $<=6-(M4(Z)?1:0)}function A7($,Z,W,Y,J,j,z){let X=$(Q1(z).relativeTo),G=Math.max(s$(J),s$(j));if(I3(G,X))return $0(gZ(((D,L,M,T)=>{let K=SZ(M0(D),M0(L),T?-1:1);if(!Number.isFinite(K[0]))throw RangeError(b4);return{...N0,...yZ(K,M)}})(J,j,G,Y)));if(!X)throw RangeError(E4);Y&&(j=w0(j));let[Q,F,V]=O4(Z,W,X),B=L4(V),U=x7(V),O=B(F,Q,J);return $0(U(F,Q,B(F,O,j),G))}function jz($,Z,W,Y,J){let j=s$(Y),[z,X,G,Q,F]=((x,b,w)=>{x=$7(x,a6);let A=OW(x),f=w(x[UG]),I=r5(x),k=p3(x,7),K0=h3(x);if(A===void 0&&K0===void 0)throw RangeError(wD);return K0==null&&(K0=0),A==null&&(A=Math.max(K0,b)),qj(A,K0),I=e5(I,K0,1),[A,K0,I,k,f]})(J,j,$),V=Math.max(j,z);if(!M4(F)&&V<=6)return $0(gZ(((x,b,w,A,f)=>{let I=F4(M0(x),w,A,f);return{...N0,...yZ(I,b)}})(Y,z,X,G,Q)));if(!F)throw RangeError(E4);let[B,U,O]=O4(Z,W,F),D=C7(O),L=L4(O),M=x7(O),T=L(U,B,Y),K=M(U,B,T,z),N=Y.sign,_=U$(K);if(N&&_&&N!==_)throw RangeError(g3);return _&&(K=B4(K,D(T),z,X,G,Q,U,B,D,L)),$0(K)}function zz($){return $.sign===-1?H4($):$}function H4($){return $0(w0($))}function w0($){let Z={};for(let W of p)Z[W]=-1*$[W]||0;return Z}function Xz($){return!$.sign}function U$($,Z=p){let W=0;for(let Y of Z){let J=Math.sign($[Y]);if(J){if(W&&W!==J)throw RangeError(RD);W=J}}return W}function gZ($){for(let Z of pD)Y1(Z,$[Z],-$j,$j,1);return Gz(e0(M0($),j1)),$}function Gz($){if(!Number.isSafeInteger($))throw RangeError(ED)}function M0($,Z=6){return Qj($,Z,p)}function yZ($,Z=6){let[W,Y]=$,J=e6(Y,Z,p);if(J[p[Z]]+=W*(n/K1[Z]),!Number.isFinite(J[p[Z]]))throw RangeError(b4);return J}function T4($,Z=5){return e6($,Z,p)}function Qz($){return Boolean(U$($,QG))}function s$($){let Z=9;for(;Z>0&&!$[p[Z]];Z--);return Z}function WD($,Z){return[$,Z]}function nJ($){let Z=Math.floor($/h6)*h6;return[Z,Z+h6]}function Bz($){let Z=D$($=d6($));if(!Z)throw RangeError(p0($));let W;if(Z.m)W=0;else{if(!Z.offset)throw RangeError(p0($));W=mZ(Z.offset)}return Z.timeZone&&R7(Z.timeZone,1),T0(i5(j4(Z),W))}function Fz($){let Z=D$(Y0($));if(!Z)throw RangeError(p0($));if(Z.timeZone)return Kz(Z,Z.offset?mZ(Z.offset):void 0);if(Z.m)throw RangeError(p0($));return Nz(Z)}function Vz($,Z){let W=D$(Y0($));if(!W||!W.timeZone)throw RangeError(p0($));let{offset:Y}=W,J=Y?mZ(Y):void 0,[,j,z]=R3(Z);return Kz(W,J,j,z)}function mZ($){let Z=R7($);if(Z===void 0)throw RangeError(p0($));return Z}function Uz($){let Z=D$(Y0($));if(!Z||Z.m)throw RangeError(p0($));return Q0(Pz(Z))}function K4($){let Z=D$(Y0($));if(!Z||Z.m)throw RangeError(p0($));return B0(Z.p?Pz(Z):Nz(Z))}function Dz($,Z){let W=b7(Y0(Z));if(W)return S7(W),i$(l5(o$(W)));let Y=K4(Z);return i$(_3($(Y.calendar),Y))}function S7($){if($.calendar!==v)throw RangeError(h1($.calendar))}function Oz($,Z){let W=E7(Y0(Z));if(W)return S7(W),l6(o$(W));let Y=K4(Z),{calendar:J}=Y,j=$(J),[z,X,G]=j.h(Y),[Q,F]=j.I(z,X),[V,B]=j.N(Q,F,G);return l6(X$(j.P(V,B,G)),J)}function Lz($){let Z,W=((Y)=>{let J=OO.exec(Y);return J?(P4(J[10]),Cz(J)):void 0})(Y0($));if(!W){if(W=D$($),!W)throw RangeError(p0($));if(!W.p)throw RangeError(p0($));if(W.m)throw RangeError(h1("Z"));S7(W)}if((Z=b7($))&&lJ(Z))throw RangeError(p0($));if((Z=E7($))&&lJ(Z))throw RangeError(p0($));return B1(z4(W,1))}function Mz($){let Z=((W)=>{let Y=HO.exec(W);return Y?((J)=>{function j(F,V,B){let U=0,O=0;if(B&&([U,G]=m1(G,K1[B])),F!==void 0){if(X)throw RangeError(h1(F));O=((D)=>{let L=parseInt(D);if(!Number.isFinite(L))throw RangeError(h1(D));return L})(F),z=1,V&&(G=k7(V)*(K1[B]/j1),X=1)}return U+O}let z=0,X=0,G=0,Q={...wZ(p,[j(J[2]),j(J[3]),j(J[4]),j(J[5]),j(J[6],J[7],5),j(J[8],J[9],4),j(J[10],J[11],3)]),...e6(G,2,p)};if(!z)throw RangeError(cX(p));return w7(J[1])<0&&(Q=w0(Q)),Q})(Y):void 0})(Y0($));if(!Z)throw RangeError(p0($));return $0(gZ(Z))}function Hz($){let Z=D$($)||b7($)||E7($);return Z?Z.calendar:$}function Tz($){let Z=D$($);return Z&&(Z.timeZone||Z.m&&zZ||Z.offset)||$}function Kz($,Z,W=0,Y=0){let J=N4($.timeZone),j=m4(J);return _0(r$(j,j4($),Z,W,Y,!j.v,$.m),J,w3($.calendar))}function Pz($){return _z(c1(j4($)))}function Nz($){return _z(X$(o$($)))}function _z($){return{...$,calendar:w3($.calendar)}}function D$($){let Z=DO.exec($);return Z?((W)=>{let Y=W[10],J=(Y||"").toUpperCase()==="Z";return{isoYear:Iz(W),isoMonth:parseInt(W[4]),isoDay:parseInt(W[5]),...Cz(W.slice(5)),...P4(W[16]),p:Boolean(W[6]),m:J,offset:J?void 0:Y}})(Z):void 0}function b7($){let Z=VO.exec($);return Z?((W)=>({isoYear:Iz(W),isoMonth:parseInt(W[4]),isoDay:1,...P4(W[5])}))(Z):void 0}function E7($){let Z=UO.exec($);return Z?((W)=>({isoYear:kZ,isoMonth:parseInt(W[1]),isoDay:parseInt(W[2]),...P4(W[3])}))(Z):void 0}function R7($,Z){let W=LO.exec($);return W?((Y,J)=>{let j=Y[4]||Y[5];if(J&&j)throw RangeError(h1(j));return O7((AZ(Y[2])*k4+AZ(Y[3])*R4+AZ(Y[4])*j1+k7(Y[5]||""))*w7(Y[1]))})(W,Z):void 0}function Iz($){let Z=w7($[1]),W=parseInt($[2]||$[3]);if(Z<0&&!W)throw RangeError(h1(-0));return Z*W}function Cz($){let Z=AZ($[3]);return{...Y4(k7($[4]||""))[0],isoHour:AZ($[1]),isoMinute:AZ($[2]),isoSecond:Z===60?59:Z}}function P4($){let Z,W,Y=[];if($.replace(MO,(J,j,z)=>{let X=Boolean(j),[G,Q]=z.split("=").reverse();if(Q){if(Q==="u-ca")Y.push(G),Z||(Z=X);else if(X||/[A-Z]/.test(Q))throw RangeError(h1(J))}else{if(W)throw RangeError(h1(J));W=G}return""}),Y.length>1&&Z)throw RangeError(h1($));return{timeZone:W,calendar:Y[0]||v}}function k7($){return parseInt($.padEnd(9,"0"))}function hZ($){return new RegExp(`^${$}$`,"i")}function w7($){return $&&$!=="+"?-1:1}function AZ($){return $===void 0?0:parseInt($)}function xz($){return N4(Y0($))}function N4($){let Z=f7($);return typeof Z=="number"?t$(Z):Z?((W)=>{if(KO.test(W))throw RangeError(CD);return W.toLowerCase().split("/").map((Y,J)=>(Y.length<=3||/\d/.test(Y))&&!/etc|yap/.test(Y)?Y.toUpperCase():Y.replace(/baja|dumont|[a-z]+/g,(j,z)=>j.length<=2&&!J||j==="in"||j==="chat"?j.toUpperCase():j.length>2||!z?dJ(j).replace(/island|noronha|murdo|rivadavia|urville/,dJ):j)).join("/")})($):zZ}function oJ($){let Z=f7($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:zZ}function f7($){let Z=R7($=$.toUpperCase(),1);return Z!==void 0?Z:$!==zZ?TO($):void 0}function q7($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function v7($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function Az($,Z,W,Y,J,j){let z=$(Q1(j).relativeTo),X=Math.max(s$(Y),s$(J));if(Xj(p,Y,J))return 0;if(I3(X,z))return E0(M0(Y),M0(J));if(!z)throw RangeError(E4);let[G,Q,F]=O4(Z,W,z),V=C7(F),B=L4(F);return E0(V(B(Q,G,Y)),V(B(Q,G,J)))}function g7($,Z){return $Z($,Z)||_4($,Z)}function $Z($,Z){return z$(R0($),R0(Z))}function _4($,Z){return z$(B$($),B$(Z))}function Sz($,Z){return!q7($,Z)}function bz($,Z){return!v7($,Z)&&!!I4($.timeZone,Z.timeZone)&&vZ($.calendar,Z.calendar)}function Ez($,Z){return!g7($,Z)&&vZ($.calendar,Z.calendar)}function Rz($,Z){return!$Z($,Z)&&vZ($.calendar,Z.calendar)}function kz($,Z){return!$Z($,Z)&&vZ($.calendar,Z.calendar)}function wz($,Z){return!$Z($,Z)&&vZ($.calendar,Z.calendar)}function fz($,Z){return!_4($,Z)}function I4($,Z){if($===Z)return 1;let W=P0($),Y=P0(Z);if(W===Y)return 1;try{return oJ(W)===oJ(Y)}catch(J){}}function y7($,Z,W,Y){let J=qZ($,G0(Y),3,5),j=C4(Z.epochNanoseconds,W.epochNanoseconds,...J);return $0($?w0(j):j)}function m7($,Z,W,Y,J,j){let z=A4(Y.calendar,J.calendar),X=G0(j),[G,Q,F,V]=qZ(W,X,5),B=Y.epochNanoseconds,U=J.epochNanoseconds,O=E0(U,B),D;if(O)if(G<6)D=C4(B,U,G,Q,F,V);else{let L=Z(((T,K)=>{if(!I4(T,K))throw RangeError(nX);return T})(Y.timeZone,J.timeZone)),M=$(z);D=vz(M,L,Y,J,O,G,X),D=B4(D,U,G,Q,F,V,M,Y,mj,q(_7,L))}else D=N0;return $0(W?w0(D):D)}function h7($,Z,W,Y,J){let j=A4(W.calendar,Y.calendar),z=G0(J),[X,G,Q,F]=qZ(Z,z,6),V=b0(W),B=b0(Y),U=E0(B,V),O;if(U)if(X<=6)O=C4(V,B,X,G,Q,F);else{let D=$(j);O=gz(D,W,Y,U,X,z),O=B4(O,B,X,G,Q,F,D,W,b0,I7)}else O=N0;return $0(Z?w0(O):O)}function p7($,Z,W,Y,J){let j=A4(W.calendar,Y.calendar),z=G0(J);return qz(Z,()=>$(j),W,Y,...qZ(Z,z,6,9,6),z)}function c7($,Z,W,Y,J){let j=A4(W.calendar,Y.calendar),z=G0(J),X=qZ(Z,z,9,9,8),G=$(j);return qz(Z,()=>G,_3(G,W),_3(G,Y),...X,z)}function qz($,Z,W,Y,J,j,z,X,G){let Q=b0(W),F=b0(Y),V;if(E0(F,Q))if(J===6)V=C4(Q,F,J,j,z,X);else{let B=Z();V=B.dateUntil(W,Y,J,G),j===6&&z===1||(V=B4(V,F,J,j,z,X,B,W,b0,D4))}else V=N0;return $0($?w0(V):V)}function d7($,Z,W,Y){let J=G0(Y),[j,z,X,G]=qZ($,J,5,5),Q=F$(u7(Z,W),k3(z,X),G),F={...N0,...T4(Q,j)};return $0($?w0(F):F)}function YD($,Z,W,Y,J,j){let z=E0(Y.epochNanoseconds,W.epochNanoseconds);return z?J<6?yz(W.epochNanoseconds,Y.epochNanoseconds,J):vz(Z,$,W,Y,z,J,j):N0}function JD($,Z,W,Y,J){let j=b0(Z),z=b0(W),X=E0(z,j);return X?Y<=6?yz(j,z,Y):gz($,Z,W,X,Y,J):N0}function vz($,Z,W,Y,J,j,z){let[X,G,Q]=((B,U,O,D)=>{function L(){return b={...e$(K,_++*-D),...T},w=u0(B,b),E0(N,w)===-D}let M=k0(U,B),T=l0(V1,M),K=k0(O,B),N=O.epochNanoseconds,_=0,x=u7(M,K),b,w;if(Math.sign(x)===-D&&_++,L()&&(D===-1||L()))throw RangeError(g3);let A=e0(r0(w,N));return[M,b,A]})(Z,W,Y,J);var F,V;return{...j===6?(F=X,V=G,{...N0,days:mz(F,V)}):$.dateUntil(X,G,j,z),...T4(Q)}}function gz($,Z,W,Y,J,j){let[z,X,G]=((Q,F,V)=>{let B=F,U=u7(Q,F);return Math.sign(U)===-V&&(B=e$(F,-V),U+=n*V),[Q,B,U]})(Z,W,Y);return{...$.dateUntil(z,X,J,j),...T4(G)}}function C4($,Z,W,Y,J,j){return{...N0,...yZ(F4(r0($,Z),Y,J,j),W)}}function yz($,Z,W){return{...N0,...yZ(r0($,Z),W)}}function mz($,Z){return x4(R0($),R0(Z))}function x4($,Z){return Math.trunc((Z-$)/c0)}function u7($,Z){return B$(Z)-B$($)}function A4($,Z){if(!vZ($,Z))throw RangeError(jW);return $}function jD($){function Z(J){return((j,z)=>({...hz(j,z),F:j.month,day:parseInt(j.day)}))(u5(W,J),Y)}let W=KW($),Y=n6($);return{id:$,O:zD(Z),B:XD(Z)}}function zD($){return d0((Z)=>{let W=R0(Z);return $(W)},WeakMap)}function XD($){let Z=$(0).year-sD;return d0((W)=>{let Y,J=fZ(W-Z),j=[],z=[];do J+=400*c0;while((Y=$(J)).year<=W);do J+=(1-Y.day)*c0,Y.year===W&&(j.push(J),z.push(Y.F)),J-=c0;while((Y=$(J)).year>=W);return{k:j.reverse(),C:tX(z.reverse())}})}function hz($,Z){let W,Y,J=pz($);if($.era){let j=zG[Z];j!==void 0&&(W=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),W==="bc"||W==="b"?W="bce":W!=="ad"&&W!=="a"||(W="ce"),Y=J,J=iz(Y,j[W]||0))}return{era:W,eraYear:Y,year:J}}function pz($){return parseInt($.relatedYear||$.year)}function S5($){let{year:Z,F:W,day:Y}=this.O($),{C:J}=this.B(Z);return[Z,J[W]+1,Y]}function C3($,Z=1,W=1){return this.B($).k[Z-1]+(W-1)*c0}function g6($){let Z=tJ(this,$),W=tJ(this,$-1),Y=Z.length;if(Y>W.length){let J=sz(this);if(J<0)return-J;for(let j=0;j<Y;j++)if(Z[j]!==W[j])return j+1}}function y6($){return x4(C3.call(this,$),C3.call(this,$+1))}function aJ($,Z){let{k:W}=this.B($),Y=Z+1,J=W;return Y>W.length&&(Y=1,J=this.B($+1).k),x4(W[Z-1],J[Y-1])}function m6($){return this.B($).k.length}function tJ($,Z){return Object.keys($.B(Z).C)}function cz($){return w3(Y0($))}function w3($){if(($=$.toLowerCase())!==v&&$!==f4&&n6($)!==n6(KW($).resolvedOptions().calendar))throw RangeError(ID($));return $}function n6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function dz($){return this.R($)[0]}function uz($){return this.R($)[1]}function l7($){let[Z]=this.h($);return x4(this.q(Z),R0($))+1}function lz($){let Z=NO.exec($);if(!Z)throw RangeError(ND($));return[parseInt(Z[1]),Boolean(Z[2])]}function o6($,Z,W){return $+(Z||W&&$>=W?1:0)}function b5($,Z){return $-(Z&&$>=Z?1:0)}function iz($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function E5($){return zG[nz($)]}function sz($){return yD[nz($)]}function nz($){return n6($.id||v)}function oz($,Z,W,Y){let J=O$(W,Y,F1,[],WG);if(J.timeZone!==void 0){let j=W.dateFromFields(J),z=ZZ(J),X=$(J.timeZone);return{epochNanoseconds:r$(Z(X),{...j,...z},J.offset!==void 0?mZ(J.offset):void 0),timeZone:X}}return{...W.dateFromFields(J),...z1}}function az($,Z,W,Y,J,j){let z=O$(W,J,F1,$G,WG),X=$(z.timeZone),[G,Q,F]=R3(j),V=W.dateFromFields(z,G4(j,G)),B=ZZ(z,G);return _0(r$(Z(X),{...V,...B},z.offset!==void 0?mZ(z.offset):void 0,Q,F),X,Y)}function tz($,Z,W){let Y=O$($,Z,F1,[],l1),J=m(W);return Q0(c1({...$.dateFromFields(Y,G4(W,J)),...ZZ(Y,J)}))}function i7($,Z,W,Y=[]){let J=O$($,Z,F1,Y);return $.dateFromFields(J,W)}function s7($,Z,W,Y){let J=O$($,Z,GW,Y);return $.yearMonthFromFields(J,W)}function n7($,Z,W,Y,J=[]){let j=O$($,W,F1,J);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=kZ),$.monthDayFromFields(j,Y)}function rz($,Z){let W=m(Z);return B1(ZZ(T1($,k5,[],1),W))}function ez($){let Z=T1($,QW);return $0(gZ({...N0,...Z}))}function O$($,Z,W,Y=[],J=[]){return T1(Z,[...$.fields(W),...J].sort(),Y)}function T1($,Z,W,Y=!W){let J={},j,z=0;for(let X of Z){if(X===j)throw RangeError(LD(X));if(X==="constructor"||X==="__proto__")throw RangeError(YW(X));let G=$[X];if(G!==void 0)z=1,Zj[X]&&(G=Zj[X](G,X)),J[X]=G;else if(W){if(W.includes(X))throw TypeError(WW(X));J[X]=jG[X]}j=X}if(Y&&!z)throw TypeError(cX(Z));return J}function ZZ($,Z){return z4(xO({...jG,...$}),Z)}function $X($,Z,W,Y,J,j){let z=G0(j),{calendar:X,timeZone:G}=W;return _0(((Q,F,V,B,U)=>{let O=f3(Q,V,B,F1,ZG,eX),[D,L,M]=R3(U,2);return r$(F,{...Q.dateFromFields(O,G4(U,D)),...ZZ(O,D)},mZ(O.offset),L,M)})($(X),Z(G),Y,J,z),G,X)}function ZX($,Z,W,Y,J){let j=G0(J);return Q0(((z,X,G,Q)=>{let F=f3(z,X,G,F1,l1),V=m(Q);return c1({...z.dateFromFields(F,G4(Q,V)),...ZZ(F,V)})})($(Z.calendar),W,Y,j))}function WX($,Z,W,Y,J){let j=G0(J);return((z,X,G,Q)=>{let F=f3(z,X,G,F1);return z.dateFromFields(F,Q)})($(Z.calendar),W,Y,j)}function YX($,Z,W,Y,J){let j=G0(J);return i$(((z,X,G,Q)=>{let F=f3(z,X,G,GW);return z.yearMonthFromFields(F,Q)})($(Z.calendar),W,Y,j))}function JX($,Z,W,Y,J){let j=G0(J);return((z,X,G,Q)=>{let F=f3(z,X,G,F1);return z.monthDayFromFields(F,Q)})($(Z.calendar),W,Y,j)}function jX($,Z,W){return B1(((Y,J,j)=>{let z=m(j);return ZZ({...l0(k5,Y),...T1(J,k5)},z)})($,Z,W))}function zX($,Z){return $0((W=$,Y=Z,gZ({...W,...T1(Y,QW)})));var W,Y}function f3($,Z,W,Y,J=[],j=[]){let z=[...$.fields(Y),...J].sort(),X=T1(Z,z,j),G=T1(W,z);return X=$.mergeFields(X,G),T1(X,z,[])}function o7($,Z){let W=O$($,Z,JG);return $.monthDayFromFields(W)}function a7($,Z,W){let Y=O$($,Z,YG);return $.yearMonthFromFields(Y,W)}function XX($,Z,W,Y,J){Z=l0(W=$.fields(W),Z),Y=T1(Y,J=$.fields(J),[]);let j=$.mergeFields(Z,Y);return j=T1(j,[...W,...J].sort(),[]),$.dateFromFields(j)}function _5($,Z){let{era:W,eraYear:Y,year:J}=Z,j=E5($);if(W!==void 0||Y!==void 0){if(W===void 0||Y===void 0)throw TypeError(HD);if(!j)throw RangeError(MD);let z=j[W];if(z===void 0)throw RangeError(KD(W));let X=iz(Y,z);if(J!==void 0&&J!==X)throw RangeError(TD);J=X}else if(J===void 0)throw TypeError(PD(j));return J}function I5($,Z,W,Y){let{month:J,monthCode:j}=Z;if(j!==void 0){let z=((X,G,Q,F)=>{let V=X.U(Q),[B,U]=lz(G),O=o6(B,U,V);if(U){let D=sz(X);if(D===void 0)throw RangeError(K3);if(D>0){if(O>D)throw RangeError(K3);if(V===void 0){if(F===1)throw RangeError(K3);O--}}else{if(O!==-D)throw RangeError(K3);if(V===void 0&&F===1)throw RangeError(K3)}}return O})($,j,W,Y);if(J!==void 0&&J!==z)throw RangeError(iX);J=z,Y=1}else if(J===void 0)throw TypeError(_D);return Y1("month",J,1,$.L(W),Y)}function rJ($,Z,W,Y,J){return h0(Z,"day",1,$.j(Y,W),J)}function C5($,Z,W,Y){let J=0,j=[];for(let z of W)Z[z]!==void 0?J=1:j.push(z);if(Object.assign($,Z),J)for(let z of Y||j)delete $[z]}function GX($){return T0($1(W4(Z4($))))}function QX($,Z,W,Y,J=v){return _0($1(W4(Z4(W))),Z(Y),$(J))}function BX($,Z,W,Y,J=0,j=0,z=0,X=0,G=0,Q=0,F=v){return Q0(c1(j4(X1(S0,wZ(q4,[Z,W,Y,J,j,z,X,G,Q])))),$(F))}function FX($,Z,W,Y,J=v){return B0(X$(o$(X1(S0,{isoYear:Z,isoMonth:W,isoDay:Y}))),$(J))}function VX($,Z,W,Y=v,J=1){let j=S0(Z),z=S0(W),X=$(Y);return i$(l5(o$({isoYear:j,isoMonth:z,isoDay:S0(J)})),X)}function UX($,Z,W,Y=v,J=kZ){let j=S0(Z),z=S0(W),X=$(Y);return l6(X$(o$({isoYear:S0(J),isoMonth:j,isoDay:z})),X)}function DX($=0,Z=0,W=0,Y=0,J=0,j=0){return B1(z4(X1(S0,wZ(V1,[$,Z,W,Y,J,j])),1))}function OX($=0,Z=0,W=0,Y=0,J=0,j=0,z=0,X=0,G=0,Q=0){return $0(gZ(X1(Tj,wZ(p,[$,Z,W,Y,J,j,z,X,G,Q]))))}function t7($,Z,W=v){return _0($.epochNanoseconds,Z,W)}function LX($){return T0($.epochNanoseconds)}function r7($,Z){return Q0(k0(Z,$))}function e7($,Z){return B0(k0(Z,$))}function MX($,Z,W){return a7($(Z.calendar),W)}function HX($,Z,W){return o7($(Z.calendar),W)}function $W($,Z){return B1(k0(Z,$))}function TX($,Z,W,Y){let J=((j,z,X,G)=>{let Q=o5(G);return u0(j(z),X,Q)})($,W,Z,Y);return _0($1(J),W,Z.calendar)}function KX($,Z,W){let Y=$(Z.calendar);return i$({...Z,...a7(Y,W)})}function PX($,Z,W){return o7($(Z.calendar),W)}function NX($,Z,W,Y,J){let j=$(J.timeZone),z=J.plainTime,X=z!==void 0?Z(z):z1;return _0(u0(W(j),{...Y,...X}),j,Y.calendar)}function _X($,Z=z1){return Q0(c1({...$,...Z}))}function IX($,Z,W){return a7($(Z.calendar),W)}function CX($,Z,W){return o7($(Z.calendar),W)}function xX($,Z,W,Y){return((J,j,z)=>XX(J,j,YG,p1(z),m3))($(Z.calendar),W,Y)}function AX($,Z,W,Y){return((J,j,z)=>XX(J,j,JG,p1(z),w4))($(Z.calendar),W,Y)}function SX($,Z,W,Y,J){let j=p1(J),z=Z(j.plainDate),X=$(j.timeZone);return _0(u0(W(X),{...z,...Y}),X,z.calendar)}function bX($,Z){return Q0(c1({...$,...Z}))}function EX($){return T0($1(EZ($,j1)))}function RX($){return T0($1(EZ($,P1)))}function kX($){return T0($1(W4(Z4($),YZ)))}function wX($){return T0($1(W4(Z4($))))}function fX($,Z,W=z1){let Y=Z.timeZone,J=$(Y),j={...k0(Z,J),...W};return _0(r$(J,j,j.offsetNanoseconds,2),Y,Z.calendar)}function qX($,Z,W){let Y=Z.timeZone,J=$(Y),j={...k0(Z,J),...W},z=mX(Z.calendar,W.calendar);return _0(r$(J,j,j.offsetNanoseconds,2),Y,z)}function vX($,Z=z1){return Q0({...$,...Z})}function gX($,Z){return Q0({...$,...Z},mX($.calendar,Z.calendar))}function S4($,Z){return{...$,calendar:Z}}function yX($,Z){return{...$,timeZone:Z}}function mX($,Z){if($===Z)return $;let W=P0($),Y=P0(Z);if(W===Y||W===v)return Z;if(Y===v)return $;throw RangeError(jW)}function GD($,Z){return(W)=>W===v?$:W===f4||W===RZ?Object.assign(Object.create($),{id:W}):Object.assign(Object.create(Z),PO(W))}function WZ($,Z,W){let Y=new Set(W);return(J)=>(((j,z)=>{for(let X of z)if(X in j)return 1;return 0})(J=v5(Y,J),$)||Object.assign(J,Z),W&&(J.timeZone=zZ,["full","long"].includes(J.timeStyle)&&(J.timeStyle="medium")),J)}function d1($,Z=ZW){let[W,,,Y]=$;return(J,j=cO,...z)=>{let X=Z(Y&&Y(...z),J,j,W),G=X.resolvedOptions();return[X,...QD($,G,z)]}}function ZW($,Z,W,Y){if(W=Y(W),$){if(W.timeZone!==void 0)throw TypeError(qD);W.timeZone=$}return new L$(Z,W)}function QD($,Z,W){let[,Y,J]=$;return W.map((j)=>(j.calendar&&((z,X,G)=>{if((G||z!==v)&&z!==X)throw RangeError(jW)})(P0(j.calendar),Z.calendar,J),Y(j,Z)))}function pZ($){let Z=q3();return V$(Z,$.getOffsetNanosecondsFor(Z))}function q3(){return EZ(Date.now(),P1)}function u1(){return Yj||(Yj=new L$().resolvedOptions().timeZone)}var BD=($,Z)=>`Non-integer ${$}: ${Z}`,FD=($,Z)=>`Non-positive ${$}: ${Z}`,VD=($,Z)=>`Non-finite ${$}: ${Z}`,UD=($)=>`Cannot convert bigint to ${$}`,DD=($)=>`Invalid bigint: ${$}`,OD="Cannot convert Symbol to string",hX="Invalid object",pX=($,Z,W,Y,J)=>J?pX($,J[Z],J[W],J[Y]):v3($,Z)+`; must be between ${W}-${Y}`,v3=($,Z)=>`Invalid ${$}: ${Z}`,WW=($)=>`Missing ${$}`,YW=($)=>`Invalid field ${$}`,LD=($)=>`Duplicate field ${$}`,cX=($)=>"No valid fields: "+$.join(),dX="Invalid bag",uX=($,Z,W)=>v3($,Z)+"; must be "+Object.keys(W).join(),lX="Cannot use valueOf",JW="Invalid calling context",MD="Forbidden era/eraYear",HD="Mismatching era/eraYear",TD="Mismatching year/eraYear",KD=($)=>`Invalid era: ${$}`,PD=($)=>"Missing year"+($?"/era/eraYear":""),ND=($)=>`Invalid monthCode: ${$}`,iX="Mismatching month/monthCode",_D="Missing month/monthCode",eJ="Cannot guess year",K3="Invalid leap month",sX="Invalid protocol",g3="Invalid protocol results",jW="Mismatching Calendars",ID=($)=>`Invalid Calendar: ${$}`,nX="Mismatching TimeZones",CD="Forbidden ICU TimeZone",xD="Out-of-bounds offset",AD="Out-of-bounds TimeZone gap",SD="Invalid TimeZone offset",bD="Ambiguous offset",b4="Out-of-bounds date",ED="Out-of-bounds duration",RD="Cannot mix duration signs",E4="Missing relativeTo",kD="Cannot use large units",wD="Required smallestUnit or largestUnit",fD="smallestUnit > largestUnit",p0=($)=>`Cannot parse: ${$}`,h1=($)=>`Invalid substring: ${$}`,oX=($)=>`Cannot format ${$}`,aX="Mismatching types for formatting",qD="Cannot specify TimeZone",tX=q(S3,($,Z)=>Z),cZ=q(S3,($,Z,W)=>W),J1=q(c6,2),R5={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},y3=Object.keys(R5),c0=86400000,rX=1000,YZ=1000,P1=1e6,j1=1e9,R4=60000000000,k4=3600000000000,n=86400000000000,K1=[1,YZ,P1,j1,R4,k4,n],l1=y3.slice(0,6),k5=b3(l1),eX=["offset"],$G=["timeZone"],ZG=l1.concat(eX),WG=ZG.concat($G),w5=["era","eraYear"],vD=w5.concat(["year"]),w4=["year"],zW=["monthCode"],XW=["month"].concat(zW),m3=["day"],GW=XW.concat(w4),YG=zW.concat(w4),F1=m3.concat(GW),gD=m3.concat(XW),JG=m3.concat(zW),jG=cZ(l1,0),v="iso8601",f4="gregory",RZ="japanese",zG={[f4]:{bce:-1,ce:0},[RZ]:{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}},yD={chinese:13,dangi:13,hebrew:-6},Y0=q($4,"string"),XG=q($4,"boolean"),mD=q($4,"number"),GG=q($4,"function"),p=y3.map(($)=>$+"s"),QW=b3(p),hD=p.slice(0,6),QG=p.slice(6),pD=QG.slice(1),cD=tX(p),N0=cZ(p,0),BW=cZ(hD,0),FW=q(Gj,p),V1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],VW=["isoDay","isoMonth","isoYear"],q4=V1.concat(VW),UW=b3(VW),BG=b3(V1),FG=b3(q4),z1=cZ(BG,0),dD=q(Gj,q4),L$=Intl.DateTimeFormat,VG="en-GB",DW=1e8,uD=DW*c0,lD=[DW,0],iD=[-DW,0],x3=275760,A3=-271821,sD=1970,kZ=1972,y1=12,nD=fZ(1868,9,8),oD=d0(oU,WeakMap),a6="smallestUnit",f5="unit",N3="roundingIncrement",x5="fractionalSecondDigits",UG="relativeTo",DG={constrain:0,reject:1},aD=Object.keys(DG),tD={compatible:0,reject:1,earlier:2,later:3},rD={reject:0,use:1,prefer:2,ignore:3},eD={auto:0,never:1,critical:2,always:3},$O={auto:0,never:1,critical:2},ZO={auto:0,never:1},WO={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},h3=q(Z7,a6),OW=q(Z7,"largestUnit"),YO=q(Z7,f5),OG=q(a$,"overflow",DG),LG=q(a$,"disambiguation",tD),JO=q(a$,"offset",rD),LW=q(a$,"calendarName",eD),jO=q(a$,"timeZoneName",$O),zO=q(a$,"offset",ZO),p3=q(a$,"roundingMode",WO),dZ="PlainYearMonth",uZ="PlainMonthDay",JZ="PlainDate",jZ="PlainDateTime",v4="PlainTime",i1="ZonedDateTime",g4="Instant",y4="Duration",XO=[Math.floor,($)=>v6($)?Math.floor($):Math.round($),Math.ceil,($)=>v6($)?Math.ceil($):Math.round($),Math.trunc,($)=>v6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>v6($)?($=Math.trunc($)||0)+$%2:Math.round($)],zZ="UTC",h6=5184000,GO=u6(1847),QO=u6(new Date().getUTCFullYear()+10),BO=/0+$/,k0=d0(ZD,WeakMap),$j=4294967295,m4=d0(($)=>{let Z=f7($);return typeof Z=="object"?new HG(Z):new MG(Z||0)});class MG{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[i5($,this.v)]}l(){}}class HG{constructor($){this.$=((Z)=>{function W(G){let Q=A5(G,z,X),[F,V]=nJ(Q),B=J(F),U=J(V);return B===U?B:Y(j(F,V),B,U,G)}function Y(G,Q,F,V){let B,U;for(;(V===void 0||(B=V<G[0]?Q:V>=G[1]?F:void 0)===void 0)&&(U=G[1]-G[0]);){let O=G[0]+Math.floor(U/2);Z(O)===F?G[1]=O:G[0]=O+1}return B}let J=d0(Z),j=d0(WD),z=GO,X=QO;return{G(G){let Q=W(G-86400),F=W(G+86400),V=G-Q,B=G-F;if(Q===F)return[V];let U=W(V);return U===W(B)?[G-U]:Q>F?[V,B]:[]},V:W,l(G,Q){let F=A5(G,z,X),[V,B]=nJ(F),U=h6*Q,O=Q<0?()=>B>z||(z=F,0):()=>V<X||(X=F,0);for(;O();){let D=J(V),L=J(B);if(D!==L){let M=j(V,B);Y(M,D,L);let T=M[0];if((z$(T,G)||1)===Q)return T}V+=U,B+=U}}}})(((Z)=>(W)=>{let Y=u5(Z,W*rX);return u6(pz(Y),parseInt(Y.month),parseInt(Y.day),parseInt(Y.hour),parseInt(Y.minute),parseInt(Y.second))-W})($))}getOffsetNanosecondsFor($){return this.$.V(Nj($))*j1}getPossibleInstantsFor($){let[Z,W]=[u6((Y=$).isoYear,Y.isoMonth,Y.isoDay,Y.isoHour,Y.isoMinute,Y.isoSecond),Y.isoMillisecond*P1+Y.isoMicrosecond*YZ+Y.isoNanosecond];var Y;return this.$.G(Z).map((J)=>$1(bZ(EZ(J,j1),W)))}l($,Z){let[W,Y]=_j($),J=this.$.l(W+(Z>0||Y?1:0),Z);if(J!==void 0)return EZ(J,j1)}}var MW="([+\u2212-])",p6="(?:[.,](\\d{1,9}))?",TG=`(?:(?:${MW}(\\d{6}))|(\\d{4}))-?(\\d{2})`,HW="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+p6+")?)?",TW=MW+HW,FO=TG+"-?(\\d{2})(?:[T ]"+HW+"(Z|"+TW+")?)?",KG="\\[(!?)([^\\]]*)\\]",h4=`((?:${KG}){0,9})`,VO=hZ(TG+h4),UO=hZ("(?:--)?(\\d{2})-?(\\d{2})"+h4),DO=hZ(FO+h4),OO=hZ("T?"+HW+"(?:"+TW+")?"+h4),LO=hZ(TW),MO=new RegExp(KG,"g"),HO=hZ(`${MW}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${p6}H)?(?:(\\d+)${p6}M)?(?:(\\d+)${p6}S)?)?`),TO=d0(($)=>new L$(VG,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),KO=/^(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$/,PO=d0(jD),KW=d0(($)=>new L$(VG,{calendar:$,timeZone:zZ,era:"short",year:"numeric",month:"short",day:"numeric"})),NO=/^M(\d{2})(L?)$/,_O={era:d6,eraYear:S0,year:S0,month:uJ,monthCode:d6,day:uJ},IO=cZ(l1,S0),CO=cZ(p,Tj),Zj=Object.assign({},_O,IO,CO,{offset:d6}),xO=q(nU,l1,V1),Wj={dateAdd($,Z,W){let Y=m(W),J,{years:j,months:z,weeks:X,days:G}=Z;if(G+=M0(Z,5)[0],j||z)J=((Q,F,V,B,U)=>{let[O,D,L]=Q.h(F);if(V){let[M,T]=Q.I(O,D);O+=V,D=o6(M,T,Q.U(O)),D=Y1("month",D,1,Q.L(O),U)}return B&&([O,D]=Q._(O,D,B)),L=Y1("day",L,1,Q.j(O,D),U),Q.q(O,D,L)})(this,$,j,z,Y);else{if(!X&&!G)return $;J=R0($)}return J+=(7*X+G)*c0,X$(J4(J))},dateUntil($,Z,W){if(W<=7){let G=0,Q=mz({...$,...z1},{...Z,...z1});return W===7&&([G,Q]=Q$(Q,7)),{...N0,weeks:G,days:Q}}let Y=this.h($),J=this.h(Z),[j,z,X]=((G,Q,F,V,B,U,O)=>{let D=B-Q,L=U-F,M=O-V;if(D||L){let T=Math.sign(D||L),K=G.j(B,U),N=0;if(Math.sign(M)===-T){let _=K;[B,U]=G._(B,U,-T),D=B-Q,L=U-F,K=G.j(B,U),N=T<0?-_:K}if(M=O-Math.min(V,K)+N,D){let[_,x]=G.I(Q,F),[b,w]=G.I(B,U);if(L=b-_||Number(w)-Number(x),Math.sign(L)===-T){let A=T<0&&-G.L(B);D=(B-=T)-Q,L=U-o6(_,x,G.U(B))+(A||G.L(B))}}}return[D,L,M]})(this,...Y,...J);return W===8&&(z+=this.J(j,Y[0]),j=0),{...N0,years:j,months:z,days:X}},dateFromFields($,Z){let W=m(Z),Y=_5(this,$),J=I5(this,$,Y,W),j=rJ(this,$,J,Y,W);return B0(X$(this.P(Y,J,j)),this.id||v)},yearMonthFromFields($,Z){let W=m(Z),Y=_5(this,$),J=I5(this,$,Y,W);return i$(l5(this.P(Y,J,1)),this.id||v)},monthDayFromFields($,Z){let W=m(Z),Y=!this.id,{monthCode:J,year:j,month:z}=$,X,G,Q,F,V;if(J!==void 0){[X,G]=lz(J),V=Jj($,"day");let B=this.N(X,G,V);if(!B)throw RangeError(eJ);if([Q,F]=B,z!==void 0&&z!==F)throw RangeError(iX);Y&&(F=Y1("month",F,1,y1,1),V=Y1("day",V,1,s5(j!==void 0?j:Q,F),W))}else{Q=j===void 0&&Y?kZ:_5(this,$),F=I5(this,$,Q,W),V=rJ(this,$,F,Q,W);let B=this.U(Q);G=F===B,X=b5(F,B);let U=this.N(X,G,V);if(!U)throw RangeError(eJ);[Q,F]=U}return l6(X$(this.P(Q,F,V)),this.id||v)},fields($){return E5(this)&&$.includes("year")?[...$,...w5]:$},mergeFields($,Z){let W=Object.assign(Object.create(null),$);return C5(W,Z,XW),E5(this)&&(C5(W,Z,vD),this.id===RZ&&C5(W,Z,gD,w5)),W},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,W]=this.h($);return this.j(Z,W)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:l7,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,W]=this.h($),[Y,J]=this.I(Z,W);return((j,z)=>"M"+J1(j)+(z?"L":""))(Y,J)},dayOfWeek:Sj,daysInWeek(){return 7}},AO={dayOfYear:l7,h:Cj,q:fZ},SO=Object.assign({},AO,{weekOfYear:dz,yearOfWeek:uz,R($){function Z(U){return(7-U<Y?7:0)-U}function W(U){let O=Aj(B+U),D=U||1,L=Z(P3(G+O*D,7));return F=(O+(L-Q)*D)/7}let Y=this.id?1:4,J=Sj($),j=this.dayOfYear($),z=P3(J-1,7),X=j-1,G=P3(z-X,7),Q=Z(G),F,V=Math.floor((X-Q)/7)+1,B=$.isoYear;return V?V>W(0)&&(V=1,B++):(V=W(-1),B--),[V,B,F]}}),bO={dayOfYear:l7,h:S5,q:C3,weekOfYear:dz,yearOfWeek:uz,R(){return[]}},lZ=GD(Object.assign({},Wj,SO,{h:Cj,ee($){return this.id===f4?bj($):this.id===RZ?oD($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[kZ,$]},K:n5,U(){},L:xj,J:($)=>$*y1,j:s5,X:Aj,P:($,Z,W)=>({isoYear:$,isoMonth:Z,isoDay:W}),q:fZ,_:($,Z,W)=>($+=r6(W,y1),(Z+=y5(W,y1))<1?($--,Z+=y1):Z>y1&&($++,Z-=y1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},Wj,bO,{h:S5,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let W=g6.call(this,$);return[b5(Z,W),W===Z]},N($,Z,W){let[Y,J,j]=S5.call(this,{isoYear:kZ,isoMonth:y1,isoDay:31}),z=g6.call(this,Y),X=J===z;(z$($,b5(J,z))||z$(Number(Z),Number(X))||z$(W,j))===1&&Y--;for(let G=0;G<100;G++){let Q=Y-G,F=g6.call(this,Q),V=o6($,Z,F);if(Z===(V===F)&&W<=aJ.call(this,Q,V))return[Q,V]}},K($){let Z=y6.call(this,$);return Z>y6.call(this,$-1)&&Z>y6.call(this,$+1)},U:g6,L:m6,J($,Z){let W=Z+$,Y=Math.sign($),J=Y<0?-1:0,j=0;for(let z=Z;z!==W;z+=Y)j+=m6.call(this,z+J);return j},j:aJ,X:y6,P($,Z,W){return J4(C3.call(this,$,Z,W))},q:C3,_($,Z,W){if(W){if(Z+=W,!Number.isSafeInteger(Z))throw RangeError(b4);if(W<0)for(;Z<1;)Z+=m6.call(this,--$);else{let Y;for(;Z>(Y=m6.call(this,$));)Z-=Y,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:W}=this.O($),{C:Y}=this.B(Z);return Y[W]+1},day($){return this.O($).day}})),G$="numeric",iZ=["timeZoneName"],PG={month:G$,day:G$},PW={year:G$,month:G$},NW=Object.assign({},PW,{day:G$}),_W={hour:G$,minute:G$,second:G$},IW=Object.assign({},NW,_W),EO=Object.assign({},IW,{timeZoneName:"short"}),RO=Object.keys(PW),kO=Object.keys(PG),wO=Object.keys(NW),fO=Object.keys(_W),CW=["dateStyle"],qO=RO.concat(CW),vO=kO.concat(CW),xW=wO.concat(CW,["weekday"]),c3=fO.concat(["dayPeriod","timeStyle"]),AW=xW.concat(c3),gO=AW.concat(iZ),yO=iZ.concat(c3),mO=iZ.concat(xW),hO=iZ.concat(["day","weekday"],c3),pO=iZ.concat(["year","weekday"],c3),cO={},SW=[WZ(AW,IW),Q4],NG=[WZ(gO,EO),Q4,0,($,Z)=>{let W=P0($.timeZone);if(Z&&P0(Z.timeZone)!==W)throw RangeError(nX);return W}],bW=[WZ(AW,IW,iZ),R0],EW=[WZ(xW,NW,yO),R0],RW=[WZ(c3,_W,mO),($)=>B$($)/P1],kW=[WZ(qO,PW,hO),R0,1],wW=[WZ(vO,PG,pO),R0,1],Yj;function I1($,Z,W,Y,J){function j(...G){if(!(this instanceof j))throw TypeError(JW);xG(this,Z(...G))}function z(G,Q){return Object.defineProperties(function(...F){return G.call(this,X(this),...F)},q5(Q))}function X(G){let Q=x0(G);if(!Q||Q.branding!==$)throw TypeError(JW);return Q}return Object.defineProperties(j.prototype,{...jj(X1(z,W)),...n$(X1(z,Y)),...t6("Temporal."+$)}),Object.defineProperties(j,{...n$(J),...q5($)}),[j,(G)=>{let Q=Object.create(j.prototype);return xG(Q,G),Q},X]}function bG($){return $=$.concat("id").sort(),(Z)=>{if(!zj(Z,$))throw TypeError(sX);return Z}}function aZ($){if(x0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(dX);return $}function p4($,Z){let W={};for(let Y in $)W[Y]=({o:J},j)=>{let z=x0(j)||{},{branding:X}=z,G=X===JZ||Z.includes(X)?z:q0(j);return J[Y](G)};return W}function vW($){let Z={};for(let W in $)Z[W]=(Y)=>{let{calendar:J}=Y;return(j=J,typeof j=="string"?lZ(j):(z=j,Object.assign(Object.create(JL),{i:z})))[W](Y);var j,z};return Z}function P$(){throw TypeError(lX)}function u3({calendar:$}){return typeof $=="string"?new lW($):$}function _G($,Z){if(Z=G0(Z),H0($)){let Y=x0($);if(Y&&Y.branding===uZ)return m(Z),Y;let J=kG($);return n7(n4(J||v),!J,$,Z)}let W=Oz(lZ,$);return m(Z),W}function EG($,Z,W){return Y=Z.call($,f0(T0(W))),O7(E3(Y));var Y}function c4($,Z=vG){let W=Object.keys(Z).sort(),Y={};for(let J of W)Y[J]=q(Z[J],$,GG($[J]));return Y}function a($,Z){return typeof $=="string"?m4($):c4($,Z)}function V0($){return a($,qW)}function N1($){if(H0($)){let Z=x0($);if(Z)switch(Z.branding){case g4:return Z;case i1:return T0(Z.epochNanoseconds)}}return Bz($)}function IG($,Z,W){let Y=Z.l(N1(W).epochNanoseconds,$);return Y?f0(T0(Y)):null}function r($){return H0($)?(x0($)||{}).timeZone||BL($):((Z)=>N4(Tz(Y0(Z))))($)}function M$($,Z){if(H0($)){let W=x0($)||{};switch(W.branding){case v4:return m(Z),W;case jZ:return m(Z),B1(W);case i1:return m(Z),$W(V0,W)}return rz($,Z)}return m(Z),Lz($)}function gW($){return $===void 0?void 0:M$($)}function sZ($,Z){if(Z=G0(Z),H0($)){let Y=x0($);return Y&&Y.branding===dZ?(m(Z),Y):s7(i4(l3($)),$,Z)}let W=Dz(lZ,$);return m(Z),W}function H$($,Z){if(Z=G0(Z),H0($)){let Y=x0($)||{};switch(Y.branding){case jZ:return m(Z),Y;case JZ:return m(Z),Q0({...Y,...z1});case i1:return m(Z),r7(V0,Y)}return tz(s4(l3($)),$,Z)}let W=Uz($);return m(Z),W}function q0($,Z){if(Z=G0(Z),H0($)){let Y=x0($)||{};switch(Y.branding){case JZ:return m(Z),Y;case jZ:return m(Z),B0(Y);case i1:return m(Z),e7(V0,Y)}return i7(s4(l3($)),$,Z)}let W=K4($);return m(Z),W}function RG($,Z,W){return G1(Z.call($,j0(B0(W,$))))}function C1($){return(Z)=>typeof Z=="string"?lZ(Z):((W,Y)=>{let J=Object.keys(Y).sort(),j={};for(let z of J)j[z]=q(Y[z],W,W[z]);return j})(Z,$)}function J0($){if(H0($)){let Z=x0($);return Z&&Z.branding===y4?Z:ez($)}return Mz($)}function d3($){if($!==void 0){if(H0($)){let Z=x0($)||{};switch(Z.branding){case i1:case JZ:return Z;case jZ:return B0(Z)}let W=l3($);return{...oz(r,a,s4(W),$),calendar:W}}return Fz($)}}function l3($){return kG($)||v}function kG($){let{calendar:Z}=$;if(Z!==void 0)return C0(Z)}function C0($){return H0($)?(x0($)||{}).calendar||CL($):((Z)=>w3(Hz(Y0(Z))))($)}function nZ($,Z){if(Z=G0(Z),H0($)){let W=x0($);if(W&&W.branding===i1)return R3(Z),W;let Y=l3($);return az(r,a,s4(Y),Y,$,Z)}return Vz($,Z)}function CG($){return X1((Z)=>(W)=>Z(fW(W)),$)}function fW($){return k0($,V0)}function dO(){let $=L$.prototype,Z=Object.getOwnPropertyDescriptors($),W=Object.getOwnPropertyDescriptors(L$),Y=function(J,j={}){if(!(this instanceof Y))return new Y(J,j);iW.set(this,((z,X={})=>{let G=new L$(z,X),Q=G.resolvedOptions(),F=Q.locale,V=l0(Object.keys(X),Q),B=d0(iO),U=(...O)=>{let D,L=O.map((M,T)=>{let K=x0(M),N=(K||{}).branding;if(T&&D&&D!==N)throw TypeError(aX);return D=N,K});return D?B(D)(F,V,...L):[G,...O]};return U.u=G,U})(J,j))};for(let J in Z){let j=Z[J],z=J.startsWith("format")&&uO(J);typeof j.value=="function"?j.value=J==="constructor"?Y:z||lO(J):z&&(j.get=function(){return z.bind(this)})}return W.prototype.value=Object.create($,Z),Object.defineProperties(Y,W),Y}function uO($){return function(...Z){let W=iW.get(this),[Y,...J]=W(...Z);return Y[$](...J)}}function lO($){return function(...Z){return iW.get(this).u[$](...Z)}}function iO($){let Z=sO[$];if(!Z)throw TypeError(oX($));return d1(Z,d0(ZW))}var sO={Instant:SW,PlainDateTime:bW,PlainDate:EW,PlainTime:RW,PlainYearMonth:kW,PlainMonthDay:wW},nO=d1(SW),oO=d1(NG),aO=d1(bW),tO=d1(EW),rO=d1(RW),eO=d1(kW),$L=d1(wW),yW={era:Uj,eraYear:m5,year:E3,month:G1,daysInMonth:G1,daysInYear:G1,inLeapYear:XG,monthsInYear:G1},u4={monthCode:Y0},mW={day:G1},wG={dayOfWeek:G1,dayOfYear:G1,weekOfYear:Dj,yearOfWeek:m5,daysInWeek:G1},fG=Object.assign({},yW,u4,mW,wG),d4=new WeakMap,x0=d4.get.bind(d4),xG=d4.set.bind(d4),ZL={...p4(yW,[dZ]),...p4(wG,[]),...p4(u4,[dZ,uZ]),...p4(mW,[uZ])},hW=vW(fG),WL=vW({...yW,...u4}),YL=vW({...u4,...mW}),i3={calendarId:($)=>P0($.calendar)},JL=X1(($,Z)=>function(W){let{i:Y}=this;return $(Y[Z](j0(B0(W,Y))))},fG),jL=S3(($)=>(Z)=>Z[$],p.concat("sign")),pW=S3(($,Z)=>(W)=>W[V1[Z]],l1),qG={epochSeconds:vj,epochMilliseconds:Q4,epochMicroseconds:gj,epochNanoseconds:yj},s3=q(v5,new Set(["branding"])),[zL,oZ,XL]=I1(uZ,q(UX,C0),{...i3,...YL},{getISOFields:s3,getCalendar:u3,with($,Z,W){return oZ(JX(NL,$,this,aZ(Z),W))},equals:($,Z)=>wz($,_G(Z)),toPlainDate($,Z){return j0(AX(n3,$,this,Z))},toLocaleString($,Z,W){let[Y,J]=$L(Z,W,$);return Y.format(J)},toString:B7,toJSON:($)=>B7($),valueOf:P$},{from:($,Z)=>oZ(_G($,Z))}),vG={getOffsetNanosecondsFor:EG,getPossibleInstantsFor($,Z,W){let Y=[...Z.call($,I0(Q0(W,v)))].map((j)=>QL(j).epochNanoseconds),J=Y.length;return J>1&&(Y.sort(E0),L7(e0(r0(Y[0],Y[J-1])))),Y}},qW={getOffsetNanosecondsFor:EG},[GL,f0,QL]=I1(g4,GX,qG,{add:($,Z)=>f0(M7(0,$,J0(Z))),subtract:($,Z)=>f0(M7(1,$,J0(Z))),until:($,Z,W)=>t(y7(0,$,N1(Z),W)),since:($,Z,W)=>t(y7(1,$,N1(Z),W)),round:($,Z)=>f0(pj($,Z)),equals:($,Z)=>Sz($,N1(Z)),toZonedDateTime($,Z){let W=p1(Z);return F0(t7($,r(W.timeZone),C0(W.calendar)))},toZonedDateTimeISO:($,Z)=>F0(t7($,r(Z))),toLocaleString($,Z,W){let[Y,J]=nO(Z,W,$);return Y.format(J)},toString:($,Z)=>j7(r,V0,$,Z),toJSON:($)=>j7(r,V0,$),valueOf:P$},{from:($)=>f0(N1($)),fromEpochSeconds:($)=>f0(EX($)),fromEpochMilliseconds:($)=>f0(RX($)),fromEpochMicroseconds:($)=>f0(kX($)),fromEpochNanoseconds:($)=>f0(wX($)),compare:($,Z)=>q7(N1($),N1(Z))}),[l4,T_]=I1("TimeZone",($)=>{let Z=xz($);return{branding:"TimeZone",id:Z,o:m4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(H$(Z)).map((W)=>f0(T0(W))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(N1(Z).epochNanoseconds),getOffsetStringFor($,Z){let W=N1(Z).epochNanoseconds,Y=c4(this,qW).getOffsetNanosecondsFor(W);return t$(Y)},getPlainDateTimeFor($,Z,W=v){let Y=N1(Z).epochNanoseconds,J=c4(this,qW).getOffsetNanosecondsFor(Y);return I0(Q0(V$(Y,J),C0(W)))},getInstantFor($,Z,W){let Y=H$(Z),J=o5(W),j=c4(this);return f0(T0(u0(j,Y,J)))},getNextTransition:({o:$},Z)=>IG(1,$,Z),getPreviousTransition:({o:$},Z)=>IG(-1,$,Z),equals($,Z){return!!I4(this,r(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=r($);return typeof Z=="string"?new l4(Z):Z}}),BL=bG(Object.keys(vG)),[FL,T$]=I1(v4,DX,pW,{getISOFields:s3,with($,Z,W){return T$(jX(this,aZ(Z),W))},add:($,Z)=>T$(N7(0,$,J0(Z))),subtract:($,Z)=>T$(N7(1,$,J0(Z))),until:($,Z,W)=>t(d7(0,$,M$(Z),W)),since:($,Z,W)=>t(d7(1,$,M$(Z),W)),round:($,Z)=>T$(uj($,Z)),equals:($,Z)=>fz($,M$(Z)),toZonedDateTime:($,Z)=>F0(SX(r,q0,a,$,Z)),toPlainDateTime:($,Z)=>I0(bX($,q0(Z))),toLocaleString($,Z,W){let[Y,J]=rO(Z,W,$);return Y.format(J)},toString:F7,toJSON:($)=>F7($),valueOf:P$},{from:($,Z)=>T$(M$($,Z)),compare:($,Z)=>_4(M$($),M$(Z))}),[VL,K$,UL]=I1(dZ,q(VX,C0),{...i3,...WL},{getISOFields:s3,getCalendar:u3,with($,Z,W){return K$(YX(PL,$,this,aZ(Z),W))},add:($,Z,W)=>K$(P7(AG,0,$,J0(Z),W)),subtract:($,Z,W)=>K$(P7(AG,1,$,J0(Z),W)),until:($,Z,W)=>t(c7(SG,0,$,sZ(Z),W)),since:($,Z,W)=>t(c7(SG,1,$,sZ(Z),W)),equals:($,Z)=>kz($,sZ(Z)),toPlainDate($,Z){return j0(xX(n3,$,this,Z))},toLocaleString($,Z,W){let[Y,J]=eO(Z,W,$);return Y.format(J)},toString:Q7,toJSON:($)=>Q7($),valueOf:P$},{from:($,Z)=>K$(sZ($,Z)),compare:($,Z)=>$Z(sZ($),sZ(Z))}),[DL,I0]=I1(jZ,q(BX,C0),{...i3,...hW,...pW},{getISOFields:s3,getCalendar:u3,with($,Z,W){return I0(ZX(n3,$,this,aZ(Z),W))},withCalendar:($,Z)=>I0(S4($,C0(Z))),withPlainDate:($,Z)=>I0(gX($,q0(Z))),withPlainTime:($,Z)=>I0(vX($,gW(Z))),add:($,Z,W)=>I0(T7(XZ,0,$,J0(Z),W)),subtract:($,Z,W)=>I0(T7(XZ,1,$,J0(Z),W)),until:($,Z,W)=>t(h7(_1,0,$,H$(Z),W)),since:($,Z,W)=>t(h7(_1,1,$,H$(Z),W)),round:($,Z)=>I0(dj($,Z)),equals:($,Z)=>Ez($,H$(Z)),toZonedDateTime:($,Z,W)=>F0(TX(a,$,r(Z),W)),toPlainDate:($)=>j0(B0($)),toPlainTime:($)=>T$(B1($)),toPlainYearMonth($){return K$(KX(i4,$,this))},toPlainMonthDay($){return oZ(PX(n4,$,this))},toLocaleString($,Z,W){let[Y,J]=aO(Z,W,$);return Y.format(J)},toString:X7,toJSON:($)=>X7($),valueOf:P$},{from:($,Z)=>I0(H$($,Z)),compare:($,Z)=>g7(H$($),H$(Z))}),[OL,j0,gG]=I1(JZ,q(FX,C0),{...i3,...hW},{getISOFields:s3,getCalendar:u3,with($,Z,W){return j0(WX(n3,$,this,aZ(Z),W))},withCalendar:($,Z)=>j0(S4($,C0(Z))),add:($,Z,W)=>j0(K7(XZ,0,$,J0(Z),W)),subtract:($,Z,W)=>j0(K7(XZ,1,$,J0(Z),W)),until:($,Z,W)=>t(p7(_1,0,$,q0(Z),W)),since:($,Z,W)=>t(p7(_1,1,$,q0(Z),W)),equals:($,Z)=>Rz($,q0(Z)),toZonedDateTime($,Z){let W=!H0(Z)||Z instanceof l4?{timeZone:Z}:Z;return F0(NX(r,M$,a,$,W))},toPlainDateTime:($,Z)=>I0(_X($,gW(Z))),toPlainYearMonth($){return K$(IX(i4,$,this))},toPlainMonthDay($){return oZ(CX(n4,$,this))},toLocaleString($,Z,W){let[Y,J]=tO(Z,W,$);return Y.format(J)},toString:G7,toJSON:($)=>G7($),valueOf:P$},{from:($,Z)=>j0(q0($,Z)),compare:($,Z)=>$Z(q0($),q0(Z))}),cW={fields($,Z,W){return[...Z.call($,W)]}},yG=Object.assign({dateFromFields($,Z,W,Y){return gG(Z.call($,Object.assign(Object.create(null),W),Y))}},cW),mG=Object.assign({yearMonthFromFields($,Z,W,Y){return UL(Z.call($,Object.assign(Object.create(null),W),Y))}},cW),hG=Object.assign({monthDayFromFields($,Z,W,Y){return XL(Z.call($,Object.assign(Object.create(null),W),Y))}},cW),dW={mergeFields($,Z,W,Y){return p1(Z.call($,Object.assign(Object.create(null),W),Object.assign(Object.create(null),Y)))}},LL=Object.assign({},yG,dW),ML=Object.assign({},mG,dW),HL=Object.assign({},hG,dW),uW={dateAdd($,Z,W,Y,J){return gG(Z.call($,j0(B0(W,$)),t($0(Y)),J))}},pG=Object.assign({},uW,{dateUntil($,Z,W,Y,J,j){return IL(Z.call($,j0(B0(W,$)),j0(B0(Y,$)),Object.assign(Object.create(null),j,{largestUnit:y3[J]})))}}),TL=Object.assign({},uW,{day:RG}),KL=Object.assign({},pG,{day:RG}),i4=C1(mG),s4=C1(yG),n4=C1(hG),PL=C1(ML),n3=C1(LL),NL=C1(HL),XZ=C1(uW),_1=C1(pG),AG=C1(TL),SG=C1(KL),[_L,t,IL]=I1(y4,OX,{...jL,blank:Xz},{with:($,Z)=>t(zX($,Z)),negated:($)=>t(H4($)),abs:($)=>t(zz($)),add:($,Z,W)=>t(A7(d3,_1,a,0,$,J0(Z),W)),subtract:($,Z,W)=>t(A7(d3,_1,a,1,$,J0(Z),W)),round:($,Z)=>t(jz(d3,_1,a,$,Z)),total:($,Z)=>hj(d3,_1,a,$,Z),toLocaleString($,Z,W){return Intl.DurationFormat?new Intl.DurationFormat(Z,W).format(this):U4($)},toString:U4,toJSON:($)=>U4($),valueOf:P$},{from:($)=>t(J0($)),compare:($,Z,W)=>Az(d3,XZ,a,J0($),J0(Z),W)}),cG={toString:($)=>$.id,toJSON:($)=>$.id,...ZL,dateAdd:({id:$,o:Z},W,Y,J)=>j0(B0(Z.dateAdd(q0(W),J0(Y),J),$)),dateUntil:({o:$},Z,W,Y)=>t($0($.dateUntil(q0(Z),q0(W),Rj(Y)))),dateFromFields:({id:$,o:Z},W,Y)=>j0(i7(Z,W,Y,Vj($))),yearMonthFromFields:({id:$,o:Z},W,Y)=>K$(s7(Z,W,Y,Bj($))),monthDayFromFields:({id:$,o:Z},W,Y)=>oZ(n7(Z,0,W,Y,Fj($))),fields({o:$},Z){let W=new Set(F1),Y=[];for(let J of Z){if(Y0(J),!W.has(J))throw RangeError(YW(J));W.delete(J),Y.push(J)}return $.fields(Y)},mergeFields:({o:$},Z,W)=>$.mergeFields(g5(h5(Z)),g5(h5(W)))},[lW]=I1("Calendar",($)=>{let Z=cz($);return{branding:"Calendar",id:Z,o:lZ(Z)}},{id:($)=>$.id},cG,{from($){let Z=C0($);return typeof Z=="string"?new lW(Z):Z}}),CL=bG(Object.keys(cG).slice(4)),[xL,F0]=I1(i1,q(QX,C0,r),{...qG,...i3,...CG(hW),...CG(pW),offset:($)=>t$(fW($).offsetNanoseconds),offsetNanoseconds:($)=>fW($).offsetNanoseconds,timeZoneId:($)=>P0($.timeZone),hoursInDay:($)=>lj(a,$)},{getISOFields:($)=>Yz(V0,$),getCalendar:u3,getTimeZone:({timeZone:$})=>typeof $=="string"?new l4($):$,with($,Z,W){return F0($X(n3,a,$,this,aZ(Z),W))},withCalendar:($,Z)=>F0(S4($,C0(Z))),withTimeZone:($,Z)=>F0(yX($,r(Z))),withPlainDate:($,Z)=>F0(qX(a,$,q0(Z))),withPlainTime:($,Z)=>F0(fX(a,$,gW(Z))),add:($,Z,W)=>F0(H7(XZ,a,0,$,J0(Z),W)),subtract:($,Z,W)=>F0(H7(XZ,a,1,$,J0(Z),W)),until:($,Z,W)=>t($0(m7(_1,a,0,$,nZ(Z),W))),since:($,Z,W)=>t($0(m7(_1,a,1,$,nZ(Z),W))),round:($,Z)=>F0(cj(a,$,Z)),startOfDay:($)=>F0(ij(a,$)),equals:($,Z)=>bz($,nZ(Z)),toInstant:($)=>f0(LX($)),toPlainDateTime:($)=>I0(r7(V0,$)),toPlainDate:($)=>j0(e7(V0,$)),toPlainTime:($)=>T$($W(V0,$)),toPlainYearMonth($){return K$(MX(i4,$,this))},toPlainMonthDay($){return oZ(HX(n4,$,this))},toLocaleString($,Z,W={}){let[Y,J]=oO(Z,W,$);return Y.format(J)},toString:($,Z)=>z7(V0,$,Z),toJSON:($)=>z7(V0,$),valueOf:P$},{from:($,Z)=>F0(nZ($,Z)),compare:($,Z)=>v7(nZ($),nZ(Z))}),AL=Object.defineProperties({},{...t6("Temporal.Now"),...n$({timeZoneId:()=>u1(),instant:()=>f0(T0(q3())),zonedDateTime:($,Z=u1())=>F0(_0(q3(),r(Z),C0($))),zonedDateTimeISO:($=u1())=>F0(_0(q3(),r($),v)),plainDateTime:($,Z=u1())=>I0(Q0(pZ(V0(r(Z))),C0($))),plainDateTimeISO:($=u1())=>I0(Q0(pZ(V0(r($))),v)),plainDate:($,Z=u1())=>j0(B0(pZ(V0(r(Z))),C0($))),plainDateISO:($=u1())=>j0(B0(pZ(V0(r($))),v)),plainTimeISO:($=u1())=>T$(B1(pZ(V0(r($)))))})}),tZ=Object.defineProperties({},{...t6("Temporal"),...n$({PlainYearMonth:VL,PlainMonthDay:zL,PlainDate:OL,PlainTime:FL,PlainDateTime:DL,ZonedDateTime:xL,Instant:GL,Calendar:lW,TimeZone:l4,Duration:_L,Now:AL})}),SL=dO(),iW=new WeakMap,bL=Object.defineProperties(Object.create(Intl),n$({DateTimeFormat:SL}));var o4="x-gemi-socket";var C_="gemi.v1",dG="/__gemi/socket",x_=/^[A-Za-z0-9_-]{1,32}$/,A_={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function R_($){return $}function uG(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:dG,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 EL,randomBytes as RL}from"crypto";function kL($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(EL("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var wL="__control",sW=250,fL=1e4,qL=15000;class nW{config;prefix;controlChannel;instanceId=RL(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??kL(),this.controlChannel=this.prefix+wL,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(W){throw Error(`The broadcast revocation ${JSON.stringify($)} could not reach the other instances.`,{cause:W})}}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 W=this.publisherClient();try{await W.publish($,Z)}catch{if(this.closed)throw Error("The broadcast driver is closed.");this.dropPublisher(W),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 W=$==="subscriber"?{...this.config.options,autoReconnect:!1}:{...this.config.options};return new Z(this.config.url,W)}connectSubscriber(){if(this.closed||this.ready)return;let $;try{$=this.createClient("subscriber")}catch(W){console.error("[gemi] Broadcast: the Redis subscriber could not be created.",W),this.scheduleReconnect();return}this.subscriber=$,this.active.clear(),$.onclose=()=>this.lost($);let Z=o3((async()=>{await $.connect(),await $.subscribe(this.controlChannel,this.onMessage);let W=[...this.wanted];if(await Promise.all(W.map((Y)=>$.subscribe(this.prefix+Y,this.onMessage))),this.subscriber!==$)throw Error("Replaced.");for(let Y of W)this.active.add(Y);return $})(),qL,"connect");this.ready=Z,Z.then(()=>{if(this.subscriber!==$)return;this.ready=null,this.reconnectAttempt=0;for(let W of this.active)if(!this.wanted.has(W))this.sync(W,!1).catch(()=>{});if(this.connectedOnce)this.hooks?.onGap?.();this.connectedOnce=!0},(W)=>{if(this.subscriber!==$||this.closed)return;console.warn(`[gemi] Broadcast: the Redis subscriber could not connect (${lG(W)}); 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(fL,sW*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(sW,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;o3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${lG(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 W=this.ready??vL(Math.min(Z,sW));await o3(W,Z,"subscribe").catch((Y)=>{if(Date.now()>=$)throw Y})}}sync($,Z){let Y=(this.chains.get($)??Promise.resolve()).catch(()=>{}).then(()=>this.reconcile($,Z));this.chains.set($,Y);let J=()=>{if(this.chains.get($)===Y)this.chains.delete($)};return Y.then(J,J),Y}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let J=this.subscriber;this.active.delete($);try{await o3(J.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(j){if(this.subscriber===J)this.drop(J);throw j}return}if(!Z)return;let Y=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await o3(Y.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(J){if(this.subscriber===Y)this.drop(Y);throw J}if(this.subscriber===Y)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 W=Z.r;if(W&&typeof W.user==="string")this.hooks?.onRevoke?.({user:W.user});else if(W&&typeof W.topic==="string")this.hooks?.onRevoke?.({topic:W.topic})}}function o3($,Z,W){let Y;return Promise.race([$,new Promise((J,j)=>{Y=setTimeout(()=>j(Error(`Redis ${W} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(Y))}function vL($){return new Promise((Z)=>setTimeout(Z,$))}function lG($){return $ instanceof Error?$.message:String($)}import{createHmac as gL,hkdfSync as yL,randomBytes as iG}from"crypto";function sG($){return gL("sha256",mL()).update($).digest("base64url").slice(0,22)}var a4=null;function mL(){let $=process.env.SECRET||void 0;if(a4&&a4.secret===$)return a4.key;let Z=$?Buffer.from(yL("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):iG(32);return a4={secret:$,key:Z},Z}function v_(){return iG(16).toString("base64url")}var hL=/^[A-Za-z0-9_-]{8,64}$/;function oW($){return typeof $==="string"&&hL.test($)}function nG($,Z,W,Y){let J={op:"ev",t:$,ev:Z};if(W!==void 0)J.d=W;if(Y)J.x=Y;return JSON.stringify(J)}class aG extends Error{bytes;limit;constructor($,Z,W){super(`The broadcast "${W}" 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 i0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=N$(uG(),$),this.driver=dL(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 a3(this,t4($,Z[0]),null)}toUser($){return new a3(this,{topic:KZ($),pattern:O0},null)}toOthers($){return new tG(this,cL($))}broadcastEvent($){let Z=$.broadcastOn(),W=Array.isArray(Z)?Z:[Z],Y=$.broadcastAs(),J=$.broadcastWith(),j=W.map((z)=>this.prepare(t4(z,void 0),Y,J,null));for(let{sent:z,frame:X}of j)this.hand(z,X)}send($,Z,W,Y){let{sent:J,frame:j}=this.prepare($,Z,W,Y);this.hand(J,j)}prepare($,Z,W,Y){ZY(Z);let J;try{J=nG($.topic,Z,W,Y?sG(Y):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,J),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(J).d,...Y?{except:Y}:{}},frame:J}}hand($,Z){aW(()=>this.publish($,Z))}publish($,Z){let W=(Y)=>console.error(`[gemi] The broadcast "${$.event}" on "${$.topic}" could not be published.`,Y);try{let Y=this.driver.publish($.topic,Z);if(Y&&typeof Y.catch==="function")Y.catch(W)}catch(Y){W(Y)}}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(W){throw this.started=!1,this.hooks=void 0,W}}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=pL($);aW(()=>this.sendRevocation(Z))}sendRevocation($){let Z=(W)=>console.error("[gemi] A broadcast revocation could not be sent.",W);try{if(typeof this.driver.revoke==="function"){let W=this.driver.revoke($);if(W&&typeof W.catch==="function")W.catch(Z);return}this.hooks?.onRevoke?.($)}catch(W){Z(W)}}checkSize($,Z){let W=Buffer.byteLength(Z,"utf8");if(W>this.config.maxEventBytes)throw new aG(W,this.config.maxEventBytes,$);let Y=this.config.warnEventBytes;if(Y!==!1&&W>Y&&!this.warnedAboutSize.has($))this.warnedAboutSize.add($),console.warn(`[gemi] The broadcast "${$}" is ${W} bytes, over ${Y}. Broadcasts are change hints: send ids and let the client fetch the data over HTTP. Warned once per event name.`)}}class a3{manager;target;except;constructor($,Z,W){this.manager=$;this.target=Z;this.except=W}emit($,...Z){this.manager.send(this.target,$,Z[0],this.except)}}class tG{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new a3(this.manager,t4($,Z[0]),this.except)}toUser($){return new a3(this.manager,{topic:KZ($),pattern:O0},this.except)}}function t4($,Z){if($Y($))return{topic:m8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:O3($,Z??{}),pattern:$};if($===O0)throw new s('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:m8($)}}function pL($){if($&&typeof $==="object"&&"user"in $)return{user:KZ($.user).slice(O0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:t4($.channel,$.params).topic};throw new s("Broadcast.revoke takes { user } or { channel }.")}function cL($){if($===null||$===void 0)return null;if(typeof $==="string")return oW($)?$:null;let W=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(o4);return oW(W)?W:null}function dL($,Z){let W=$.driver;if(W===void 0||W==="memory")return new oG;if(W==="redis"){let Y=Z?.config.get("redis",{})??{},J=$.redis??{};return new nW({url:J.url??Y.url??process.env.REDIS_URL,options:J.options??Y.options,prefix:J.prefix,subscribeTimeoutMs:J.subscribeTimeoutMs,healthCheckMs:J.healthCheckMs})}if(typeof W==="function"){if(!Z)throw Error("A broadcast driver factory needs the application to be called with.");return W(Z)}if(typeof W==="object"&&W!==null&&typeof W.publish==="function")return W;throw Error(`Unknown broadcast driver "${String(W)}" in app/config/broadcast.ts. Use "memory" or "redis", or pass a BroadcastDriver.`)}class tW extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class uL{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1;clientFor($){return Promise.resolve(void 0)}async isAvailable($){return await this.clientFor($)!==null}async redirectUriFor($){return(await this.clientFor($))?.redirectUri}}import{createHash as rW,createHmac as lL,randomBytes as rG,timingSafeEqual as ZQ}from"crypto";var r3=600,r4="gemi_oauth",iL=`__Host-${r4}`;function rZ($,Z=r4){if(Z===r4)return $?iL:r4;return $?`__Host-${Z}`:Z}function t3($){return $.toString("base64url")}function WQ($){return lL("sha256",IZ()).update(`gemi-oauth-state:${$}`).digest()}function eG($,Z){let W=rW("sha256").update($).digest(),Y=rW("sha256").update(Z).digest();return ZQ(W,Y)&&$.length===Z.length}function e4($,Z=Date.now(),W={}){let Y=t3(rG(32)),J=t3(rG(32)),j=sL(J),z={provider:$,state:Y,codeVerifier:J,expiresAt:Z+r3*1000,...W.subject!==void 0?{subject:W.subject}:{},...W.returnTo!==void 0?{returnTo:W.returnTo}:{},...W.redirectUri!==void 0?{redirectUri:W.redirectUri}:{}};return{state:Y,codeVerifier:J,codeChallenge:j,cookieValue:nL(z)}}function sL($){return t3(rW("sha256").update($).digest())}function nL($){let Z=t3(Buffer.from(JSON.stringify($)));return`${Z}.${t3(WQ(Z))}`}function oL($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let W=$.slice(0,Z),Y=Buffer.from($.slice(Z+1),"base64url"),J=WQ(W);if(Y.length!==J.length||!ZQ(Y,J))return null;try{let j=JSON.parse(Buffer.from(W,"base64url").toString("utf8"));if(typeof j?.provider!=="string"||typeof j?.state!=="string"||typeof j?.codeVerifier!=="string"||typeof j?.expiresAt!=="number"||j.subject!==void 0&&typeof j.subject!=="string"||j.returnTo!==void 0&&typeof j.returnTo!=="string"||j.redirectUri!==void 0&&typeof j.redirectUri!=="string")return null;return j}catch{return null}}var _$=new Map,$Q=1e4;function aL($,Z,W){if(_$.size>=$Q){for(let[Y,J]of _$)if(J<=W)_$.delete(Y);while(_$.size>=$Q){let Y=_$.keys().next().value;if(Y===void 0)break;_$.delete(Y)}}_$.set($,Z)}function $8($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let W=oL($.cookieValue);if(!W)return{ok:!1,reason:"invalid_state"};let Y=eG(W.state,$.returnedState),J=eG(W.provider,$.provider);if(!Y||!J)return{ok:!1,reason:"invalid_state"};if(W.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(_$.has(W.state))return{ok:!1,reason:"invalid_state"};return aL(W.state,W.expiresAt,Z),{ok:!0,payload:W}}var eW=new WeakMap;function rL($){let Z=eW.get($);if(!Z)Z=$(tL(32).toString("hex")),eW.set($,Z),Z.catch(()=>eW.delete($));return Z}async function Z8($,Z,W){if(typeof W==="string"&&W!=="")return await $.verifyPassword(Z,W);try{await $.verifyPassword(Z,await rL($.hashPassword))}catch{}return!1}async function GZ($,Z){let W=Z.user??Z.session?.user;if(!W||!$.onAuthenticated)return;let{password:Y,...J}=W;await $.onAuthenticated({...Z,user:J})}class Z9 extends Error{}function $9($){return typeof $==="string"&&$!==""?$:null}function YQ($){return h$($)}var eL=256;function JQ($){return typeof $==="string"&&$!==""&&$.length<=eL?$:null}function jQ($){let{password:Z,code:W,...Y}=$;return Y}var Y8="intended_url";function GQ($){if($.cookies.get(Y8))$.ctx().setCookie(Y8,"",{maxAge:-1})}function zQ($){let Z=$.cookies.get(Y8);if(!Z)return null;GQ($);try{return H1(decodeURIComponent(Z),"")||null}catch{return null}}class W9 extends S{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class QQ extends S{schema={email:{required:"Email is required",email:"Invalid email"}}}class BQ extends S{schema={password:{required:"Password is required",password:"Invalid password"}}}function W8(){throw new y0("Not found",{status:404})}async function s1($,Z){if(!await g1(H(R).config[$],Z))W8()}async function e3($,Z,W,Y){let{config:J}=H(R),j={signIn:"sign-in",signUp:"sign-up",forgot:"forgot",reset:"reset"}[$];await p$(j,Z,W,J.passwordLimits?.[$]??{},J.rateLimitKey,Y)}async function XQ($,Z,W){let{config:Y}=H(R);await e3("signIn",h$($),W,async(J)=>{if(J==="perEmail"&&typeof Z==="string")await Z8(Y,Z,null)})}async function eZ($){return await g1(H(R).config.verifyEmail,$)}class Z0 extends H3{async me(){let $=await g0.user();if(!$)throw new j5;return $}async verifyEmail($=new S){await s1("password",$);let Z=await $.input(),{userProvider:W}=H(R),Y=$9(Z.get("token"));if(!Y)return{email:null};let J=await W.findUserByVerificationToken(Y);if(!J)return{email:null};return await W.verifyUser(J.email),{email:J.email}}async signInWithMagicLink($=new S){let Z=H(R),{userProvider:W}=Z;if(!await g1(Z.config.magicLink,$)&&!await g1(Z.config.emailCode.enabled,$))W8();let Y=$9($.search.get("token")),J=null;try{J=h$(decodeURIComponent($.search.get("email")??""))}catch{}if(await p$("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp},Z.config.rateLimitKey),!J||!Y||!await Z.verifyMagicLinkToken(J,Y))return{error:"Invalid token"};await W.verifyUser(J);let j=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",j.token,H(R).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON(),{req:$}),await GZ(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){await s1("magicLink",$);let Z=H(R),W=await $.input(),{email:Y,pin:J}=W.toJSON(),j=h$(Y),z=JQ(J);if(await p$("verify",j,$,Z.config.emailCode.verifyLimit,Z.config.rateLimitKey),!j||!z)throw new u({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new u({pin:["Too many attempts"]});if(X.status!=="ok")throw new u({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new S){let Z=H(R),W=await this.verifyPinRequest($),Y=await Z.createOrUpdateSessionV2({email:W});return $.ctx().setCookie("access_token",Y.token,H(R).accessTokenCookieOptions($,Y.expiresAt)),await Z.config.onSignIn(Y,$.search.toJSON(),{req:$}),await GZ(Z.config,{session:Y,isNewUser:!1,method:"magic-link",req:$}),Y}async signInWithPin($=new S){let Z=H(R),W=await this.verifyPinRequest($),Y=await Z.createOrUpdateSession({email:W});return $.ctx().setCookie("access_token",Y.token,H(R).accessTokenCookieOptions($,Y.expiresAt)),await Z.config.onSignIn(Y,$.search.toJSON(),{req:$}),await GZ(Z.config,{session:Y,isNewUser:!1,method:"magic-link",req:$}),{session:Y}}async signInV2($=new W9){await s1("password",$);let Z=await $.input(),{email:W,password:Y}=Z.toJSON(),J=W.toLowerCase().trim(),j=H(R);await XQ(W,Y,$);let z=await j.userProvider.findUserByEmailAddress(J,await eZ($)),X=typeof Y==="string"&&await Z8(j.config,Y,z?.password);if(!z||!X)throw new u({invalid_credentials:["Invalid credentials"]});let G=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,H(R).accessTokenCookieOptions($,G.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await GZ(j.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...F}=z;return F}async signIn($=new W9){await s1("password",$);let Z=await $.input(),{email:W,password:Y}=Z.toJSON(),J=W.toLowerCase().trim(),j=H(R);await XQ(W,Y,$);let z=await j.userProvider.findUserByEmailAddress(J,await eZ($)),X=typeof Y==="string"&&await Z8(j.config,Y,z?.password);if(!z||!X)throw new u({invalid_credentials:["Invalid credentials"]});let G=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,H(R).accessTokenCookieOptions($,G.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await GZ(j.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...F}=z;return F}async signUp(){let $=H(R),{userProvider:Z,config:W}=$,Y=new W.signUpRequest;await s1("password",Y);let J=await Y.input(),{email:j,password:z,name:X,invitationId:G}=J.toJSON(),Q={method:"password",input:jQ(J.toJSON()),req:Y},F=YQ(j);if(await e3("signUp",F,Y),!F)throw new u({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new u({password:["Invalid password"]});if(G!=null&&typeof G!=="string")throw new u({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(F,!1))throw new u({email:["Email address already exists"]});let B=await W.hashPassword(z),U=H(l).detectLocale(Y),O;if(G)O=await Z.findInvitation(G,F);let D,L="",M=!1,T=(_)=>_.catch((x)=>{throw M=!0,x}),K=(_)=>T(Z.createUser(_)),N=async(_)=>{if(M&&await Z.findUserByEmailAddress(F,!1))throw new u({email:["Email address already exists"]});throw _};if(O)D=await Z.transaction(async()=>{await T(Z.deleteInvitationById(G));let _=await K({email:F,name:X,password:B,emailVerifiedAt:new Date,locale:U});return await Z.createAccount({organizationId:O.organizationId,userId:_.id,organizationRole:O.role}),await W.onUserCreated(_,Q),_}).catch(N);else{if(L=await W.generateEmailVerificationToken(F),typeof W.verifyEmail==="function"&&!await eZ(Y))L="";D=await Z.transaction(async()=>{let _=await K({email:F,name:X,password:B,verificationToken:L,locale:U});return await W.onUserCreated(_,Q),_}).catch(N)}return await W.onSignUp(D,L,Y.search.toJSON(),{req:Y}),D}async signOut($=new S){let Z=w$($),W=H(R),{config:Y}=W,J=await W.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",H(R).accessTokenCookieOptions($,new Date(0))),H(R).cookieDomain($))$.ctx().setCookie("access_token","",{...H(R).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(J?.user)$M(J.user),J.user.extension=await Y.extendSession(J.user),await Y.onSignOut(J.user,{req:$});return{}}async forgotPassword($=new QQ){await s1("password",$);let Z=await $.input(),W=YQ(Z.get("email"));if(await e3("forgot",W,$),!W)return{};let{userProvider:Y,config:J}=H(R),j=await Y.findUserByEmailAddress(W,await eZ($));if(!j)return{};let z=await J.generateForgotPasswordToken(j);return await Y.createPasswordResetToken({user:j,token:z}),await J.onForgotPassword(j,z,{req:$}),{}}async resetPassword($=new BQ){await s1("password",$);let{userProvider:Z,config:W}=H(R),Y=await $.input(),{password:J,token:j}=Y.toJSON(),z=$9(j);await e3("reset",null,$);let X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new u({token:["Invalid token"]});if(tZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(tZ.Now.instant()).sign>=0)throw new u({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let Q=await Z.findUserByEmailAddress(X.user.email,await eZ($));if(!Q)throw new u({email:["User not found"]});let F=await W.hashPassword(J);return await Z.updateUserPassword({id:Q.id,password:F}),await Z.deleteAllUserSessions(Q.id),await W.onResetPassword(Q,{req:$}),{}}async changePassword($=new S){await s1("password",$);let{userProvider:Z,config:W}=H(R),Y=await g0.user(),J=await $.input(),{oldPassword:j,newPassword:z}=J.toJSON();if(await e3("signIn",h$(Y?.email),$),typeof z!=="string")throw new u({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(Y.email,await eZ($));if(!(typeof j==="string"&&await Z8(W,j,X?.password)))throw new u({oldPassword:["Incorrect password"]});let Q=await W.hashPassword(z);return await Z.updateUserPassword({id:Y.id,password:Q}),await Z.deleteAllUserSessions(Y.id),{}}async oauthRedirect($=new S){let{provider:Z}=$.params,W=H(R).config.oauthProviders,Y=Object.hasOwn(W,Z),J=await xZ(W,Z,$);if(!J){if(Y)throw new y0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=PZ($.rawRequest),z=H1($.search.get(a0),"");if(z)$.ctx().setCookie(Y8,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else GQ($);let X=typeof J.redirectUriFor==="function"?await J.redirectUriFor($):void 0,{state:G,codeChallenge:Q,cookieValue:F}=e4(Z,Date.now(),X!==void 0?{redirectUri:X}:{});return $.ctx().setCookie(rZ(j),F,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:r3}),{destination:await J.getRedirectUrl($,{state:G,codeChallenge:Q,codeChallengeMethod:"S256"})}}async oauthCallback($=new S){let{provider:Z}=$.params,W=H(R),{userProvider:Y,config:J}=W,j=Object.hasOwn(J.oauthProviders,Z),z=await xZ(J.oauthProviders,Z,$);if(j&&!z)throw new y0("Not found",{status:404});let X=PZ($.rawRequest),G=rZ(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 F=$.search.get("error");if(F)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(F)?F:"provider_error");let V=$8({provider:Z,cookieValue:Q,returnedState:$.search.get("state")});if("reason"in V)return console.error(`Authentication error: OAuth callback refused (${V.reason})`),this.oauthFailure($,V.reason);if(V.payload.redirectUri!==void 0&&typeof z.redirectUriFor==="function"){let A=await z.redirectUriFor($);if(A!==void 0&&A!==V.payload.redirectUri)return console.error("Authentication error: OAuth callback refused (redirect_mismatch)"),this.oauthFailure($,"redirect_mismatch")}if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let B;try{B=await z.onCallback($,{state:V.payload.state,codeVerifier:V.payload.codeVerifier})}catch(A){if(A instanceof tW)return this.oauthFailure($,A.code);return console.error("Authentication error: OAuth provider callback failed",A),this.oauthFailure($,"provider_error")}let{name:U,username:O,providerId:D,emailVerified:L}=B??{},M=typeof B?.email==="string"?B.email:void 0,T=M?w6(M):null,K=D?await Y.findUserBySocialAccount(Z,D):null,N="signin",_=!K&&!T&&!M&&!!D&&z.createUsersWithoutEmail===!0;if(!K&&_){if(z.createUsers===!1)return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");try{K=await this.createOAuthUserWithoutEmail({provider:Z,providerId:D,name:U,username:O,locale:H(l).detectLocale($),req:$}),N="signup"}catch(A){let f=await Y.findUserBySocialAccount(Z,D);if(!f)throw A;K=f}}if(!K){if(!T)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,M?"invalid_email":D?"missing_email":"no_identity");if(L===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let A=H(l).detectLocale($);try{let f=await this.linkOAuthAccount({provider:Z,providerId:D,email:T,rawEmail:M,name:U,username:O,locale:A,req:$,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(f==="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(f==="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(f)K=f.user,N=f.action}catch(f){let I=D?await Y.findUserBySocialAccount(Z,D):null;if(!I)throw f;K=I}if(!K)return this.oauthFailure($,"account_conflict")}let x=await W.createOrUpdateSessionV2({email:K.email,id:K.id});if($.ctx().setCookie("access_token",x.token,H(R).accessTokenCookieOptions($,x.expiresAt)),N==="signup")await J.onSignUp(K,"",$.search.toJSON(),{req:$});else await J.onSignIn(K,$.search.toJSON(),{req:$});await GZ(W.config,{session:x,user:K,isNewUser:N==="signup",method:"oauth",req:$});let b=zQ($)??J.redirectPath,w=J.oauthCompleteProfilePath?H1(J.oauthCompleteProfilePath,""):"";if(w&&!K.email){let A=new URL(w,"http://gemi.invalid");A.searchParams.set(a0,b),b=`${A.pathname}${A.search}${A.hash}`}return{session:x,redirectTo:b}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:W}=H(R);return await Z.transaction(async()=>{let Y=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:Y.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await W.onUserCreated(Y,{method:"oauth",input:{},req:$.req}),Y})}oauthFailure($,Z){let W=zQ($),Y=H(R).config.oauthFailurePath;if(Y){let J=H1(Y,"");if(J){let j=new URL(J,"http://gemi.invalid");if(j.searchParams.set("error",Z),W)j.searchParams.set(a0,W);f1.external(`${j.pathname}${j.search}${j.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(Y)}`)}return{session:null,error:Z,redirectTo:W}}async linkOAuthAccount($){let{provider:Z,providerId:W,email:Y,rawEmail:J,name:j,username:z,locale:X}=$,{userProvider:G,config:Q}=H(R),F=(O)=>({provider:Z,userId:O,email:Y,username:z,providerId:W,expiresAt:new Date,accessToken:"",refreshToken:""}),V=await G.findUserByEmailAddress(Y,!1),B=J?.trim();if(!V&&B&&B!==Y)V=await G.findUserByEmailAddress(B,!1);if(V){if($.linkExisting===!1)return"account_exists";if(!W)return{user:V,action:"signin"};let O=await G.findSocialAccounts(V.id,Z);if(O.some((L)=>L.providerId===W))return{user:V,action:"signin"};if(O.some((L)=>L.providerId))return console.error(`Authentication error: user ${V.id} is already linked to a different ${Z} account`),null;let D=O[0];if(D){if(!await G.claimSocialAccount(D,W))throw Error(`${Z} account link changed concurrently`)}else await G.createSocialAccount(F(V.id));return{user:V,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await G.transaction(async()=>{let O=await G.createUser({email:Y,name:j,locale:X,emailVerifiedAt:new Date});if(W)await G.createSocialAccount(F(O.id));return await Q.onUserCreated(O,{method:"oauth",input:{},req:$.req}),O}),action:"signup"}}async createMagicLinkToken($=new S){await s1("magicLink",$);let Z=await $.input(),W=h$(Z.get("email")),Y=H(R),{uniformMagicLinkResponse:J,requestLimit:j}=Y.config.emailCode;if(await p$("request",W,$,j,Y.config.rateLimitKey),!W)return{email:null};let{user:z,pin:X,token:G}=await Y.createMagicLinkToken(W);if(z)return await Y.config.onMagicLinkCreated(z,{email:W,pin:X,token:G,req:$}),{email:W};return{email:J?W:null}}async requestEmailCode($=new S){let Z=H(R),W=Z.config.emailCode;if(!await g1(W.enabled,$))W8();let Y=await $.input(),J=w6(Y.get("email"));if(await p$("request",J,$,W.requestLimit,Z.config.rateLimitKey),!J)throw new u({email:["Invalid email"]});let j=await Z.userProvider.findUserByEmailAddress(J,!1);if(j||W.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(J,W.length);await W.send({email:J,code:z,token:X,isNewUser:!j,req:$})}return{ok:!0}}async verifyEmailCode($=new S){let Z=H(R),{userProvider:W,config:Y}=Z;if(!await g1(Y.emailCode.enabled,$))W8();let J=await $.input(),{email:j,code:z,name:X}=J.toJSON(),G=w6(j),Q=JQ(z);if(await p$("verify",G,$,Y.emailCode.verifyLimit,Y.rateLimitKey),!G||!Q)throw new u({code:["invalid_code"]});let F=null;if(!PJ(Q,Y.emailCode)){let D=await Z.verifyOneTimeCode(G,Q,{claim:!1});if(D.status==="too_many_attempts")throw new u({code:["too_many_attempts"]});if(D.status!=="ok")throw new u({code:["invalid_code"]});F=D.row}let V=async()=>F?await Z.claimOneTimeCode(G,F.id):!0,B=await W.findUserByEmailAddress(G,!1),U=!1;if(B){if(!await V())throw new u({code:["invalid_code"]});await W.verifyUser(G)}else if(Y.emailCode.createUser){let D=H(l).detectLocale($),L=!1;try{B=await W.transaction(async()=>{if(!await V())throw new Z9;let M=await W.createUser({email:G,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:D}).catch((T)=>{throw L=!0,T});return await Y.onUserCreated(M,{method:"email-code",input:jQ(J.toJSON()),req:$}),M}),U=!0}catch(M){if(M instanceof Z9)throw new u({code:["invalid_code"]});if(!L)throw M;let T=await W.findUserByEmailAddress(G,!1);if(!T)throw M;if(!await V())throw new u({code:["invalid_code"]});B=T}}else throw await V(),new u({code:["invalid_code"]});let O=await Z.createOrUpdateSessionV2({email:G,id:B.id});return $.ctx().setCookie("access_token",O.token,H(R).accessTokenCookieOptions($,O.expiresAt)),await Y.onSignIn(O,$.search.toJSON(),{req:$}),await GZ(Z.config,{session:O,isNewUser:U,method:"email-code",req:$}),{session:O,isNewUser:U}}}function $M($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let W=H();if(typeof W?.bound!=="function"||!W.bound(i0))return;W.make(i0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var FQ="gemi_oauth_connection";class J8 extends H3{async connect($=new S){let Z=String($.params.provider??""),Y=H($6).providers[Z],J=await g0.user(),j=H1($.search.get(a0),"");if(!Y)return this.finish(j,Z,"unknown_provider");let z=PZ($.rawRequest),{state:X,codeChallenge:G,cookieValue:Q}=e4(VQ(Z),Date.now(),{subject:String(J.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(rZ(z,FQ),Q,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:r3}),f1.external(Y.authorizationUrl({state:X,codeChallenge:G,redirectUri:UQ($,Z,Y.config.redirectUri)})),{destination:"/"}}async callback($=new S){let Z=String($.params.provider??""),W=H($6),Y=await g0.user(),J=PZ($.rawRequest),j=rZ(J,FQ),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:J,maxAge:-1});let X=$8({provider:VQ(Z),cookieValue:z,returnedState:$.search.get("state")}),G="payload"in X?X.payload.returnTo??"":"",Q=W.providers[Z];if(!Q)return this.finish(G,Z,"unknown_provider");let F=$.search.get("error");if(F)return this.finish(G,Z,/^[a-z0-9_]{1,64}$/.test(F)?F:"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(Y.id))return this.finish(G,Z,"user_mismatch");let V=$.search.get("code");if(!V)return this.finish(G,Z,"missing_code");try{let B=await Q.exchangeCode({code:V,codeVerifier:X.payload.codeVerifier,redirectUri:UQ($,Z,Q.config.redirectUri)}),U=await W.save(Y,Z,B);await H(R).config.onConnected({user:Y,provider:Z,connection:U,profile:B.profile??null,req:$})}catch(B){if(B instanceof DQ)return console.error(`OAuth connection to ${Z} failed: ${B.message}`),this.finish(G,Z,B.providerError??B.code);throw B}return this.finish(G,Z)}finish($,Z,W){let Y=$||H1(H(R).config.redirectPath,"/"),J=new URL(Y,"http://gemi.invalid");if(J.searchParams.set("connection",Z),W)J.searchParams.set("connection_error",W);throw f1.external(`${J.pathname}${J.search}${J.hash}`),Error("unreachable: Redirect.external throws")}}function VQ($){return`connection:${$}`}function UQ($,Z,W){if(W)return W;return`${QZ()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function OQ($){return $.magicLink!==!1||D5($.emailCode?.enabled)}function LQ($){return Object.keys($.oauthProviders??{}).length>0}function MQ($={}){let Z=[];if(OQ($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:D5($.emailCode?.enabled)&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(LQ($)){let Y=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:Y},{view:"auth/OauthCallback",requiredBy:Y})}return Z}class HQ extends q1{middlewares=["cache:private"];routes={"/:provider":this.redirect([J8,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([J8,"callback"]).middleware([I6,"auth"])}}function TQ($={}){let Z=OQ($),W=LQ($);class Y extends q1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[Z0,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[Z0,"oauthCallback"])}}return class extends q1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[Z0,"signInWithMagicLink"])}:{},...W?{"/oauth":Y}:{},"/connections":HQ}}}class Y9 extends A0{middlewares=["cache:private"];routes={"/sign-in":this.post(Z0,"signIn"),"/sign-in-v2":this.post(Z0,"signInV2"),"/sign-up":this.post(Z0,"signUp"),"/sign-out":this.post(Z0,"signOut"),"/forgot-password":this.post(Z0,"forgotPassword"),"/reset-password":this.post(Z0,"resetPassword"),"/change-password":this.post(Z0,"changePassword"),"/verify-email":this.post(Z0,"verifyEmail"),"/me":this.get(Z0,"me").middleware(["auth"]),"/magic-link":this.post(Z0,"createMagicLinkToken"),"/sign-in-with-pin":this.post(Z0,"signInWithPin"),"/sign-in-with-pin-v2":this.post(Z0,"signInWithPinV2"),"/email-code":this.post(Z0,"requestEmailCode"),"/email-code/verify":this.post(Z0,"verifyEmailCode")}}class J9 extends A0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new S().params.locale;return await H(l).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new S,Z=`/${$.params.scope??""}`,W=$.params.locale,Y=H(l),J=W??Y.detectLocale($),j=Y.getPageTranslations(J,Z);return $.ctx().setCookie("i18n-locale",J,{expires:new Date(Date.now()+31536000000)}),{[J]:j}})}}class j9{}class z9 extends j9{async resize($,Z){let{height:W,width:Y,quality:J,fit:j}=Z;return await(await j8("The Sharp image optimization driver"))($).resize(Y>0?Y:void 0,W>0?W:void 0,{fit:j}).webp({quality:J>0?J:80,force:!0}).toBuffer()}}function oI($){return $}function KQ(){return{driver:new z9,allowedHosts:[],maxSize:10485760,timeout:1e4}}class U0 extends Error{status;constructor($,Z,W){super(Z,W);this.status=$;this.name="ImageSourceError"}}var ZM=new Set([301,302,303,307,308]),WM="/api/__gemi__/services/image/";async function NQ($,Z){let W=Z.maxRedirects??5,Y=AbortSignal.timeout(Z.timeout),J=Z.ownOrigins[0]??Z.localOrigin,j=PQ($,J);try{for(let z=0;;z++){let X=await YM(j,Z,Y),G=X.headers.get("location");if(ZM.has(X.status)&&G){if(await X.body?.cancel().catch(()=>{}),z>=W)throw new U0(502,"The image redirects too many times");j=PQ(G,j.href);continue}if(!X.ok)throw await X.body?.cancel().catch(()=>{}),new U0(404,"Image not found");if(!X.headers.get("content-type")?.split(";")[0].trim().toLowerCase()?.startsWith("image/"))throw await X.body?.cancel().catch(()=>{}),new U0(415,"The source is not an image");return{bytes:Buffer.from(await X.arrayBuffer()),cacheControl:X.headers.get("cache-control")}}}catch(z){if(z instanceof TypeError&&z.message.startsWith("safeFetch:"))throw z;throw jM(z,Y)}}function PQ($,Z){let W;try{W=new URL($,Z)}catch{throw new U0(400,"The url parameter is not a URL")}if(W.protocol!=="http:"&&W.protocol!=="https:")throw new U0(400,"Only http(s) images can be resized");return W}async function YM($,Z,W){let Y={method:"GET",redirect:"manual",signal:W,timeout:Z.timeout,maxSize:Z.maxSize,headers:{accept:"image/*"}},J=$;if(Z.ownOrigins.includes($.origin)){if($.pathname.startsWith(WM))throw new U0(403,"This image source is not allowed");if(JM($.pathname))throw new U0(403,"This image source is not allowed");let j=new URL(Z.localOrigin).origin,z=new URL(`${$.pathname}${$.search}`,j);if(z.origin===j)return v1(z,{...Y,allowPrivate:!0,ports:"any"});J=z}if(Z.allowedHosts.length===0)throw new U0(403,"This image source is not allowed");return v1(J,{...Z.external,...Y,allow:Z.allowedHosts})}function JM($){let Z=$;for(let W=0;W<5;W++){if(/^[/\\][/\\]/.test(Z))return!0;let Y;try{Y=decodeURIComponent(Z)}catch{return!0}if(Y===Z)return!1;Z=Y}return!0}function jM($,Z){if($ instanceof U0)return $;if(Z.aborted)return new U0(504,"The image took too long to load",{cause:$});if($ instanceof x6)switch($.code){case"blocked-host":case"blocked-address":case"invalid-url":return new U0(403,"This image source is not allowed",{cause:$});case"too-large":return new U0(413,"The image is too large",{cause:$});case"timeout":return new U0(504,"The image took too long to load",{cause:$})}return new U0(502,"The image could not be loaded",{cause:$})}class X9 extends A0{routes={"/resize":this.file(async()=>{let $=new S,Z=new URL($.rawRequest.url),W=Z.searchParams.get("url"),Y=Number(Z.searchParams.get("w")),J=Number(Z.searchParams.get("h")),j=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!W)return _Q(400,"url query parameter is required");let X=H(IQ),G=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],Q=QZ();if(Q&&URL.canParse(Q))G.push(new URL(Q).origin);let F;try{F=await NQ(W,{ownOrigins:G,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(U){if(U instanceof U0)return _Q(U.status,U.message);throw U}let V=await X.resize(F.bytes,{height:J,width:Y,fit:j,quality:z}),B=new Headers({"Content-Type":"image/webp","Content-Length":`${V.byteLength}`});if(F.cacheControl)B.set("Cache-Control",F.cacheControl);return new Response(new Uint8Array(V),{headers:B})})}}function _Q($,Z){return Response.json({error:Z},{status:$})}class IQ{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=KQ();this.driver=$.driver??Z.driver,this.allowedHosts=$.allowedHosts??Z.allowedHosts,this.maxSize=$.maxSize??Z.maxSize,this.timeout=$.timeout??Z.timeout}resize($,Z){return this.driver.resize($,Z)}}class G9 extends A0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(H(CQ).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function BC($){return $}function xQ(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function AQ(){return{partialRendering:!0,localeRouting:"prefix",theme:{},publicFiles:!0,assetRoutes:!1,assetCors:!1,onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function zM($){return"run"in $}function XM($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function GM($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function QM($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function BM($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function SQ($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function FM($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let W=`/${Z}`.replace(/\/{2,}/g,"/");return W.length>1?W.replace(/\/$/,""):W}function Q9($,Z="",W=[],Y){let J={},j=(X)=>{return(X.corsPolicy===void 0?Y:X.corsPolicy)||void 0};function z(X,G,Q,F,V,B,U){let O=X==="/"?"":X,D=Z==="/"?"":Z,L=FM((`${D}${O}`===""?"/":`${D}${O}`).replaceAll("//","/"));if(!J[L])J[L]={};J[L][G.toUpperCase()]={exec:Q,middleware:[...W,...F],...V?{source:V}:{},...B?{bodyLimitDefault:B}:{},...U?{cors:U}:{}},J[L].OPTIONS={exec:()=>{let T=new S().ctx().headers;return new Response(null,{headers:T,status:204})},middleware:[]}}for(let[X,G]of Object.entries($)){if(BM(G)){let Q=G;for(let F of["GET","POST","PUT","DELETE"])z(X,F,Q.run.bind(Q),Q.middlewares,void 0,void 0,j(Q));continue}if(zM(G)){let Q=G,F=Q.method,V=Q.middlewares,B=Q.run.bind(Q),U=j(Q);if(z(X,F,B,V,Q.source,Q.__internal_bodyLimitDefault,U),SQ(G))z(X,"HEAD",B,V,Q.source,void 0,U)}if(XM(G))for(let[Q,F]of Object.entries(G)){let V=F,B=V.middlewares,U=V.run.bind(V),O=j(V);if(z(X,Q,U,B,V.source,V.__internal_bodyLimitDefault,O),Q==="get"&&SQ(V))z(X,"HEAD",U,B,V.source,void 0,O)}if(QM(G)){let Q=new G,F=`the router at "${Z}${X}"`;if(Q.cors===!0)throw Error(`CORS policy on ${F}: \`cors = true\` is not a policy; write one such as { origins: "*" }.`);let V=Q.cors===void 0?Y:Q.cors===!1?void 0:D3(Q.cors,F),B=Q9(Q.routes,`${Z}${X}`,[...W,...Q.middlewares],V);for(let[U,O]of Object.entries(B)){let D=U.replaceAll("//","/");J[D]={...J[D],...O}}}if(GM(G)){let{first:Q,second:F}=G;for(let[V,B]of Object.entries(Q)){let U=B.middlewares,O=B.run.bind(B),[D,...L]=X.split("/").reverse();if(!D.startsWith(":"))throw Error("Resource route must end with a dynamic segment");z(L.reverse().join("/"),V,O,U,B.source,void 0,j(B))}for(let[V,B]of Object.entries(F)){let U=B.middlewares,O=B.run.bind(B);z(X,V,O,U,B.source,void 0,j(B))}}}return Object.fromEntries(Object.entries(J).sort(([X],[G])=>{let Q=X.split("/").length+X.split(":").length,F=G.split("/").length+G.split(":").length;return Q-F}))}var VM=Object.defineProperty,C=($,Z)=>VM($,"name",{value:Z,configurable:!0}),W3=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,W,Y,J,j){this.type=$,this.name=Z,this.prefix=W,this.value=Y,this.suffix=J,this.modifier=j}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};C(W3,"Part");var UM=/[$_\p{ID_Start}]/u,DM=/[$_\u200C\u200D\p{ID_Continue}]/u,F9=".*";function bQ($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}C(bQ,"isASCII");function D9($,Z=!1){let W=[],Y=0;for(;Y<$.length;){let J=$[Y],j=C(function(z){if(!Z)throw TypeError(z);W.push({type:"INVALID_CHAR",index:Y,value:$[Y++]})},"ErrorOrInvalid");if(J==="*"){W.push({type:"ASTERISK",index:Y,value:$[Y++]});continue}if(J==="+"||J==="?"){W.push({type:"OTHER_MODIFIER",index:Y,value:$[Y++]});continue}if(J==="\\"){W.push({type:"ESCAPED_CHAR",index:Y++,value:$[Y++]});continue}if(J==="{"){W.push({type:"OPEN",index:Y,value:$[Y++]});continue}if(J==="}"){W.push({type:"CLOSE",index:Y,value:$[Y++]});continue}if(J===":"){let z="",X=Y+1;for(;X<$.length;){let G=$.substr(X,1);if(X===Y+1&&UM.test(G)||X!==Y+1&&DM.test(G)){z+=$[X++];continue}break}if(!z){j(`Missing parameter name at ${Y}`);continue}W.push({type:"NAME",index:Y,value:z}),Y=X;continue}if(J==="("){let z=1,X="",G=Y+1,Q=!1;if($[G]==="?"){j(`Pattern cannot start with "?" at ${G}`);continue}for(;G<$.length;){if(!bQ($[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 ${Y}`);continue}if(!X){j(`Missing pattern at ${Y}`);continue}W.push({type:"REGEX",index:Y,value:X}),Y=G;continue}W.push({type:"CHAR",index:Y,value:$[Y++]})}return W.push({type:"END",index:Y,value:""}),W}C(D9,"lexer");function O9($,Z={}){let W=D9($);Z.delimiter??="/#?",Z.prefixes??="./";let Y=`[^${s0(Z.delimiter)}]+?`,J=[],j=0,z=0,X="",G=new Set,Q=C((K)=>{if(z<W.length&&W[z].type===K)return W[z++].value},"tryConsume"),F=C(()=>Q("OTHER_MODIFIER")??Q("ASTERISK"),"tryConsumeModifier"),V=C((K)=>{let N=Q(K);if(N!==void 0)return N;let{type:_,index:x}=W[z];throw TypeError(`Unexpected ${_} at ${x}, expected ${K}`)},"mustConsume"),B=C(()=>{let K="",N;for(;N=Q("CHAR")??Q("ESCAPED_CHAR");)K+=N;return K},"consumeText"),U=C((K)=>K,"DefaultEncodePart"),O=Z.encodePart||U,D="",L=C((K)=>{D+=K},"appendToPendingFixedValue"),M=C(()=>{D.length&&(J.push(new W3(3,"","",O(D),"",3)),D="")},"maybeAddPartFromPendingFixedValue"),T=C((K,N,_,x,b)=>{let w=3;switch(b){case"?":w=1;break;case"*":w=0;break;case"+":w=2;break}if(!N&&!_&&w===3){L(K);return}if(M(),!N&&!_){if(!K)return;J.push(new W3(3,"","",O(K),"",w));return}let A;_?_==="*"?A=F9:A=_:A=Y;let f=2;A===Y?(f=1,A=""):A===F9&&(f=0,A="");let I;if(N?I=N:_&&(I=j++),G.has(I))throw TypeError(`Duplicate name '${I}'.`);G.add(I),J.push(new W3(f,I,O(K),A,O(x),w))},"addPart");for(;z<W.length;){let K=Q("CHAR"),N=Q("NAME"),_=Q("REGEX");if(!N&&!_&&(_=Q("ASTERISK")),N||_){let b=K??"";Z.prefixes.indexOf(b)===-1&&(L(b),b=""),M();let w=F();T(b,N,_,"",w);continue}let x=K??Q("ESCAPED_CHAR");if(x){L(x);continue}if(Q("OPEN")){let b=B(),w=Q("NAME"),A=Q("REGEX");!w&&!A&&(A=Q("ASTERISK"));let f=B();V("CLOSE");let I=F();T(b,w,A,f,I);continue}M(),V("END")}return J}C(O9,"parse");function s0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}C(s0,"escapeString");function V9($){return $&&$.ignoreCase?"ui":"u"}C(V9,"flags");function EQ($,Z,W){return L9(O9($,W),Z,W)}C(EQ,"stringToRegexp");function BZ($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}C(BZ,"modifierToString");function L9($,Z,W={}){W.delimiter??="/#?",W.prefixes??="./",W.sensitive??=!1,W.strict??=!1,W.end??=!0,W.start??=!0,W.endsWith="";let Y=W.start?"^":"";for(let X of $){if(X.type===3){X.modifier===3?Y+=s0(X.value):Y+=`(?:${s0(X.value)})${BZ(X.modifier)}`;continue}Z&&Z.push(X.name);let G=`[^${s0(W.delimiter)}]+?`,Q=X.value;if(X.type===1?Q=G:X.type===0&&(Q=F9),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?Y+=`(${Q})${BZ(X.modifier)}`:Y+=`((?:${Q})${BZ(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){Y+=`(?:${s0(X.prefix)}(${Q})${s0(X.suffix)})`,Y+=BZ(X.modifier);continue}Y+=`(?:${s0(X.prefix)}`,Y+=`((?:${Q})(?:`,Y+=s0(X.suffix),Y+=s0(X.prefix),Y+=`(?:${Q}))*)${s0(X.suffix)})`,X.modifier===0&&(Y+="?")}let J=`[${s0(W.endsWith)}]|$`,j=`[${s0(W.delimiter)}]`;if(W.end)return W.strict||(Y+=`${j}?`),W.endsWith.length?Y+=`(?=${J})`:Y+="$",new RegExp(Y,V9(W));W.strict||(Y+=`(?:${j}(?=${J}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=W.delimiter.indexOf(X)>-1)}return z||(Y+=`(?=${j}|${J})`),new RegExp(Y,V9(W))}C(L9,"partsToRegexp");var C$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},OM={delimiter:".",prefixes:"",sensitive:!0,strict:!0},LM={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function RQ($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}C(RQ,"isAbsolutePathname");function M9($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}C(M9,"maybeStripPrefix");function kQ($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}C(kQ,"maybeStripSuffix");function H9($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}C(H9,"treatAsIPv6Hostname");var wQ=["ftp","file","http","https","ws","wss"];function T9($){if(!$)return!0;for(let Z of wQ)if($.test(Z))return!0;return!1}C(T9,"isSpecialScheme");function fQ($,Z){if($=M9($,"#"),Z||$==="")return $;let W=new URL("https://example.com");return W.hash=$,W.hash?W.hash.substring(1,W.hash.length):""}C(fQ,"canonicalizeHash");function qQ($,Z){if($=M9($,"?"),Z||$==="")return $;let W=new URL("https://example.com");return W.search=$,W.search?W.search.substring(1,W.search.length):""}C(qQ,"canonicalizeSearch");function vQ($,Z){return Z||$===""?$:H9($)?N9($):P9($)}C(vQ,"canonicalizeHostname");function gQ($,Z){if(Z||$==="")return $;let W=new URL("https://example.com");return W.password=$,W.password}C(gQ,"canonicalizePassword");function yQ($,Z){if(Z||$==="")return $;let W=new URL("https://example.com");return W.username=$,W.username}C(yQ,"canonicalizeUsername");function mQ($,Z,W){if(W||$==="")return $;if(Z&&!wQ.includes(Z))return new URL(`${Z}:${$}`).pathname;let Y=$[0]=="/";return $=new URL(Y?$:"/-"+$,"https://example.com").pathname,Y||($=$.substring(2,$.length)),$}C(mQ,"canonicalizePathname");function hQ($,Z,W){return K9(Z)===$&&($=""),W||$===""?$:_9($)}C(hQ,"canonicalizePort");function pQ($,Z){return $=kQ($,":"),Z||$===""?$:z8($)}C(pQ,"canonicalizeProtocol");function K9($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}C(K9,"defaultPortForProtocol");function z8($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}C(z8,"protocolEncodeCallback");function cQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}C(cQ,"usernameEncodeCallback");function dQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}C(dQ,"passwordEncodeCallback");function P9($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}C(P9,"hostnameEncodeCallback");function N9($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}C(N9,"ipv6HostnameEncodeCallback");function _9($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}C(_9,"portEncodeCallback");function uQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}C(uQ,"standardURLPathnameEncodeCallback");function lQ($){return $===""?$:new URL(`data:${$}`).pathname}C(lQ,"pathURLPathnameEncodeCallback");function iQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}C(iQ,"searchEncodeCallback");function sQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}C(sQ,"hashEncodeCallback");var nQ=class{#j;#Y=[];#Z={};#$=0;#J=1;#Q=0;#X=0;#U=0;#D=0;#O=!1;constructor($){this.#j=$}get result(){return this.#Z}parse(){for(this.#Y=D9(this.#j,!0);this.#$<this.#Y.length;this.#$+=this.#J){if(this.#J=1,this.#Y[this.#$].type==="END"){if(this.#X===0){this.#T(),this.#B()?this.#W(9,1):this.#F()?this.#W(8,1):this.#W(7,0);continue}else if(this.#X===2){this.#V(5);continue}this.#W(10,0);break}if(this.#U>0)if(this.#x())this.#U-=1;else continue;if(this.#C()){this.#U+=1;continue}switch(this.#X){case 0:this.#K()&&this.#V(1);break;case 1:if(this.#K()){this.#b();let $=7,Z=1;this.#N()?($=2,Z=3):this.#O&&($=2),this.#W($,Z)}break;case 2:this.#M()?this.#V(3):(this.#H()||this.#F()||this.#B())&&this.#V(5);break;case 3:this.#_()?this.#W(4,1):this.#M()&&this.#W(5,1);break;case 4:this.#M()&&this.#W(5,1);break;case 5:this.#A()?this.#D+=1:this.#S()&&(this.#D-=1),this.#I()&&!this.#D?this.#W(6,1):this.#H()?this.#W(7,0):this.#F()?this.#W(8,1):this.#B()&&this.#W(9,1);break;case 6:this.#H()?this.#W(7,0):this.#F()?this.#W(8,1):this.#B()&&this.#W(9,1);break;case 7:this.#F()?this.#W(8,1):this.#B()&&this.#W(9,1);break;case 8:this.#B()&&this.#W(9,1);break;case 9:break;case 10:break}}this.#Z.hostname!==void 0&&this.#Z.port===void 0&&(this.#Z.port="")}#W($,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.#O?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#P($,Z)}#P($,Z){this.#X=$,this.#Q=this.#$+Z,this.#$+=Z,this.#J=0}#T(){this.#$=this.#Q,this.#J=0}#V($){this.#T(),this.#X=$}#L($){return $<0&&($=this.#Y.length-$),$<this.#Y.length?this.#Y[$]:this.#Y[this.#Y.length-1]}#z($,Z){let W=this.#L($);return W.value===Z&&(W.type==="CHAR"||W.type==="ESCAPED_CHAR"||W.type==="INVALID_CHAR")}#K(){return this.#z(this.#$,":")}#N(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#M(){return this.#z(this.#$,"@")}#_(){return this.#z(this.#$,":")}#I(){return this.#z(this.#$,":")}#H(){return this.#z(this.#$,"/")}#F(){if(this.#z(this.#$,"?"))return!0;if(this.#Y[this.#$].value!=="?")return!1;let $=this.#L(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#B(){return this.#z(this.#$,"#")}#C(){return this.#Y[this.#$].type=="OPEN"}#x(){return this.#Y[this.#$].type=="CLOSE"}#A(){return this.#z(this.#$,"[")}#S(){return this.#z(this.#$,"]")}#G(){let $=this.#Y[this.#$],Z=this.#L(this.#Q).index;return this.#j.substring(Z,$.index)}#b(){let $={};Object.assign($,C$),$.encodePart=z8;let Z=EQ(this.#G(),void 0,$);this.#O=T9(Z)}};C(nQ,"Parser");var B9=["protocol","username","password","hostname","port","pathname","search","hash"],I$="*";function U9($,Z){if(typeof $!="string")throw TypeError("parameter 1 is not of type 'string'.");let W=new URL($,Z);return{protocol:W.protocol.substring(0,W.protocol.length-1),username:W.username,password:W.password,hostname:W.hostname,port:W.port,pathname:W.pathname,search:W.search!==""?W.search.substring(1,W.search.length):void 0,hash:W.hash!==""?W.hash.substring(1,W.hash.length):void 0}}C(U9,"extractValues");function x1($,Z){return Z?Z3($):$}C(x1,"processBaseURLString");function $3($,Z,W){let Y;if(typeof Z.baseURL=="string")try{Y=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=x1(Y.protocol.substring(0,Y.protocol.length-1),W)),!W&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=x1(Y.username,W)),!W&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=x1(Y.password,W)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=x1(Y.hostname,W)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=x1(Y.port,W)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=x1(Y.pathname,W)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=x1(Y.search.substring(1,Y.search.length),W)),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=x1(Y.hash.substring(1,Y.hash.length),W))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=pQ(Z.protocol,W)),typeof Z.username=="string"&&($.username=yQ(Z.username,W)),typeof Z.password=="string"&&($.password=gQ(Z.password,W)),typeof Z.hostname=="string"&&($.hostname=vQ(Z.hostname,W)),typeof Z.port=="string"&&($.port=hQ(Z.port,$.protocol,W)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,Y&&!RQ($.pathname,W)){let J=Y.pathname.lastIndexOf("/");J>=0&&($.pathname=x1(Y.pathname.substring(0,J+1),W)+$.pathname)}$.pathname=mQ($.pathname,$.protocol,W)}return typeof Z.search=="string"&&($.search=qQ(Z.search,W)),typeof Z.hash=="string"&&($.hash=fQ(Z.hash,W)),$}C($3,"applyInit");function Z3($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}C(Z3,"escapePatternString");function oQ($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}C(oQ,"escapeRegexpString");function aQ($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let W=".*",Y=`[^${oQ(Z.delimiter)}]+?`,J=/[$_\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+=Z3(X.value);continue}j+=`{${Z3(X.value)}}${BZ(X.modifier)}`;continue}let G=X.hasCustomName(),Q=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),F=z>0?$[z-1]:null,V=z<$.length-1?$[z+1]:null;if(!Q&&G&&X.type===1&&X.modifier===3&&V&&!V.prefix.length&&!V.suffix.length)if(V.type===3){let B=V.value.length>0?V.value[0]:"";Q=J.test(B)}else Q=!V.hasCustomName();if(!Q&&!X.prefix.length&&F&&F.type===3){let B=F.value[F.value.length-1];Q=Z.prefixes.includes(B)}Q&&(j+="{"),j+=Z3(X.prefix),G&&(j+=`:${X.name}`),X.type===2?j+=`(${X.value})`:X.type===1?G||(j+=`(${Y})`):X.type===0&&(!G&&(!F||F.type===3||F.modifier!==3||Q||X.prefix!=="")?j+="*":j+=`(${W})`),X.type===1&&G&&X.suffix.length&&J.test(X.suffix[0])&&(j+="\\"),j+=Z3(X.suffix),Q&&(j+="}"),X.modifier!==3&&(j+=BZ(X.modifier))}return j}C(aQ,"partsToPattern");var Z6=class{#j;#Y={};#Z={};#$={};#J={};#Q=!1;constructor($={},Z,W){try{let Y;if(typeof Z=="string"?Y=Z:W=Z,typeof $=="string"){let X=new nQ($);if(X.parse(),$=X.result,Y===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=Y}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(Y)throw TypeError("parameter 1 is not of type 'string'.")}typeof W>"u"&&(W={ignoreCase:!1});let J={ignoreCase:W.ignoreCase===!0},j={pathname:I$,protocol:I$,username:I$,password:I$,hostname:I$,port:I$,search:I$,hash:I$};this.#j=$3(j,$,!0),K9(this.#j.protocol)===this.#j.port&&(this.#j.port="");let z;for(z of B9){if(!(z in this.#j))continue;let X={},G=this.#j[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,C$),X.encodePart=z8;break;case"username":Object.assign(X,C$),X.encodePart=cQ;break;case"password":Object.assign(X,C$),X.encodePart=dQ;break;case"hostname":Object.assign(X,OM),H9(G)?X.encodePart=N9:X.encodePart=P9;break;case"port":Object.assign(X,C$),X.encodePart=_9;break;case"pathname":T9(this.#Y.protocol)?(Object.assign(X,LM,J),X.encodePart=uQ):(Object.assign(X,C$,J),X.encodePart=lQ);break;case"search":Object.assign(X,C$,J),X.encodePart=iQ;break;case"hash":Object.assign(X,C$,J),X.encodePart=sQ;break}try{this.#J[z]=O9(G,X),this.#Y[z]=L9(this.#J[z],this.#Z[z],X),this.#$[z]=aQ(this.#J[z],X),this.#Q=this.#Q||this.#J[z].some((Q)=>Q.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#j[z]}'.`)}}}catch(Y){throw TypeError(`Failed to construct 'URLPattern': ${Y.message}`)}}get[Symbol.toStringTag](){return"URLPattern"}test($={},Z){let W={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"?W=$3(W,$,!1):W=$3(W,U9($,Z),!1)}catch{return!1}let Y;for(Y of B9)if(!this.#Y[Y].exec(W[Y]))return!1;return!0}exec($={},Z){let W={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"?W=$3(W,$,!1):W=$3(W,U9($,Z),!1)}catch{return null}let Y={};Z?Y.inputs=[$,Z]:Y.inputs=[$];let J;for(J of B9){let j=this.#Y[J].exec(W[J]);if(!j)return null;let z={};for(let[X,G]of this.#Z[J].entries())if(typeof G=="string"||typeof G=="number"){let Q=j[X+1];z[G]=Q}Y[J]={input:W[J]??"",groups:z}}return Y}static compareComponent($,Z,W){let Y=C((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"),J=new W3(3,"","","","",3),j=new W3(0,"","","","",3),z=C((X,G)=>{let Q=0;for(;Q<Math.min(X.length,G.length);++Q){let F=Y(X[Q],G[Q]);if(F)return F}return X.length===G.length?0:Y(X[Q]??J,G[Q]??J)},"comparePartList");return!Z.#$[$]&&!W.#$[$]?0:Z.#$[$]&&!W.#$[$]?z(Z.#J[$],[j]):!Z.#$[$]&&W.#$[$]?z([j],W.#J[$]):z(Z.#J[$],W.#J[$])}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}};C(Z6,"URLPattern");if(!globalThis.URLPattern)globalThis.URLPattern=Z6;function X8($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function I9($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function C9($){let Z=X8($);return Z.length>1?Z.replace(/\/$/,""):Z}function tQ($,Z){return Z.map((W)=>({...W,path:C9(I9($,W.path))}))}function G8($){let Z={};for(let[W,Y]of Object.entries($))if("run"in Y){let J=Y;if("children"in J){let j=new J.children,z=G8(j.routes);for(let[X,{exec:G,middleware:Q,segments:F,features:V,static:B}]of Object.entries(z)){let U=I9(W,X),O=(D)=>J.run.call(J,D,W);Z[X8(U)]={exec:[O,...G],middleware:[...J.middlewares,...Q],features:[...J.featureGates,...V],viewPath:J.viewPath,segments:[{path:C9(W),viewPath:J.viewPath,...J.alwaysRuns?{alwaysRun:!0}:{}},...tQ(W,F)],...B?{static:B}:{}}}}else{let j=(z)=>J.run.call(J,z,W);Z[X8(W)]={exec:[j],middleware:J.middlewares,features:J.featureGates,viewPath:J.viewPath,segments:[{path:C9(W),viewPath:J.viewPath}],..."staticOptions"in J&&J.staticOptions?{static:J.staticOptions}:{}}}}else{let J=new Y,j=G8(J.routes);for(let[z,{exec:X,middleware:G,viewPath:Q,segments:F,features:V,static:B}]of Object.entries(j)){let U=I9(W,z);Z[X8(U)]={exec:X,middleware:[...J.middlewares,...G],features:[...J.featureGates,...V],viewPath:Q,segments:tQ(W,F),...B?{static:B}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([W],[Y])=>{let J=W.split("/").length+W.split(":").length,j=Y.split("/").length+Y.split(":").length;return J-j}))}var x9="theme";function rQ($){return $==="light"||$==="dark"||$==="system"}function eQ($){return`!function(o){try{var e=null,d=document.documentElement,c=d.classList,k=document.cookie.split(';'),i,j,v;
|
|
14
|
+
for(i=0;i<k.length;i++){j=k[i].indexOf('=');if(j>0&&k[i].slice(0,j).trim()===o.cookie){v=decodeURIComponent(k[i].slice(j+1).trim());break}}
|
|
15
|
+
if(v!=='light'&&v!=='dark'&&v!=='system'){try{v=localStorage.getItem('theme')}catch(x){}}
|
|
16
|
+
if(v==='light'||v==='dark'||v==='system')e=v;else e=o.default;
|
|
17
|
+
if(!e)return;
|
|
18
|
+
if(e==='system')e=window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';
|
|
19
|
+
c.remove(e==='dark'?'light':'dark');c.add(e);d.style.colorScheme=e}catch(x){}}(${$})`}function Y3($,Z){for(let[W,Y]of Object.entries($)){let J=new Z6({pathname:W});if(J.test({pathname:Z}))return{routePath:W,params:J.exec({pathname:Z})?.pathname.groups??{},route:Y}}return null}function $B($,Z){return Y3($,Z)?.route.segments.at(-1)?.viewPath==="FILE"}function ZB($,Z){return Z.endsWith(".json")&&!$B($,Z)}function WB($,Z){return Z.endsWith(".og")&&!$B($,Z)}var FZ={startIndex:0,carriedViews:[]};function YB($,Z){let W=L0($.path,Z);return W.includes("*")?null:W}function MM($,Z){if(!$)return FZ;if($.search!==Z.search)return FZ;let W=Math.min($.segments.length,Z.segments.length-1),Y=0;while(Y<W){let J=$.segments[Y],j=Z.segments[Y];if(j.alwaysRun)break;if(J.viewPath!==j.viewPath)break;let z=YB(J,$.params),X=YB(j,Z.params);if(z===null||X===null||z!==X)break;Y++}if(Y===0)return FZ;return{startIndex:Y,carriedViews:Z.segments.slice(0,Y).map(({viewPath:J})=>J)}}function HM($,Z){let[,W,...Y]=$.split("/");if(!Z.includes(W))return $;let J=`/${Y.join("/")}`;return J==="/"?"/":J.replace(/\/$/,"")}function JB($){let{flatViewRoutes:Z,supportedLocales:W,from:Y,origin:J,to:j}=$;if(!Y)return FZ;let z;try{z=new URL(Y,J)}catch{return FZ}if(z.origin!==J)return FZ;let X=Y3(Z,HM(z.pathname,W));if(!X)return FZ;return MM({segments:X.route.segments,params:X.params,search:z.search},j)}var A9="x-gemi-from";import{cloneElement as DH,createElement as n1,Fragment as sB}from"react";import{createElement as jB,Fragment as zB}from"react";function XB($,Z,W){return[jB(zB,{key:"preloads"},...$),jB(zB,{key:"head"},...Z),W]}function TM($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function Q8($){let Z={};for(let[W,Y]of Object.entries($))if("run"in Y){let J=Y.viewPath;if("children"in Y){Z[W]=[J];let j=new Y.children,z=Q8(j.routes);for(let[X,G]of Object.entries(z)){let Q=W==="/"?X:`${W}${X}`,F=X==="/"&&W!=="/"?W:Q;Z[F]=[J,...G]}if(Z[W].length===1)delete Z[W]}else Z[W]=[J]}else{let J=new Y,j=Q8(J.routes);for(let[z,X]of Object.entries(j)){let G=W==="/"?z:`${W}${z}`,Q=z==="/"&&W!=="/"?W:G;Z[Q]=X}}return Object.fromEntries(Object.entries(Z).map(([W,Y])=>[TM(W),Y]))}function B8($,Z){let[W,Y]=Z,J=$.find(([j])=>j===W);if(!J){$.push([W,[...Y]]);return}for(let j of Y)B8(J[1],j)}function F8($){let Z=[];for(let[W,Y]of Object.entries($))if("run"in Y){let J=Y.viewPath;if(J==="__")continue;if(J==="REDIRECT")continue;if(J==="FILE")continue;if("children"in Y){let j=new Y.children,z=F8(j.routes);B8(Z,[J,z])}else B8(Z,[J,[]])}else{let J=new Y,j=F8(J.routes);for(let z of j)B8(Z,z)}return Z}function S9($){let Z=[];for(let[W,Y]of $)Z.push(W,...S9(Y).flat());return Array.from(new Set(Z))}function GB($,Z){let[,W,...Y]=$.split("/");if(W===void 0||!Z.includes(W))return{locale:null,pathname:$||"/"};return{locale:W,pathname:`/${Y.join("/")}`}}class x$ extends h{static getFacadeAccessor(){return l}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=P.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(P.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??x$.locale(),$.timeZone??x$.timeZone())}static setLocale($=x$.locale(),Z={}){let W=this.getFacadeRoot(),Y=$;if(!W.supportedLocales.includes($))Y=W.defaultLocale;let J=P.getStore();if(Z.cookie!==!1)J.setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return J.setLocale(Y),Y}}class b9{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function QB($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var KM=50;class VZ{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((W)=>W.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(),(W)=>({path:W.path,variantKey:W.variantKey,startedAt:W.startedAt,settledAt:W.settledAt,status:W.status,source:W.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 J=JSON.stringify($.data)?.length??0;Z=J>=1024?`${(J/1024).toFixed(1)} kB`:`${J} B`}catch{Z="an unserializable payload"}let W=($.settledAt??0)-$.startedAt,Y=$.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 (${W}ms, resolved ${Z}) could not overlap the others. It still streamed. If the query belongs on this route, \`Query.prefetch("${$.patternPath}"${Y})\` 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.`)}locate($,Z){let W=Z.params??{},Y=new URLSearchParams(QB(Z.search??{}));Y.delete("json"),Y.sort();let J=L0($,W),j=Y.toString();return{params:W,searchParams:Y,path:J,variantKey:j,key:this.keyFor(J,j)}}find($,Z={}){return this.entries.get(this.locate($,Z).key)}entriesFor($){return Array.from(this.entries.values()).filter((Z)=>Z.path===$)}read($,Z){return this.entries.get(this.keyFor($,Z))}ensure($,Z={},W="render"){let{params:Y,searchParams:J,path:j,variantKey:z,key:X}=this.locate($,Z),G=this.entries.get(X);if(G)return G;let Q;if(W==="render"&&this.renderStartedAt!==null){let U=Math.round(performance.now()-this.renderStartedAt);if(U>KM)Q=U}let F,V=new Promise((U)=>{F=U}),B={path:j,patternPath:$,variantKey:z,lateBy:Q,status:"pending",promise:V,source:W,startedAt:this.elapsed()};return this.entries.set(X,B),this.fetcher($,Y,J).then((U)=>{B.status="resolved",B.data=U},(U)=>{B.status="rejected",B.error=U}).then(()=>{if(B.settledAt=this.elapsed(),this.maybeLogLateDiscovery(B),B.status==="rejected"&&this.failListener)this.failListener(B);if(this.settleListener)this.settleListener(B);else this.settledBacklog.push(B);F()}),B}prefill($,Z,W){let{path:Y,variantKey:J,key:j}=this.locate($,Z),z=this.entries.get(j);if(z)return z;let X=this.elapsed(),G={path:Y,patternPath:$,variantKey:J,status:"resolved",data:W,promise:Promise.resolve(),source:"prefetch",startedAt:X,settledAt:X};return this.entries.set(j,G),G}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,W]of this.entries){if(W.status!=="resolved")continue;this.shipped.add(Z),$[W.path]??={},$[W.path][W.variantKey]=W.data}return $}onSettle($){this.settleListener=(W)=>{if(this.shipped.has(this.keyFor(W.path,W.variantKey)))return;$(W)};let Z=this.settledBacklog;this.settledBacklog=[];for(let W of Z)this.settleListener(W)}}class Z1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,W,Y,J){super(typeof Y?.message==="string"?Y.message:`Request to /api${$} failed with status ${W}`);this.path=$;this.variantKey=Z;this.status=W;this.body=Y;this.retryAfter=J;this.name="QueryError"}}function J3(){let $=JSON.stringify({error:Y$("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function E9(){return{status:403,error:{message:"Forbidden"}}}function X3($){let Z=j3.getStore(),W=P.getStore();return(Y,J,j)=>{let z=new URL($.url).origin,X=[L0(Y,J),j.toString()].filter((V)=>V.length>0).join("?"),G=new Request(`${z}/${X}`,{headers:$.headers,signal:$.signal}),Q=V8($);if(Q)z3(G,Q);let F=new S(G,J);return j3.run(Z,()=>P.run(F,async()=>{let V=W?.locale;if(V&&H(l).isLocaleAware)P.getStore().setLocale(V);try{let B=H(U1).dispatchers(Q).api,U=await B.runRouteMiddleware(Y,F)??await B.getRouteData(Y);if(r1(U)){if(!U.ok)throw new Z1(L0(Y,J),j.toString(),U.status,U.body);return U.body}if(U instanceof Response){let O=await U.json().catch(()=>null);if(!U.ok)throw new Z1(L0(Y,J),j.toString(),U.status,O);return O}return U}catch(B){if(B instanceof Z1)throw B;let U=new Z1(L0(Y,J),j.toString(),500,{message:B instanceof Error?B.message:String(B)});throw U.cause=B,U}}))}}var PM=new Set(["script","style","template","title"]),NM=/\shidden([\s=/]|$)/i,_M=/"[^"]*"|'[^']*'/g;function IM($){let Z=0,W=0,Y=0,J=0;while(J<$.length){let j=$.indexOf("<",J),z=j===-1?$.length:j;if(z>J){let V=$.slice(J,z).replace(/\s+/g,"").length;if(Y>0)W+=V;else Z+=V}if(j===-1)break;if($.startsWith("<!--",j)){let V=$.indexOf("-->",j+4);J=V===-1?$.length:V+3;continue}let X=$.indexOf(">",j);if(X===-1)break;let G=$.slice(j+1,X);J=X+1;let Q=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(G)?.[1]?.toLowerCase();if(!Q)continue;let F=G.startsWith("/");if(!F&&PM.has(Q)&&!G.endsWith("/")){let V=$.indexOf(`</${Q}`,J);J=V===-1?$.length:V;continue}if(Q!=="div")continue;if(F){if(Y>0)Y-=1}else if(Y>0)Y+=1;else if(NM.test(G.replace(_M,'""')))Y=1}return{shellChars:Z,deferredChars:W}}var CM=1000,xM=64;function AM($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function SM($,Z){if(Z.deferredChars<CM)return null;if(Z.shellChars>=xM)return null;return`[gemi] GET ${$} streams ${AM(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 BB($=console.warn){let Z=new Set;return{shouldObserve(W){return!Z.has(W)},report(W,Y){if(Z.has(W))return;let J=SM(W,Y);if(!J)return;Z.add(W),$(J)}}}function FB(){let $=new TextDecoder,Z="";return{onChunk(W){Z+=$.decode(W,{stream:!0})},measure(){return Z+=$.decode(),IM(Z)}}}function VB($,Z,W=1e4,Y){let J=new TextEncoder,j=()=>{};return new ReadableStream({start(z){let X=!1,G=(F)=>{if(X)return;X=!0,clearTimeout(Q);try{z.close()}catch{}Y?.({aborted:F})};j=G,z.enqueue(J.encode(`${JSON.stringify($)}
|
|
20
|
+
`)),Z.onSettle((F)=>{if(X||F.status!=="resolved")return;z.enqueue(J.encode(`${JSON.stringify([F.path,F.variantKey,F.data])}
|
|
21
|
+
`))});let Q=setTimeout(()=>G(!0),W);Z.allSettled().then(()=>G(!1),()=>G(!1))},cancel(){j(!1)}})}import{Fragment as sx,createContext as nM,createElement as nx,lazy as ox,use as ax,useContext as tx}from"react";import{createContext as bM}from"react";var EM=bM(null);import{createContext as wM,useContext as Tx}from"react";import{useContext as Dx}from"react";import{createContext as RM}from"react";import{jsx as Fx}from"react/jsx-runtime";var kM=RM({});var fM="gemi.islandI18n",qM=globalThis[Symbol.for(fM)]??=wM(null);import{createContext as _B,useMemo as yx,useRef as mx}from"react";class R9{subscribers=new Set;value;constructor($){this.value=$,this.subscribe=this.subscribe.bind(this),this.next=this.next.bind(this),this.getValue=this.getValue.bind(this)}subscribe($){return this.subscribers.add($),()=>{this.subscribers.delete($)}}next($){this.value=$,this.subscribers.forEach((Z)=>Z($))}getValue(){return this.value}}function UB($,Z=Date.now()){if($==null)return;let W=$.trim();if(W==="")return;if(/^\d+$/.test(W))return Number(W)*1000;let Y=Date.parse(W);if(Number.isNaN(Y))return;return Math.max(0,Y-Z)}function DB($){if($.status===204||$.status===205)return Promise.resolve(null);let Z=$.headers?.get?.("Content-Type")??"";if(/^text\/plain\b/i.test(Z))return $.text();return $.json()}var OB="/auth/sign-in",vM=1000,gM=2,k9,w9=null,G3="idle",LB=0,f9=[];function HB($,Z){if($!==401)return!1;let W=Z&&typeof Z==="object"?Z.error:void 0;if(typeof W==="string")return W==="Authentication error";return!!W&&typeof W==="object"&&W.kind==="authentication"}function yM($){let Z=$?.get?.(q9);if(typeof Z!=="string"||Z==="")return OB;if(/^https?:\/\//i.test(Z))return Z;if(Z.startsWith("/")&&!Z.startsWith("//")&&!Z.includes("\\"))return Z;return OB}function mM(){let $=w9?.current();if($)return $;if(typeof window>"u")return null;return{pathname:window.location.pathname,search:window.location.search}}var MB=($)=>$.replace(/\/+$/,"")||"/";function hM($,Z){let W=s8($),Y=new URL($,"http://gemi.invalid");if(!W&&MB(Y.pathname)===MB(Z.pathname))return null;return Y.searchParams.set(a0,W?Z.pathname:`${Z.pathname}${Z.search}`),W?Y.href:`${Y.pathname}${Y.search}`}function pM($){if(!s8($)&&w9)w9.replace($);else window.location.replace($)}function TB($){if(!k9||typeof window>"u")return;if(!HB($.status,$.body))return;if($.path.split("?")[0]==="/auth/me")return;if(G3==="handled")return;if(G3==="idle"&&LB>=gM)return;if($.refetch)f9.push($.refetch);if(G3==="checking")return;G3="checking",LB++;let Z=$;setTimeout(()=>{cM(Z)},vM)}async function cM($){let Z=!1,W=$.headers?.get?.(q9)?$.headers:null;try{let X=await fetch("/api/auth/me",{cache:"no-store",headers:{Accept:"application/json"}}),G=null;try{G=await X.json()}catch{}if(Z=HB(X.status,G),Z&&!W)W=X.headers}catch{}let Y=f9;if(f9=[],!Z){G3="idle";for(let X of Y)try{X()}catch(G){console.error(G)}return}G3="handled";let J=mM();if(!J)return;let j=hM(yM(W),J);if(!j)return;let z={source:$.source,path:$.path,error:$.error,signInUrl:j,redirect:()=>pM(j)};try{if(k9==="redirect")z.redirect();else k9?.(z)}catch(X){console.error(X)}}class v9 extends Error{url;timeout;constructor($,Z){super(`Request to ${$} timed out after ${Z}ms`);this.url=$;this.timeout=Z;this.name="TimeoutError"}}function KB($,Z){let W=!1,Y=!1,J,j=1/0,z=null,X=(G)=>{if(!$||Y)return;if(typeof G!=="number"||!(G>0)||!Number.isFinite(G))return;let Q=Date.now();if(Q+G>=j)return;if(J=G,j=Q+G,z!==null)clearTimeout(z);z=setTimeout(()=>{W=!0,$.abort()},G)};return X(Z),{timedOut:()=>W,timeout:()=>J,tighten:X,clear:()=>{if(Y=!0,z!==null)clearTimeout(z)}}}var g9=5000,dM=2147483647;class UZ{store;staleVariants=new Set;lastFetchRecord=new Map;key;inflight=new Set;pending=new Map;watchers=new Map;failures=new Map;retryTimers=new Map;seq=0;issued=new Map;applied=new Map;controllers=new Map;streamed=new Set;timeouts=new Map;renderTimeouts=new Map;renderTimeoutsClearing=!1;requestTimers=new Map;constructor($,Z){this.key=$,this.store=new R9(new Map),this.hydrate(Z)}hydrate($,Z=!1){let W=this.store.getValue(),Y=Date.now(),J=!1;for(let[j,z]of Object.entries($??{})){if(z===void 0)continue;let X=W.get(j);if(X?.loading)continue;if(X?.hasData&&X.data===z)continue;if(this.fill(W,j,z,Y),Z)this.streamed.add(j);J=!0}if(J)this.store.next(W)}pendingFor($){let Z=this.pending.get($);if(!Z){let W;Z={promise:new Promise((J)=>{W=J}),resolve:W},this.pending.set($,Z)}return Z}settle($){let Z=this.pending.get($);if(Z)this.pending.delete($),Z.resolve()}isStale($,Z){if(this.staleVariants.has($))return!0;let W=Date.now();return W-(this.lastFetchRecord.get($)??W)>=Z}peek($){return this.store.getValue().get($)}peekForHydration($){return this.streamed.has($)?void 0:this.peek($)}setRequestTimeout($,Z){if(!PB(Z))return;this.tightenInflight($,Z);let W=this.renderTimeouts.get($);if(W===void 0||Z<W)this.renderTimeouts.set($,Z);if(this.renderTimeoutsClearing)return;this.renderTimeoutsClearing=!0,Promise.resolve().then(()=>{this.renderTimeoutsClearing=!1,this.renderTimeouts.clear()})}holdRequestTimeout($,Z){if(!PB(Z))return()=>{};this.tightenInflight($,Z);let W={},Y=this.timeouts.get($);if(!Y)Y=new Map,this.timeouts.set($,Y);return Y.set(W,Z),()=>{let J=this.timeouts.get($);if(!J)return;if(J.delete(W),J.size===0)this.timeouts.delete($)}}tightenInflight($,Z){for(let W of this.requestTimers.get($)??[])W.tighten(Z)}requestTimeout($){let Z=this.renderTimeouts.get($);for(let W of this.timeouts.get($)?.values()??[])if(Z===void 0||W<Z)Z=W;return Z}isFetching($){return this.inflight.has($)}start($){if(typeof window>"u")return;if(this.store.getValue().has($))return;if(this.inflight.has($))return;this.resolveVariant($,!0)}read($,Z=g9){let W=this.peek($);if(W?.hasData){if(!this.inflight.has($)&&this.isStale($,Z))this.lastFetchRecord.set($,Date.now()),this.resolveVariant($,!0);return{state:W}}if(W?.error)return{state:W};if(typeof window>"u")return{state:W};let Y=this.pendingFor($);if(!this.inflight.has($))this.resolveVariant($,!0);return{state:W,promise:Y.promise}}getVariant($,Z=g9){let W=this.store.getValue();if(!W.has($)){if(!this.inflight.has($))this.resolveVariant($)}else{let Y=W.get($);if(!Y.loading&&!this.inflight.has($)){if(!Y.hasData)return this.resolveVariant($),W.get($);if(this.isStale($,Z))return this.lastFetchRecord.set($,Date.now()),this.resolveVariant($,!0),W.get($)}}return W.get($)}revalidate($,Z=g9){if(typeof window>"u")return;if(this.inflight.has($))return;let W=this.peek($);if(W?.loading)return;if(W?.hasData){if(!this.isStale($,Z))return;this.lastFetchRecord.set($,Date.now())}this.resolveVariant($,!0)}clearError($){let Z=this.store.getValue(),W=!1;for(let[Y,J]of Z){if($!==void 0&&Y!==$)continue;if(J.error)Z.set(Y,{...J,error:null,reconnecting:!1}),W=!0}if(W)this.store.next(Z)}retain($){this.watchers.set($,(this.watchers.get($)??0)+1);let Z=!1;return()=>{if(Z)return;Z=!0;let W=(this.watchers.get($)??1)-1;if(W>0)this.watchers.set($,W);else this.watchers.delete($),this.cancelRetry($),this.setReconnecting($,!1),this.scheduleAbort($)}}scheduleAbort($){if(!this.controllers.has($))return;setTimeout(()=>{if(this.watchers.has($))return;this.abort($)},0)}abort($){let Z=this.controllers.get($);if(!Z)return;this.controllers.delete($);for(let W of Z)W.abort()}failureCount($){return this.failures.get($)??0}scheduleRetry($,Z){if(typeof window>"u")return;if(this.setReconnecting($,!0),this.retryTimers.has($)||this.inflight.has($))return;let W=Math.min(Math.max(0,Z||0),dM),Y=setTimeout(()=>{if(this.retryTimers.delete($),!this.watchers.has($))return;if(this.inflight.has($))return;let J=this.peek($);if(!J?.error||J.loading)return;this.resolveVariant($,J.hasData,!0,!0)},W);this.retryTimers.set($,Y)}giveUpRetry($){if(this.retryTimers.has($)||this.inflight.has($))return;this.setReconnecting($,!1)}setReconnecting($,Z){let W=this.store.getValue(),Y=W.get($);if(!Y||!!Y.reconnecting===Z)return;this.store.next(W.set($,{...Y,reconnecting:Z}))}cancelRetry($){let Z=this.retryTimers.get($);if(Z!==void 0)clearTimeout(Z),this.retryTimers.delete($)}retryNow($){if(typeof window>"u")return;if(this.inflight.has($))return;let Z=this.peek($);if(!Z?.error||Z.loading)return;this.resolveVariant($,!0)}variantKeys(){return[...this.store.getValue().keys()]}invalidate($,Z){this.dropHttpCache($);let W=this.store.getValue(),Y=W.get($);if(Z&&Y?.hasData)this.markApplied($),this.store.next(W.set($,{...Y,data:Z(Y.data),error:null,reconnecting:!1}));if(this.staleVariants.add($),this.watchers.has($))this.resolveVariant($,!1,!1)}dropHttpCache($){let Z=[typeof window<"u"&&window.location?.origin?window.location.origin:"",this.key,$].filter((W)=>W.length>0).join("?");try{if(caches)caches?.delete(Z)}catch{}}mutate($,Z=(W)=>W){this.dropHttpCache($);let W=this.store.getValue(),Y=W.get($);if(!Y||!Y.hasData){this.resolveVariant($,!1,!1);return}let J=Z(Y.data);this.markApplied($),this.staleVariants.add($),this.store.next(W.set($,{loading:!1,data:J,hasData:!0,error:null,version:Y.version})),this.resolveVariant($,!1,!1)}fill($,Z,W,Y){$.set(Z,{loading:!1,data:W,hasData:!0,error:null,version:Y}),this.staleVariants.delete(Z),this.lastFetchRecord.set(Z,Y),this.failures.delete(Z),this.cancelRetry(Z),this.settle(Z)}refetch($){this.resolveVariant($,!1,!1)}markApplied($){this.applied.set($,this.seq)}async resolveVariant($,Z=!1,W=!0,Y=!1){if(typeof window>"u")return;this.cancelRetry($),this.inflight.add($);let J=++this.seq;this.issued.set($,J);let j=typeof AbortController>"u"?null:new AbortController;if(j){let U=this.controllers.get($);if(!U)U=new Set,this.controllers.set($,U);U.add(j)}let z=KB(j,this.requestTimeout($)),X=this.requestTimers.get($);if(!X)X=new Set,this.requestTimers.set($,X);X.add(z);let G=()=>this.issued.get($)===J,Q=()=>(this.applied.get($)??0)>=J,F=()=>{this.failures.set($,Y?(this.failures.get($)??0)+1:1)},V=this.store.getValue(),B=(U)=>{if(!G())return;F();let O=V.get($);this.store.next(V.set($,{loading:!1,data:O?.data,hasData:O?.hasData??!1,error:U,version:O?.version,reconnecting:O?.reconnecting}))};try{let U=V.get($);if(!Z)V.set($,{loading:!0,data:U?.data,hasData:U?.hasData??!1,error:U?.error,version:U?.version,reconnecting:U?.reconnecting});let O=null,D=null,L=[this.key,$].filter((M)=>M.length).join("?");try{D=await fetch(`/api${L}`,{cache:W&&!this.staleVariants.has($)?"default":"reload",signal:j?.signal});try{O=await DB(D)}catch(M){if(D.ok||z.timedOut())throw M;O=null}}catch(M){if(z.timedOut()){B(new v9(`/api${L}`,z.timeout()));return}if(j?.signal.aborted){let T=V.get($);if(G()&&T?.loading)this.store.next(V.set($,{...T,loading:!1}));return}console.error(`Error fetching url /api${L}`,M),B(M);return}if(D.ok){if(Q()){let T=V.get($);if(G()&&T?.loading)this.store.next(V.set($,{...T,loading:!1}));return}this.applied.set($,J);let M=V.get($);this.store.next(V.set($,{loading:G()?!1:M?.loading??!1,data:O,hasData:!0,error:null,version:Date.now()})),this.staleVariants.delete($),this.lastFetchRecord.set($,Date.now()),this.failures.delete($)}else{let M=new Z1(this.key,$,D.status,O,UB(D.headers?.get?.("retry-after")));if(B(M),G())TB({source:"query",path:this.key,status:D.status,body:O,headers:D.headers,error:M,refetch:()=>this.resolveVariant($,!0,!1)})}}finally{z.clear();let U=this.requestTimers.get($);if(U?.delete(z),U?.size===0)this.requestTimers.delete($);if(j){let O=this.controllers.get($);if(O?.delete(j),O?.size===0)this.controllers.delete($)}if(G())this.inflight.delete($);this.settle($)}}}function PB($){return typeof $==="number"&&$>0}import{jsx as lM}from"react/jsx-runtime";var px=_B(null);var IB=_B({getResource:($,Z={})=>{return new UZ($,Z)},hydrate:()=>{},allResources:()=>[],clearErrors:()=>{}});function uM(){let $=new Map;return{getResource(Z,W){let Y=$.get(Z);if(!Y)Y=new UZ(Z,W??{}),$.set(Z,Y);return Y},hydrate(Z,W=!1){if(!Z)return;for(let[Y,J]of Object.entries(Z)){if(!J||typeof J!=="object")continue;let j=$.get(Y);if(!j)j=new UZ(Y,{}),$.set(Y,j);j.hydrate(J,W)}},allResources:()=>$.values(),clearErrors(){for(let Z of $.values())Z.clearError()}}}var NB="gemi.islandQueries";if(typeof window<"u"){let $=globalThis;if(!$[Symbol.for(NB)]){let Z=uM(),W={seed:Z.hydrate,Provider:({children:Y})=>lM(IB.Provider,{value:Z,children:Y})};$[Symbol.for(NB)]=W}}import{createContext as iM}from"react";var sM=iM(null);function CB($,Z={},W){let Y=new Set,J=new Map,j=W?{ensure(Q,F){let V=W.find(Q,F);if(!V||V.source!=="prefetch"||V.status==="rejected")return null;return z(V),V}}:null,z=(Q)=>J.set(`${Q.path}?${Q.variantKey}`,Q),G={queries:j,queriesRead:J,createQueryManager:()=>{if(!W)return null;let Q=new Map;return{getResource(F,V){let B=Q.get(F);if(!B){let U=new Map(W.entriesFor(F).filter((D)=>D.source==="prefetch"&&D.status==="resolved").map((D)=>[D.variantKey,D]));B=new UZ(F,U.size>0?Object.fromEntries(Array.from(U,([D,L])=>[D,L.data])):V??{});let O=B.peek.bind(B);B.peek=(D)=>{let L=U.get(D);if(L)z(L);return O(D)},Q.set(F,B)}return B},hydrate(){},allResources:()=>Q.values(),clearErrors(){}}},islands:[],render:$,instances:new WeakMap,count:0,i18n:{},localeAware:Boolean(Z.currentLocale),i18nUsed:!1,dictionaries:[],sink:{use(Q,F,V){let B=`${Q} ${F}`;if(Y.has(B))return;Y.add(B),G.dictionaries.push([Q,F,V])},onUse(){}}};for(let Q of["currentLocale","defaultLocale","timeZone"])Object.defineProperty(G.i18n,Q,{enumerable:!0,get(){return G.i18nUsed=!0,Z[Q]}});return G}function xB($){if(!$.i18nUsed&&!$.localeAware)return;let{currentLocale:Z,defaultLocale:W,timeZone:Y}=$.i18n;return{...Z?{currentLocale:Z}:{},...W?{defaultLocale:W}:{},...Y?{timeZone:Y}:{},...$.dictionaries.length>0?{dictionaries:$.dictionaries}:{}}}function AB($){let Z;for(let W of $.queriesRead.values()){if(W.status!=="resolved")continue;Z??={},(Z[W.path]??={})[W.variantKey]=W.data}return Z}var W6="gemi-slot",SB="data-slot",bB="data-gemi-slot";var oM=Symbol.for("gemi.staticRender"),EB=globalThis[oM]??=nM(null);import{createHash as qB}from"crypto";var y9='var r=document,i=window,a=history;i.__gemi_nav?.d();var C=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:C.signal,...s}),q=i.__gemi_nav={d:()=>C.abort()},y=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},L=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},D=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")y(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>y(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),y(n,s)});for(let m of n.children)l.observe(m)}}},R=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(R)?.content,O=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],N=O(r),p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},v={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,Y=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},j=(t)=>{let e=r.body,n=t.body,s=L(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),D(e,s)},H=async(t,e)=>{let n=++b,s=!e&&v[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||O(d)!=N)throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),j(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)Y(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),v[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=v[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(v[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(R)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();D(r,L(r));_(!0);';import{createHash as aM}from"crypto";import{existsSync as kB,readFileSync as tM}from"fs";import{join as c9}from"path";var wB=".script",rM=[".ts",".js"],eM="document-scripts.json",fB="data-gemi-script",$H=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function ZH($){if(typeof $!=="string"||!$H.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 WH($,Z){for(let W of rM){let Y=c9($,"views",`${Z}${wB}${W}`);if(kB(Y))return Y}return null}async function RB($){let Z=await Bun.build({entrypoints:[$],target:"browser",format:"iife",minify:!0,throw:!1});if(!Z.success||!Z.outputs[0]){let Y=Z.logs.map((J)=>String(J)).join(`
|
|
22
|
+
`);throw Error(`The document script ${$} does not bundle.
|
|
23
|
+
${Y}`)}let W=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(W))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 W}function d9($){return`'sha256-${aM("sha256").update($).digest("base64")}'`}var m9,h9=new Map;function YH(){if(m9===void 0){let $=c9(p9(),"dist","server",eM);m9=kB($)?JSON.parse(tM($,"utf8")):null}return m9??null}async function u9($){ZH($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=YH()?.[$];if(j!==void 0)return j;let z=h9.get($);if(z)return z}let W=c9(p9(),"app"),Y=WH(W,$);if(!Y)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${wB}.ts (or .js).`);if(!Z)return RB(Y);let J=RB(Y);return h9.set($,J),J.catch(()=>h9.delete($)),J}async function QA($){return d9(await u9($))}var JH="gemi-islands",jH="gemi-island-i18n",zH="gemi-island-queries",MA=`'sha256-${qB("sha256").update(s9).digest("base64")}'`;function l9($,Z,W,Y){if(!W)return $;let J=Y?$.lastIndexOf(Z):$.indexOf(Z);return J===-1?$+W:$.slice(0,J)+W+$.slice(J)}var i9=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),HA=`'sha256-${qB("sha256").update(y9).digest("base64")}'`,XH='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',GH="gemi-static";function vB($,Z,W,Y,J,j,z){let X=new Set,G=[];if(W)G=Z.islands.map((T)=>{let K=T.module?W(T.module):void 0;if(!K)return console.error(`[gemi] island ${T.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(T.load==="eager"){for(let N of K.preload)X.add(N);if(T.preloadDynamic)for(let N of K.dynamicPreload??[])X.add(N)}return{s:K.src,e:T.export,l:T.load}});let Q=G.some((T)=>T!==null),F=j?`<script type="module" ${fB}="${i9(j.name)}">${j.source}</script>`:"";if(j)z?.push(j.source);if(!Q&&!J)return l9($,"</head>",F,!1);let B=(J?`<meta name="${GH}" content="${i9(J.identity)}"${J.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...X].map((T)=>`<link rel="modulepreload" href="${i9(T)}"/>`).join("")+F,U=J?y9:s9,O=Y?XH+U:U;z?.push(O);let D=Q?xB(Z):void 0,L=Q?AB(Z):void 0,M=(Q?`<script type="application/json" id="${JH}">${t0({i:G})}</script>`:"")+(D?`<script type="application/json" id="${jH}">${t0(D)}</script>`:"")+(L?`<script type="application/json" id="${zH}">${t0(L)}</script>`:"")+`<script type="module">${O}</script>`;return l9(l9($,"</head>",B,!1),"</body>",M,!0)}function QH($,Z){let W=/<(\/?)template\b[^>]*>/gi;W.lastIndex=Z;let Y=0;for(let J=W.exec($);J;J=W.exec($))if(Y+=J[1]?-1:1,Y===0)return W.lastIndex;return-1}function gB($){let Z=`<template ${bB}="`;for(let W=$.lastIndexOf(Z);W!==-1;W=$.lastIndexOf(Z)){let Y=QH($,W);if(Y===-1)break;let J=W+Z.length,j=$.slice(J,$.indexOf('"',J)),z=$.indexOf(">",J)+1,X=$.slice(z,Y-11);$=$.slice(0,W)+$.slice(Y);let G=`<${W6} ${SB}="${j}" style="display:contents"></${W6}>`;$=$.split(G).join(`<${W6} style="display:contents">${X}</${W6}>`)}return $}function n9($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function pB($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}function BH($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var yB=new Set,FH=new Set(["public","private","s-maxage","proxy-revalidate"]);function o9($,Z){let W=$.get("Cache-Control");if(!W||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(W))return;let Y=cB(W);if(Bun.env.NODE_ENV!=="production"&&!yB.has(Z)){yB.add(Z);let J=[...new Set($.getSetCookie().map((j)=>j.split("=")[0]))];console.warn(`[gemi] The view "${Z??""}" sets cookies (${J.join(", ")}) on a response with Cache-Control "${W}", so it was sent "${Y}" instead: a shared cache would hand those cookies to every visitor. To let a CDN cache the page, make it a static view with .static({ cacheControl }).`)}$.set("Cache-Control",Y)}function cB($){return["private",...$.split(",").map((W)=>W.trim()).filter((W)=>{let Y=W.split("=")[0].trim().toLowerCase();return Y!==""&&!FH.has(Y)})].join(", ")}var mB=new Set;function dB($,Z,W){let Y=$.get("Cache-Control");if(!Y||!/(^|[\s,])(public|s-maxage)\b/i.test(Y))return;let J=cB(Y);if(W&&Bun.env.NODE_ENV!=="production"&&!mB.has(Z))mB.add(Z),console.warn(`[gemi] The static view "${Z??""}" asked for a CSP nonce (cspNonce()) on a response with Cache-Control "${Y}", so it was sent "${J}" instead: a shared cache would hand the same nonce to every visitor. Allow a static page's scripts by hash instead (route.view.csp does).`);$.set("Cache-Control",J)}var hB=new Set;function uB($,Z){if(!BH($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!hB.has(Z))hB.add(Z),console.warn(`[gemi] The file route "${Z??""}" set a cookie on a response with Cache-Control "${$.headers.get("Cache-Control")}", so the cookie was not sent: a shared cache would hand it to every visitor. Make the response private, or set the cookie elsewhere.`);try{return $.headers.delete("Set-Cookie"),$}catch{let W=new Headers($.headers);return W.delete("Set-Cookie"),new Response($.body,{status:$.status,statusText:$.statusText,headers:W})}}var VH="'strict-dynamic' 'self' https: 'unsafe-inline'",lB="Content-Security-Policy",iB="Content-Security-Policy-Report-Only";function UH($,Z={}){let W=[...$.nonce?[`'nonce-${$.nonce}'`]:[],...$.hashes??[]],Y=[W.length>0?`script-src ${W.join(" ")} ${VH}`:"script-src 'none'","object-src 'none'","base-uri 'self'"];if(Z.reportUri)Y.push(`report-uri ${Z.reportUri}`);return Y.join("; ")}function a9($,Z,W){if(!Z)return;if($.has(lB)||$.has(iB))return;let Y=Z===!0?{}:Z;$.set(Y.reportOnly?iB:lB,UH({nonce:W.nonce,hashes:[...new Set(W.inlineScripts??[])].map(d9)},Y))}var OH=async()=>(await import("./chunk-rqknf5k0.js")).default,t9,Y6=async(...$)=>{return t9??=import("react-dom/server.browser").catch((Z)=>{throw t9=void 0,Z}),(await t9).renderToReadableStream(...$)},nB=1e4,oB="no-locale",LH="no-theme";async function MH($,Z,W){let Y=`${W==="italic"?"italic,":""}wght@${W==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${Y}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var Y2="/assets";function HH($){return $===Y2||$.startsWith(`${Y2}/`)}function TH($){let Z=$.filter(HH);if(Z.length>0){let W=Z.length>1;throw Error(`View route path${W?"s":""} ${Z.map((Y)=>`"${Y}"`).join(", ")} use${W?"":"s"} the reserved "${Y2}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else, or set \`assetRoutes: true\` on these views' config (route.view or a route.domains group's view).`)}}function KH($){let Z=H(U1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function r9($){let{status:Z=400,error:W,body:Y,...J}=$;return new Response(Y??W?.message,{...J,status:Z})}function PH($){let{status:Z=400,data:W,directive:Y,headers:J}=$,j=new Headers(J);if(!j.has("Cache-Control"))j.set("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");return new Response(JSON.stringify({data:W,directive:Y}),{headers:j,status:Z})}class J6{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=BB();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;assetCors;translate;csp;constructor($,Z={}){let W=AQ();if(this.partialRendering=$.partialRendering??W.partialRendering,this.localeRouting=$.localeRouting??W.localeRouting,this.detectLocale=$.detectLocale,this.detectLocale&&this.localeRouting!=="off")throw Error('`view.detectLocale` needs `view.localeRouting: "off"`: on locale-routed views the URL, the `i18n-locale` cookie and `Accept-Language` decide the locale. A `route.domains` group that inherits it and keeps locale routing can set `detectLocale: undefined`.');this.theme=$.theme??W.theme,this.defaultMeta=$.meta,this.notFound=$.notFound,this.publicFiles=$.publicFiles??W.publicFiles,this.assetRoutes=$.assetRoutes??W.assetRoutes,this.assetCors=$.assetCors??W.assetCors,this.translate=$.translate,this.csp=$.csp,this.hooks={onNotFound:$.onNotFound??W.onNotFound,onRequestStart:$.onRequestStart??W.onRequestStart,onRequestEnd:$.onRequestEnd??W.onRequestEnd,onRequestFail:$.onRequestFail??W.onRequestFail,onStreamComplete:$.onStreamComplete??W.onStreamComplete};let Y={"/":$.rootRouter,"/auth":TQ(Z)};if(this.requiredViews=Object.fromEntries(MQ(Z).map(({view:J,requiredBy:j})=>[J,j])),this.flatViewRoutes=G8(Y),!this.assetRoutes)TH(Object.keys(this.flatViewRoutes));this.routeManifest=Q8(Y),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,J])=>J.at(-1)!=="FILE")),this.componentTree=F8(Y),this.flatComponentTree=S9(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,J])=>J.static).map(([J])=>J);for(let J of this.staticRoutes){let j=this.flatViewRoutes[J].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}if(this.notFound){for(let J of[this.notFound.view,this.notFound.static?.layout])if(J&&!this.flatComponentTree.includes(J))this.flatComponentTree.push(J)}this.root=$.root}async passesFeatureGates($){let Z=H(j$);for(let W of $)if(!await Z.enabled(W))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)U8();return await this.hooks.onRequestEnd($)}completeStream($,Z){let W=(Y)=>{DZ.error(Y?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(Y)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(W)}catch(Y){W(Y)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:W,views:Y,routeKey:J}=$,j=()=>{let G=new Set(Z?.preload??[]);for(let Q of Y)for(let F of W?.[Q]??[])G.add(F);return[...G].map((Q)=>n1("link",{key:`modulepreload:${Q}`,rel:"modulepreload",href:Q}))};if(!W)return j();let z=this.preloadCache.get(W);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(W,z);let X=z.byRoute.get(J);if(!X)X=j(),z.byRoute.set(J,X);return X}async renderStatic($){let{req:Z,runInRequestScope:W,staticView:Y,currentViews:J,data:j,serverQueries:z,headers:X}=$,G;if(Y.layout){if(G=$.viewImportMap[Y.layout],!G)throw Error(`The static layout "${Y.layout}" was not found. It is a view path: a file at app/views/${Y.layout}.tsx whose default export renders the document.`)}let Q=await $.getStyles(J,{static:!0,layout:Y.layout});z.markRenderStart();let F=W2(),V=new AbortController,B=setTimeout(()=>V.abort(),nB),U=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},O=CB(async(D,L)=>{let M=await Y6(D,{signal:V.signal,identifierPrefix:L,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});return await M.allReady.catch(()=>{}),await new Response(M).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone},z);try{let D,L=typeof Y.script==="function"?await W(()=>Y.script(Z)):Y.script;if(L)D={name:L,source:await u9(L)};let M;if(Y.navigation){let x=Y.navigation===!0?{}:Y.navigation,b=x.version?String(await W(()=>x.version(Z))):"";M={identity:[Y.layout??"",$.buildId??"",D?.name??"",b].join("|"),prefetch:x.prefetch==="none"?"none":"intent"}}let T=await Y6(n1(EB.Provider,{value:O,children:n1(sB,{children:[...Q,n1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:F,rootLayout:G,key:"root"})]})}),{signal:V.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});await T.allReady.catch(()=>{});let K=gB(await new Response(T).text()),N=[],_=vB(K,O,$.resolveIsland,Bun.env.NODE_ENV!=="production",M,D,N);return a9(X,this.csp,{nonce:e9(Z.rawRequest),inlineScripts:N}),new Response(_,{status:$.status,headers:X})}finally{clearTimeout(B),W(()=>this.completeStream(Z,z.summarize(V.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:W,csrfTokenHMAC:Y,currentPathName:J,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:F,noStream:V,noTheme:B,url:U,user:O,viewData:D,breadcrumbs:L,urlLocaleSegment:M,meta:T,isOgRequest:K,appId:N,features:_,staticView:x,cspNonce:b}=$,w=this.theme===!1||B||x?null:{cookie:this.theme.cookie??x9,default:this.theme.default??null,value:NH(Z,this.theme.cookie??x9)},A=M?GB(G,[M]).pathname:G,f={kind:"view",data:{meta:T,pageData:{[A]:D},__csrf:Y.toString("base64"),prefetchedData:{},i18n:z,auth:{user:O},routeManifest:this.clientRouteManifest,breadcrumbs:L,router:{urlLocaleSegment:M,pathname:J,params:X,currentPath:G,searchParams:U.search,is404:!J?!0:!1,domain:Z.domain?KH(Z):null},appId:N,features:_,theme:w,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},I=this.root,k=this.routeManifest[J];return async(K0)=>{let{bootstrapModules:B3=[],loaders:MZ,getStyles:S$,viewImportMap:c,cssManifest:g,ogMap:D0,viewModules:D1,clientEntry:b$,modulePreloadManifest:F3,assetBase:n0,resolveIsland:E$,buildId:E1}=K0,R1=b$?[]:B3,i=(y)=>[y,`window.loaders=${MZ}`,...b$?[`import(${JSON.stringify(b$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(K){let y=null,O1=null;for(let E of k??[])if(typeof D0[E]==="function")O1=E,y=D0[E];if(!y)return new Response("Not found",{status:404});let G6=Object.values(f.data.pageData)[0];try{await Y6(n1(y,G6[O1]),{onError:()=>{}})}catch(E){let{fonts:e,...t1}=E.satoriOptions,Q6=await Promise.all(e.map((B6)=>{return MH(B6.name,B6.weight,B6.style).then((eF)=>({...B6,data:eF}))})),k2=new Headers(j);k2.set("Content-Type","image/png");let[oF,aF]=await Promise.all([OH(),j8("Rendering an OG image")]),tF=await oF(E.jsx,{...t1,fonts:Q6}),rF=await aF(Buffer.from(tF)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(rF),{headers:k2})}return new Response("data")}if(x&&J)return await this.renderStatic({req:Z,runInRequestScope:W,staticView:x,currentViews:k,data:f.data,serverQueries:Q,headers:j,getStyles:S$,viewImportMap:c,viewModules:D1,resolveIsland:E$,buildId:E1,status:200});if(x&&!J&&this.notFound){let y=this.notFound.view;if(!c[y])throw Error(`The not-found view "${y}" (route.view.notFound) was not found. It is a view path: a file at app/views/${y}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:W,staticView:x,currentViews:[y],data:f.data,serverQueries:Q,headers:j,getStyles:S$,viewImportMap:{...c,"404":c[y]},viewModules:D1&&{...D1,"404":D1[y]},resolveIsland:E$,buildId:E1,status:$.refusedStatus??404})}if(f.data.cssManifest=g,f.data.modulePreloadManifest=F3??{},n0&&n0!=="/")f.data.assetBase=n0;if(E1&&E1!=="dev")f.data.buildId=E1;let b8=aB(this.modulePreloadLinks({clientEntry:b$,modulePreloadManifest:F3,views:k??["404"],routeKey:J??"404"}),b),E8=aB(await S$(k??["404"]),b);f.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let W1=new AbortController,HZ=setTimeout(()=>W1.abort(),nB),R$=q6(F)||V,a1=Bun.env.NODE_ENV!=="production"&&!R$&&J&&this.shellReporter.shouldObserve(J)?FB():null,k$=W2();try{let y=await Y6(n1(sB,{children:XB(b8,[...E8,...w?[n1("script",{key:"theme-script",nonce:b,dangerouslySetInnerHTML:{__html:eQ(t0({cookie:w.cookie,default:w.default}))}})]:[]],n1(I,{data:f.data,viewImportMap:c,viewModules:D1,serverQueries:Q,dictionarySink:k$,cspNonce:b,key:"root"}))}),{bootstrapScriptContent:i(`window.__GEMI_DATA__ = ${t0(f.data)}`),bootstrapModules:R1,nonce:b,signal:W1.signal,...R$?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(O1){if(Bun.env.NODE_ENV!=="production")console.error(O1)}});if(y.allReady.catch(()=>{}).finally(()=>clearTimeout(HZ)),R$)await y.allReady.catch(()=>{});return new Response(M5(y,Q,{onShell:R$?void 0:()=>Q.markShell(),onChunk:a1?.onChunk,onClose:()=>W(()=>{if(this.completeStream(Z,Q.summarize(W1.signal.aborted)),a1)this.shellReporter.report(J,a1.measure())})},k$,b),{status:!J?$.refusedStatus??404:200,headers:j})}catch(y){if(clearTimeout(HZ),Bun.env.NODE_ENV==="production")throw W(()=>this.completeStream(Z,Q.summarize(W1.signal.aborted))),y;let O1=await Y6(n1("div"),{bootstrapScriptContent:i(`window.error= ${t0(y.message)}; window.stack_trace=${t0(y.stack)};window.__GEMI_DATA__ = ${t0(f.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...R1]:R1,nonce:b});return new Response(M5(O1,Q,{onClose:()=>W(()=>this.completeStream(Z,Q.summarize(W1.signal.aborted)))},void 0,b),{status:!J?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,W){if(q$(Z))return 404;if(Z?.kind===Z$){let Y=Z.payload?.view?.status;return Y===403||Y===404?Y:null}if(W$(Z)){if(!W.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof Z1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let W=new URL($.url),Y=ZB(this.flatViewRoutes,W.pathname),J=WB(this.flatViewRoutes,W.pathname),j=Y?W.pathname.slice(0,-5):J?W.pathname.slice(0,-3):W.pathname,[,z,...X]=j.split("/"),G=j,Q=null,F=null,V=H(l),B=Y3(this.flatViewRoutes,j),U=V.isLocaleAware&&this.localeRouting==="prefix"&&!B?.route.middleware.includes(oB);if(U&&V.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,F=z;if(($.method==="GET"||$.method==="HEAD")&&!Y&&!J&&B===null&&W.pathname.endsWith("/")&&!W.pathname.startsWith("//")){let I=W.pathname.replace(/\/+$/,""),k=U&&V.supportedLocales.includes(I.slice(1));if(I&&!k)return new Response("",{status:301,headers:{Location:`${I}${W.search}`}})}if(U&&!J&&F===null&&!(F===null&&B!==null)){let I=$2(z,V.supportedLocales,V.defaultLocale);if(I){let k=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${I}${k}${Y?".json":""}${W.search}`}})}}if(U&&!J){let I=H(l).detectLocale(new S($,{},"view",G));if(F===null&&I!==V.defaultLocale){let k=W.pathname==="/"?"":W.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${I}${k}${W.search}`}})}}G=G.replace("//","/");let D=[],L=[],M=null,T={},K=null,N=!1,_=!1,x=[],b,w=!1,A=!1;try{let I=Y3(this.flatViewRoutes,G);if(F&&I?.route.middleware.includes(oB))I=null;if(I){if(w=!0,M=I.routePath,T=I.params,D=I.route.exec,L=I.route.middleware,x=I.route.features,N=L.includes("no-stream"),_=L.includes(LH),b=I.route.static,A=I.route.segments.at(-1)?.viewPath==="FILE",Y&&this.partialRendering){let k=$.headers.get(A9),K0=JB({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(l).supportedLocales,from:k,origin:W.origin,to:{segments:I.route.segments,params:T,search:W.search}});if(K0.startIndex>0)D=D.slice(K0.startIndex),K={from:k,carriedViews:K0.carriedViews}}}}catch(I){throw I}if(b&&Y)return new Response("Not found",{status:404});let f=new S($,T,"view",M);return this.hooks.onRequestStart(f),await P.run(f,async()=>{let I=null,k=P.getStore(),K0=j3.getStore(),B3=(g)=>j3.run(K0,()=>P.runWith(k,g));k.serverQueries=new VZ(X3($));let MZ=new Set;k.serverQueries.onQueryFail((g)=>{MZ.add(g.error);try{B3(()=>Promise.resolve(this.hooks.onRequestFail(c,g.error)).catch(()=>{}))}catch{}});let S$=n9(A?{}:b??(M===null&&!Y?this.notFound?.static:void 0));if(F){let g=F.replaceAll("/","");x$.setLocale(g,{cookie:S$.locale})}else if(V.isLocaleAware&&!U)k.setLocale(V.defaultLocale);else x$.setLocale(void 0,{cookie:S$.locale});let c=k.req;if(S$.session)U8();try{let g=null;if(this.detectLocale&&!U&&H(l).isLocaleAware){let{supportedLocales:E,defaultLocale:e}=H(l),t1=await this.detectLocale(c,{supportedLocales:E,defaultLocale:e}),Q6=typeof t1==="string"?$2(t1,E,e):null;if(Q6)k.setLocale(Q6)}try{await H($$).runMiddleware(L)}catch(E){if(g=this.viewRefusalStatus(c,E,MZ),g===null)throw E}if(g!==null||x.length>0&&!await this.passesFeatureGates(x))M=null,D=[],c.routePath="";let D0=H(l),D1=D0.isEnabled,b$=D0.isLocaleAware,F3=new S($,c.params),n0={defaultLocale:D0.defaultLocale,timeZone:D0.detectTimeZone(F3)};if(b$){let E=null;if(F)E=F.replaceAll("/",""),k.setLocale(E);else if(!U)E=k.locale??D0.defaultLocale;else E=D0.detectLocale(F3),k.setLocale(E);let e=D1?D0.getPageTranslations(E,c.routePath):{};n0={...n0,supportedLocales:D0.supportedLocales,currentLocale:E,dictionary:{[E]:e},defaultLocale:D0.defaultLocale,...U?{}:{localeRouting:"off"}}}await Z2(n0.currentLocale??"");let E$;try{E$=await Promise.all(D.map((E)=>E(c)))}catch(E){if(g=this.viewRefusalStatus(c,E,MZ),g===null)throw E;M=null,D=[],c.routePath="",E$=[]}let E1=void 0;if(M===null){if(E1=await this.hooks.onNotFound(c,{status:g??404}),b$&&!U&&k.locale&&k.locale!==n0.currentLocale){let E=k.locale;n0={...n0,currentLocale:E,dictionary:{[E]:D1?D0.getPageTranslations(E,c.routePath):{}}},await Z2(E)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(c):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:R1,headers:i}=k;if(g!==null)i.set("Cache-Control","no-store");I={data:E$,cookies:R1,headers:i,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:M,params:c.params,urlLocaleSegment:Q,meta:k.renderMeta(),appId:H(b9).id,features:await H(j$).forClient()};let{params:b8,user:E8}=I,W1={},HZ={};for(let E of E$??[]){let[e,t1]=Object.entries(E)?.[0]??[];if(!e||!t1)continue;HZ[`${e}:${M}`]=t1.breadcrumb,W1[e]=t1}let R$=M===null&&this.notFound&&!Y?this.notFound.static:void 0;if(R$&&E1)W1["404"]=E1;let a1=W1.FILE;if(a1){try{await this.onRequestEnd(c,{mintSession:!1})}catch(e){DZ.error(e?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(e)})}let E;if(a1 instanceof Response)E=D8(a1,i,R1);else{for(let e of R1)i.append("Set-Cookie",e.toString());E=await i8(a1,i)}return uB(E,M)}if(Y){i.set("Content-Type","application/x-ndjson; charset=utf-8"),i.append("Vary",A9),R1.forEach((e)=>i.append("Set-Cookie",e.toString())),o9(i,M),await this.hooks.onRequestEnd(c);let E={meta:K&&!k.metadata.touched?null:I.meta,data:{[G]:W1},breadcrumbs:HZ,prefetchedData:k.serverQueries.snapshotResolved(),i18n:n0,features:I.features,is404:!M,appId:I.appId,partial:K};return new Response(VB(E,k.serverQueries,void 0,({aborted:e})=>B3(()=>this.completeStream(c,k.serverQueries.summarize(e)))),{headers:i})}i.set("Content-Type","text/html; charset=utf-8");let k$=M?b:R$,y=Boolean(k$),O1=n9(k$);if(!N&&!y)i.append("Vary","User-Agent");if(!y||O1.session)U8();for(let E of R1)i.append("Set-Cookie",E.toString());if(!y||O1.csrf){let E=Bun.CSRF.generate(process.env.SECRET);i.append("Set-Cookie",`csrf_token=${E}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(c,{mintSession:!y||O1.session})}catch(E){DZ.error(E?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(E)})}if(y&&(M||!w))pB(i,k$);o9(i,M);let G6=y?void 0:tB($);if(!y)a9(i,this.csp,{nonce:G6});if(e9($))dB(i,M,y);return await this.render({req:c,runInRequestScope:B3,csrfTokenHMAC:Buffer.from(""),currentPathName:M,headers:i,i18n:n0,params:b8,pathname:W.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:N,noTheme:_,url:W,user:E8,viewData:W1,breadcrumbs:HZ,urlLocaleSegment:Q,meta:I.meta,appId:I.appId,features:I.features,isOgRequest:J,staticView:k$,refusedStatus:g??void 0,cspNonce:G6})}catch(g){if(g.kind===Z$){let D0=Y?PH(g.payload.viewData??g.payload.api):r9(g.payload.view);for(let D1 of k.cookies)D0.headers.append("Set-Cookie",D1.toString());return D0}if(!MZ.has(g))this.hooks.onRequestFail(c,g);if(W$(g))return console.error(g),Y?J3():r9(E9());if(g instanceof Z1&&g.status===403)return Y?J3():r9(E9());throw g}},Z)}}function aB($,Z){return Z?$.map((W)=>DH(W,{nonce:Z})):$}function NH($,Z){let W=$.cookies?.get(Z);return rQ(W)?W:null}function _H($){return(Array.isArray($)?$:String($).split("/")).map((W)=>encodeURIComponent(String(W))).join("/")}function j2($,Z={}){let W=$.replace(/\/:(\w+)([*?]?)/g,(Y,J,j)=>{let z=Object.hasOwn(Z,J)?Z[J]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${J}.`)}return`/${j==="*"?_H(z):encodeURIComponent(String(z))}`});return`${O8}${W==="/"?"":W}`||O8}var rB=new Map;function eB($,Z){let W=rB.get($);if(!W)W=new URLPattern({pathname:`${O8}${$==="/"?"":$}`}),rB.set($,W);let Y;try{Y=new URL(Z,"http://localhost").pathname}catch{return null}let J=W.exec({pathname:Y})?.pathname.groups;return J?z2(J):null}function z2($){let Z=[];try{for(let[W,Y]of Object.entries($))if(Y!==void 0)Z.push([W,decodeURIComponent(Y)])}catch{return null}return Object.fromEntries(Z)}function X2(){let $=JSON.stringify({error:Y$("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 YF extends A0{routes={"/api-routes":this.get(()=>{let $=H(L8).flatRoutes,Z=[];for(let[W,Y]of Object.entries($))for(let[J,j]of Object.entries(Y)){let{exec:z,middleware:X}=j;Z.push({path:W,method:J,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=H(J6).flatViewRoutes,Z=[];for(let[W,{middleware:Y,viewPath:J}]of Object.entries($))Z.push({path:W,method:"GET",viewPath:J,middleware:Y});return Z})}}var IH=new Set([e1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),CH=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,xH=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function AH($,Z,W,Y){for(let[J,j]of Object.entries(W.headers??{})){if(j===void 0||j===null)continue;let z=J.toLowerCase();if(IH.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${J}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(Y&&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(J,j)}for(let[J,j]of Object.entries(W.cookies??{})){if(j===void 0||j===null)continue;if(J===e1)throw Error(`dispatchAs: credentials may not set the "${e1}" cookie. The access token stays the initiator's.`);if(!CH.test(J)||!xH.test(j))throw Error(`dispatchAs: "${J}" is not a cookie a Cookie header can carry.`);Z.push(`${J}=${j}`)}}function SH($,Z){let W=$.body.getReader(),Y=!1,J=()=>{if(Y)return;Y=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await W.read()}catch(G){J(),z.error(G);return}if(X.done){J();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await W.cancel(z)}finally{J()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function $F($){let{status:Z=400,data:W,headers:Y}=$,J=new Headers({"Content-Type":"application/json",...Y});if(!J.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(JSON.stringify(W),{status:Z,headers:J})}function D8($,Z,W){let Y=[];Z?.forEach((z,X)=>Y.push([X,z]));let J=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(W??[])];if(Y.length===0&&J.length===0)return $;let j=(z)=>{for(let[X,G]of Y){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,G)}for(let X of J)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function bH(){return Bun.env.NODE_ENV==="development"}class L8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=xQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=Q9({"/":$.rootRouter,"/auth":Y9,"/__gemi__/services/i18n":J9,"/__gemi__/services/image":X9,...bH()?{"/__gemi__/services/logs":G9,"/__gemi__/debug":YF}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),W=WF(Z.pathname),Y={},J;for(let[j]of Object.entries(this.flatRoutes))try{let X=new URLPattern({pathname:j}).exec({pathname:W});if(X){let G=z2(X.pathname.groups);if(!G)break;J=j,Y=G;break}}catch(z){console.error(z)}return{params:Y,path:J}}async runRouteMiddleware($,Z){let Y=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await H($$).runMiddleware(Y)}catch(J){if(J.kind===Z$)return $F(J.payload.api);else{if(q$(J))return X2();if(this.onRequestFail(Z,J),console.error(J),W$(J))return J3();throw J}}}async getRouteData($){let Z=this.flatRoutes[$],W=P.getStore(),Y=Z[W.req.rawRequest.method].exec??(()=>Promise.resolve({})),J={};try{J=await Y()}catch(j){if(j.kind===Z$)return $F(j.payload.api);if(q$(j))return X2();if(this.onRequestFail(W.req,j),console.error(j),W$(j))return J3();throw j}return J}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,W){let Y=async()=>{try{if(!this.isFrameworkRoute(W))await this.onRequestEnd(Z)}catch(J){DZ.error(J?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(J)})}finally{$.destroy()}};if(!$.hasPendingWork()){await Y();return}$.whenIdle().then(Y).catch((J)=>{console.error(J)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:W,path:Y}=this.getRouteHandlerAndParams($),J=this.flatRoutes[Y];if(J&&c2($)){let X={};for(let[G,Q]of Object.entries(J))if(G!=="OPTIONS")X[G]=Q.cors;if(Object.values(X).some(Boolean))return d2($,X)}if(!J||!J[$.method])return new Response(JSON.stringify({error:Y$("not_found","Not found",404)}),{status:404});let j=J[$.method].cors,z=await this.dispatchRoute($,W,Y,Z);return j?p2(z,j,$):z}async dispatchRoute($,Z,W,Y){let J=this.flatRoutes[W],j=new S($,Z,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await P.run(j,async()=>{let z=P.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,W)};try{let Q=H(l);if(Q.isEnabled){let D=Q.detectLocale(j);z.setLocale(D)}z.setRequest(j),H($$).applyDefaultBodyLimit($,J[$.method].bodyLimitDefault);let F=await this.runRouteMiddleware(W,j);if(F instanceof Response){let D=D8(F,z.headers,z.cookies);return await G(),D}let V=await this.getRouteData(W),B=z.headers,U=z.cookies;if(V instanceof Response){let D=D8(V,B,U);if(this.isOpenEndedBody($,D)){let L=SH(D,()=>this.endRequest(z,j,W));return X=!0,L}return await G(),D}let O=(r1(V)?V:L1.json(V)).toResponse(B,U);return await G(),O}catch(Q){if(!X)try{await G()}catch(F){console.error(F)}throw Q}},Y)}async dispatchAs($,Z,W,Y,J){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${W}`),X=`/api${W.split(/[?#]/)[0]}`;if(!W.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: "${W}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let G=J?.identity;if(G!==void 0&&(typeof G!=="object"||!G?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let Q=new Headers,F=[],V=G?null:$.cookies.get(e1);if(V)F.push(`${e1}=${V}`);if(J?.credentials)AH(Q,F,J.credentials,G!==void 0);if(F.length>0)Q.set("Cookie",F.join("; "));let B=G?null:$.headers.get(e1);if(B)Q.set(e1,B);let U=$.headers.get("User-Agent");if(U)Q.set("User-Agent",U);let O;if(Y instanceof FormData)O=Y;else if(Y!==void 0)Q.set("Content-Type","application/json"),O=JSON.stringify(Y);let D=new Request(z,{method:Z,headers:Q,body:O,...J?.signal?{signal:J.signal}:{}});if(ZF(D,P6($),G?.grant,J?.progress),$.domain)z3(D,$.domain);let L=G?{user:G.user}:void 0;return P.exit(()=>L6.exit(()=>this.handleApiRequest(D,L)))}}import{timingSafeEqual as EH}from"crypto";var T8="",B2="*",RH=60000,kH=1e4,M8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,H8=16,G2=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,Q2="x-forwarded-host",wH=/^[A-Za-z][A-Za-z0-9_-]*$/;function jF($){return $.startsWith(":")}function F2($){return $.subdomain===void 0}function V2($){return F2($)?$.name:$.subdomain}function fH($){let{params:Z}=$;return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function j6($,Z){if($===null)return!1;let W=Buffer.from($,"utf8"),Y=Buffer.from(Z,"utf8");return W.length===Y.length&&EH(W,Y)}function qH($){if(!$)return[];if($===!0)return[{header:Q2,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],W=Array.isArray($)?null:Q2;return Z.map((Y)=>({header:Y.hostHeader?.toLowerCase()??W,clientIpHeader:Y.clientIpHeader?.toLowerCase()??null,secret:Y.secret?{header:Y.secret.header.toLowerCase(),value:Y.secret.value}:null}))}function vH($){if(!$||$===!0)return;if(!Array.isArray($)){JF($,"route.domains.trustProxy",Q2);return}if($.length===0)throw Error("`route.domains.trustProxy` is an empty list. List at least one proxy, or leave `trustProxy` out.");let Z=new Map;$.forEach((W,Y)=>{let J=`route.domains.trustProxy[${Y}]`;if(typeof W!=="object"||W===null||Array.isArray(W))throw Error(`\`${J}\` must be an object: { hostHeader?, clientIpHeader?, secret }. \`true\` is only accepted on its own.`);if(!W.secret)throw Error(`\`${J}.secret\` is required: in a list, each proxy proves itself with a secret of its own.`);if(W.hostHeader===void 0&&W.clientIpHeader===void 0)throw Error(`\`${J}\` names neither \`hostHeader\` nor \`clientIpHeader\`, so it would trust nothing.`);JF(W,J,null);let j=Z.get(W.secret.value);if(j!==void 0)throw Error(`\`${J}.secret.value\` is the same as \`route.domains.trustProxy[${j}].secret.value\`. Give each proxy a secret of its own.`);Z.set(W.secret.value,Y)})}function JF($,Z,W){let{hostHeader:Y,clientIpHeader:J,secret:j}=$;if(Y!==void 0&&(typeof Y!=="string"||!G2.test(Y)))throw Error(`\`${Z}.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(Y)}.`);let z=(Y??W)?.toLowerCase()??null;if(J!==void 0){if(typeof J!=="string"||!G2.test(J))throw Error(`\`${Z}.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(J)}.`);if(!j)throw Error(`\`${Z}.clientIpHeader\` needs \`secret\`: without proof the proxy sent it, any client that reaches the app directly picks its own address.`);if(J.toLowerCase()===z)throw Error(`\`${Z}.clientIpHeader\` names the same header as \`hostHeader\`.`);if(typeof j.header==="string"&&J.toLowerCase()===j.header.toLowerCase())throw Error(`\`${Z}.clientIpHeader\` names the same header as \`secret.header\`.`)}if(!j)return;if(typeof j.header!=="string"||!G2.test(j.header))throw Error(`\`${Z}.secret.header\` must be a header name. Got "${j.header}".`);if(j.header.toLowerCase()===z)throw Error(`\`${Z}.secret.header\` names the same header as \`hostHeader\`; the secret needs a header of its own.`);if(typeof j.value!=="string"||j.value.length<H8)throw Error(`\`${Z}.secret.value\` must be at least ${H8} characters. A guessable one lets any client name its own host.`)}function A1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function gH($){try{let Z=new URL(`http://${$.trim()}`),W=Z.hostname.toLowerCase().replace(/\.$/,"");return W?Z.port?`${W}:${Z.port}`:W:null}catch{return null}}function zF($){if($===void 0)return[];if($===!0)return!0;if(!Array.isArray($))throw Error(`\`route.domains.devHosts\` must be a list of hostnames (or \`true\`). Got ${JSON.stringify($)}.`);return $.map((Z,W)=>{let Y=typeof Z==="string"?Z.trim().toLowerCase():"",J=Y.startsWith(".")?Y.slice(1):Y;if(!J||!J.split(".").every((j)=>M8.test(j)))throw Error(`\`route.domains.devHosts[${W}]\` must be a bare hostname, e.g. "app.acme.test", or ".acme.test" for the domain and its subdomains \u2014 no scheme, port, path or "*". Got ${JSON.stringify(Z)}.`);return Y})}function yH($){let Z=A1($.root),W=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==W||!Z.split(".").every((j)=>M8.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<H8)throw Error(`\`route.domains.ask.secret\` must be at least ${H8} characters. A guessable one is worse than leaving \`ask\` out.`);vH($.trustProxy),zF($.devHosts);let Y=new Set,J=null;for(let j of $.groups??[]){let z=j;if(z.subdomain!==void 0&&z.name!==void 0)throw Error(`The group "${z.subdomain}" declares both \`subdomain\` and \`name\` ("${z.name}"). Give a subdomain group its subdomain only, or leave \`subdomain\` out for a group only \`custom.resolve\` reaches.`);if(F2(j)){let{name:G}=j;if(typeof G!=="string"||!wH.test(G))throw Error(`A \`route.domains\` group needs a \`subdomain\`, or a \`name\` for a group only \`custom.resolve\` reaches. A name is one identifier, e.g. "shop-home": a letter, then letters, digits, "-" or "_". Got ${JSON.stringify(G)}.`);if(Y.has(G))throw Error(`\`route.domains\` declares "${G}" twice, as a subdomain or as a group's name.`);if(Y.add(G),j.exists)throw Error(`The group "${G}" has no subdomain, so \`exists\` has no param to check. Return \`null\` from \`custom.resolve\` for a host it should not serve.`);continue}let{subdomain:X}=j;if(Y.has(X))throw Error(`\`route.domains\` declares "${X}" twice, as a subdomain or as a group's name.`);if(Y.add(X),jF(X)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(X))throw Error(`"${X}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(J)throw Error(`\`route.domains\` declares two param subdomains, "${J.subdomain}" and "${X}"; a host could match either.`);J=j;continue}if(j.exists)throw Error(`The subdomain "${X}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!X.split(".").every((G)=>M8.test(G)))throw Error(`"${X}" is not a valid subdomain.`)}if($.custom&&!Y.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain or name.`);if($.ask&&J&&!J.exists)throw Error(`\`route.domains.ask\` is set, so "${J.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class U2{root;devHosts;hostTrusts;fixed=new Map;param=null;groupKeys=new Set;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){yH($),this.root=A1($.root),this.devHosts=zF($.devHosts),this.hostTrusts=qH($.trustProxy);for(let Z of $.groups??[]){if(this.groupKeys.add(V2(Z)),F2(Z))continue;if(jF(Z.subdomain))this.param={...Z,paramName:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z)}this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??RH,this.askSecret=$.ask?.secret??null,this.proxySecretHeaders=Array.from(new Set(this.hostTrusts.flatMap((Z)=>Z.secret?[Z.secret.header]:[])))}trustOf($){let Z=null;for(let W of this.hostTrusts)if((!W.secret||j6($.headers.get(W.secret.header),W.secret.value))&&!Z)Z=W;return Z}forwardedHost($){let Z=this.trustOf($)?.header;if(!Z)return null;return $.headers.get(Z)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.trustOf($);if(!Z?.clientIpHeader||!Z.secret)return null;let W=$.headers.get(Z.clientIpHeader)?.split(",")[0];return W===void 0?null:J$(W)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return A1(this.forwardedHost($))??A1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),W=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),Y=W==="http"||W==="https"?W:Z.protocol.replace(/:$/,""),J=this.forwardedHost($),j=J&&A1(J)?gH(J):null;return`${Y}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let W=await this.match(Z,$);if(W)return W;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:B2,params:{},custom:!0};return null}async allows($,Z){let W=A1($);return W?await this.match(W,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:T8,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let Y=$.slice(0,-(this.root.length+1)),J=this.fixed.get(Y);if(J)return{host:$,group:J.subdomain,params:{},custom:!1};if(this.param&&M8.test(Y)){let j={[this.param.paramName]:Y};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 W=await this.resolveCustom($);return W?{host:$,group:W.group,params:W.params,custom:!0}:null}async callResolve($){let Z=this.custom,W=await Z.resolve($)??null;if(W===null)return null;if(!fH(W))return{group:Z.group,params:W};if(typeof W.group!=="string"||!this.groupKeys.has(W.group))throw Error(`\`route.domains.custom.resolve\` returned the group ${JSON.stringify(W.group)} for "${$}", but no group declares that subdomain or name.`);return{group:W.group,params:W.params}}async resolveCustom($){let Z=Date.now(),W=this.cache.get($);if(W&&W.expiresAt>Z)return this.cache.delete($),this.cache.set($,W),W.value;let Y=this.inFlight.get($);if(Y)return Y;let J=this.callResolve($);this.inFlight.set($,J);let j;try{j=await J}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=kH)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=A1($);if(Z)this.cache.delete(Z)}}}var mH={kind:"none"};function rS($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return mH;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function eS($,Z,W){if(W.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let Y=Z;if(W.kind==="hops"){let J=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=J.length-W.hops,z=j>=0?J[j]:J[0];Y=(z===void 0?null:J$(z))??Z}if(Y)$.set("x-forwarded-for",Y);else $.delete("x-forwarded-for")}var XF=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,GF=16;function $b($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",Y=$.GEMI_PROXY_SECRET??"";if(Z===""&&W===""&&Y==="")return null;if(Z===""||W===""||Y==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!XF.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!XF.test(W))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(W)}.`);if(Z.toLowerCase()===W.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(Y.length<GF)throw Error(`GEMI_PROXY_SECRET must be at least ${GF} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:W.toLowerCase(),secret:Y}}function QF($,Z){if(!j6($.get(Z.secretHeader),Z.secret))return null;let W=$.get(Z.header)?.split(",")[0];return W===void 0?null:J$(W)}var hH="/__gemi__/domains/ask";class U1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;staticFilesVary=!1;constructor($,Z){this.groups.set(T8,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:W}=Z;if(this.acceptsCustomDomains=Boolean(W?.custom),!W){this.resolver=null;return}this.resolver=new U2(W);let Y=(J)=>({api:J.api?new L8({...Z.api,...J.api}):$.api,view:J.view?new J6({...Z.view,...J.view},Z.auth):$.view});for(let J of W.groups??[])this.groups.set(V2(J),Y(J));if(W.custom?.fallback)this.groups.set(B2,Y(W.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((J)=>J.publicFiles!==$.view.publicFiles||J.assetRoutes!==$.view.assetRoutes||J.assetCors!==$.view.assetCors)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes,assetCors:Z.assetCors}}applyClientIp($){let Z=this.clientIpTrust;if(Z)D2($,Z.secretHeader);let W=this.resolver?.trustedClientIp($)??(Z?QF($.headers,Z):null);if(!W)return;$.headers.set("x-forwarded-for",W),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);for(let W of this.resolver.proxySecretHeaders)D2($,W);let Z=V8($)??await this.resolver.resolve($);if(!Z)return null;return z3($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==hH)return null;if(!j6(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let W=Z.searchParams.get("domain"),Y=W?await this.resolver.allows(W,$):!1;return new Response(null,{status:Y?200:404})}dispatchers($){return this.groups.get($?.group??T8)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[W,Y]of this.groups){if($.has(Y.view))continue;$.add(Y.view),Z.push({group:W,view:Y.view})}return Z}}function Q3($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var BF=600000;function FF($,Z){return[R6($,Z),R6($,Z-1)]}class R{static token="auth";config;provider;constructor($={},Z=new N5){_J($.oauthProviders),this.config={...N$(IJ($),$),emailCode:L5($.emailCode),passwordLimits:O5($.passwordLimits)},this.provider=Z}async oauthProvider($){return await xZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await hJ(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,sameSite:"Lax",domain:this.cookieDomain($)}}publicOrigin($){let Z=H().bound(U1)?H(U1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let W=Z==="root"?H(U1).resolver?.root:A1(Z);if(!W)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let Y=$.domain?.host??A1(new URL($.rawRequest.url).host);return Y===W||Y?.endsWith(`.${W}`)?W:void 0}async getSession($,Z){if(!$)return null;if(!X5($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let W=await this.userProvider.findSession({token:$,userAgent:Z});if(!W?.user)return null;let Y=Date.now(),J=Q3(W.expiresAt),j=Q3(W.absoluteExpiresAt);if(J<=Y||j<=Y)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(W,Y);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,W){let Y=P.getStore()?.req;if(!Y)return null;let J=Date.now(),j=Math.floor(J/BF),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await W(X,{token:$,req:Y,userAgent:Z}))return null;let Q=R6($,j),F=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:Q,userId:F,userAgent:Z,...this.freshLifetime(J)}),!0}))z=Q}if(!z){for(let Q of FF($,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)Y.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(Y,new Date(G.expiresAt)));return G}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(X5($)||!this.config.migrateLegacySession){let J=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),J}let W=Math.floor(Date.now()/BF),Y=FF($,W);return this.userProvider.withLegacySessionLock($,async()=>{let J=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of Y){if(J?.user)break;J=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of Y)await this.userProvider.deleteSession({token:j});return J})}requestCarryingCookie($){let Z=P.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let W=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=W/2)return $;let Y=new Date(Math.min(Z+W,new Date($.absoluteExpiresAt).getTime())),J=await this.userProvider.updateSession({token:$.token,expiresAt:Y}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,Y));if(!J)return $;return{...$,expiresAt:J.expiresAt??Y}}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 W=await this.createOrUpdateSession({email:$,id:Z.id}),Y=new S;if(Y.ctx().setCookie("access_token",W.token,this.accessTokenCookieOptions(Y,W.expiresAt)),W?.user)W.user.extension=await this.config.extendSession(W.user);return W}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),W=null;if(Z?.user)W=await this.config.extendSession(Z.user),Z.user.extension=W;return Z}async createOrUpdateSession($){let Z=new S,W=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!W)throw new g$;let Y=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),J=XJ(W),j=await this.userProvider.createSessionV2({token:J,userId:W,userAgent:Y,...this.freshLifetime(Date.now())}),z=null;try{z=await this.userProvider.findSession({token:J,userAgent:Y??""})}catch(X){console.error("Reading the new session back failed:",X)}return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:W,token:Y}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:W,token:Y}}return{}}async issueOneTimeCode($,Z){let{activeCodes:W,expiresInMinutes:Y,linkExpiresInMinutes:J}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:UJ(Z),G=k6("link",$,j),Q=k6("pin",$,X);if(W===1)await this.userProvider.deleteMagicLinkToken($);else{let F=Math.max(Y,J)*60000,B=(await this.userProvider.listMagicLinkTokensByEmail($,W-1)).filter((U)=>Q3(U.createdAt)+F>Date.now()&&U.pin!==Q&&U.token!==G);await this.userProvider.deleteMagicLinkTokensExcept($,B.map((U)=>U.id))}return await this.userProvider.createMagicLinkToken({email:$,token:G,pin:Q}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let W=await this.userProvider.findMagicLinkTokenByEmail($);return W?[W]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,W={}){let{expiresInMinutes:Y,maxAttempts:J}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return CZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((Q)=>Q3(Q.createdAt)+Y*60000>Date.now());if(z.length===0)return CZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let Q of z)if(!await LJ(Q.id,Q3(Q.createdAt),J,Y))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let G=null;for(let Q of z)if(CZ("pin",$,Q.pin,Z))G??=Q;if(!G)return{status:"invalid"};if(W.claim!==!1&&!await this.claimOneTimeCode($,G.id))return{status:"invalid"};return{status:"ok",row:G}}async verifyMagicLinkToken($,Z){let W=await this.oneTimeCodeRows($);if(W.length===0)return CZ("link",$,void 0,Z),!1;let Y=null;for(let j of W)if(CZ("link",$,j.token,Z))Y??=j;if(!Y)return!1;if(Q3(Y.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,Y.id)}}class g0 extends h{static getFacadeAccessor(){return R}static async user(){let $=await g0.userOrNull();if($)return $;throw new g$({redirectTo:_6(P.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=P.getStore();if($?.user)return $.user;let Z=await V6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=P.getStore()?.req;return H1(Z?.search.get(a0),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await g0.user();if(!await $(Z))throw new NZ}static async guardSafe($){let Z=await g0.user();try{return await $(Z)}catch(W){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}var O2="x-gemi-invalidate";function VF($){return encodeURIComponent(JSON.stringify([...new Set($)]))}function UF($){if(!$)return[];try{let Z=JSON.parse(decodeURIComponent($));return Array.isArray(Z)?Z.filter((W)=>typeof W==="string"):[]}catch{return[]}}class K8{static ensure($,Z={}){let W=P.getStore();if(W.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return W.serverQueries??=new VZ(X3(W.req.rawRequest)),W.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let W=K8.ensure($,Z[0]);if(await W.promise,W.status==="rejected")throw W.error;return W.data}static prefetch($,...Z){K8.ensure($,Z[0])}static noPrefetch(){let $=P.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new VZ(X3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}static prefill($,Z,W){let Y=P.getStore();if(Y.req.kind==="api")throw Error("Query.prefill() cannot be called from an API request");Y.serverQueries??=new VZ(X3(Y.req.rawRequest)),Y.serverQueries.prefill($,Z,W)}static invalidate(...$){let Z=P.getStore(),W=UF(Z.headers.get(O2));Z.setHeaders(O2,VF([...W,...$]))}}function DF($,Z,W="/"){let Y=new URL($.origin),J=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(W.startsWith("/")?W:`/${W}`,Y),z=pH(J);if(!z)throw Error(`"${J}" 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 pH($){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 OF{static origin($){return L2($)}static absolute($,...Z){return`${QZ()}${L0(String($),Z[0]??{})}`}static relative($,...Z){return L0(String($),Z[0]??{})}static forDomain($,Z,...W){let Y=H(U1).resolver;if(!Y)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let J=P.getStore()?.req?.rawRequest,j=J?Y.publicOrigin(J):QZ();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return DF({root:Y.root,origin:j},$,L0(String(Z),W[0]??{}))}static api($,...Z){return j2(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${L2()}${j2(String($),Z[0]??{})}`}static matchApi($,Z){return eB(String($),Z)}}class LF{name="Meta";static description($){P.getStore().metadata.description($)}static title($){P.getStore().metadata.title($)}static openGraph($){P.getStore().metadata.openGraph($)}static htmlAttributes($){P.getStore().metadata.htmlAttributes($)}static canonical($){P.getStore().metadata.canonical($)}static alternates($){P.getStore().metadata.alternates($)}static tags($){P.getStore().metadata.tags($)}static robots($){P.getStore().metadata.robots($)}static translate($=!0){P.getStore().metadata.translate($)}static fonts($){P.getStore().metadata.fonts($)}}var cH={set($,Z,W){P.getStore().setCookie($,Z,W)},setIfAbsent($,Z,W){if(P.getStore().req.cookies.has($))return!1;return P.getStore().setCookie($,Z,W),!0},delete($,Z){P.getStore().deleteCookie($,Z)}};class o1 extends h{static getFacadeAccessor(){return OZ}static get client(){return this.getFacadeRoot().client}static get($){return o1.client.get($)}static set($,Z){return o1.client.set($,Z)}static del(...$){return o1.client.del(...$)}static exists($){return o1.client.exists($)}static incr($){return o1.client.incr($)}static expire($,Z){return o1.client.expire($,Z)}static ttl($){return o1.client.ttl($)}}function tb($){return $}function MF(){return{store:"memory",ttl:null}}class M2{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,W){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:W===null?null:this.now()+W});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 dH="500";class H2{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,W){let Y=[this.prefix+$,Z];if(W!==null)Y.push("PX",String(Math.max(1,Math.round(W))));await this.client.send("SET",Y)}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=`${uH(this.prefix)}*`,W="0";do{let Y=await $.send("SCAN",[W,"MATCH",Z,"COUNT",dH]),[J,j]=Array.isArray(Y)?Y:["0",[]];if(W=String(J),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(W!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=H(),Z=$.bound(OZ)?$.make(OZ).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 uH($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var lH="k:",HF="tag:",iH="t:";class T2{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,W){await this.manager.write(await this.storeKey($),Z,W)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),W=await this.manager.read(Z);if(!W.found)return;return await this.manager.store.delete(Z),W.value}async remember($,Z,W){let[Y,J]=typeof Z==="function"?[void 0,Z]:[Z,W];if(typeof J!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),Y,J)}}class K2 extends T2{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=N$(MF(),$),this.config.ttl!==null&&this.config.ttl!==void 0)LZ(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 W of Z)if(typeof W!=="string"||W==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(W)}.`);return new KF(this,Z)}async flush(){await this.store.flush()}async storeKey($){return lH+PF($)}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,W){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let Y=this.ttlMs(W);if(Y===0){await this.store.delete($);return}let J=JSON.stringify(Z);if(J===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,J,Y)}async rememberAt($,Z,W){let Y=await this.read($);if(Y.found)return Y.value;let J=this.inflight.get($);if(J)return J;let j=(async()=>{try{let z=await W();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 W=HF+Z,Y=await this.store.get(W);if(Y!==null)return Y;let J=TF();return await this.store.set(W,J,null),J}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(HF+Z,TF(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:LZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new M2(this.config.memory);if($==="redis"){let Z=this.options.application;return new H2({...this.config.redis,client:Z?{send:(W,Y)=>Z.make(OZ).client.send(W,Y)}: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 KF extends T2{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){PF($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${iH}${Z.join(",")}:${$}`}}function PF($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function TF(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class NF extends h{static getFacadeAccessor(){return K2}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,W){return this.getFacadeRoot().set($,Z,W)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,W){let Y=this.getFacadeRoot();return typeof Z==="function"?Y.remember($,Z):Y.remember($,Z,W)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class _F extends h{static getFacadeAccessor(){return m0}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},W){return this.getFacadeRoot().enforce($,Z,W)}}class CF extends h{static getFacadeAccessor(){return IF}static run($,Z,W){return this.getFacadeRoot().run($,Z,W)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class AF extends h{static getFacadeAccessor(){return xF}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class SF extends h{static getFacadeAccessor(){return $6}static for($,Z,W){return this.getFacadeRoot().for($,Z,W)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,W){return this.getFacadeRoot().save($,Z,W)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}class bF extends h{static getFacadeAccessor(){return z6}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,W){return this.getFacadeRoot().stream($,Z,W)}}class X6 extends i0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(i0)?$.make(i0):void 0;if(Z instanceof X6)return Z;let W=new X6($,Z);return $.instance(i0,W),W}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(i0,this.previous);return}this.application.forget(i0)}assertSent($,Z,W){if(this.matching($,Z,W).length>0)return;throw Error(`Expected ${P2($,Z,W)} to have been broadcast. ${this.summary()}`)}assertNotSent($,Z,W){let Y=this.matching($,Z,W);if(Y.length===0)return;throw Error(`Expected ${P2($,Z,W)} not to have been broadcast, but it was broadcast ${N2(Y.length)}: ${_2(Y)}.`)}assertSentTimes($,Z,W,Y){let J=this.matching($,W,Y);if(J.length===Z)return;throw Error(`Expected ${P2($,W,Y)} to have been broadcast ${N2(Z)}, but it was broadcast ${N2(J.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"}: ${_2(this.sent)}.`)}matching($,Z,W){return TZ($),this.sent.filter((Y)=>(Y.pattern===$||WY($,Y.topic))&&(Z===void 0||Y.event===Z)&&(W===void 0||W(Y.data,Y)))}summary(){if(this.sent.length===0)return"Nothing was broadcast.";return`Broadcast: ${_2(this.sent)}.`}}function P2($,Z,W){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(W?" matching the predicate":"")}function N2($){return`${$} ${$===1?"time":"times"}`}function _2($){return $.map((Z)=>`${Z.topic} ${Z.event}(${sH(Z.data)})`).join(", ")}function sH($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class EF extends h{static getFacadeAccessor(){return i0}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 X6.install(H())}}function vE($){return $}function RF(){return{store:"memory",sweepLimit:500}}var I2=["completed","failed","cancelled","timed_out"],S1=["pending","running"];function b1($){return I2.includes($)}class C2{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(),W={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(W.id,W),structuredClone(W)}async get($){let Z=this.runs.get($);return Z?structuredClone(Z):null}async list($){let Z=[];for(let W of this.runs.values()){if($.kind!==void 0&&W.kind!==$.kind)continue;if($.subject!==void 0&&W.subject!==$.subject)continue;if($.owner!==void 0&&W.owner!==$.owner)continue;if($.statuses&&!$.statuses.includes(W.status))continue;Z.push(W)}return Z.reverse().sort((W,Y)=>Y.createdAt-W.createdAt),Z.slice(0,x2($.limit)).map((W)=>structuredClone(W))}async transition($,Z,W){let Y=this.runs.get($);if(!Y||!Z.includes(Y.status))return null;let J=structuredClone(W),j=this.tick();if(J.status!==void 0){if(Y.startedAt===null&&J.status!=="pending")Y.startedAt=j;if(b1(J.status))Y.finishedAt=j;Y.status=J.status}if("progress"in J)Y.progress=J.progress??null;if("result"in J)Y.result=J.result??null;if("error"in J)Y.error=J.error??null;return Y.version+=1,Y.updatedAt=j,structuredClone(Y)}async overdue($,Z){let W=[];for(let Y of this.runs.values())if(S1.includes(Y.status)&&Y.deadlineAt!==null&&Y.deadlineAt<=$)W.push(Y);return W.sort((Y,J)=>Y.deadlineAt-J.deadlineAt),W.slice(0,Math.max(0,Z)).map((Y)=>structuredClone(Y))}async now(){return this.tick()}async prune($){let Z=this.tick()-$,W=0;for(let[Y,J]of this.runs)if(J.finishedAt!==null&&J.finishedAt<=Z)this.runs.delete(Y),W++;return W}tick(){return this.clock=Math.max(this.clock,Date.now()),this.clock}}function x2($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class b2{table;sql;dialect;connection;constructor($,Z={}){let W=Z.table??"gemi_runs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(W))throw Error(`The runs table name "${W}" is not a plain identifier. Use letters, digits and underscores.`);this.table=W,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of nH(this.dialect,this.table))await this.sql.unsafe($)}async create($){let Z=this.q(),W=this.clock(Z),Y=$.deadlineMs===null?Z`NULL`:Z`${W} + ${this.ms(Z,$.deadlineMs)}`,J=$.status==="running"?W:Z`NULL`;await Z`
|
|
24
|
+
INSERT INTO ${this.name(Z)}
|
|
25
|
+
(id, kind, subject, owner, status, meta, version,
|
|
26
|
+
created_at, started_at, updated_at, deadline_at)
|
|
27
|
+
VALUES
|
|
28
|
+
(${$.id}, ${$.kind}, ${$.subject}, ${$.owner}, ${$.status},
|
|
29
|
+
${N8($.meta)}, 1, ${W}, ${J}, ${W}, ${Y})
|
|
30
|
+
`;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(),W=await Z`SELECT * FROM ${this.name(Z)} WHERE id = ${$}`;return W[0]?S2(W[0]):null}async list($){let Z=this.q(),W=[Z`1 = 1`];if($.kind!==void 0)W.push(Z`kind = ${$.kind}`);if($.subject!==void 0)W.push(Z`subject = ${$.subject}`);if($.owner!==void 0)W.push(Z`owner = ${$.owner}`);if($.statuses!==void 0)W.push($.statuses.length===0?Z`1 = 0`:Z`status IN (${P8(Z,$.statuses)})`);let Y=W.reduce((j,z)=>Z`${j} AND ${z}`);return(await Z`
|
|
31
|
+
SELECT * FROM ${this.name(Z)}
|
|
32
|
+
WHERE ${Y}
|
|
33
|
+
ORDER BY created_at DESC, id DESC
|
|
34
|
+
LIMIT ${x2($.limit)}
|
|
35
|
+
`).map(S2)}async transition($,Z,W){if(Z.length===0)return null;let Y=this.q(),J=this.clock(Y),j=[Y`updated_at = ${J}`,Y`version = version + 1`];if(W.status!==void 0){if(j.push(Y`status = ${W.status}`),W.status!=="pending")j.push(Y`started_at = COALESCE(started_at, ${J})`);if(b1(W.status))j.push(Y`finished_at = ${J}`)}if("progress"in W)j.push(Y`progress = ${N8(W.progress)}`);if("result"in W)j.push(Y`result = ${N8(W.result)}`);if("error"in W)j.push(Y`error = ${N8(W.error)}`);let z=j.reduce((G,Q)=>Y`${G}, ${Q}`),X=await Y`
|
|
36
|
+
UPDATE ${this.name(Y)} SET ${z}
|
|
37
|
+
WHERE id = ${$} AND status IN (${P8(Y,Z)})
|
|
38
|
+
`;if(wF(X)===0)return null;return this.get($)}async overdue($,Z){let W=this.q();return(await W`
|
|
39
|
+
SELECT * FROM ${this.name(W)}
|
|
40
|
+
WHERE status IN (${P8(W,S1)})
|
|
41
|
+
AND deadline_at IS NOT NULL AND deadline_at <= ${this.ms(W,$)}
|
|
42
|
+
ORDER BY deadline_at, id
|
|
43
|
+
LIMIT ${Math.max(0,Math.floor(Z))}
|
|
44
|
+
`).map(S2)}async now(){let $=this.q(),[Z]=await $`SELECT ${this.clock($)} AS now`;return Number(Z.now)}async prune($){let Z=this.q(),W=await Z`
|
|
45
|
+
DELETE FROM ${this.name(Z)}
|
|
46
|
+
WHERE status IN (${P8(Z,I2)})
|
|
47
|
+
AND finished_at <= ${this.clock(Z)} - ${this.ms(Z,$)}
|
|
48
|
+
`;return wF(W)}joinable(){if(this.connection===void 0)return;let $=c$();if($===void 0||d$()!==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 W=Math.max(0,Math.round(Z));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${W} AS SIGNED)`:$`CAST(${W} AS BIGINT)`}}function P8($,Z){return Z.map((W)=>$`${W}`).reduce((W,Y)=>$`${W}, ${Y}`)}function N8($){return $===void 0||$===null?null:JSON.stringify($)}function _8($){if($===null||$===void 0)return null;return JSON.parse(String($))}function A2($){return $===null||$===void 0?null:Number($)}function kF($){return $===null||$===void 0?null:String($)}function S2($){return{id:String($.id),kind:String($.kind),subject:kF($.subject),owner:kF($.owner),status:String($.status),meta:_8($.meta),progress:_8($.progress),result:_8($.result),error:_8($.error),version:Number($.version),createdAt:Number($.created_at),startedAt:A2($.started_at),updatedAt:Number($.updated_at),finishedAt:A2($.finished_at),deadlineAt:A2($.deadline_at)}}function wF($){let Z=$;return Math.max(Number(Z.count??0),Number(Z.affectedRows??0))}function nH($,Z){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
|
|
49
|
+
\`id\` VARCHAR(191) NOT NULL,
|
|
50
|
+
\`kind\` VARCHAR(191) NOT NULL,
|
|
51
|
+
\`subject\` VARCHAR(191) NULL,
|
|
52
|
+
\`owner\` VARCHAR(191) NULL,
|
|
53
|
+
\`status\` VARCHAR(191) NOT NULL,
|
|
54
|
+
\`meta\` LONGTEXT NULL,
|
|
55
|
+
\`progress\` LONGTEXT NULL,
|
|
56
|
+
\`result\` LONGTEXT NULL,
|
|
57
|
+
\`error\` LONGTEXT NULL,
|
|
58
|
+
\`version\` INTEGER NOT NULL DEFAULT 1,
|
|
59
|
+
\`created_at\` BIGINT NOT NULL,
|
|
60
|
+
\`started_at\` BIGINT NULL,
|
|
61
|
+
\`updated_at\` BIGINT NOT NULL,
|
|
62
|
+
\`finished_at\` BIGINT NULL,
|
|
63
|
+
\`deadline_at\` BIGINT NULL,
|
|
64
|
+
|
|
65
|
+
INDEX \`${Z}_subject_created_at_idx\`(\`subject\`, \`created_at\`),
|
|
66
|
+
INDEX \`${Z}_status_deadline_at_idx\`(\`status\`, \`deadline_at\`),
|
|
67
|
+
PRIMARY KEY (\`id\`)
|
|
68
|
+
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let W=$==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',Y=$==="sqlite"?"":`,
|
|
69
|
+
|
|
70
|
+
CONSTRAINT "${Z}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${Z}" (
|
|
71
|
+
${W}
|
|
72
|
+
"kind" TEXT NOT NULL,
|
|
73
|
+
"subject" TEXT,
|
|
74
|
+
"owner" TEXT,
|
|
75
|
+
"status" TEXT NOT NULL,
|
|
76
|
+
"meta" TEXT,
|
|
77
|
+
"progress" TEXT,
|
|
78
|
+
"result" TEXT,
|
|
79
|
+
"error" TEXT,
|
|
80
|
+
"version" INTEGER NOT NULL DEFAULT 1,
|
|
81
|
+
"created_at" BIGINT NOT NULL,
|
|
82
|
+
"started_at" BIGINT,
|
|
83
|
+
"updated_at" BIGINT NOT NULL,
|
|
84
|
+
"finished_at" BIGINT,
|
|
85
|
+
"deadline_at" BIGINT${Y}
|
|
86
|
+
)`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var fF=191,qF=30000;class I8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class C8 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 E2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=N$(RF(),$),this.store=tH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(z6);return this.ownFeed??=new z6,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){yF("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;yF("id",Z);let W=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:LZ($.deadline)});return await this.publish(W),W}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return aH(Z),this.change($,S1,{status:"running",progress:Z})}complete($,Z){return this.change($,S1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,S1,{status:"failed",error:gF(Z)})}cancel($,Z){return this.change($,S1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let W=this.feed.subscribe(this.channel($));try{await W.ready();let Y=await this.start($)??await this.store.get($);if(!Y)throw new I8($);if(b1(Y.status))return Y;let J=new AbortController,j=this.watch($,Y,W,J),z={id:$,record:Y,signal:J.signal,progress:async(G)=>{if(J.signal.aborted)return;await this.progress($,G)}},X;try{let G=await Z(z);X=await this.complete($,G)}catch(G){if(!(G instanceof C8)&&!J.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,S1,{status:"failed",error:G instanceof C8?gF(G):{message:"The run failed.",code:"error"}})}finally{J.abort(),W.close(),await j}return X??await this.store.get($)??Y}finally{W.close()}}async wait($,Z={}){let{signal:W}=Z;W?.throwIfAborted();let Y=Z.timeout===void 0?1/0:Date.now()+LZ(Z.timeout),J=this.feed.subscribe(this.channel($),{signal:W});try{await J.ready();let j=await this.store.get($);if(!j)throw new I8($);let z=null;for(;;){if(b1(j.status))return j;W?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let G=Y-Date.now();if(G<=0)return j;if(z??=J.isClosed?new Promise(()=>{}):J.next(),await vF(z,Math.min(G,X??1/0,qF),W))z=null;j=await this.store.get($)??j}}finally{J.close()}}async*subscribe($,Z={}){let W=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await W.ready();let Y=await this.store.get($);if(!Y)throw new I8($);if(yield Y,b1(Y.status))return;for await(let J of W){let j=oH(J,$)??await this.store.get($);if(!j||j.version<=Y.version)continue;if(Y=j,yield Y,b1(Y.status))return}}finally{W.close()}}stream($,Z,W={}){return this.feed.stream($,this.channel(Z),W)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let W of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(W.id))Z++;return Z}async prune($){let Z=LZ($);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||b1(Z.status))return null;let W=await this.untilDeadline(Z);if(W===null||W>0)return null;return this.change($,S1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,W,Y){let J=new Promise((z)=>{if(Y.signal.aborted)z("ended");Y.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(Y.signal.aborted)return;if(b1(Z.status)){Y.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=W.next();let X=await Promise.race([J,vF(j,Math.min(z??1/0,qF))]);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,W){let Y=await this.store.transition($,Z,W);if(Y)await this.publish(Y);return Y}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function vF($,Z,W){return new Promise((Y,J)=>{let j=Number.isFinite(Z)?setTimeout(()=>G(!1),Math.max(0,Z)):null,z=()=>{X(),J(W.reason)},X=()=>{if(j)clearTimeout(j);W?.removeEventListener("abort",z)},G=(Q)=>{X(),Y(Q)};W?.addEventListener("abort",z,{once:!0}),$.then(()=>G(!0),()=>G(!0))})}function oH($,Z){if($.type!=="change")return null;let W=$.data;if(!W||typeof W!=="object"||W.id!==Z||typeof W.version!=="number")return null;return W}function gF($){if(typeof $==="string")return{message:$};if($ instanceof C8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function yF($,Z){if(typeof Z!=="string"||Z===""||Z.length>fF)throw TypeError(`A run's ${$} is a string of 1 to ${fF} characters; got ${JSON.stringify(Z)}.`)}function aH($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function tH($,Z){if($==="memory")return new C2;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 W=Z.make(u$).connection();return new b2(W)}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 mF extends h{static getFacadeAccessor(){return E2}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,W){return this.getFacadeRoot().stream($,Z,W)}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 hF extends h{static getFacadeAccessor(){return j$}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,W){return this.getFacadeRoot().set($,Z,W)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class R2{value;constructor($){this.value=$}}var rH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function eH($){let Z=["SET TRANSACTION READ ONLY"],W=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[Y,J]of W){let j=$[Y];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${Y} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${J} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!rH.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class S8{bound;constructor($){this.bound=$}get name(){return this.bound??d$()}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,W=this.connection(Z);return A8(W.sql,(Y)=>x8(Z,()=>$(Y)),{slowTransactionThreshold:W.config.slowTransactionThreshold,connection:Z,dialect:W.dialect})}async readOnly($,Z){let W=typeof $==="function"?{}:$,Y=typeof $==="function"?$:Z;if(typeof Y!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let J=eH(W??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if(c$()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await A8(z.sql,async(X)=>{for(let Q of J)await X.unsafe(Q);await uF();let G=await x8(j,()=>Y(X));throw new R2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j,dialect:z.dialect,deferSettings:!0})}catch(X){if(X instanceof R2)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-hmdpf21x.js");return Z(this.handle()??$.sql,$.dialect)}async withSettings($,Z){let W=this.connection();if(W.dialect!=="postgres")throw Error(`DB.withSettings is supported on Postgres only, and the "${W.name}" connection is ${W.dialect}.`);return lF($,Z)}run($,Z){let W=this.connection(),{text:Y,values:J}=sF($,iF(W.dialect),Z),j=this.handle();if(j===void 0&&dF()){let z=this.name;return A8(W.sql,(X)=>x8(z,()=>X.unsafe(Y,J)),{slowTransactionThreshold:W.config.slowTransactionThreshold,connection:z,dialect:W.dialect})}if(j===void 0)return W.sql.unsafe(Y,J);return j.unsafe(Y,J).catch((z)=>{throw cF(j),z})}handle(){let $=c$();if($===void 0)return;return d$()===this.name?$:void 0}connection($=this.name){return pF($),H(u$).connection($)}}var A$=new S8;class nF extends h{static getFacadeAccessor(){return u$}static connection($){return new S8($)}static get sql(){return A$.sql}static get dialect(){return A$.dialect}static query($){return A$.query($)}static execute($){return A$.execute($)}static transaction($){return A$.transaction($)}static withSettings($,Z){return A$.withSettings($,Z)}static readOnly($,Z){return A$.readOnly($,Z)}static schema(){return A$.schema()}static close(){return this.getFacadeRoot().close()}}export{L1 as _e,ZV as $e,v0 as af,U3 as bf,f8 as cf,A0 as df,V6 as ef,z5 as ff,X5 as gf,XJ as hf,M1 as if,m0 as jf,J$ as kf,TY as lf,W0 as mf,_Y as nf,P6 as of,v$ as pf,GJ as qf,QJ as rf,Q5 as sf,B5 as tf,k6 as uf,CZ as vf,KJ as wf,EU as xf,PJ as yf,RU as zf,hN as Af,IJ as Bf,kJ as Cf,H5 as Df,wJ as Ef,fJ as Ff,mU as Gf,qJ as Hf,T5 as If,cU as Jf,dU as Kf,K5 as Lf,vJ as Mf,gJ as Nf,j$ as Of,yJ as Pf,sU as Qf,N5 as Rf,o8 as Sf,I6 as Tf,f1 as Uf,i8 as Vf,q1 as Wf,x$ as Xf,K8 as Yf,OF as Zf,LF as _f,cH as $f,o1 as ag,tb as bg,MF as cg,M2 as dg,H2 as eg,K2 as fg,KF as gg,NF as hg,_F as ig,CF as jg,AF as kg,SF as lg,bF as mg,s as ng,O3 as og,o4 as pg,C_ as qg,x_ as rg,A_ as sg,R_ as tg,uG as ug,nW as vg,sG as wg,v_ as xg,aG as yg,i0 as zg,a3 as Ag,tG as Bg,EF as Cg,vE as Dg,I2 as Eg,S1 as Fg,b1 as Gg,C2 as Hg,b2 as Ig,nH as Jg,I8 as Kg,C8 as Lg,E2 as Mg,mF as Ng,hF as Og,S8 as Pg,nF as Qg,tW as Rg,uL as Sg,j9 as Tg,z9 as Ug,oI as Vg,KQ as Wg,IQ as Xg,D6 as Yg,$$ as Zg,BC as _g,xQ as $g,AQ as ah,ZB as bh,b9 as ch,J3 as dh,E9 as eh,QA as fh,MA as gh,HA as hh,BH as ih,o9 as jh,UH as kh,Y2 as lh,HH as mh,r9 as nh,PH as oh,J6 as ph,X2 as qh,$F as rh,D8 as sh,L8 as th,rS as uh,eS as vh,$b as wh,U1 as xh,R as yh,g0 as zh,O6 as Ah,QY as Bh,OV as Ch,zY as Dh,FY as Eh,h8 as Fh,M6 as Gh,p8 as Hh,VY as Ih,d8 as Jh,H6 as Kh,T6 as Lh,OY as Mh,eT as Nh,LY as Oh,z0 as Ph,o as Qh,k1 as Rh,MY as Sh,$K as Th,o0 as Uh,HY as Vh,L3 as Wh,SY as Xh,u8 as Yh,vV as Zh,gV as _h,qY as $h,gY as ai,mY as bi,pY as ci,cY as di,dY as ei,t8 as fi,pV as gi,X0 as hi,$J as ii,_Z as ji,jJ as ki};
|
|
87
|
+
|
|
88
|
+
//# debugId=C3D9F6E69E5B923A64756E2164756E21
|