gemi 0.123.0 → 0.125.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/AgentController.d.ts +185 -3
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/client/index.d.ts +1 -1
- package/dist/ai/client/index.d.ts.map +1 -1
- package/dist/ai/client/index.js +38 -9
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/client/reducer.d.ts.map +1 -1
- package/dist/ai/index.d.ts +2 -2
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +31 -48
- package/dist/ai/index.js.map +6 -15
- package/dist/ai/types.d.ts +26 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/useChat.d.ts +35 -2
- package/dist/ai/useChat.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/auth/AuthController.d.ts.map +1 -1
- package/dist/auth/AuthManager.d.ts +11 -0
- package/dist/auth/AuthManager.d.ts.map +1 -1
- package/dist/auth/AuthServiceProvider.d.ts +2 -0
- package/dist/auth/AuthServiceProvider.d.ts.map +1 -1
- package/dist/auth/config.d.ts +71 -2
- package/dist/auth/config.d.ts.map +1 -1
- package/dist/auth/oauth/providers.d.ts +10 -0
- package/dist/auth/oauth/providers.d.ts.map +1 -0
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-fyk07w01.js → chunk-0x1s02r1.js} +3 -3
- package/dist/{chunk-fyk07w01.js.map → chunk-0x1s02r1.js.map} +1 -1
- package/dist/{chunk-ycsrpf47.js → chunk-1jcngq6w.js} +3 -3
- package/dist/{chunk-ycsrpf47.js.map → chunk-1jcngq6w.js.map} +1 -1
- package/dist/{chunk-gwnmgkq5.js → chunk-1mxb44n9.js} +2 -2
- package/dist/{chunk-gwnmgkq5.js.map → chunk-1mxb44n9.js.map} +1 -1
- package/dist/{chunk-y67evsdy.js → chunk-1n40bdxf.js} +2 -2
- package/dist/{chunk-y67evsdy.js.map → chunk-1n40bdxf.js.map} +1 -1
- package/dist/chunk-1xmh61fg.js +5 -0
- package/dist/{chunk-tazvfppr.js.map → chunk-1xmh61fg.js.map} +1 -1
- package/dist/{chunk-sxa70wgn.js → chunk-3br5zr7a.js} +3 -3
- package/dist/{chunk-sxa70wgn.js.map → chunk-3br5zr7a.js.map} +1 -1
- package/dist/{chunk-w61sphn5.js → chunk-3kxe9geg.js} +3 -3
- package/dist/{chunk-w61sphn5.js.map → chunk-3kxe9geg.js.map} +1 -1
- package/dist/{chunk-w0jfqnw9.js → chunk-5fh4pvyt.js} +2 -2
- package/dist/{chunk-w0jfqnw9.js.map → chunk-5fh4pvyt.js.map} +1 -1
- package/dist/{chunk-hnrzm5pf.js → chunk-6gwxvmjv.js} +3 -3
- package/dist/{chunk-hnrzm5pf.js.map → chunk-6gwxvmjv.js.map} +1 -1
- package/dist/{chunk-j0cnsgjq.js → chunk-6q6bhkyf.js} +1 -1
- package/dist/{chunk-5a4qbtez.js → chunk-6vz75swk.js} +2 -2
- package/dist/{chunk-5a4qbtez.js.map → chunk-6vz75swk.js.map} +1 -1
- package/dist/chunk-6wgh7nk6.js +15 -0
- package/dist/{chunk-z23h4s1a.js.map → chunk-6wgh7nk6.js.map} +6 -5
- package/dist/chunk-7vrrgxwm.js +22 -0
- package/dist/chunk-7vrrgxwm.js.map +21 -0
- package/dist/{chunk-kvas36p6.js → chunk-7zj6bk9a.js} +2 -2
- package/dist/{chunk-kvas36p6.js.map → chunk-7zj6bk9a.js.map} +1 -1
- package/dist/{chunk-kdjhgtp9.js → chunk-8tvfmy1a.js} +4 -4
- package/dist/{chunk-kdjhgtp9.js.map → chunk-8tvfmy1a.js.map} +1 -1
- package/dist/{chunk-vd6zn8c4.js → chunk-910p6ne6.js} +2 -2
- package/dist/{chunk-vd6zn8c4.js.map → chunk-910p6ne6.js.map} +1 -1
- package/dist/{chunk-96a1459v.js → chunk-ap3g6rbw.js} +2 -2
- package/dist/{chunk-96a1459v.js.map → chunk-ap3g6rbw.js.map} +1 -1
- package/dist/{chunk-4qpypa3h.js → chunk-ayfjjgv2.js} +1 -1
- package/dist/chunk-b4x1dt3s.js +10 -0
- package/dist/chunk-b4x1dt3s.js.map +43 -0
- package/dist/{chunk-aafanq8n.js → chunk-b7a22evs.js} +3 -3
- package/dist/{chunk-aafanq8n.js.map → chunk-b7a22evs.js.map} +1 -1
- package/dist/{chunk-rjtmgbay.js → chunk-bny9s44t.js} +2 -2
- package/dist/{chunk-rjtmgbay.js.map → chunk-bny9s44t.js.map} +1 -1
- package/dist/{chunk-k17wx7gz.js → chunk-by5gwr8x.js} +2 -2
- package/dist/{chunk-k17wx7gz.js.map → chunk-by5gwr8x.js.map} +1 -1
- package/dist/{chunk-53hc0ah1.js → chunk-c0qpv8x7.js} +2 -2
- package/dist/{chunk-53hc0ah1.js.map → chunk-c0qpv8x7.js.map} +1 -1
- package/dist/{chunk-9t08wbkd.js → chunk-cpem1j1x.js} +2 -2
- package/dist/{chunk-9t08wbkd.js.map → chunk-cpem1j1x.js.map} +1 -1
- package/dist/{chunk-vwnd4jb5.js → chunk-crnfxn9n.js} +2 -2
- package/dist/{chunk-vwnd4jb5.js.map → chunk-crnfxn9n.js.map} +1 -1
- package/dist/{chunk-s5jxc63j.js → chunk-cwt8e782.js} +3 -3
- package/dist/{chunk-s5jxc63j.js.map → chunk-cwt8e782.js.map} +1 -1
- package/dist/{chunk-0tc0j3pf.js → chunk-dxyxd7b3.js} +2 -2
- package/dist/{chunk-0tc0j3pf.js.map → chunk-dxyxd7b3.js.map} +1 -1
- package/dist/{chunk-nf608sb1.js → chunk-dy58aztm.js} +2 -2
- package/dist/{chunk-nf608sb1.js.map → chunk-dy58aztm.js.map} +1 -1
- package/dist/chunk-entpqjyn.js +5 -0
- package/dist/chunk-entpqjyn.js.map +10 -0
- package/dist/{chunk-qen6587t.js → chunk-eq5svwca.js} +2 -2
- package/dist/{chunk-qen6587t.js.map → chunk-eq5svwca.js.map} +1 -1
- package/dist/{chunk-n1a2zj5z.js → chunk-erzfs4t2.js} +2 -2
- package/dist/{chunk-n1a2zj5z.js.map → chunk-erzfs4t2.js.map} +3 -3
- package/dist/{chunk-pfm9ngch.js → chunk-ex41d03h.js} +2 -2
- package/dist/{chunk-pfm9ngch.js.map → chunk-ex41d03h.js.map} +1 -1
- package/dist/{chunk-fxxbwyce.js → chunk-ey1xrbaz.js} +2 -2
- package/dist/{chunk-fxxbwyce.js.map → chunk-ey1xrbaz.js.map} +1 -1
- package/dist/chunk-eyptwf54.js +57 -0
- package/dist/{chunk-gvp6brdt.js.map → chunk-eyptwf54.js.map} +25 -22
- package/dist/{chunk-x0jahbqj.js → chunk-g52fcwca.js} +2 -2
- package/dist/{chunk-x0jahbqj.js.map → chunk-g52fcwca.js.map} +1 -1
- package/dist/{chunk-hs88b8gt.js → chunk-ghcvztxn.js} +2 -2
- package/dist/{chunk-hs88b8gt.js.map → chunk-ghcvztxn.js.map} +1 -1
- package/dist/{chunk-rjm1kj8n.js → chunk-gp00enrk.js} +1 -1
- package/dist/{chunk-08fcqny0.js → chunk-h8w9mzjj.js} +6 -6
- package/dist/{chunk-08fcqny0.js.map → chunk-h8w9mzjj.js.map} +7 -7
- package/dist/{chunk-9p7eq7bz.js → chunk-hff9w6rt.js} +2 -2
- package/dist/{chunk-9p7eq7bz.js.map → chunk-hff9w6rt.js.map} +1 -1
- package/dist/{chunk-ay8nat73.js → chunk-hxn0s3zh.js} +2 -2
- package/dist/{chunk-ay8nat73.js.map → chunk-hxn0s3zh.js.map} +1 -1
- package/dist/{chunk-de7hxe73.js → chunk-hzen9gh4.js} +2 -2
- package/dist/{chunk-de7hxe73.js.map → chunk-hzen9gh4.js.map} +1 -1
- package/dist/{chunk-xhmtph39.js → chunk-j10a0m7q.js} +1 -1
- package/dist/{chunk-wqharhrp.js → chunk-j12hpdxk.js} +1 -1
- package/dist/{chunk-bk2aheea.js → chunk-j5rwv09s.js} +2 -2
- package/dist/{chunk-bk2aheea.js.map → chunk-j5rwv09s.js.map} +1 -1
- package/dist/{chunk-zjej5vqh.js → chunk-jykkqwcy.js} +3 -3
- package/dist/{chunk-zjej5vqh.js.map → chunk-jykkqwcy.js.map} +1 -1
- package/dist/{chunk-9a9ef0f1.js → chunk-k1ebt28j.js} +2 -2
- package/dist/{chunk-9a9ef0f1.js.map → chunk-k1ebt28j.js.map} +1 -1
- package/dist/{chunk-q1e3q01h.js → chunk-kcsa57km.js} +2 -2
- package/dist/{chunk-q1e3q01h.js.map → chunk-kcsa57km.js.map} +1 -1
- package/dist/{chunk-r5tadf14.js → chunk-khdkrfxp.js} +2 -2
- package/dist/{chunk-r5tadf14.js.map → chunk-khdkrfxp.js.map} +1 -1
- package/dist/{chunk-fsy344zb.js → chunk-knq4ack4.js} +2 -2
- package/dist/{chunk-fsy344zb.js.map → chunk-knq4ack4.js.map} +1 -1
- package/dist/{chunk-f1thqe6j.js → chunk-m7pghdcy.js} +2 -2
- package/dist/{chunk-f1thqe6j.js.map → chunk-m7pghdcy.js.map} +1 -1
- package/dist/{chunk-enta97jb.js → chunk-mmqnq1qh.js} +3 -3
- package/dist/{chunk-enta97jb.js.map → chunk-mmqnq1qh.js.map} +1 -1
- package/dist/{chunk-0qmc7snf.js → chunk-n3z83qhq.js} +2 -2
- package/dist/{chunk-0qmc7snf.js.map → chunk-n3z83qhq.js.map} +1 -1
- package/dist/{chunk-mxbtcaed.js → chunk-npbf06c1.js} +2 -2
- package/dist/{chunk-mxbtcaed.js.map → chunk-npbf06c1.js.map} +1 -1
- package/dist/{chunk-6gjvqtcp.js → chunk-p5df4pn7.js} +2 -2
- package/dist/{chunk-6gjvqtcp.js.map → chunk-p5df4pn7.js.map} +1 -1
- package/dist/{chunk-ywgvxx35.js → chunk-p6jbmcrg.js} +2 -2
- package/dist/{chunk-ywgvxx35.js.map → chunk-p6jbmcrg.js.map} +1 -1
- package/dist/{chunk-d3ywmeb7.js → chunk-p7mvp5nf.js} +2 -2
- package/dist/{chunk-d3ywmeb7.js.map → chunk-p7mvp5nf.js.map} +1 -1
- package/dist/{chunk-52xkw2bs.js → chunk-q6ah4yjg.js} +2 -2
- package/dist/{chunk-52xkw2bs.js.map → chunk-q6ah4yjg.js.map} +1 -1
- package/dist/{chunk-6pxavyh3.js → chunk-r923001x.js} +2 -2
- package/dist/{chunk-6pxavyh3.js.map → chunk-r923001x.js.map} +1 -1
- package/dist/{chunk-1f1sb3w7.js → chunk-rany5zgk.js} +2 -2
- package/dist/{chunk-1f1sb3w7.js.map → chunk-rany5zgk.js.map} +1 -1
- package/dist/{chunk-30xxc6r7.js → chunk-rmgkc3a2.js} +2 -2
- package/dist/{chunk-30xxc6r7.js.map → chunk-rmgkc3a2.js.map} +1 -1
- package/dist/{chunk-ebx5hnqn.js → chunk-rvspb96n.js} +3 -3
- package/dist/{chunk-ebx5hnqn.js.map → chunk-rvspb96n.js.map} +1 -1
- package/dist/{chunk-kzstewtm.js → chunk-rwmja4zs.js} +2 -2
- package/dist/{chunk-kzstewtm.js.map → chunk-rwmja4zs.js.map} +1 -1
- package/dist/{chunk-8x73yyfs.js → chunk-s4semb89.js} +1 -1
- package/dist/chunk-s4xg69r9.js +24 -0
- package/dist/{chunk-vpgbn494.js.map → chunk-s4xg69r9.js.map} +2 -2
- package/dist/{chunk-58ffbwdc.js → chunk-stn0a56e.js} +2 -2
- package/dist/{chunk-58ffbwdc.js.map → chunk-stn0a56e.js.map} +1 -1
- package/dist/{chunk-73v34hw8.js → chunk-sv125fqq.js} +2 -2
- package/dist/{chunk-73v34hw8.js.map → chunk-sv125fqq.js.map} +1 -1
- package/dist/{chunk-h76mddt3.js → chunk-t2t63wa0.js} +2 -2
- package/dist/{chunk-h76mddt3.js.map → chunk-t2t63wa0.js.map} +1 -1
- package/dist/{chunk-675kzd7z.js → chunk-t6qpm2j7.js} +2 -2
- package/dist/{chunk-675kzd7z.js.map → chunk-t6qpm2j7.js.map} +1 -1
- package/dist/chunk-tabsxzg9.js +5 -0
- package/dist/chunk-tabsxzg9.js.map +13 -0
- package/dist/{chunk-2vc72qez.js → chunk-vhvvjaj3.js} +3 -3
- package/dist/{chunk-2vc72qez.js.map → chunk-vhvvjaj3.js.map} +1 -1
- package/dist/{chunk-2amj1eyp.js → chunk-x2j84d06.js} +2 -2
- package/dist/{chunk-2amj1eyp.js.map → chunk-x2j84d06.js.map} +1 -1
- package/dist/{chunk-dmj6ysym.js → chunk-xe2pm36q.js} +2 -2
- package/dist/{chunk-dmj6ysym.js.map → chunk-xe2pm36q.js.map} +1 -1
- package/dist/{chunk-rkgsvsrj.js → chunk-xfvegbxn.js} +2 -2
- package/dist/{chunk-rkgsvsrj.js.map → chunk-xfvegbxn.js.map} +1 -1
- package/dist/{chunk-nvngb4ed.js → chunk-y9f2see3.js} +3 -3
- package/dist/{chunk-nvngb4ed.js.map → chunk-y9f2see3.js.map} +1 -1
- package/dist/{chunk-1kdga1b2.js → chunk-yhht1j7f.js} +2 -2
- package/dist/{chunk-1kdga1b2.js.map → chunk-yhht1j7f.js.map} +1 -1
- package/dist/{chunk-eevna943.js → chunk-z5nfve1k.js} +2 -2
- package/dist/chunk-z5nfve1k.js.map +10 -0
- package/dist/{chunk-j8vc3bze.js → chunk-zq5375wd.js} +3 -3
- package/dist/{chunk-j8vc3bze.js.map → chunk-zq5375wd.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-CgK2mmVV.js → ThemeProvider-CS2a1snV.js} +34 -3
- package/dist/chunks/ThemeProvider-CS2a1snV.js.map +1 -0
- package/dist/client/Mutation.d.ts +7 -6
- package/dist/client/Mutation.d.ts.map +1 -1
- package/dist/client/MutationError.d.ts +53 -1
- package/dist/client/MutationError.d.ts.map +1 -1
- package/dist/client/QueryResource.d.ts +9 -0
- package/dist/client/QueryResource.d.ts.map +1 -1
- package/dist/client/auth/useEmailCode.d.ts +3 -3
- package/dist/client/auth/useForgotPassword.d.ts +1 -1
- package/dist/client/auth/useResetPassword.d.ts +1 -1
- package/dist/client/auth/useSignIn.d.ts +1 -1
- package/dist/client/auth/useSignOut.d.ts +1 -1
- package/dist/client/auth/useSignUp.d.ts +1 -1
- package/dist/client/index.d.ts +4 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +136 -9
- package/dist/client/index.js.map +1 -1
- package/dist/client/realtime/RealtimeClient.d.ts +8 -1
- package/dist/client/realtime/RealtimeClient.d.ts.map +1 -1
- package/dist/client/useMutation.d.ts +18 -8
- package/dist/client/useMutation.d.ts.map +1 -1
- package/dist/client/useSetQueryData.d.ts +69 -0
- package/dist/client/useSetQueryData.d.ts.map +1 -0
- 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/Auth.d.ts +29 -2
- package/dist/facades/Auth.d.ts.map +1 -1
- package/dist/facades/RateLimiter.d.ts +16 -1
- package/dist/facades/RateLimiter.d.ts.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/HttpRequest.d.ts +14 -0
- package/dist/http/HttpRequest.d.ts.map +1 -1
- package/dist/http/McpRouter.d.ts +121 -2
- package/dist/http/McpRouter.d.ts.map +1 -1
- package/dist/http/RateLimitExceededError.d.ts +24 -0
- package/dist/http/RateLimitExceededError.d.ts.map +1 -0
- package/dist/http/RateLimitMiddleware.d.ts +2 -5
- package/dist/http/RateLimitMiddleware.d.ts.map +1 -1
- package/dist/http/index.d.ts +2 -1
- 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/http/refusal.d.ts +6 -1
- package/dist/http/refusal.d.ts.map +1 -1
- package/dist/http/requestContext.d.ts +3 -1
- package/dist/http/requestContext.d.ts.map +1 -1
- package/dist/http/requestState.d.ts +57 -0
- package/dist/http/requestState.d.ts.map +1 -0
- 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 +2 -2
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +2 -2
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/Server.d.ts.map +1 -1
- package/dist/server/health.d.ts +67 -0
- package/dist/server/health.d.ts.map +1 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +5 -4
- package/dist/server/shutdown.d.ts +3 -4
- package/dist/server/shutdown.d.ts.map +1 -1
- package/dist/services/broadcast/BroadcastDriver.d.ts +3 -1
- package/dist/services/broadcast/BroadcastDriver.d.ts.map +1 -1
- package/dist/services/broadcast/BroadcastManager.d.ts.map +1 -1
- package/dist/services/broadcast/BroadcastServiceProvider.d.ts +10 -0
- package/dist/services/broadcast/BroadcastServiceProvider.d.ts.map +1 -1
- package/dist/services/broadcast/RedisBroadcastDriver.d.ts +155 -0
- package/dist/services/broadcast/RedisBroadcastDriver.d.ts.map +1 -0
- package/dist/services/broadcast/SocketHub.d.ts +9 -0
- package/dist/services/broadcast/SocketHub.d.ts.map +1 -1
- package/dist/services/broadcast/config.d.ts +16 -3
- package/dist/services/broadcast/config.d.ts.map +1 -1
- package/dist/services/broadcast/workerWarning.d.ts +10 -0
- package/dist/services/broadcast/workerWarning.d.ts.map +1 -0
- package/dist/services/features/gate.d.ts +11 -0
- package/dist/services/features/gate.d.ts.map +1 -0
- package/dist/services/index.d.ts +6 -5
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +3 -3
- package/dist/services/index.js.map +2 -2
- package/dist/services/logging/LogManager.d.ts +1 -0
- package/dist/services/logging/LogManager.d.ts.map +1 -1
- package/dist/services/logging/config.d.ts +23 -1
- package/dist/services/logging/config.d.ts.map +1 -1
- package/dist/services/logging/consoleSink.d.ts +25 -0
- package/dist/services/logging/consoleSink.d.ts.map +1 -0
- package/dist/services/mcp/McpRegistry.d.ts +106 -14
- package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
- package/dist/services/mcp/http/McpHttpServer.d.ts +41 -2
- package/dist/services/mcp/http/McpHttpServer.d.ts.map +1 -1
- package/dist/services/mcp/toAgentTools.d.ts +21 -3
- package/dist/services/mcp/toAgentTools.d.ts.map +1 -1
- package/dist/services/queue/WorkerProcess.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +5 -4
- package/dist/services/rate-limiter/RateLimiter.d.ts +12 -0
- package/dist/services/rate-limiter/RateLimiter.d.ts.map +1 -1
- package/dist/services/router/globalMiddleware.d.ts +4 -3
- package/dist/services/router/globalMiddleware.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/skills/gemi-react-best-practices/SKILL.md +1 -1
- package/skills/gemi-react-best-practices/rules/query-mutate-over-refetch.md +14 -0
- package/skills/gemi-react-best-practices/rules/routing-middleware-dsl.md +2 -1
- package/dist/chunk-39dx7xrz.js +0 -10
- package/dist/chunk-39dx7xrz.js.map +0 -43
- package/dist/chunk-d0wr9jk4.js +0 -5
- package/dist/chunk-d0wr9jk4.js.map +0 -12
- package/dist/chunk-eevna943.js.map +0 -10
- package/dist/chunk-gvp6brdt.js +0 -57
- package/dist/chunk-kc924zjz.js +0 -5
- package/dist/chunk-kc924zjz.js.map +0 -12
- package/dist/chunk-tazvfppr.js +0 -5
- package/dist/chunk-vpgbn494.js +0 -24
- package/dist/chunk-z23h4s1a.js +0 -14
- package/dist/chunks/ThemeProvider-CgK2mmVV.js.map +0 -1
- /package/dist/{chunk-j0cnsgjq.js.map → chunk-6q6bhkyf.js.map} +0 -0
- /package/dist/{chunk-4qpypa3h.js.map → chunk-ayfjjgv2.js.map} +0 -0
- /package/dist/{chunk-rjm1kj8n.js.map → chunk-gp00enrk.js.map} +0 -0
- /package/dist/{chunk-xhmtph39.js.map → chunk-j10a0m7q.js.map} +0 -0
- /package/dist/{chunk-wqharhrp.js.map → chunk-j12hpdxk.js.map} +0 -0
- /package/dist/{chunk-8x73yyfs.js.map → chunk-s4semb89.js.map} +0 -0
package/dist/chunk-gvp6brdt.js
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Cf as uG}from"./chunk-w61sphn5.js";import{Wf as dG}from"./chunk-s5jxc63j.js";import{$f as XG,$g as AG,Ng as l3,Ug as a$,Xf as lZ,Yg as rz,Zg as k$,_g as MG,ag as m5,bg as p5,bh as EG,cg as l8,dg as m8,gg as p8,hg as h8,ig as yZ,jg as mX,kg as OG,lg as G5,mg as v,rg as C,sg as Fj,tg as n$,ug as i8,vg as u3,xg as F$,yg as g,zg as I8}from"./chunk-z23h4s1a.js";import{eh as v1,fh as P0,gh as m1,hh as d5}from"./chunk-n1a2zj5z.js";import{ih as AX,jh as f8,kh as N}from"./chunk-kc924zjz.js";import{nh as iz,qh as x3}from"./chunk-ebx5hnqn.js";import{uh as N9,xh as PG}from"./chunk-nvngb4ed.js";import{Ph as X$,Uh as g1}from"./chunk-96a1459v.js";import{ii as LG}from"./chunk-1f1sb3w7.js";import{ji as xZ}from"./chunk-73v34hw8.js";import{Ai as cG,ki as h3,li as L1,mi as O$,ni as pG,oi as hG,qi as CZ,ri as SG}from"./chunk-2vc72qez.js";import{Pi as B$}from"./chunk-mxbtcaed.js";import{Ui as WG,Zi as v2}from"./chunk-pfm9ngch.js";import{ej as JG,jj as i}from"./chunk-q1e3q01h.js";import{kj as kZ,nj as T}from"./chunk-hnrzm5pf.js";import{vj as k2}from"./chunk-dmj6ysym.js";import{wj as RG}from"./chunk-eevna943.js";import{Hj as GG}from"./chunk-rkgsvsrj.js";import{Mj as A8}from"./chunk-ay8nat73.js";function y3($){return typeof $==="function"&&$.prototype!==void 0}function l0($){return typeof $==="string"?[$]:$}function q3($,Z){let j=Z?"attachment":"inline",J=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${j}; filename="${J}"; filename*=UTF-8''${encodeURIComponent($)}`}function ZF($){return"total"in $&&"partial"in $&&"body"in $}function Z5(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function mZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":h8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function jF($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(ZF($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,j=Z instanceof Blob?Z:null,J=$.total??j?.size??-1;return{body:Z,start:$.start??0,end:$.end??J-1,total:J,partial:$.partial??!1,type:$.type??j?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function c8($,Z){if($ instanceof Response)return $;if(!$)return Z5();let j=await jF($),{body:J,start:W,end:Y,total:z,partial:X}=j;if(J instanceof Blob&&"exists"in J&&typeof J.exists==="function"){if(!await J.exists())return Z5()}let{range:G}=Z;if(G){if(z<=0)return mZ(Math.max(z,0));if(!X){if(J instanceof Blob){let K=m8(G,z);if(!K)return mZ(z);J=J.slice(K.start,K.end+1),W=K.start,Y=K.end,X=!0}}}let F=Boolean(G)&&X,Q=F?206:j.status,O=new Headers;if(O.set("Accept-Ranges","bytes"),O.set("Content-Type",j.type||"application/octet-stream"),O.set("X-Content-Type-Options","nosniff"),F)O.set("Content-Range",p8(W,Y,z)),O.set("Content-Length",String(Y-W+1));else if(z>=0)O.set("Content-Length",String(z));if(j.name)O.set("Content-Disposition",q3(j.name,j.download));if(j.etag)O.set("ETag",j.etag);if(j.lastModified)O.set("Last-Modified",j.lastModified.toUTCString());for(let[K,D]of Object.entries(j.extraHeaders))O.set(K,D);if((Z.method??"GET").toUpperCase()==="HEAD"){if(J&&"cancel"in J&&typeof J.cancel==="function")await J.cancel();return new Response(null,{status:Q,headers:O})}return new Response(J,{status:Q,headers:O})}class d$ extends P0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var j5={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function hZ($){if(typeof $==="number"){if(Number.isFinite($)&&$>=0)return Math.floor($);if($===1/0)return 1/0}else{let Z=$.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let j=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(j&&(j[2]===""||(j[2]in j5)))return Math.floor(Number(j[1])*(j5[j[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var pZ=new WeakMap;function W5($){return pZ.has($)}function Y5($){return pZ.get($)?.limit??null}function z5($){let Z=pZ.get($);return Z?Z.read>Z.limit:!1}function JF($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function u8($,Z){let j=JF($);if(j!==null&&j>Z)throw new d$(Z)}function v3($,Z,j={}){let J=pZ.get($);if(J)J.limit=Z;else{let W={limit:Z,read:0,stream:void 0,used:!1};pZ.set($,W),YF($,W)}if(j.checkDeclared!==!1)u8($,Z)}function WF($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function d8($,Z){if(Z.stream!==void 0)return Z.stream;let j=WF($);if(!j)return Z.stream=null;let J;return Z.stream=new ReadableStream({async pull(W){J??=j.getReader();let{done:Y,value:z}=await J.read();if(Y){W.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new d$(Z.limit);W.error(X),J.cancel(X).catch(()=>{});return}W.enqueue(z)},cancel(W){return J?J.cancel(W):j.cancel(W)}},{highWaterMark:0}),Z.stream}async function c$($,Z){if(u8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let j=d8($,Z);if(!j)return new Uint8Array(0);let J=j.getReader(),W=[],Y=0;for(;;){let{done:G,value:F}=await J.read();if(G)break;W.push(F),Y+=F.byteLength}let z=new Uint8Array(Y),X=0;for(let G of W)z.set(G,X),X+=G.byteLength;return z}function J5($){return $.headers.get("Content-Type")??""}function YF($,Z){let j=(J,W)=>Object.defineProperty($,J,{configurable:!0,...W});j("body",{get:()=>d8($,Z)}),j("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),j("bytes",{value:()=>c$($,Z)}),j("arrayBuffer",{value:async()=>{let J=await c$($,Z);return J.buffer.slice(J.byteOffset,J.byteOffset+J.byteLength)}}),j("text",{value:async()=>new TextDecoder().decode(await c$($,Z))}),j("json",{value:async()=>JSON.parse(new TextDecoder().decode(await c$($,Z)))}),j("blob",{value:async()=>new Blob([await c$($,Z)],{type:J5($)})}),j("formData",{value:async()=>new Response(await c$($,Z),{headers:{"Content-Type":J5($)}}).formData()}),j("clone",{value:()=>{u8($,Z.limit);let J=d8($,Z),W=null;if(J){let[Y,z]=J.tee();Z.stream=Y,W=z}return new Request($.url,{method:$.method,headers:$.headers,body:W,signal:$.signal,duplex:"half"})}})}function X5($){return y3($)}class J0{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];constructor($,Z,j){this.method=$;this.handler=Z;this.methodName=j;this.handler=Z,this.methodName=j,this.method=$}get source(){if(!X5(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(X5(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=l0($),this}}class F5{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=l0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let j of G5($.rawRequest))delete Z[j];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(j){if(z5($.rawRequest))throw new d$(Y5($.rawRequest));throw j}}}class Q5{constructor(...$){return new J0(...$)}}class K5 extends J0{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),j=Z?.req?.rawRequest,J=l8(j?.headers.get("Range"));if(Z)Z.rangeRequest=J;try{let W=await super.run($);return await c8(W,{range:J,method:j?.method})}catch(W){if(W instanceof i8)return mZ(W.total);throw W}finally{if(Z)Z.rangeRequest=null}}}class O5{constructor(...$){return new K5(...$)}}class B5{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new J0("GET",$,"list"),post:new J0("POST",$,"store")},this.second={get:new J0("GET",$,"show"),put:new J0("PUT",$,"update"),delete:new J0("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class R0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new J0("GET",$,Z)}post($,Z){return new J0("POST",$,Z)}put($,Z){return new J0("PUT",$,Z)}patch($,Z){return new J0("PATCH",$,Z)}delete($,Z){return new J0("DELETE",$,Z)}resource($){return new B5($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${zF($)}.`);return XF($,this)}file($,Z){return new Q5("GET",$,Z)}stream($,Z){return new O5("GET",$,Z)}proxy($,Z={}){return new F5($,Z)}}function zF($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function XF($,Z){let j={stream:new J0("POST",$,"stream"),attach:new J0("POST",$,"attach"),stop:new J0("POST",$,"stop"),upload:new J0("POST",$,"upload")};return class extends R0{static __internal_brand="AgentRoute";static controller=$;static handlers=j;constructor(){super();this.middlewares=[...Z?.middlewares??[]]}routes={"/":j.stream,"/attach":j.attach,"/stop":j.stop,"/files":j.upload};static middleware(W){if(W.stream)j.stream.middleware(W.stream);if(W.attach)j.attach.middleware(W.attach);if(W.stop)j.stop.middleware(W.stop);if(W.upload)j.upload.middleware(W.upload);return this}}}var y1="access_token";function z$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function g3($,Z){let j=z$(Z);if(!j)return null;return(await $.getSession(j,Z.headers.get("User-Agent")))?.user??null}var GF=/^[A-Za-z0-9_-]+$/,FF=/^:[A-Za-z_][A-Za-z0-9_]*$/,D5=/^[A-Za-z0-9_-]{1,128}$/,QF=/^[A-Za-z0-9_.:-]+$/;class p extends Error{constructor($){super($);this.name="InvalidChannelError"}}function U5($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function u$($){if(typeof $!=="string"||$.length===0)throw new p("A channel pattern must be a non-empty string.");if($.length>255)throw new p(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),j=new Set;for(let J of Z){if(FF.test(J)){let W=J.slice(1);if(j.has(W))throw new p(`The channel pattern "${$}" names the param "${W}" twice.`);j.add(W);continue}if(J.startsWith("__"))throw new p(`The channel "${$}" has the segment "${J}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!GF.test(J))throw new p(`The channel pattern "${$}" has an invalid segment "${J}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function cZ($,Z={}){let j=u$($),J=new Set,W=j.map((Y)=>{if(!Y.startsWith(":"))return Y;let z=Y.slice(1);J.add(z);let X=Z[z];if(X===void 0||X===null)throw new p(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!D5.test(G))throw new p(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let Y of Object.keys(Z))if(!J.has(Y))throw new p(`The channel "${$}" has no param "${Y}".`);if(W.length>255)throw new p(`The topic built from "${$}" is longer than 255 characters.`);return W}function s8($){if(u$($).some((j)=>j.startsWith(":")))throw new p(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function V5($){if(typeof $!=="string"||$.length===0||$.length>64||!QF.test($))throw new p(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function T5($,Z){if($===Z)return!0;if($===Q0)return Z.startsWith(`${Q0}.`)&&Z.split(".").length===2;let j=$.split("."),J=Z.split(".");if(j.length!==J.length)return!1;return j.every((W,Y)=>W===J[Y]||W.startsWith(":")&&D5.test(J[Y]))}var Q0="user";function l$($){let Z=typeof $==="object"&&$!==null?$.id:$;return cZ(`${Q0}.:id`,{id:Z})}class r{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class m3 extends r{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return v3(this.req.rawRequest,hZ(Z)),{}}}function KF($){let Z=new Map;for(let j of $)if(typeof j==="string"){let[J,W=""]=j.split(":");if(J.startsWith("-")){if(Z.has(J.replace("-","")))Z.delete(J.replace("-",""))}else Z.set(J,W.split(",").filter(Boolean))}else Z.set(j,[]);return Z}var OF={"body-limit":m3};class q1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:hZ($.bodyLimit)}get aliases(){return{...OF,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!W5($))v3($,this.defaultBodyLimit,{checkDeclared:!1})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new C,j=this.aliases,J=[];for(let[W,Y]of KF($).entries())if(typeof W==="string"){let z=j[W];if(z){let X=new z(Z);J.push({run:()=>X.run.call(X,...Y),runsOnRefusal:M5(z)})}}else if(y3(W)){let z=new W(Z);J.push({run:z.run.bind(z),runsOnRefusal:M5(W)})}else J.push({run:W,runsOnRefusal:!1});return(async()=>{let W={};for(let Y=0;Y<J.length;Y++)try{W={...W,...await J[Y].run()}}catch(z){throw await BF(J.slice(Y+1)),z}return W})()}}function M5($){return $?.runsOnRefusal===!0}async function BF($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(j){console.error(j)}}}class p3{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...l0($)],this}events(...$){return this}}class P5{static __brand="ChannelRouter";channels={};public(){return new p3("public")}private($){return new p3("private",$)}async authorize($,Z,j={},J={}){try{TF(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let W=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!N5(W))return{ok:!1,code:"unknown_channel"};let Y=null;try{if(Z===Q0){if(Object.keys(j??{}).length>0)return{ok:!1,code:"invalid_params"}}else Y=cZ(Z,j??{})}catch(G){if(G instanceof p)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(j??{}).map(([G,F])=>[G,String(F)])),X=new C($,z,"api",Z);return N.exit(()=>h3.exit(()=>N.run(X,async()=>{let G=N.getStore();try{if(W.middlewares.length>0)await T(q1).runMiddleware(W.middlewares);if(Z===Q0){let F=await I5(X);if(!F)return{ok:!1,code:"denied"};if(Y=l$(F),W.visibility==="private"&&W.authorizer){if(await L5(W.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:Y,pattern:Z}}if(W.visibility==="private"){if((W.authorizer?await L5(W.authorizer,X,z):await I5(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:Y,pattern:Z}}catch(F){if(VF(F))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,F),{ok:!1,code:"error"}}finally{G.destroy()}},J.carried)))}}async function DF($,Z,j={},J={}){let W=typeof $==="function"?new $:$;_5(W);let Y=J.as,z,X=null;if(Y instanceof Request)z=Y;else if(Y&&typeof Y==="object"&&Y.rawRequest instanceof Request)z=Y.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=Y?{user:Y}:null;return(await W.authorize(z,Z,j,{carried:X})).ok}function N5($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function I5($){if(!N.getStore().user&&z$($)===null)return null;try{return await h0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function L5($,Z,j){if(UF($))return new $().authorize(Z,j);return $(Z,j)}function UF($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function VF($){return $?.kind===v1||g1($)||X$($)}var H5=new WeakSet;function TF($){if(H5.has($))return;_5($),H5.add($)}function _5($){let Z=Object.entries($.channels),j=[];for(let[J,W]of Z){if(!N5(W))throw new p(`The channel "${J}" is not declared with this.public() or this.private().`);let Y=u$(J);if(Y[0].startsWith(":"))throw new p(`The channel pattern "${J}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(J!==Q0&&Y.length===2&&Y[0]===Q0)throw new p(`The channel pattern "${J}" 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(J!==Q0&&W.visibility==="private"&&!W.authorizer&&Y.some((z)=>z.startsWith(":")))throw new p(`The private channel "${J}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);j.push({pattern:J,segments:J===Q0?[Q0,":id"]:Y})}for(let J=0;J<j.length;J++)for(let W=J+1;W<j.length;W++)if(MF(j[J].segments,j[W].segments))throw new p(`The channel patterns "${j[J].pattern}" and "${j[W].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 MF($,Z){if($.length!==Z.length)return!1;return $.every((j,J)=>j===Z[J]||j.startsWith(":")||Z[J].startsWith(":"))}class o8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,j){this.as=$;this.input=Z;this.bind=j}}class n8{method;url;meta;__internal_brand="McpRoute";constructor($,Z,j){this.method=$;this.url=Z;this.meta=j}}class C5{static __brand="McpRouter";routes={};scopes;param($){return new o8($.as,$.input,$.bind)}fromApiRoute($,Z,j){return new n8($,Z,j)}}function K0($,Z){return $.replace(/:([^/]+[*?]?)/g,(j,J)=>{let W=J.endsWith("?")||J.endsWith("*"),Y=W?J.slice(0,-1):J,z=Z[Y];if(z===void 0){if(W)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${Y}`);console.error(`Missing parameter: ${Y} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class a8 extends P0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class M1{static to($,...Z){let[j={}]=Z,{search:J={},params:W={},permanent:Y,status:z}={params:{},status:307,permanent:!1,...j},X=new URLSearchParams(J).toString();throw new a8([K0($,W)||"/",X.toString()].filter(Boolean).join("?"),z??(Y?301:307))}static external($,Z=307){throw new a8($,Z)}}var x5=Symbol.for("gemi.HttpResponse");class G${kind;body;status;headers;[x5]=!0;constructor($,Z,j,J){this.kind=$;this.body=Z;this.status=j;this.headers=J}static json($,Z={}){let j=Z.status??200;return IF(j),new G$("json",$,j,new Headers(Z.headers))}static error($,Z,j={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return G$.json({error:Z},{...j,status:$})}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let j=$,J=this.serialize(j);for(let W of Z)j.append("Set-Cookie",W);this.headers.forEach((W,Y)=>{if(Y.toLowerCase()!=="set-cookie")j.set(Y,W)});for(let W of this.headers.getSetCookie())j.append("Set-Cookie",W);if(this.status>=400&&!this.headers.has("Cache-Control"))j.set("Cache-Control","no-store");return new Response(J,{status:this.status,headers:j})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null}}}function IF($){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.json: a ${$} response has no body.`)}function i$($){return typeof $==="object"&&$!==null&&$[x5]===!0}function LF($,Z,j={}){return G$.error($,Z,j)}class S5{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,j]=$;this.handler=(J)=>{return new Z()[j](J)}}}async run($,Z){let{destination:j,permanent:J=!1,status:W=307}=await this.handler($);if(!j)throw Error(`Redirect destination is required see ${Z}`);return M1.to(j,{permanent:J,status:W}),{}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function r8($,Z){if($ instanceof Response)return $;let j=$ instanceof Blob,J=j?$:$.file,W=j?$.name:$.name??$.file?.name,Y=(j?$.type:$.type??$.file?.type)||"",z=j?!1:$.download??!1,X=j?200:$.status??200;if(!j)for(let[G,F]of Object.entries($.headers??{}))Z.set(G,F);if(J instanceof Blob&&"exists"in J&&typeof J.exists==="function"){if(!await J.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",Y||"application/octet-stream"),J instanceof Blob)Z.set("Content-Length",String(J.size));if(W)Z.set("Content-Disposition",q3(W,z));return new Response(J instanceof Blob?J.stream():J,{status:X,headers:Z})}class f5{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,j]=$;this.handler=(J)=>{return new Z()[j](J)}}}async run($,Z){let j=await this.handler($);if(!j)throw Error(`File route handler must return a file see ${Z}`);return{FILE:j}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function A5($,Z){if(i$($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class E5{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[j,J]=Z;this.handler=(W)=>{return new j()[J](W)}}}async run($,Z){let j=A5(await this.handler($),this.viewPath);return{[this.viewPath]:{...j,breadcrumb:{label:j?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=l0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class R5{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,j){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends I1{routes=j??{}};else if(Array.isArray(Z)){let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)},this.children=class extends I1{routes=j??{}}}else this.children=class extends I1{routes=Z},this.handler=()=>({})}async run($,Z){let j=A5(await this.handler($),this.viewPath);return{[this.viewPath]:{...j,breadcrumb:{label:j?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class I1{middlewares=[];featureGates=[];routes={};view($,Z){return new E5($,Z)}file($){return new f5($)}redirect($){return new S5($)}layout($,Z,j){return new R5($,Z,j)}}function HF($){return $}function PF(){return{aliases:{},global:[],bodyLimit:null}}var J1="redirect";function W1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let j=new URL($,"http://gemi.invalid");if(j.origin!=="http://gemi.invalid")return Z;let J=`${j.search}${j.hash}`.replaceAll("/","%2F"),W=`${j.pathname}${J}`.replaceAll(":","%3A");return W.startsWith("//")?Z:W}catch{return Z}}function s$($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function NF($,Z=!0){let j=new URL($.rawRequest.url),J=j.pathname.replace(/\.(json|og)$/,""),[,W,...Y]=J.split("/");if(T(i).supportedLocales.includes(W))J=`/${Y.join("/")}`;return Z?`${J}${j.search}`:J}function _F($,Z){let j=(J)=>J.replace(/\/+$/,"")||"/";return j($)===j(Z)}function c3($,Z){let j=Z||T(f).config.signInPath,J=/^[a-z][a-z\d+.-]*:/i.test(j);if(J?!/^https?:\/\//i.test(j):!j.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${j}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let W=new URL(j,"http://gemi.invalid");if($?.kind==="view"){let Y=NF($,!J);if(J||!_F(new URL(Y,W).pathname,W.pathname))W.searchParams.set(J1,Y)}return J?W.href:`${W.pathname}${W.search}`}class b5 extends r{async run($){let Z=N.getStore(),j=Z.req;if(Z.user)return{};let J=await g3(T(f),j);if(!J)throw new F$({redirectTo:c3(j,$)});return Z.setUser(J),{}}}var e8="gemi_same_site",t8="private, no-cache, no-store, max-age=0, must-revalidate";class d3 extends r{run(){let $=N.getStore(),Z=$?.req;if(!Z||$.user)return{};let j=Z.rawRequest;if(Z.kind!=="view"||j.method!=="GET"&&j.method!=="HEAD")return{};let J=new URL(j.url);if(/\.(json|og)$/.test(J.pathname))return{};if(J.searchParams.has(e8))return{};if(z$(Z))return{};let W=j.headers.get("Sec-Fetch-Site");if(W&&W!=="cross-site")return{};throw J.searchParams.set(e8,"1"),new w5(`${J.pathname}${J.search}`)}}class w5 extends P0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=CF($),j={"Content-Type":"text/html; charset=utf-8","Cache-Control":t8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":t8}},viewData:{status:200,data:{},headers:{"Cache-Control":t8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:j,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function CF($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class k5 extends r{async run(...$){let[Z="public",j="864000",...J]=$,W=`${Z}, max-age=${j}${J.length>0?", ":""}${J.join(", ")}`;if($.length===0)W="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")W="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")W="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",W);return{}}}var y5={"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 q5 extends r{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let j={...y5,...this.config.origins[Z]};for(let[J,W]of Object.entries(j))$.ctx().setHeaders(J,W)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let j={...y5,...this.config.origins["*"]};delete j["Access-Control-Allow-Credentials"];for(let[J,W]of Object.entries(j))$.ctx().setHeaders(J,W)}return{}}}class Y1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let j=Z.limit??this.config.limit,J=Z.window??this.config.window,W=Z.cost??1;if(v5("window",J),v5("limit",j),!Number.isFinite(W)||W<0)throw Error(`Rate limiter cost must be zero or greater, got ${W}`);return await this.config.driver.consume({key:$,limit:j,window:J*1000,cost:W})}}function v5($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}class dZ extends P0{constructor($){super("Rate limit exceeded");let Z={"Content-Type":"application/json",...$?c5($):{}};this.payload={api:{status:429,data:{error:m1("rate_limit","Rate limit exceeded",429)},headers:Z},view:{error:{message:"Rate limit exceeded"},status:429,headers:Z}}}}class h5 extends r{async run($,Z){let j=xF();if(!j)return{};let J=await j.consume(this.key(),{limit:g5($)??this.config.limit,window:g5(Z)??this.config.window});if(this.config.headers!==!1){let W=this.req.ctx?.();if(W)for(let[Y,z]of Object.entries(c5(J)))W.setHeaders(Y,z)}if(!J.allowed)throw new dZ(J);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=m5(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${o$(this.req)}:${this.req.routePath??"*"}`}}function xF(){try{let $=T();return $.bound(Y1)?$.make(Y1):null}catch{return null}}function o$($){let Z=p5($.rawRequest);if(Z!==void 0)return Z;let j=$.headers.get("x-forwarded-for");if(j){let[J]=j.split(",");if(J?.trim())return J.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function c5($){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}function g5($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class u5 extends r{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new $j;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new $j;return{}}}class $j extends P0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:d5("csrf","Invalid CSRF token",403)}},view:{}}}class l5{policiesList={};constructor(){let $=this.register();for(let Z of $){let j=new Z;this.policiesList[Z.name]=j}}register(){return[]}}class i5{all($,Z){return!0}}class Zj{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new n$:new u3}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let j=this.answers.get($.rawRequest);if(!j)j=new Map,this.answers.set($.rawRequest,j);let J=j.get(Z);if(!J)J=this.decide($,Z),j.set(Z,J);return J}async allows($,Z){try{return await this.authorize($,Z),!0}catch(j){if(this.isRefusal(j))return!1;throw j}}fromRoute($=new C,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,j)=>this.fromRoute(Z,j||void 0);this.middlewareClass=class extends r{async run(j){await $(this.req,j)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:j,body:J})=>{let W;if(j!==void 0){if(W=$.thread?await $.thread(j,Z):null,W===null||W===void 0)throw this.refusal()}if(J!==void 0){let Y=await $.body(J,Z);if(await this.authorize(Z,Y),j!==void 0&&String(W)!==String(Y))throw this.refusal();return}if(j!==void 0)await this.authorize(Z,W)}}}async decide($,Z){let j=await this.options.load(Z,$);if(j===null||j===void 0||!await this.options.allow(j,$))throw this.refusal();return j}isRefusal($){return this.refuse==="forbidden"?$ instanceof n$:$ instanceof u3}}function SF($){return new Zj($)}async function i3($,Z,j=!1){if(!$.body)return new Uint8Array;let[J,W]=await hF($.body),z=J.length>=2&&J[0]===31&&J[1]===139?W.pipeThrough(new DecompressionStream("gzip")):W;return pF(z,Z,j,$.url)}async function pF($,Z,j,J){let W=$.getReader(),Y=[],z=0;try{for(;;){let{done:F,value:Q}=await W.read();if(F)break;if(z+Q.byteLength>Z){if(!j)throw new l3(J,Z);Y.push(Q.subarray(0,Z-z)),z=Z;break}Y.push(Q),z+=Q.byteLength}}finally{W.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let F of Y)X.set(F,G),G+=F.byteLength;return X}async function hF($){let Z=$.getReader(),j=await Z.read(),J=j.done?new Uint8Array:j.value,W=new ReadableStream({start(Y){if(j.done)Y.close();else Y.enqueue(J)},async pull(Y){let z=await Z.read();if(z.done)Y.close();else Y.enqueue(z.value)},cancel(Y){return Z.cancel(Y)}});return[J,W]}function s3($){return new TextDecoder("utf-8").decode($)}var cF={"&":"&","<":"<",">":">",'"':""","'":"'"};function Q$($){return $.replace(/[&<>"']/g,(Z)=>cF[Z])}var dF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function jj($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,j)=>{if(j[0]!=="#")return dF[j]??Z;let J=j[1]==="x"?parseInt(j.slice(2),16):parseInt(j.slice(1),10);return J>0&&J<=1114111?String.fromCodePoint(J):Z})}function Jj($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function s5($,Z){let j=$.length,J=0;while(J<j){if(Z.stopped?.())return;let W=$.indexOf("<",J);if(W===-1){Z.text(jj($.slice(J)));return}if(W>J)Z.text(jj($.slice(J,W)));if($.startsWith("<!--",W)){let Y=$.indexOf("-->",W+4);if(Y===-1)return;J=Y+3}else if($.startsWith("<![CDATA[",W)){let Y=$.indexOf("]]>",W+9);if(Y===-1)return;Z.text($.slice(W+9,Y)),J=Y+3}else if($.startsWith("<?",W)){let Y=$.indexOf("?>",W+2);if(Y===-1)return;J=Y+2}else if($.startsWith("<!",W)){let Y=$.indexOf(">",W+2);if(Y===-1)return;let z=$.indexOf("[",W+2);if(z!==-1&&z<Y){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;J=G+1}else J=Y+1}else if($[W+1]==="/"){let Y=$.indexOf(">",W+2);if(Y===-1)return;Z.close(Jj($.slice(W+2,Y).trim())),J=Y+1}else{let Y=uF($,W+1);if(Y===-1)return;let z=$.slice(W+1,Y),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),F=Jj(z.slice(0,G));if(F){if(Z.open(F,lF(z.slice(G)),X),X)Z.close(F)}J=Y+1}}}function uF($,Z){let j=null;for(let J=Z;J<$.length;J++){let W=$[J];if(j){if(W===j)j=null}else if(W==='"'||W==="'")j=W;else if(W===">")return J}return-1}function lF($){let Z={},j=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let J of $.matchAll(j))Z[Jj(J[1])]=jj(J[2]??J[3]??"");return Z}class W0 extends Error{url;status;constructor($,Z=null,j=null){super($);this.url=Z;this.status=j;this.name="SitemapError"}}var t5="http://www.sitemaps.org/schemas/sitemap/0.9",iF="http://www.w3.org/1999/xhtml",zj=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
|
-
`,o5=`<urlset xmlns="${t5}" xmlns:xhtml="${iF}">
|
|
4
|
-
`,n5=`</urlset>
|
|
5
|
-
`,K$=50000,uZ=52428800,a5=2048,sF=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),oF=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,nF="application/xml; charset=utf-8",r5=new TextEncoder;function Xj($,Z){let j;try{j=new URL($)}catch{throw new W0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(j.protocol!=="http:"&&j.protocol!=="https:")throw new W0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let J=j.href;if(J.length>a5)throw new W0(`Sitemap: ${Z} is over ${a5} characters: "${J.slice(0,80)}\u2026".`);return J}function e5($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new W0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!oF.test($))throw new W0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function aF($){let Z=Xj($.loc,"loc"),j=`<url><loc>${Q$(Z)}</loc>`;if($.lastmod!=null)j+=`<lastmod>${Q$(e5($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!sF.has($.changefreq))throw new W0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);j+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let J=$.priority;if(!Number.isFinite(J)||J<0||J>1)throw new W0(`Sitemap: priority ${J} of ${Z} is not between 0 and 1.`);j+=`<priority>${Number(J.toFixed(4))}</priority>`}for(let J of $.alternates??[]){let W=J.hrefLang?.trim();if(!W)throw new W0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let Y=Xj(J.href,`alternate href of ${Z}`);j+=`<xhtml:link rel="alternate" hreflang="${Q$(W)}" href="${Q$(Y)}"/>`}return`${j}</url>
|
|
6
|
-
`}function rF($){let Z=$.maxUrls??K$,j=$.maxBytes??uZ;if(!Number.isInteger(Z)||Z<1||Z>K$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${K$}.`);if(!Number.isInteger(j)||j<1||j>uZ)throw RangeError(`Sitemap: maxBytes must be an integer from 1 to ${uZ}.`);return{maxUrls:Z,maxBytes:j}}function $9($,Z={}){let{maxUrls:j,maxBytes:J}=rF(Z),W=r5.encode(zj+o5+n5).byteLength,Y=[],z=[],X=W,G=()=>{Y.push(zj+o5+z.join("")+n5),z=[],X=W};for(let F of $){let Q=aF(F),O=r5.encode(Q).byteLength;if(W+O>J)throw new W0(`Sitemap: the entry for ${F.loc} alone is over maxBytes (${J}).`);if(z.length===j||X+O>J)G();z.push(Q),X+=O}if(z.length>0||Y.length===0)G();return Y}function Z9($){let Z="",j=0;for(let J of $){if(++j>K$)throw new W0(`Sitemap: an index can list at most ${K$} sitemaps.`);let W=Xj(J.loc,"sitemap loc");if(Z+=`<sitemap><loc>${Q$(W)}</loc>`,J.lastmod!=null)Z+=`<lastmod>${Q$(e5(J.lastmod,W))}</lastmod>`;Z+=`</sitemap>
|
|
7
|
-
`}return`${zj}<sitemapindex xmlns="${t5}">
|
|
8
|
-
${Z}</sitemapindex>
|
|
9
|
-
`}function Wj($,Z,j){let J=new Headers(j);if(!J.has("content-type"))J.set("content-type",nF);return new Response($,{status:Z,headers:J})}function tF($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function eF($,Z={}){let j=$9($,Z),J=tF(Z.page);if(J!==null){let Y=j[J-1];return Y?Wj(Y,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(j.length===1)return Wj(j[0],200,Z.headers);let W=Z.pageUrl;if(!W)throw new W0(`Sitemap: the entries need ${j.length} files, so Sitemap.response needs \`pageUrl\` to list them in an index.`);return Wj(Z9(j.map((Y,z)=>({loc:W(z+1)}))),200,Z.headers)}function Yj($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function j9($,Z={}){let j=Z.maxUrls??1/0,J=$.replace(/^\uFEFF/,"").trimStart();if(!J.startsWith("<")){let K=[];for(let D of J.split(/\r?\n/)){if(K.length>=j)break;let B=D.trim()?Yj(D):null;if(B)K.push({loc:B})}if(K.length===0&&J.length>0)throw new W0("Sitemap: the document is neither XML nor a list of URLs.");return{kind:"urlset",urls:K}}let W=null,Y=[],z=[],X=[],G=null,F=null,Q="",O=()=>W==="index"?z.length:Y.length;if(s5(J,{stopped:()=>O()>=j,open(K,D){let B=X[X.length-1];if(X.push(K),W===null){if(K==="urlset")W="urlset";else if(K==="sitemapindex")W="index";return}if(W==="urlset"&&K==="url"&&B==="urlset"||W==="index"&&K==="sitemap"&&B==="sitemapindex")G={};else if(G&&(B==="url"||B==="sitemap")&&(K==="loc"||K==="lastmod"||K==="changefreq"||K==="priority"))F=K,Q="";else if(G&&W==="urlset"&&B==="url"&&K==="link"){let U=D.href?Yj(D.href):null;if(D.rel?.toLowerCase()==="alternate"&&D.hreflang&&U)(G.alternates??=[]).push({hrefLang:D.hreflang,href:U})}},close(K){let D=X.lastIndexOf(K);if(D===-1)return;if(X.length=D,F&&K===F&&G)G[F]=Q.trim(),F=null;else if(G&&(K==="url"||K==="sitemap")){let B=G;G=null,F=null;let U=B.loc?Yj(B.loc):null;if(!U)return;if(W==="index"){z.push(B.lastmod?{loc:U,lastmod:B.lastmod}:{loc:U});return}let V={loc:U};if(B.lastmod)V.lastmod=B.lastmod;if(B.changefreq)V.changefreq=B.changefreq;let M=B.priority?Number(B.priority):NaN;if(Number.isFinite(M))V.priority=M;if(B.alternates)V.alternates=B.alternates;Y.push(V)}},text(K){if(F)Q+=K}}),W===null)throw new W0("Sitemap: the document has no <urlset> or <sitemapindex>.");return W==="index"?{kind:W,sitemaps:z}:{kind:W,urls:Y}}async function*$Q($,Z={}){let{maxUrls:j=K$,maxSitemaps:J=50,maxDepth:W=3,maxSize:Y=uZ,onError:z,...X}=Z,G=[{url:String($),depth:0}],F=new Set,Q=0,O=0;while(G.length>0&&O<j&&Q<J){let K=G.shift(),D=K.url.replace(/#.*$/,"");if(F.has(D))continue;F.add(D),Q++;let B;try{let U=await a$(K.url,{...X,maxSize:Y});if(!U.ok)throw U.body?.cancel().catch(()=>{}),new W0(`Sitemap: ${K.url} answered ${U.status}.`,K.url,U.status);let V=s3(await i3(U,Y));B=j9(V,{maxUrls:Math.max(j-O,J-Q)})}catch(U){if(K.depth===0||!z||X.signal?.aborted)throw U;z(U,K.url);continue}if(B.kind==="index"){if(K.depth>=W)continue;G=B.sitemaps.slice(0,J-Q).map((V)=>({url:V.loc,depth:K.depth+1})).concat(G);continue}for(let U of B.urls)if(yield{...U,sitemap:K.url},++O>=j)return}}var J9={response:eF,chunk:$9,index:Z9,parse:j9,read:$Q,MAX_URLS:K$,MAX_BYTES:uZ};var ZQ=512000,jQ=new TextEncoder;function W9($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function Y9($){let Z="";for(let j=0;j<$.length;j++){let J=$[j];if(J==="%"&&/^[0-9a-fA-F]{2}$/.test($.slice(j+1,j+3)))Z+=`%${$.slice(j+1,j+3).toUpperCase()}`,j+=2;else if(J.charCodeAt(0)>126||J.charCodeAt(0)<=32){let W=$.codePointAt(j);if(W>65535)j++;for(let Y of jQ.encode(String.fromCodePoint(W)))Z+=`%${Y.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=J}return Z}function JQ($,Z){let j=$.endsWith("$"),J=j?$.slice(0,-1):$,W=0,Y=0,z=-1,X=0;while(Y<Z.length)if(W<J.length&&J[W]!=="*"&&J[W]===Z[Y])W++,Y++;else if(W<J.length&&J[W]==="*")z=W++,X=Y;else if(W===J.length&&!j)return!0;else if(z!==-1)W=z+1,Y=++X;else return!1;while(W<J.length&&J[W]==="*")W++;return W===J.length}class r${groups;sitemaps;status;constructor($,Z,j="parsed"){this.groups=$;this.sitemaps=Z;this.status=j}groupsFor($){let Z=W9($)||"*";if(Z!=="*"){let j=this.groups.filter((J)=>J.userAgents.includes(Z));if(j.length>0)return j}return this.groups.filter((j)=>j.userAgents.includes("*"))}isAllowed($,Z="*"){let j;if($ instanceof URL||/^[a-z][a-z0-9+.-]*:/i.test($)){let W=new URL(String($));j=W.pathname+W.search}else j=$.startsWith("/")?$:`/${$}`;if(j==="/robots.txt")return!0;if(this.status==="unavailable")return!0;if(this.status==="unreachable")return!1;j=Y9(j);let J=null;for(let W of this.groupsFor(Z))for(let Y of W.rules){if(!JQ(Y.path,j))continue;let z=Y.path.length,X=Y.type==="allow";if(!J||z>J.length||z===J.length&&X)J={length:z,allow:X}}return J?J.allow:!0}crawlDelay($="*"){for(let Z of this.groupsFor($))if(Z.crawlDelay!==void 0)return Z.crawlDelay;return null}}var WQ={"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 z9($,Z={}){let j=[],J=[],W=null,Y=!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(),F=G.indexOf(":");if(F===-1)continue;let Q=WQ[G.slice(0,F).trim().toLowerCase()],O=G.slice(F+1).trim();if(!Q)continue;if(Q==="sitemap"){if(!O||/\s/.test(O))continue;try{let K=Z.url?new URL(O,Z.url):new URL(O);if(K.protocol==="http:"||K.protocol==="https:")J.push(K.href)}catch{}continue}if(Q==="user-agent"){if(!Y||!W)W={userAgents:[],rules:[]},j.push(W),Y=!0;let K=W9(O);if(K)W.userAgents.push(K);continue}if(!W)continue;if(Y=!1,Q==="crawl-delay"){let K=Number(O);if(Number.isFinite(K)&&K>=0)W.crawlDelay=K;continue}if(!O)continue;W.rules.push({type:Q,path:Y9(O)})}return new r$(j,J)}async function YQ($,Z={}){let{maxSize:j=ZQ,...J}=Z,W=new URL("/robots.txt",$),Y=await a$(W,{...J,maxSize:Number.MAX_SAFE_INTEGER}),z=Y.status;if(z===429||z>=500)return Y.body?.cancel().catch(()=>{}),new r$([],[],"unreachable");if(z>=400)return Y.body?.cancel().catch(()=>{}),new r$([],[],"unavailable");let X=await i3(Y,j,!0),G=s3(X);if(X.byteLength>=j)G=G.slice(0,Math.max(0,G.lastIndexOf(`
|
|
10
|
-
`)));return z9(G,{url:Y.url})}function Gj($){return $===void 0?[]:typeof $==="string"?[$]:$}function o3($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
|
|
11
|
-
`}function X9($){let Z=[];for(let J of $.rules??[]){let W=Gj(J.userAgent);if(W.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let Y=W.map((X)=>o3("User-agent",X)).join(""),z=[...Gj(J.allow).map((X)=>["Allow",X]),...Gj(J.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 "*".`);Y+=o3(X,G)}if(z.length===0)Y+=`Disallow:
|
|
12
|
-
`;if(J.crawlDelay!==void 0){if(!Number.isFinite(J.crawlDelay)||J.crawlDelay<0)throw TypeError(`Robots: crawlDelay ${J.crawlDelay} is not a number of seconds.`);Y+=o3("Crawl-delay",String(J.crawlDelay))}Z.push(Y)}let j=($.sitemaps??[]).map((J)=>{let W;try{W=new URL(J)}catch{throw TypeError(`Robots: sitemap "${J}" is not an absolute URL.`)}return o3("Sitemap",W.href)});if(j.length>0)Z.push(j.join(""));return Z.join(`
|
|
13
|
-
`)}function zQ($,Z={}){let j=new Headers(Z.headers);if(!j.has("content-type"))j.set("content-type","text/plain; charset=utf-8");return new Response(X9($),{status:200,headers:j})}var G9={response:zQ,text:X9,parse:z9,fetch:YQ};import{createHmac as F9,randomBytes as XQ}from"crypto";var Qj="v2.";function Kj($){return $.startsWith(Qj)}function t$(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function Q9($){let Z=XQ(16).toString("hex"),j=F9("sha256",t$()).update(`${$}:${Z}`).digest("hex");return`${Qj}${j}`}function n3($,Z){let j=F9("sha256",t$()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${Qj}${j}`}import{createHash as QQ,createHmac as KQ,randomInt as OQ,timingSafeEqual as B9}from"crypto";function K9($,Z){return Math.floor($/Z)*Z}function GQ($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function Oj($,Z,j,J){return Z*GQ(j,J)+$}function FQ($){let{current:Z,previous:j,elapsed:J,window:W,limit:Y,cost:z}=$,X=Y-z;if(X<0)return W;let G=Math.max(0,W-J);if(j>0){let Q=W*(1-(X-Z)/j);if(Q<=W)return Math.max(0,Math.ceil(Q-J))}if(Z<=X)return G;if(Z<=0)return G;let F=W*(1-X/Z);return G+Math.max(0,Math.ceil(F))}function O9($){let{allowed:Z,current:j,previous:J,now:W,elapsed:Y,window:z,limit:X,cost:G}=$;if(Z){let Q=Oj(j,J,Y,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-Q)),resetAt:W-Y+z,retryAfter:0}}let F=FQ({current:j,previous:J,elapsed:Y,window:z,limit:X,cost:G});return{allowed:!1,limit:X,remaining:0,resetAt:W+F,retryAfter:F}}class Bj{}class Dj extends Bj{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:j,window:J}=$,W=$.cost??1,Y=Date.now(),z=K9(Y,J),X=Y-z,G=this.roll(Z,J,z);G.limit=j;let Q=Oj(G.current,G.previous,X,J)+W<=j;if(Q)G.current+=W;if(this.buckets.delete(Z),this.buckets.set(Z,G),this.buckets.size>this.maxKeys)this.evict(Y);return O9({allowed:Q,current:G.current,previous:G.previous,now:Y,elapsed:X,window:J,limit:j,cost:W})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,j){let J=this.buckets.get($);if(!J||J.window!==Z)return{window:Z,limit:0,windowStart:j,current:0,previous:0};if(J.windowStart===j)return J;if(J.windowStart+Z===j)return J.previous=J.current,J.current=0,J.windowStart=j,J;return J.previous=0,J.current=0,J.windowStart=j,J}evict($){for(let[J,W]of this.buckets)if($-W.windowStart>=W.window*2)this.buckets.delete(J);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let j=[...this.buckets].map(([J,W],Y)=>({key:J,order:Y,spent:W.limit>0?(W.current+W.previous)/W.limit:0}));j.sort((J,W)=>J.spent-W.spent||J.order-W.order);for(let{key:J}of j){if(this.buckets.size<=Z)break;this.buckets.delete(J)}}}var V9="h1.";function a3($,Z,j){let J=KQ("sha256",t$()).update(`gemi:one-time:${$}:${Z}:${j}`).digest("hex");return`${V9}${J}`}function iZ($,Z,j,J){let W=typeof J==="string"?J:"",Y=typeof j==="string"?j:"",z=Y.startsWith(V9),X=a3($,Z,W),G=Buffer.from(z?X:W),F=Buffer.from(Y);if(G.length!==F.length||W===""||Y==="")return B9(G,G),!1;return B9(G,F)}function T9($){let Z="";for(let j=0;j<$;j++)Z+=String(OQ(0,10));return Z}var M9=320;function sZ($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>M9)return null;return Z.toLowerCase()}function r3($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>M9)return null;let j=Z.toLowerCase();if(j.length<3||j.length>254||!/^[^\s@]+@[^\s@]+$/.test(j))return null;return j}var D9=null;function I9(){try{let $=T();if(typeof $?.bound==="function"&&$.bound(Y1))return $.make(Y1)}catch{}return D9??=new Y1({driver:new Dj,limit:1000,window:60}),D9}function U9($){return $.length<=64?$:`sha256:${QQ("sha256").update($).digest("hex")}`}async function e$($,Z,j,J){let W=I9(),Y=[[`auth:code-${$}:ip:${U9(o$(j))}`,J.perIp]];if(Z!==null)Y.push([`auth:code-${$}:email:${U9(Z)}`,J.perEmail]);for(let[z,X]of Y){if(!X)continue;let[G,F]=X,Q=await W.consume(z,{limit:G,window:F});if(!Q.allowed)throw new dZ(Q)}}async function L9($,Z,j,J=10){let W=Math.max(86400,Math.ceil(J*60*(j+1)));return(await I9().consume(`auth:code-attempt:${$}:${Z}`,{limit:j,window:W})).allowed}import{randomBytes as Vj}from"crypto";class Uj extends C{schema={name:{string:"Invalid name",required:"Name is required","min:2":"Name must be at least 3 characters"},email:{string:"Invalid email",required:"Email is required",email:"Invalid email"},password:{"min:8":"Password must be at least 9 characters"}}}function t3($,Z,j,J=1/0){if(!Number.isInteger(Z)||Z<j||Z>J){let W=J===1/0?`an integer of at least ${j}`:`an integer from ${j} to ${J}`;throw Error(`auth.emailCode.${$} must be ${W}, got ${Z}`)}}function Tj($={}){let Z=$.length??6,j=$.expiresInMinutes??10,J=$.linkExpiresInMinutes??10080,W=$.maxAttempts??5;return t3("length",Z,4,12),t3("expiresInMinutes",j,1),t3("linkExpiresInMinutes",J,1),t3("maxAttempts",W,1),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:j,linkExpiresInMinutes:J,maxAttempts:W,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:Y,code:z})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${Y}: ${z} (set auth.emailCode.send to deliver it)`)})}}async function BQ($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function cT($){return $}function H9($={}){return{basePath:"/auth",verifyEmail:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:Uj,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:BQ,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>Vj(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return Vj(32).toString("hex")},generateMagicLinkToken:()=>Vj(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:Tj($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}function Mj($){if($&&typeof $==="object")delete $.password;return $}function DQ(){return new Proxy({},{get:($,Z)=>N9(Z)})}var P9=new WeakMap;function _9($){if($&&typeof $==="object"){for(let Z of Object.values($))_9(Z);Object.freeze($)}return $}var UQ={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},VQ=_9({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:UQ});class Ij{models;constructor($=DQ()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return VQ}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let j=this.models.User.$connection??O$(),J=T(B$).connection(j),W=()=>this.transaction(async()=>{if(J.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await L1()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(J.dialect!=="sqlite"||L1())return W();let z=(P9.get(J)??Promise.resolve()).then(W,W);return P9.set(J,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return Mj(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return Mj(Z)}async findUserByEmailAddress($,Z){return await this.run(()=>this.models.User.findUnique({where:Z?{email:$,emailVerifiedAt:{not:null}}:{email:$}}))}async findUserByVerificationToken($){if(typeof $!=="string"||$==="")return null;return await this.run(()=>this.models.User.findFirst({where:{verificationToken:$}}))}async verifyUser($){return await this.run(()=>this.models.User.update({where:{email:$},data:{emailVerifiedAt:new Date}}))}async createSession($){return await this.run(()=>this.models.Session.create({data:$,include:{user:!0}}))}async createSessionV2($){return await this.run(()=>this.models.Session.create({data:$,select:this.sessionSelect()}))}async findSession($){if(!$.token)return null;try{return await this.run(()=>this.models.Session.findUnique({where:{token:$.token},select:this.sessionSelect()}))}catch(Z){return console.error("findSession failed:",Z),null}}async updateSession($){return await this.run(()=>this.models.Session.update({where:{token:$.token},data:{expiresAt:$.expiresAt},select:this.sessionSelect()}))}async deleteSession($){if(!$.token)return;await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}))}async claimLegacySession($){if(!$.token)return!1;let{count:Z}=await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}));return Z>0}async deleteAllUserSessions($){await this.run(()=>this.models.Session.deleteMany({where:{userId:$}}))}async createPasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.create({data:{token:$.token,user:{connect:{id:$.user.id}}}}))}async findPasswordResetToken($){if(typeof $.token!=="string"||$.token==="")return null;return await this.run(()=>this.models.PasswordResetToken.findUnique({where:{token:$.token},include:{user:!0}}))}async deletePasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.delete({where:{token:$.token}}))}async findInvitation($,Z){if(typeof $!=="string"||typeof Z!=="string")return null;return await this.run(()=>this.models.OrganizationInvitation.findFirst({where:{publicId:$,email:Z}}))}async deleteInvitationById($){await this.run(()=>this.models.OrganizationInvitation.delete({where:{publicId:$}}))}async createAccount($){return await this.run(()=>this.models.Account.create({data:{userId:$.userId,organizationId:$.organizationId,organizationRole:$.organizationRole}}))}async createMagicLinkToken($){return await this.run(()=>this.models.MagicLinkToken.create({data:{email:$.email,token:$.token,pin:$.pin}}))}async findUserMagicLinkToken($){let Z=(j)=>typeof j==="string"&&j!=="";if(!Z($.email))return null;if($.token!==void 0&&!Z($.token))return null;if($.token===void 0&&!Z($.pin))return null;return await this.run(()=>$.token?this.models.MagicLinkToken.findUnique({where:{token_email:{token:$.token,email:$.email}}}):this.models.MagicLinkToken.findUnique({where:{pin_email:{pin:$.pin,email:$.email}}}))}async findMagicLinkTokenByEmail($){return await this.run(()=>this.models.MagicLinkToken.findFirst({where:{email:$},orderBy:{id:"desc"}}))}async claimMagicLinkToken($){let{count:Z}=await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{id:$}}));return Z===1}async deleteMagicLinkToken($){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$}}))}async createSocialAccount($){return await this.run(()=>this.models.SocialAccount.create({data:$}))}async findUserBySocialAccount($,Z){if(!Z)return null;let j=await this.run(()=>this.models.SocialAccount.findFirst({where:{provider:$,providerId:Z},include:{user:!0}}));return j?Mj(j.user):null}async findSocialAccounts($,Z){return await this.run(()=>this.models.SocialAccount.findMany({where:{userId:$,provider:Z},orderBy:{id:"asc"}}))}async claimSocialAccount($,Z){let{count:j}=await this.run(()=>this.models.SocialAccount.updateMany({where:{id:$.id,providerId:$.providerId},data:{providerId:Z}}));return j===1}}import{randomBytes as BB}from"crypto";function b0($,Z,j,J,W){return i0(Z,p9($,Z),j,J,W)}function i0($,Z,j,J,W,Y){let z=_j(Z,j,J);if(W&&Z!==z)throw RangeError(NY($,Z,j,J,Y));return z}function p9($,Z){let j=$[Z];if(j===void 0)throw TypeError(e4(Z));return j}function B0($){return $!==null&&/object|function/.test(typeof $)}function y0($,Z=Map){let j=new Z;return(J,...W)=>{if(j.has(J))return j.get(J);let Y=$(J,...W);return j.set(J,Y),Y}}function bj($){return T$({name:$},1)}function T$($,Z){return a0((j)=>({value:j,configurable:1,writable:!Z}),$)}function h9($){return a0((Z)=>({get:Z,configurable:1}),$)}function D6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function zZ($,Z){let j={},J=$.length;for(let W of Z)j[$[--J]]=W;return j}function a0($,Z,j){let J={};for(let W in Z)J[W]=$(Z[W],W,j);return J}function j3($,Z,j){let J={};for(let W=0;W<Z.length;W++){let Y=Z[W];J[Y]=$(Y,W,j)}return J}function TQ($,Z,j){let J={};for(let W=0;W<$.length;W++)J[Z[W]]=j[$[W]];return J}function v0($,Z){let j={};for(let J of $)j[J]=Z[J];return j}function wj($,Z){let j={};for(let J in Z)$.has(J)||(j[J]=Z[J]);return j}function kj($){$={...$};let Z=Object.keys($);for(let j of Z)$[j]===void 0&&delete $[j];return $}function c9($,Z){for(let j of Z)if(!(j in $))return 0;return 1}function d9($,Z,j){for(let J of $)if(Z[J]!==j[J])return 0;return 1}function u9($,Z,j){let J={...j};for(let W=0;W<Z;W++)J[$[W]]=0;return J}function b($,...Z){return(...j)=>$(...Z,...j)}function C9($){return $[0].toUpperCase()+$.substring(1)}function J3($){return $.slice().sort()}function Y6($,Z){return String(Z).padStart($,"0")}function p1($,Z){return Math.sign($-Z)}function _j($,Z,j){return Math.min(Math.max($,Z),j)}function P1($,Z){return[Math.floor($/Z),nZ($,Z)]}function nZ($,Z){return($%Z+Z)%Z}function d1($,Z){return[U6($,Z),yj($,Z)]}function U6($,Z){return Math.trunc($/Z)||0}function yj($,Z){return $%Z||0}function e3($){return Math.abs($%1)===0.5}function l9($,Z,j){let J=0,W=0;for(let X=0;X<=Z;X++){let G=$[j[X]],F=X1[X],Q=h/F,[O,K]=d1(G,Q);J+=K*F,W+=O}let[Y,z]=d1(J,h);return[W+Y,z]}function V6($,Z,j){let J={};for(let W=Z;W>=0;W--){let Y=X1[W];J[j[W]]=U6($,Y),$=yj($,Y)}return J}function i9($){return $===w?a6:[]}function s9($){return $===w?B3:[]}function o9($){return $===w?["year","day"]:[]}function n9($){if($!==void 0)return t($)}function a9($){if($!==void 0)return r0($)}function qj($){if($!==void 0)return W3($)}function r0($){return e9(W3($))}function W3($){return t9(GK($))}function vj($){if($==null)throw TypeError("Cannot be null or undefined");return $}function r9($,Z){if(Z==null)throw RangeError(e4($));return Z}function _1($){if(!B0($))throw TypeError(PY);return $}function T6($,Z,j=$){if(typeof Z!==$)throw TypeError(Q3(j,Z));return Z}function t9($,Z="number"){if(!Number.isInteger($))throw RangeError(wQ(Z,$));return $||0}function e9($,Z="number"){if($<=0)throw RangeError(kQ(Z,$));return $}function gj($){if(typeof $=="symbol")throw TypeError(gQ);return String($)}function z6($,Z){return B0($)?String($):t($,Z)}function M6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(vQ($));return $}function $7($,Z="number"){if(typeof $=="bigint")throw TypeError(qQ(Z));if($=Number($),!Number.isFinite($))throw RangeError(yQ(Z,$));return $}function N0($,Z){return Math.trunc($7($,Z))||0}function Z7($,Z){return t9($7($,Z),Z)}function x9($,Z){return e9(N0($,Z),Z)}function mj($,Z){let[j,J]=d1(Z,h),W=$+j,Y=Math.sign(W);return Y&&Y===-Math.sign(J)&&(W-=Y,J+=Y*h),[W,J]}function ZZ($,Z,j=1){return mj($[0]+Z[0]*j,$[1]+Z[1]*j)}function jZ($,Z){return mj($[0],$[1]+Z)}function c0($,Z){return ZZ(Z,$,-1)}function C0($,Z){return p1($[0],Z[0])||p1($[1],Z[1])}function j7($,Z,j){return C0($,Z)===-1||C0($,j)===1}function I6($,Z=1){let j=BigInt(h/Z);return[Number($/j),Number($%j)*Z]}function JZ($,Z=1){let j=h/Z,[J,W]=d1($,j);return[J,W*Z]}function J7($,Z=1){let[j,J]=$,W=Math.floor(J/Z),Y=h/Z;return BigInt(j)*BigInt(Y)+BigInt(W)}function d0($,Z=1,j){let[J,W]=$,[Y,z]=d1(W,Z);return J*(h/Z)+(Y+(j?z/Z:0))}function pj($,Z,j=P1){let[J,W]=$,[Y,z]=j(W,Z);return[J*(h/Z)+Y,z]}function hj($,Z){let j=$.formatToParts(Z),J={};for(let W of j)J[W.type]=W.value;return J}function cj($){return b0($,"isoYear",Z3,$3,1),$.isoYear===Z3?b0($,"isoMonth",4,12,1):$.isoYear===$3&&b0($,"isoMonth",1,9,1),$}function h1($){return C1({...$,...n0,isoHour:12}),$}function C1($){let Z=b0($,"isoYear",Z3,$3,1),j=Z===Z3?1:Z===$3?-1:0;return j&&u0(_0({...$,isoDay:$.isoDay+j,isoNanosecond:$.isoNanosecond-j})),$}function u0($){if(!$||j7($,UK,DK))throw RangeError(i6);return $}function u1($){return l9($,5,Z1)[1]}function L6($){let[Z,j]=P1($,h);return[V6(j,5,Z1),Z]}function W7($){return Y7($)[0]}function Y7($){return pj($,o0)}function x0($){return XZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function _0($){let Z=x0($);if(Z!==void 0){let[j,J]=d1(Z,k0);return[j,J*G1+($.isoMicrosecond||0)*x$+($.isoNanosecond||0)]}}function dj($,Z){let[j,J]=L6(u1($)-Z);return u0(_0({...$,isoDay:$.isoDay+J,...j}))}function X6(...$){return XZ(...$)/kY}function XZ(...$){let[Z,j]=z7(...$),J=Z.valueOf();if(!isNaN(J))return J-j*k0}function z7($,Z=1,j=1,J=0,W=0,Y=0,z=0){let X=$===Z3?1:$===$3?-1:0,G=new Date;return G.setUTCHours(J,W,Y,z),G.setUTCFullYear($,Z-1,j+X),[G,X]}function i1($,Z){let[j,J]=jZ($,Z);J<0&&(J+=h,j-=1);let[W,Y]=P1(J,G1),[z,X]=P1(Y,x$);return H6(j*k0+W,z,X)}function H6($,Z=0,j=0){let J=Math.ceil(Math.max(0,Math.abs($)-BK)/k0)*Math.sign($),W=new Date($-J*k0);return zZ(t6,[W.getUTCFullYear(),W.getUTCMonth()+1,W.getUTCDate()+J,W.getUTCHours(),W.getUTCMinutes(),W.getUTCSeconds(),W.getUTCMilliseconds(),Z,j])}function X7($){return[$.isoYear,$.isoMonth,$.isoDay]}function G7(){return H1}function uj($,Z){switch(Z){case 2:return lj($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function F7($){return lj($)?366:365}function lj($){return $%4==0&&($%100!=0||$%400==0)}function Q7($){let[Z,j]=z7($.isoYear,$.isoMonth,$.isoDay);return nZ(Z.getUTCDay()-j,7)||7}function K7({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function MQ($){let Z=x0($);if(Z<TK)return K7($);let j=hj(TJ(WZ),Z),{era:J,eraYear:W}=PW(j,WZ);return[J,W]}function P6($){return M$($),N6($,1),$}function M$($){return O7($,1),$}function S9($){return d9(FJ,$,O7($))}function O7($,Z){let{isoYear:j}=$,J=b0($,"isoMonth",1,G7(),Z);return{isoYear:j,isoMonth:J,isoDay:b0($,"isoDay",1,uj(j,J),Z)}}function N6($,Z){return zZ(Z1,[b0($,"isoHour",0,23,Z),b0($,"isoMinute",0,59,Z),b0($,"isoSecond",0,59,Z),b0($,"isoMillisecond",0,999,Z),b0($,"isoMicrosecond",0,999,Z),b0($,"isoNanosecond",0,999,Z)])}function y($){return $===void 0?0:rY(_1($))}function Y3($,Z=0){$=t0($);let j=tY($),J=SK($,Z);return[rY($),J,j]}function ij($){return tY(t0($))}function B7($){return $=t0($),OJ($,9,6,1)}function GZ($,Z,j,J=9,W=0,Y=4){Z=t0(Z);let z=OJ(Z,J,W),X=nj(Z),G=U3(Z,Y),F=D3(Z,J,W,1);return z==null?z=Math.max(j,F):T7(z,F),X=aj(X,F,1),$&&(G=((Q)=>Q<4?(Q+2)%4:Q)(G)),[z,F,X,G]}function _6($,Z=6,j){let J=nj($=rj($,B6)),W=U3($,7),Y=D3($,Z);return Y=r9(B6,Y),J=aj(J,Y,void 0,j),[Y,J,W]}function sj($){return BJ(t0($))}function D7($,Z){return oj(t0($),Z)}function oj($,Z=4){let j=V7($);return[U3($,4),...U7(D3($,Z),j)]}function U7($,Z){return $!=null?[X1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function nj($){let Z=$[aZ];return Z===void 0?1:N0(Z,aZ)}function aj($,Z,j,J){let W=J?h:X1[Z+1];if(W){let Y=X1[Z];if(W%(($=i0(aZ,$,1,W/Y-(J?0:1),1))*Y))throw RangeError(Q3(aZ,$))}else $=i0(aZ,$,1,j?1e9:1,1);return $}function V7($){let Z=$[Nj];if(Z!==void 0){if(typeof Z!="number"){if(gj(Z)==="auto")return;throw RangeError(Q3(Nj,Z))}Z=i0(Nj,Math.floor(Z),0,9,1)}return Z}function t0($){return $===void 0?{}:_1($)}function rj($,Z){return typeof $=="string"?{[Z]:$}:_1($)}function Y0($){if($!==void 0){if(B0($))return Object.assign(Object.create(null),$);throw TypeError(PY)}}function C6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:IK[Z]})}function tj($,Z,j=9,J=0,W){let Y=Z[$];if(Y===void 0)return W?J:void 0;if(Y=gj(Y),Y==="auto")return W?J:null;let z=fj[Y];if(z===void 0&&(z=KK[Y]),z===void 0)throw RangeError(xY($,Y,fj));return i0($,z,J,j,1,O3),z}function I$($,Z,j,J=0){let W=j[$];if(W===void 0)return J;let Y=gj(W),z=Z[Y];if(z===void 0)throw RangeError(xY($,Y,Z));return z}function T7($,Z){if(Z>$)throw RangeError(JK)}function D0($){return{branding:$8,epochNanoseconds:$}}function M0($,Z,j){return{branding:A1,calendar:j,timeZone:Z,epochNanoseconds:$}}function z0($,Z=$.calendar){return{branding:f$,calendar:Z,...v0(sY,$)}}function X0($,Z=$.calendar){return{branding:S$,calendar:Z,...v0(QJ,$)}}function U$($,Z=$.calendar){return{branding:VZ,calendar:Z,...v0(QJ,$)}}function G6($,Z=$.calendar){return{branding:TZ,calendar:Z,...v0(QJ,$)}}function e0($){return{branding:e6,...v0(iY,$)}}function s($){return{branding:Z8,sign:s1($),...v0(zJ,$)}}function M7($){return W7($.epochNanoseconds)}function x6($){return pj($.epochNanoseconds,G1)[0]}function I7($){return J7($.epochNanoseconds,x$)}function L7($){return J7($.epochNanoseconds)}function H7($){return $.epochNanoseconds}function V0($){return typeof $=="string"?$:t($.id)}function FZ($,Z){return $===Z||V0($)===V0(Z)}function P7($,Z,j,J,W){let Y=V$(J),[z,X]=((V,M)=>{let I=M((V=rj(V,Rj))[nY]),P=xK(V);return P=r9(Rj,P),[P,I]})(W,$);if(tZ(Math.max(z,Y),X))return f9(J,z);if(!X)throw RangeError(s6);let[G,F,Q]=b6(Z,j,X),O=P4(Q),K=w6(Q),D=N4(Q),B=K(F,G,J),U=D(F,G,B,z);return tZ(z,X)?f9(U,z):((V,M,I,P,A,x,E)=>{let S=s1(V),[H,L]=ej(P,GJ(I,V),I,S,A,x,E),m=$4(M,H,L);return V[q[I]]+m*S})(U,O(B),z,F,G,O,K)}function f9($,Z){return d0(O0($),X1[Z],1)}function ej($,Z,j,J,W,Y,z){let X=q[j],G={...Z,[X]:Z[X]+J},F=z($,W,Z),Q=z($,W,G);return[Y(F),Y(Q)]}function $4($,Z,j){let J=d0(c0(Z,j));if(!J)throw RangeError(K3);return d0(c0(Z,$))/J}function N7($,Z){let[j,J,W]=_6(Z,5,1);return D0(f6($.epochNanoseconds,j,J,W,1))}function _7($,Z,j){let{epochNanoseconds:J,timeZone:W,calendar:Y}=Z,[z,X,G]=_6(j);if(z===0&&X===1)return Z;let F=$(W);if(z===6)J=((Q,O,K,D)=>{let B=S0(K,O),[U,V]=Q(B),M=K.epochNanoseconds,I=q0(O,U),P=q0(O,V);if(j7(M,I,P))throw RangeError(K3);return w7($4(M,I,P),D)?P:I})(R7,F,Z,G);else{let Q=F.getOffsetNanosecondsFor(J);J=H$(F,A7(i1(J,Q),z,X,G),Q,2,0,1)}return M0(J,W,Y)}function C7($,Z){return z0(A7($,..._6(Z)),$.calendar)}function x7($,Z){let[j,J,W]=_6(Z,5);var Y;return e0((Y=W,Z4($,z3(j,J),Y)[0]))}function S7($,Z){let j=$(Z.timeZone),J=S0(Z,j),[W,Y]=R7(J),z=d0(c0(q0(j,W),q0(j,Y)),n6,1);if(z<=0)throw RangeError(K3);return z}function f7($,Z){let{timeZone:j,calendar:J}=Z,W=((Y,z,X)=>q0(z,Y(S0(X,z))))(b7,$(j),Z);return M0(W,j,J)}function A7($,Z,j,J){return E7($,z3(Z,j),J)}function E7($,Z,j){let[J,W]=Z4($,Z,j);return C1({...P$($,W),...J})}function Z4($,Z,j){return L6(l1(u1($),Z,j))}function F6($){return l1($,o6,7)}function z3($,Z){return X1[$]*Z}function R7($){let Z=b7($);return[Z,P$(Z,1)]}function b7($){return OK(6,$)}function IQ($,Z,j){let J=Math.min(V$($),6);return KZ(A6(O0($,J),Z,j),J)}function S6($,Z,j,J,W,Y,z,X,G,F){if(J===0&&W===1)return $;let Q=tZ(J,X)?k6(X)&&J<6&&j>=6?HQ:LQ:PQ,[O,K,D]=Q($,Z,j,J,W,Y,z,X,G,F);return D&&J!==7&&(O=((B,U,V,M,I,P,A,x)=>{let E=s1(B);for(let S=M+1;S<=V;S++){if(S===7&&V!==7)continue;let H=GJ(S,B);H[q[S]]+=E;let L=d0(c0(A(x(I,P,H)),U));if(L&&Math.sign(L)!==E)break;B=H}return B})(O,K,j,Math.max(6,J),z,X,G,F)),O}function f6($,Z,j,J,W){if(Z===6){let Y=((z)=>z[0]+z[1]/h)($);return[l1(Y,j,J),0]}return A6($,z3(Z,j),J,W)}function A6($,Z,j,J){let[W,Y]=$;J&&Y<0&&(Y+=h,W-=1);let[z,X]=P1(l1(Y,Z,j),h);return mj(W+z,X)}function l1($,Z,j){return w7($/Z,j)*Z}function w7($,Z){return EK[Z]($)}function LQ($,Z,j,J,W,Y){let z=s1($),X=O0($),G=f6(X,J,W,Y),F=c0(X,G),Q=Math.sign(G[0]-X[0])===z,O=KZ(G,Math.min(j,6));return[{...$,...O},ZZ(Z,F),Q]}function HQ($,Z,j,J,W,Y,z,X,G,F){let Q=s1($),O=d0(O0($,5)),K=z3(J,W),D=l1(O,K,Y),[B,U]=ej(z,{...$,...XJ},6,Q,X,G,F),V=D-d0(c0(B,U)),M=0;V&&Math.sign(V)!==Q?Z=jZ(B,D):(M+=Q,D=l1(V,K,Y),Z=jZ(U,D));let I=q6(D);return[{...$,...I,days:$.days+M},Z,Boolean(M)]}function PQ($,Z,j,J,W,Y,z,X,G,F){let Q=s1($),O=q[J],K=GJ(J,$);J===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let D=U6($[O],W)*W;K[O]=D;let[B,U]=ej(z,K,J,W*Q,X,G,F),V=D+$4(Z,B,U)*Q*W,M=l1(V,W,Y),I=Math.sign(M-V)===Q;return K[O]=M,[K,I?U:B,I]}function j4($,Z,j,J){let[W,Y,z,X]=((F)=>{let Q=oj(F=t0(F));return[F.timeZone,...Q]})(J),G=W!==void 0;return((F,Q,O,K,D,B)=>{O=A6(O,D,K,1);let U=Q.getOffsetNanosecondsFor(O);return F4(i1(O,U),B)+(F?L$(F6(U)):"Z")})(G,Z(G?$(W):A$),j.epochNanoseconds,Y,z,X)}function J4($,Z,j){let[J,W,Y,z,X,G]=((F)=>{F=t0(F);let Q=BJ(F),O=V7(F),K=AK(F),D=U3(F,4),B=D3(F,4);return[Q,fK(F),K,D,...U7(B,O)]})(j);return((F,Q,O,K,D,B,U,V,M,I)=>{K=A6(K,M,V,1);let P=F(O).getOffsetNanosecondsFor(K);return F4(i1(K,P),I)+L$(F6(P),U)+((A,x)=>x!==1?"["+(x===2?"!":"")+V0(A)+"]":"")(O,B)+Q4(Q,D)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,J,W,Y,z,X,G)}function W4($,Z){let[j,J,W,Y]=((F)=>(F=t0(F),[BJ(F),...oj(F)]))(Z);return z=$.calendar,X=j,G=Y,F4(E7($,W,J),G)+Q4(z,X);var z,X,G}function Y4($,Z){return j=$.calendar,J=$,W=sj(Z),Q6(J)+Q4(j,W);var j,J,W}function z4($,Z){return k7($.calendar,y7,$,sj(Z))}function X4($,Z){return k7($.calendar,NQ,$,sj(Z))}function G4($,Z){let[j,J,W]=D7(Z);return Y=W,q7(Z4($,J,j)[0],Y);var Y}function E6($,Z){let[j,J,W]=D7(Z,3);return J>1&&($={...$,...IQ($,J,j)}),((Y,z)=>{let{sign:X}=Y,G=X===-1?f0(Y):Y,{hours:F,minutes:Q}=G,[O,K]=pj(O0(G,3),o0,d1);u7(O);let D=K4(K,z),B=z>=0||!X||D;return(X<0?"-":"")+"P"+A9({Y:D$(G.years),M:D$(G.months),W:D$(G.weeks),D:D$(G.days)})+(F||Q||O||B?"T"+A9({H:D$(F),M:D$(Q),S:D$(O,B)+D}):"")})($,W)}function k7($,Z,j,J){let W=V0($),Y=J>1||J===0&&W!==w;return J===1?W===w?Z(j):Q6(j):Y?Q6(j)+v7(W,J===2):Z(j)}function A9($){let Z=[];for(let j in $){let J=$[j];J&&Z.push(J,j)}return Z.join("")}function F4($,Z){return Q6($)+"T"+q7($,Z)}function Q6($){return y7($)+"-"+s0($.isoDay)}function y7($){let{isoYear:Z}=$;return(Z<0||Z>9999?g7(Z)+Y6(6,Math.abs(Z)):Y6(4,Z))+"-"+s0($.isoMonth)}function NQ($){return s0($.isoMonth)+"-"+s0($.isoDay)}function q7($,Z){let j=[s0($.isoHour),s0($.isoMinute)];return Z!==-1&&j.push(s0($.isoSecond)+((J,W,Y,z)=>K4(J*G1+W*x$+Y,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),j.join(":")}function L$($,Z=0){if(Z===1)return"";let[j,J]=P1(Math.abs($),n6),[W,Y]=P1(J,o6),[z,X]=P1(Y,o0);return g7($)+s0(j)+":"+s0(W)+(z||X?":"+s0(z)+K4(X):"")}function Q4($,Z){if(Z!==1){let j=V0($);if(Z>1||Z===0&&j!==w)return v7(j,Z===2)}return""}function v7($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function K4($,Z){let j=Y6(9,$);return j=Z===void 0?j.replace(wK,""):j.slice(0,Z),j?"."+j:""}function g7($){return $<0?"-":"+"}function D$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function _Q($,Z){let{epochNanoseconds:j}=$,J=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(j),W=i1(j,J);return{calendar:$.calendar,...W,offsetNanoseconds:J}}function m7($,Z){let j=S0(Z,$);return{calendar:Z.calendar,...v0(sY,j),offset:L$(j.offsetNanoseconds),timeZone:Z.timeZone}}function H$($,Z,j,J=0,W=0,Y,z){if(j!==void 0&&J===1&&(J===1||z))return dj(Z,j);let X=$.getPossibleInstantsFor(Z);if(j!==void 0&&J!==3){let G=((F,Q,O,K)=>{let D=_0(Q);K&&(O=F6(O));for(let B of F){let U=d0(c0(B,D));if(K&&(U=F6(U)),U===O)return B}})(X,Z,j,Y);if(G!==void 0)return G;if(J===0)throw RangeError(rQ)}return z?_0(Z):q0($,Z,W,X)}function q0($,Z,j=0,J=$.getPossibleInstantsFor(Z)){if(J.length===1)return J[0];if(j===1)throw RangeError(tQ);if(J.length)return J[j===3?1:0];let W=_0(Z),Y=((X,G)=>{let F=X.getOffsetNanosecondsFor(jZ(G,-h));return B4(X.getOffsetNanosecondsFor(jZ(G,h))-F)})($,W),z=Y*(j===2?-1:1);return(J=$.getPossibleInstantsFor(i1(W,z)))[j===2?0:J.length-1]}function O4($){if(Math.abs($)>=h)throw RangeError(nQ);return $}function B4($){if($>h)throw RangeError(aQ);return $}function D4($,Z,j){return D0(u0(ZZ(Z.epochNanoseconds,((J)=>{if(l7(J))throw RangeError(ZK);return O0(J,5)})($?f0(j):j))))}function U4($,Z,j,J,W,Y=Object.create(null)){let z=Z(J.timeZone),X=$(J.calendar);return{...J,...L4(z,X,J,j?f0(W):W,Y)}}function V4($,Z,j,J,W=Object.create(null)){let{calendar:Y}=j;return z0(H4($(Y),j,Z?f0(J):J,W),Y)}function T4($,Z,j,J,W){let{calendar:Y}=j;return X0(R6($(Y),j,Z?f0(J):J,W),Y)}function M4($,Z,j,J,W=Object.create(null)){let Y=j.calendar,z=$(Y),X=rZ(z,j);Z&&(J=y6(J)),J.sign<0&&(X=z.dateAdd(X,{...T0,months:1}),X=P$(X,-1));let G=z.dateAdd(X,J,W);return U$(rZ(z,G),Y)}function I4($,Z,j){return e0(p7(Z,$?f0(j):j)[0])}function L4($,Z,j,J,W){let Y=O0(J,5),z=j.epochNanoseconds;if(l7(J)){let X=S0(j,$);z=ZZ(q0($,{...R6(Z,X,{...J,...XJ},W),...v0(Z1,X)}),Y)}else z=ZZ(z,Y),y(W);return{epochNanoseconds:u0(z)}}function H4($,Z,j,J){let[W,Y]=p7(Z,j);return C1({...R6($,Z,{...j,...XJ,days:j.days+Y},J),...W})}function R6($,Z,j,J){if(j.years||j.months||j.weeks)return $.dateAdd(Z,j,J);y(J);let W=j.days+O0(j,5)[0];return W?h1(P$(Z,W)):Z}function rZ($,Z,j=1){return P$(Z,j-$.day(Z))}function p7($,Z){let[j,J]=O0(Z,5),[W,Y]=L6(u1($)+J);return[W,j+Y]}function P$($,Z){return Z?{...$,...H6(x0($)+Z*k0)}:$}function b6($,Z,j){let J=$(j.calendar);return k6(j)?[j,J,Z(j.timeZone)]:[{...j,...n0},J]}function P4($){return $?H7:_0}function w6($){return $?b(L4,$):H4}function N4($){return $?b(xQ,$):SQ}function k6($){return $&&$.epochNanoseconds}function tZ($,Z){return $<=6-(k6(Z)?1:0)}function _4($,Z,j,J,W,Y,z){let X=$(t0(z).relativeTo),G=Math.max(V$(W),V$(Y));if(tZ(G,X))return s(QZ(((U,V,M,I)=>{let P=ZZ(O0(U),O0(V),I?-1:1);if(!Number.isFinite(P[0]))throw RangeError(i6);return{...T0,...KZ(P,M)}})(W,Y,G,J)));if(!X)throw RangeError(s6);J&&(Y=f0(Y));let[F,Q,O]=b6(Z,j,X),K=w6(O),D=N4(O),B=K(Q,F,W);return s(D(Q,F,K(Q,B,Y),G))}function h7($,Z,j,J,W){let Y=V$(J),[z,X,G,F,Q]=((E,S,H)=>{E=rj(E,B6);let L=OJ(E),m=H(E[nY]),u=nj(E),k1=U3(E,7),Z0=D3(E);if(L===void 0&&Z0===void 0)throw RangeError(jK);return Z0==null&&(Z0=0),L==null&&(L=Math.max(Z0,S)),T7(L,Z0),u=aj(u,Z0,1),[L,Z0,u,k1,m]})(W,Y,$),O=Math.max(Y,z);if(!k6(Q)&&O<=6)return s(QZ(((E,S,H,L,m)=>{let u=f6(O0(E),H,L,m);return{...T0,...KZ(u,S)}})(J,z,X,G,F)));if(!Q)throw RangeError(s6);let[K,D,B]=b6(Z,j,Q),U=P4(B),V=w6(B),M=N4(B),I=V(D,K,J),P=M(D,K,I,z),A=J.sign,x=s1(P);if(A&&x&&A!==x)throw RangeError(K3);return x&&(P=S6(P,U(I),z,X,G,F,D,K,U,V)),s(P)}function c7($){return $.sign===-1?y6($):$}function y6($){return s(f0($))}function f0($){let Z={};for(let j of q)Z[j]=-1*$[j]||0;return Z}function d7($){return!$.sign}function s1($,Z=q){let j=0;for(let J of Z){let W=Math.sign($[J]);if(W){if(j&&j!==W)throw RangeError($K);j=W}}return j}function QZ($){for(let Z of QK)i0(Z,$[Z],-q9,q9,1);return u7(d0(O0($),o0)),$}function u7($){if(!Number.isSafeInteger($))throw RangeError(eQ)}function O0($,Z=6){return l9($,Z,q)}function KZ($,Z=6){let[j,J]=$,W=V6(J,Z,q);if(W[q[Z]]+=j*(h/X1[Z]),!Number.isFinite(W[q[Z]]))throw RangeError(i6);return W}function q6($,Z=5){return V6($,Z,q)}function l7($){return Boolean(s1($,lY))}function V$($){let Z=9;for(;Z>0&&!$[q[Z]];Z--);return Z}function CQ($,Z){return[$,Z]}function E9($){let Z=Math.floor($/J6)*J6;return[Z,Z+J6]}function i7($){let Z=o1($=z6($));if(!Z)throw RangeError(w0($));let j;if(Z.m)j=0;else{if(!Z.offset)throw RangeError(w0($));j=OZ(Z.offset)}return Z.timeZone&&f4(Z.timeZone,1),D0(dj(P6(Z),j))}function s7($){let Z=o1(t($));if(!Z)throw RangeError(w0($));if(Z.timeZone)return jW(Z,Z.offset?OZ(Z.offset):void 0);if(Z.m)throw RangeError(w0($));return WW(Z)}function o7($,Z){let j=o1(t($));if(!j||!j.timeZone)throw RangeError(w0($));let{offset:J}=j,W=J?OZ(J):void 0,[,Y,z]=Y3(Z);return jW(j,W,Y,z)}function OZ($){let Z=f4($);if(Z===void 0)throw RangeError(w0($));return Z}function n7($){let Z=o1(t($));if(!Z||Z.m)throw RangeError(w0($));return z0(JW(Z))}function v6($){let Z=o1(t($));if(!Z||Z.m)throw RangeError(w0($));return X0(Z.p?JW(Z):WW(Z))}function a7($,Z){let j=x4(t(Z));if(j)return C4(j),U$(cj(M$(j)));let J=v6(Z);return U$(rZ($(J.calendar),J))}function C4($){if($.calendar!==w)throw RangeError(N1($.calendar))}function r7($,Z){let j=S4(t(Z));if(j)return C4(j),G6(M$(j));let J=v6(Z),{calendar:W}=J,Y=$(W),[z,X,G]=Y.h(J),[F,Q]=Y.I(z,X),[O,K]=Y.N(F,Q,G);return G6(h1(Y.P(O,K,G)),W)}function t7($){let Z,j=((J)=>{let W=gK.exec(J);return W?(g6(W[10]),XW(W)):void 0})(t($));if(!j){if(j=o1($),!j)throw RangeError(w0($));if(!j.p)throw RangeError(w0($));if(j.m)throw RangeError(N1("Z"));C4(j)}if((Z=x4($))&&S9(Z))throw RangeError(w0($));if((Z=S4($))&&S9(Z))throw RangeError(w0($));return e0(N6(j,1))}function e7($){let Z=((j)=>{let J=hK.exec(j);return J?((W)=>{function Y(Q,O,K){let D=0,B=0;if(K&&([D,G]=P1(G,X1[K])),Q!==void 0){if(X)throw RangeError(N1(Q));B=((U)=>{let V=parseInt(U);if(!Number.isFinite(V))throw RangeError(N1(U));return V})(Q),z=1,O&&(G=A4(O)*(X1[K]/o0),X=1)}return D+B}let z=0,X=0,G=0,F={...zZ(q,[Y(W[2]),Y(W[3]),Y(W[4]),Y(W[5]),Y(W[6],W[7],5),Y(W[8],W[9],4),Y(W[10],W[11],3)]),...V6(G,2,q)};if(!z)throw RangeError(_Y(q));return E4(W[1])<0&&(F=f0(F)),F})(J):void 0})(t($));if(!Z)throw RangeError(w0($));return s(QZ(Z))}function $W($){let Z=o1($)||x4($)||S4($);return Z?Z.calendar:$}function ZW($){let Z=o1($);return Z&&(Z.timeZone||Z.m&&A$||Z.offset)||$}function jW($,Z,j=0,J=0){let W=m6($.timeZone),Y=j8(W);return M0(H$(Y,P6($),Z,j,J,!Y.v,$.m),W,X3($.calendar))}function JW($){return YW(C1(P6($)))}function WW($){return YW(h1(M$($)))}function YW($){return{...$,calendar:X3($.calendar)}}function o1($){let Z=vK.exec($);return Z?((j)=>{let J=j[10],W=(J||"").toUpperCase()==="Z";return{isoYear:zW(j),isoMonth:parseInt(j[4]),isoDay:parseInt(j[5]),...XW(j.slice(5)),...g6(j[16]),p:Boolean(j[6]),m:W,offset:W?void 0:J}})(Z):void 0}function x4($){let Z=yK.exec($);return Z?((j)=>({isoYear:zW(j),isoMonth:parseInt(j[4]),isoDay:1,...g6(j[5])}))(Z):void 0}function S4($){let Z=qK.exec($);return Z?((j)=>({isoYear:YZ,isoMonth:parseInt(j[1]),isoDay:parseInt(j[2]),...g6(j[3])}))(Z):void 0}function f4($,Z){let j=mK.exec($);return j?((J,W)=>{let Y=J[4]||J[5];if(W&&Y)throw RangeError(N1(Y));return O4(($Z(J[2])*n6+$Z(J[3])*o6+$Z(J[4])*o0+A4(J[5]||""))*E4(J[1]))})(j,Z):void 0}function zW($){let Z=E4($[1]),j=parseInt($[2]||$[3]);if(Z<0&&!j)throw RangeError(N1(-0));return Z*j}function XW($){let Z=$Z($[3]);return{...L6(A4($[4]||""))[0],isoHour:$Z($[1]),isoMinute:$Z($[2]),isoSecond:Z===60?59:Z}}function g6($){let Z,j,J=[];if($.replace(pK,(W,Y,z)=>{let X=Boolean(Y),[G,F]=z.split("=").reverse();if(F){if(F==="u-ca")J.push(G),Z||(Z=X);else if(X||/[A-Z]/.test(F))throw RangeError(N1(W))}else{if(j)throw RangeError(N1(W));j=G}return""}),J.length>1&&Z)throw RangeError(N1($));return{timeZone:j,calendar:J[0]||w}}function A4($){return parseInt($.padEnd(9,"0"))}function BZ($){return new RegExp(`^${$}$`,"i")}function E4($){return $&&$!=="+"?-1:1}function $Z($){return $===void 0?0:parseInt($)}function GW($){return m6(t($))}function m6($){let Z=R4($);return typeof Z=="number"?L$(Z):Z?((j)=>{if(dK.test(j))throw RangeError(oQ);return j.toLowerCase().split("/").map((J,W)=>(J.length<=3||/\d/.test(J))&&!/etc|yap/.test(J)?J.toUpperCase():J.replace(/baja|dumont|[a-z]+/g,(Y,z)=>Y.length<=2&&!W||Y==="in"||Y==="chat"?Y.toUpperCase():Y.length>2||!z?C9(Y).replace(/island|noronha|murdo|rivadavia|urville/,C9):Y)).join("/")})($):A$}function R9($){let Z=R4($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:A$}function R4($){let Z=f4($=$.toUpperCase(),1);return Z!==void 0?Z:$!==A$?cK($):void 0}function b4($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function w4($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function FW($,Z,j,J,W,Y){let z=$(t0(Y).relativeTo),X=Math.max(V$(J),V$(W));if(d9(q,J,W))return 0;if(tZ(X,z))return C0(O0(J),O0(W));if(!z)throw RangeError(s6);let[G,F,Q]=b6(Z,j,z),O=P4(Q),K=w6(Q);return C0(O(K(F,G,J)),O(K(F,G,W)))}function k4($,Z){return N$($,Z)||p6($,Z)}function N$($,Z){return p1(x0($),x0(Z))}function p6($,Z){return p1(u1($),u1(Z))}function QW($,Z){return!b4($,Z)}function KW($,Z){return!w4($,Z)&&!!h6($.timeZone,Z.timeZone)&&FZ($.calendar,Z.calendar)}function OW($,Z){return!k4($,Z)&&FZ($.calendar,Z.calendar)}function BW($,Z){return!N$($,Z)&&FZ($.calendar,Z.calendar)}function DW($,Z){return!N$($,Z)&&FZ($.calendar,Z.calendar)}function UW($,Z){return!N$($,Z)&&FZ($.calendar,Z.calendar)}function VW($,Z){return!p6($,Z)}function h6($,Z){if($===Z)return 1;let j=V0($),J=V0(Z);if(j===J)return 1;try{return R9(j)===R9(J)}catch(W){}}function y4($,Z,j,J){let W=GZ($,Y0(J),3,5),Y=c6(Z.epochNanoseconds,j.epochNanoseconds,...W);return s($?f0(Y):Y)}function q4($,Z,j,J,W,Y){let z=u6(J.calendar,W.calendar),X=Y0(Y),[G,F,Q,O]=GZ(j,X,5),K=J.epochNanoseconds,D=W.epochNanoseconds,B=C0(D,K),U;if(B)if(G<6)U=c6(K,D,G,F,Q,O);else{let V=Z(((I,P)=>{if(!h6(I,P))throw RangeError(EY);return I})(J.timeZone,W.timeZone)),M=$(z);U=MW(M,V,J,W,B,G,X),U=S6(U,D,G,F,Q,O,M,J,H7,b(L4,V))}else U=T0;return s(j?f0(U):U)}function v4($,Z,j,J,W){let Y=u6(j.calendar,J.calendar),z=Y0(W),[X,G,F,Q]=GZ(Z,z,6),O=_0(j),K=_0(J),D=C0(K,O),B;if(D)if(X<=6)B=c6(O,K,X,G,F,Q);else{let U=$(Y);B=IW(U,j,J,D,X,z),B=S6(B,K,X,G,F,Q,U,j,_0,H4)}else B=T0;return s(Z?f0(B):B)}function g4($,Z,j,J,W){let Y=u6(j.calendar,J.calendar),z=Y0(W);return TW(Z,()=>$(Y),j,J,...GZ(Z,z,6,9,6),z)}function m4($,Z,j,J,W){let Y=u6(j.calendar,J.calendar),z=Y0(W),X=GZ(Z,z,9,9,8),G=$(Y);return TW(Z,()=>G,rZ(G,j),rZ(G,J),...X,z)}function TW($,Z,j,J,W,Y,z,X,G){let F=_0(j),Q=_0(J),O;if(C0(Q,F))if(W===6)O=c6(F,Q,W,Y,z,X);else{let K=Z();O=K.dateUntil(j,J,W,G),Y===6&&z===1||(O=S6(O,Q,W,Y,z,X,K,j,_0,R6))}else O=T0;return s($?f0(O):O)}function p4($,Z,j,J){let W=Y0(J),[Y,z,X,G]=GZ($,W,5,5),F=l1(h4(Z,j),z3(z,X),G),Q={...T0,...q6(F,Y)};return s($?f0(Q):Q)}function xQ($,Z,j,J,W,Y){let z=C0(J.epochNanoseconds,j.epochNanoseconds);return z?W<6?LW(j.epochNanoseconds,J.epochNanoseconds,W):MW(Z,$,j,J,z,W,Y):T0}function SQ($,Z,j,J,W){let Y=_0(Z),z=_0(j),X=C0(z,Y);return X?J<=6?LW(Y,z,J):IW($,Z,j,X,J,W):T0}function MW($,Z,j,J,W,Y,z){let[X,G,F]=((K,D,B,U)=>{function V(){return S={...P$(P,x++*-U),...I},H=q0(K,S),C0(A,H)===-U}let M=S0(D,K),I=v0(Z1,M),P=S0(B,K),A=B.epochNanoseconds,x=0,E=h4(M,P),S,H;if(Math.sign(E)===-U&&x++,V()&&(U===-1||V()))throw RangeError(K3);let L=d0(c0(H,A));return[M,S,L]})(Z,j,J,W);var Q,O;return{...Y===6?(Q=X,O=G,{...T0,days:HW(Q,O)}):$.dateUntil(X,G,Y,z),...q6(F)}}function IW($,Z,j,J,W,Y){let[z,X,G]=((F,Q,O)=>{let K=Q,D=h4(F,Q);return Math.sign(D)===-O&&(K=P$(Q,-O),D+=h*O),[F,K,D]})(Z,j,J);return{...$.dateUntil(z,X,W,Y),...q6(G)}}function c6($,Z,j,J,W,Y){return{...T0,...KZ(f6(c0($,Z),J,W,Y),j)}}function LW($,Z,j){return{...T0,...KZ(c0($,Z),j)}}function HW($,Z){return d6(x0($),x0(Z))}function d6($,Z){return Math.trunc((Z-$)/k0)}function h4($,Z){return u1(Z)-u1($)}function u6($,Z){if(!FZ($,Z))throw RangeError(jJ);return $}function fQ($){function Z(W){return((Y,z)=>({...PW(Y,z),F:Y.month,day:parseInt(Y.day)}))(hj(j,W),J)}let j=TJ($),J=K6($);return{id:$,O:AQ(Z),B:EQ(Z)}}function AQ($){return y0((Z)=>{let j=x0(Z);return $(j)},WeakMap)}function EQ($){let Z=$(0).year-VK;return y0((j)=>{let J,W=XZ(j-Z),Y=[],z=[];do W+=400*k0;while((J=$(W)).year<=j);do W+=(1-J.day)*k0,J.year===j&&(Y.push(W),z.push(J.F)),W-=k0;while((J=$(W)).year>=j);return{k:Y.reverse(),C:wY(z.reverse())}})}function PW($,Z){let j,J,W=NW($);if($.era){let Y=cY[Z];Y!==void 0&&(j=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),j==="bc"||j==="b"?j="bce":j!=="ad"&&j!=="a"||(j="ce"),J=W,W=fW(J,Y[j]||0))}return{era:j,eraYear:J,year:W}}function NW($){return parseInt($.relatedYear||$.year)}function Cj($){let{year:Z,F:j,day:J}=this.O($),{C:W}=this.B(Z);return[Z,W[j]+1,J]}function eZ($,Z=1,j=1){return this.B($).k[Z-1]+(j-1)*k0}function $6($){let Z=w9(this,$),j=w9(this,$-1),J=Z.length;if(J>j.length){let W=AW(this);if(W<0)return-W;for(let Y=0;Y<J;Y++)if(Z[Y]!==j[Y])return Y+1}}function Z6($){return d6(eZ.call(this,$),eZ.call(this,$+1))}function b9($,Z){let{k:j}=this.B($),J=Z+1,W=j;return J>j.length&&(J=1,W=this.B($+1).k),d6(j[Z-1],W[J-1])}function j6($){return this.B($).k.length}function w9($,Z){return Object.keys($.B(Z).C)}function _W($){return X3(t($))}function X3($){if(($=$.toLowerCase())!==w&&$!==r6&&K6($)!==K6(TJ($).resolvedOptions().calendar))throw RangeError(sQ($));return $}function K6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function CW($){return this.R($)[0]}function xW($){return this.R($)[1]}function c4($){let[Z]=this.h($);return d6(this.q(Z),x0($))+1}function SW($){let Z=lK.exec($);if(!Z)throw RangeError(lQ($));return[parseInt(Z[1]),Boolean(Z[2])]}function O6($,Z,j){return $+(Z||j&&$>=j?1:0)}function xj($,Z){return $-(Z&&$>=Z?1:0)}function fW($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function Sj($){return cY[EW($)]}function AW($){return XK[EW($)]}function EW($){return K6($.id||w)}function RW($,Z,j,J){let W=n1(j,J,$1,[],gY);if(W.timeZone!==void 0){let Y=j.dateFromFields(W),z=_$(W),X=$(W.timeZone);return{epochNanoseconds:H$(Z(X),{...Y,...z},W.offset!==void 0?OZ(W.offset):void 0),timeZone:X}}return{...j.dateFromFields(W),...n0}}function bW($,Z,j,J,W,Y){let z=n1(j,W,$1,qY,gY),X=$(z.timeZone),[G,F,Q]=Y3(Y),O=j.dateFromFields(z,C6(Y,G)),K=_$(z,G);return M0(H$(Z(X),{...O,...K},z.offset!==void 0?OZ(z.offset):void 0,F,Q),X,J)}function wW($,Z,j){let J=n1($,Z,$1,[],f1),W=y(j);return z0(C1({...$.dateFromFields(J,C6(j,W)),..._$(J,W)}))}function d4($,Z,j,J=[]){let W=n1($,Z,$1,J);return $.dateFromFields(W,j)}function u4($,Z,j,J){let W=n1($,Z,YJ,J);return $.yearMonthFromFields(W,j)}function l4($,Z,j,J,W=[]){let Y=n1($,j,$1,W);return Z&&Y.month!==void 0&&Y.monthCode===void 0&&Y.year===void 0&&(Y.year=YZ),$.monthDayFromFields(Y,J)}function kW($,Z){let j=y(Z);return e0(_$(z1($,Aj,[],1),j))}function yW($){let Z=z1($,zJ);return s(QZ({...T0,...Z}))}function n1($,Z,j,J=[],W=[]){return z1(Z,[...$.fields(j),...W].sort(),J)}function z1($,Z,j,J=!j){let W={},Y,z=0;for(let X of Z){if(X===Y)throw RangeError(mQ(X));if(X==="constructor"||X==="__proto__")throw RangeError($J(X));let G=$[X];if(G!==void 0)z=1,v9[X]&&(G=v9[X](G,X)),W[X]=G;else if(j){if(j.includes(X))throw TypeError(e4(X));W[X]=hY[X]}Y=X}if(J&&!z)throw TypeError(_Y(Z));return W}function _$($,Z){return N6(nK({...hY,...$}),Z)}function qW($,Z,j,J,W,Y){let z=Y0(Y),{calendar:X,timeZone:G}=j;return M0(((F,Q,O,K,D)=>{let B=G3(F,O,K,$1,vY,yY),[U,V,M]=Y3(D,2);return H$(Q,{...F.dateFromFields(B,C6(D,U)),..._$(B,U)},OZ(B.offset),V,M)})($(X),Z(G),J,W,z),G,X)}function vW($,Z,j,J,W){let Y=Y0(W);return z0(((z,X,G,F)=>{let Q=G3(z,X,G,$1,f1),O=y(F);return C1({...z.dateFromFields(Q,C6(F,O)),..._$(Q,O)})})($(Z.calendar),j,J,Y))}function gW($,Z,j,J,W){let Y=Y0(W);return((z,X,G,F)=>{let Q=G3(z,X,G,$1);return z.dateFromFields(Q,F)})($(Z.calendar),j,J,Y)}function mW($,Z,j,J,W){let Y=Y0(W);return U$(((z,X,G,F)=>{let Q=G3(z,X,G,YJ);return z.yearMonthFromFields(Q,F)})($(Z.calendar),j,J,Y))}function pW($,Z,j,J,W){let Y=Y0(W);return((z,X,G,F)=>{let Q=G3(z,X,G,$1);return z.monthDayFromFields(Q,F)})($(Z.calendar),j,J,Y)}function hW($,Z,j){return e0(((J,W,Y)=>{let z=y(Y);return _$({...v0(Aj,J),...z1(W,Aj)},z)})($,Z,j))}function cW($,Z){return s((j=$,J=Z,QZ({...j,...z1(J,zJ)})));var j,J}function G3($,Z,j,J,W=[],Y=[]){let z=[...$.fields(J),...W].sort(),X=z1(Z,z,Y),G=z1(j,z);return X=$.mergeFields(X,G),z1(X,z,[])}function i4($,Z){let j=n1($,Z,pY);return $.monthDayFromFields(j)}function s4($,Z,j){let J=n1($,Z,mY);return $.yearMonthFromFields(J,j)}function dW($,Z,j,J,W){Z=v0(j=$.fields(j),Z),J=z1(J,W=$.fields(W),[]);let Y=$.mergeFields(Z,J);return Y=z1(Y,[...j,...W].sort(),[]),$.dateFromFields(Y)}function Lj($,Z){let{era:j,eraYear:J,year:W}=Z,Y=Sj($);if(j!==void 0||J!==void 0){if(j===void 0||J===void 0)throw TypeError(hQ);if(!Y)throw RangeError(pQ);let z=Y[j];if(z===void 0)throw RangeError(dQ(j));let X=fW(J,z);if(W!==void 0&&W!==X)throw RangeError(cQ);W=X}else if(W===void 0)throw TypeError(uQ(Y));return W}function Hj($,Z,j,J){let{month:W,monthCode:Y}=Z;if(Y!==void 0){let z=((X,G,F,Q)=>{let O=X.U(F),[K,D]=SW(G),B=O6(K,D,O);if(D){let U=AW(X);if(U===void 0)throw RangeError(oZ);if(U>0){if(B>U)throw RangeError(oZ);if(O===void 0){if(Q===1)throw RangeError(oZ);B--}}else{if(B!==-U)throw RangeError(oZ);if(O===void 0&&Q===1)throw RangeError(oZ)}}return B})($,Y,j,J);if(W!==void 0&&W!==z)throw RangeError(fY);W=z,J=1}else if(W===void 0)throw TypeError(iQ);return i0("month",W,1,$.L(j),J)}function k9($,Z,j,J,W){return b0(Z,"day",1,$.j(J,j),W)}function Pj($,Z,j,J){let W=0,Y=[];for(let z of j)Z[z]!==void 0?W=1:Y.push(z);if(Object.assign($,Z),W)for(let z of J||Y)delete $[z]}function uW($){return D0(u0(I6(M6($))))}function lW($,Z,j,J,W=w){return M0(u0(I6(M6(j))),Z(J),$(W))}function iW($,Z,j,J,W=0,Y=0,z=0,X=0,G=0,F=0,Q=w){return z0(C1(P6(a0(N0,zZ(t6,[Z,j,J,W,Y,z,X,G,F])))),$(Q))}function sW($,Z,j,J,W=w){return X0(h1(M$(a0(N0,{isoYear:Z,isoMonth:j,isoDay:J}))),$(W))}function oW($,Z,j,J=w,W=1){let Y=N0(Z),z=N0(j),X=$(J);return U$(cj(M$({isoYear:Y,isoMonth:z,isoDay:N0(W)})),X)}function nW($,Z,j,J=w,W=YZ){let Y=N0(Z),z=N0(j),X=$(J);return G6(h1(M$({isoYear:N0(W),isoMonth:Y,isoDay:z})),X)}function aW($=0,Z=0,j=0,J=0,W=0,Y=0){return e0(N6(a0(N0,zZ(Z1,[$,Z,j,J,W,Y])),1))}function rW($=0,Z=0,j=0,J=0,W=0,Y=0,z=0,X=0,G=0,F=0){return s(QZ(a0(Z7,zZ(q,[$,Z,j,J,W,Y,z,X,G,F]))))}function o4($,Z,j=w){return M0($.epochNanoseconds,Z,j)}function tW($){return D0($.epochNanoseconds)}function n4($,Z){return z0(S0(Z,$))}function a4($,Z){return X0(S0(Z,$))}function eW($,Z,j){return s4($(Z.calendar),j)}function $Y($,Z,j){return i4($(Z.calendar),j)}function r4($,Z){return e0(S0(Z,$))}function ZY($,Z,j,J){let W=((Y,z,X,G)=>{let F=ij(G);return q0(Y(z),X,F)})($,j,Z,J);return M0(u0(W),j,Z.calendar)}function jY($,Z,j){let J=$(Z.calendar);return U$({...Z,...s4(J,j)})}function JY($,Z,j){return i4($(Z.calendar),j)}function WY($,Z,j,J,W){let Y=$(W.timeZone),z=W.plainTime,X=z!==void 0?Z(z):n0;return M0(q0(j(Y),{...J,...X}),Y,J.calendar)}function YY($,Z=n0){return z0(C1({...$,...Z}))}function zY($,Z,j){return s4($(Z.calendar),j)}function XY($,Z,j){return i4($(Z.calendar),j)}function GY($,Z,j,J){return((W,Y,z)=>dW(W,Y,mY,_1(z),B3))($(Z.calendar),j,J)}function FY($,Z,j,J){return((W,Y,z)=>dW(W,Y,pY,_1(z),a6))($(Z.calendar),j,J)}function QY($,Z,j,J,W){let Y=_1(W),z=Z(Y.plainDate),X=$(Y.timeZone);return M0(q0(j(X),{...z,...J}),X,z.calendar)}function KY($,Z){return z0(C1({...$,...Z}))}function OY($){return D0(u0(JZ($,o0)))}function BY($){return D0(u0(JZ($,G1)))}function DY($){return D0(u0(I6(M6($),x$)))}function UY($){return D0(u0(I6(M6($))))}function VY($,Z,j=n0){let J=Z.timeZone,W=$(J),Y={...S0(Z,W),...j};return M0(H$(W,Y,Y.offsetNanoseconds,2),J,Z.calendar)}function TY($,Z,j){let J=Z.timeZone,W=$(J),Y={...S0(Z,W),...j},z=HY(Z.calendar,j.calendar);return M0(H$(W,Y,Y.offsetNanoseconds,2),J,z)}function MY($,Z=n0){return z0({...$,...Z})}function IY($,Z){return z0({...$,...Z},HY($.calendar,Z.calendar))}function l6($,Z){return{...$,calendar:Z}}function LY($,Z){return{...$,timeZone:Z}}function HY($,Z){if($===Z)return $;let j=V0($),J=V0(Z);if(j===J||j===w)return Z;if(J===w)return $;throw RangeError(jJ)}function RQ($,Z){return(j)=>j===w?$:j===r6||j===WZ?Object.assign(Object.create($),{id:j}):Object.assign(Object.create(Z),uK(j))}function C$($,Z,j){let J=new Set(j);return(W)=>(((Y,z)=>{for(let X of z)if(X in Y)return 1;return 0})(W=wj(J,W),$)||Object.assign(W,Z),j&&(W.timeZone=A$,["full","long"].includes(W.timeStyle)&&(W.timeStyle="medium")),W)}function x1($,Z=t4){let[j,,,J]=$;return(W,Y=KO,...z)=>{let X=Z(J&&J(...z),W,Y,j),G=X.resolvedOptions();return[X,...bQ($,G,z)]}}function t4($,Z,j,J){if(j=J(j),$){if(j.timeZone!==void 0)throw TypeError(WK);j.timeZone=$}return new a1(Z,j)}function bQ($,Z,j){let[,J,W]=$;return j.map((Y)=>(Y.calendar&&((z,X,G)=>{if((G||z!==w)&&z!==X)throw RangeError(jJ)})(V0(Y.calendar),Z.calendar,W),J(Y,Z)))}function DZ($){let Z=F3();return i1(Z,$.getOffsetNanosecondsFor(Z))}function F3(){return JZ(Date.now(),G1)}function S1(){return m9||(m9=new a1().resolvedOptions().timeZone)}var wQ=($,Z)=>`Non-integer ${$}: ${Z}`,kQ=($,Z)=>`Non-positive ${$}: ${Z}`,yQ=($,Z)=>`Non-finite ${$}: ${Z}`,qQ=($)=>`Cannot convert bigint to ${$}`,vQ=($)=>`Invalid bigint: ${$}`,gQ="Cannot convert Symbol to string",PY="Invalid object",NY=($,Z,j,J,W)=>W?NY($,W[Z],W[j],W[J]):Q3($,Z)+`; must be between ${j}-${J}`,Q3=($,Z)=>`Invalid ${$}: ${Z}`,e4=($)=>`Missing ${$}`,$J=($)=>`Invalid field ${$}`,mQ=($)=>`Duplicate field ${$}`,_Y=($)=>"No valid fields: "+$.join(),CY="Invalid bag",xY=($,Z,j)=>Q3($,Z)+"; must be "+Object.keys(j).join(),SY="Cannot use valueOf",ZJ="Invalid calling context",pQ="Forbidden era/eraYear",hQ="Mismatching era/eraYear",cQ="Mismatching year/eraYear",dQ=($)=>`Invalid era: ${$}`,uQ=($)=>"Missing year"+($?"/era/eraYear":""),lQ=($)=>`Invalid monthCode: ${$}`,fY="Mismatching month/monthCode",iQ="Missing month/monthCode",y9="Cannot guess year",oZ="Invalid leap month",AY="Invalid protocol",K3="Invalid protocol results",jJ="Mismatching Calendars",sQ=($)=>`Invalid Calendar: ${$}`,EY="Mismatching TimeZones",oQ="Forbidden ICU TimeZone",nQ="Out-of-bounds offset",aQ="Out-of-bounds TimeZone gap",rQ="Invalid TimeZone offset",tQ="Ambiguous offset",i6="Out-of-bounds date",eQ="Out-of-bounds duration",$K="Cannot mix duration signs",s6="Missing relativeTo",ZK="Cannot use large units",jK="Required smallestUnit or largestUnit",JK="smallestUnit > largestUnit",w0=($)=>`Cannot parse: ${$}`,N1=($)=>`Invalid substring: ${$}`,RY=($)=>`Cannot format ${$}`,bY="Mismatching types for formatting",WK="Cannot specify TimeZone",wY=b(j3,($,Z)=>Z),UZ=b(j3,($,Z,j)=>j),s0=b(Y6,2),fj={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},O3=Object.keys(fj),k0=86400000,kY=1000,x$=1000,G1=1e6,o0=1e9,o6=60000000000,n6=3600000000000,h=86400000000000,X1=[1,x$,G1,o0,o6,n6,h],f1=O3.slice(0,6),Aj=J3(f1),yY=["offset"],qY=["timeZone"],vY=f1.concat(yY),gY=vY.concat(qY),Ej=["era","eraYear"],YK=Ej.concat(["year"]),a6=["year"],JJ=["monthCode"],WJ=["month"].concat(JJ),B3=["day"],YJ=WJ.concat(a6),mY=JJ.concat(a6),$1=B3.concat(YJ),zK=B3.concat(WJ),pY=B3.concat(JJ),hY=UZ(f1,0),w="iso8601",r6="gregory",WZ="japanese",cY={[r6]:{bce:-1,ce:0},[WZ]:{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}},XK={chinese:13,dangi:13,hebrew:-6},t=b(T6,"string"),dY=b(T6,"boolean"),GK=b(T6,"number"),uY=b(T6,"function"),q=O3.map(($)=>$+"s"),zJ=J3(q),FK=q.slice(0,6),lY=q.slice(6),QK=lY.slice(1),KK=wY(q),T0=UZ(q,0),XJ=UZ(FK,0),GJ=b(u9,q),Z1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],FJ=["isoDay","isoMonth","isoYear"],t6=Z1.concat(FJ),QJ=J3(FJ),iY=J3(Z1),sY=J3(t6),n0=UZ(iY,0),OK=b(u9,t6),a1=Intl.DateTimeFormat,oY="en-GB",KJ=1e8,BK=KJ*k0,DK=[KJ,0],UK=[-KJ,0],$3=275760,Z3=-271821,VK=1970,YZ=1972,H1=12,TK=XZ(1868,9,8),MK=y0(MQ,WeakMap),B6="smallestUnit",Rj="unit",aZ="roundingIncrement",Nj="fractionalSecondDigits",nY="relativeTo",aY={constrain:0,reject:1},IK=Object.keys(aY),LK={compatible:0,reject:1,earlier:2,later:3},HK={reject:0,use:1,prefer:2,ignore:3},PK={auto:0,never:1,critical:2,always:3},NK={auto:0,never:1,critical:2},_K={auto:0,never:1},CK={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},D3=b(tj,B6),OJ=b(tj,"largestUnit"),xK=b(tj,Rj),rY=b(I$,"overflow",aY),tY=b(I$,"disambiguation",LK),SK=b(I$,"offset",HK),BJ=b(I$,"calendarName",PK),fK=b(I$,"timeZoneName",NK),AK=b(I$,"offset",_K),U3=b(I$,"roundingMode",CK),VZ="PlainYearMonth",TZ="PlainMonthDay",S$="PlainDate",f$="PlainDateTime",e6="PlainTime",A1="ZonedDateTime",$8="Instant",Z8="Duration",EK=[Math.floor,($)=>e3($)?Math.floor($):Math.round($),Math.ceil,($)=>e3($)?Math.ceil($):Math.round($),Math.trunc,($)=>e3($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>e3($)?($=Math.trunc($)||0)+$%2:Math.round($)],A$="UTC",J6=5184000,RK=X6(1847),bK=X6(new Date().getUTCFullYear()+10),wK=/0+$/,S0=y0(_Q,WeakMap),q9=4294967295,j8=y0(($)=>{let Z=R4($);return typeof Z=="object"?new $z(Z):new eY(Z||0)});class eY{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[dj($,this.v)]}l(){}}class $z{constructor($){this.$=((Z)=>{function j(G){let F=_j(G,z,X),[Q,O]=E9(F),K=W(Q),D=W(O);return K===D?K:J(Y(Q,O),K,D,G)}function J(G,F,Q,O){let K,D;for(;(O===void 0||(K=O<G[0]?F:O>=G[1]?Q:void 0)===void 0)&&(D=G[1]-G[0]);){let B=G[0]+Math.floor(D/2);Z(B)===Q?G[1]=B:G[0]=B+1}return K}let W=y0(Z),Y=y0(CQ),z=RK,X=bK;return{G(G){let F=j(G-86400),Q=j(G+86400),O=G-F,K=G-Q;if(F===Q)return[O];let D=j(O);return D===j(K)?[G-D]:F>Q?[O,K]:[]},V:j,l(G,F){let Q=_j(G,z,X),[O,K]=E9(Q),D=J6*F,B=F<0?()=>K>z||(z=Q,0):()=>O<X||(X=Q,0);for(;B();){let U=W(O),V=W(K);if(U!==V){let M=Y(O,K);J(M,U,V);let I=M[0];if((p1(I,G)||1)===F)return I}O+=D,K+=D}}}})(((Z)=>(j)=>{let J=hj(Z,j*kY);return X6(NW(J),parseInt(J.month),parseInt(J.day),parseInt(J.hour),parseInt(J.minute),parseInt(J.second))-j})($))}getOffsetNanosecondsFor($){return this.$.V(W7($))*o0}getPossibleInstantsFor($){let[Z,j]=[X6((J=$).isoYear,J.isoMonth,J.isoDay,J.isoHour,J.isoMinute,J.isoSecond),J.isoMillisecond*G1+J.isoMicrosecond*x$+J.isoNanosecond];var J;return this.$.G(Z).map((W)=>u0(jZ(JZ(W,o0),j)))}l($,Z){let[j,J]=Y7($),W=this.$.l(j+(Z>0||J?1:0),Z);if(W!==void 0)return JZ(W,o0)}}var DJ="([+\u2212-])",W6="(?:[.,](\\d{1,9}))?",Zz=`(?:(?:${DJ}(\\d{6}))|(\\d{4}))-?(\\d{2})`,UJ="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+W6+")?)?",VJ=DJ+UJ,kK=Zz+"-?(\\d{2})(?:[T ]"+UJ+"(Z|"+VJ+")?)?",jz="\\[(!?)([^\\]]*)\\]",J8=`((?:${jz}){0,9})`,yK=BZ(Zz+J8),qK=BZ("(?:--)?(\\d{2})-?(\\d{2})"+J8),vK=BZ(kK+J8),gK=BZ("T?"+UJ+"(?:"+VJ+")?"+J8),mK=BZ(VJ),pK=new RegExp(jz,"g"),hK=BZ(`${DJ}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${W6}H)?(?:(\\d+)${W6}M)?(?:(\\d+)${W6}S)?)?`),cK=y0(($)=>new a1(oY,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),dK=/^(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$/,uK=y0(fQ),TJ=y0(($)=>new a1(oY,{calendar:$,timeZone:A$,era:"short",year:"numeric",month:"short",day:"numeric"})),lK=/^M(\d{2})(L?)$/,iK={era:z6,eraYear:N0,year:N0,month:x9,monthCode:z6,day:x9},sK=UZ(f1,N0),oK=UZ(q,Z7),v9=Object.assign({},iK,sK,oK,{offset:z6}),nK=b(TQ,f1,Z1),g9={dateAdd($,Z,j){let J=y(j),W,{years:Y,months:z,weeks:X,days:G}=Z;if(G+=O0(Z,5)[0],Y||z)W=((F,Q,O,K,D)=>{let[B,U,V]=F.h(Q);if(O){let[M,I]=F.I(B,U);B+=O,U=O6(M,I,F.U(B)),U=i0("month",U,1,F.L(B),D)}return K&&([B,U]=F._(B,U,K)),V=i0("day",V,1,F.j(B,U),D),F.q(B,U,V)})(this,$,Y,z,J);else{if(!X&&!G)return $;W=x0($)}return W+=(7*X+G)*k0,h1(H6(W))},dateUntil($,Z,j){if(j<=7){let G=0,F=HW({...$,...n0},{...Z,...n0});return j===7&&([G,F]=d1(F,7)),{...T0,weeks:G,days:F}}let J=this.h($),W=this.h(Z),[Y,z,X]=((G,F,Q,O,K,D,B)=>{let U=K-F,V=D-Q,M=B-O;if(U||V){let I=Math.sign(U||V),P=G.j(K,D),A=0;if(Math.sign(M)===-I){let x=P;[K,D]=G._(K,D,-I),U=K-F,V=D-Q,P=G.j(K,D),A=I<0?-x:P}if(M=B-Math.min(O,P)+A,U){let[x,E]=G.I(F,Q),[S,H]=G.I(K,D);if(V=S-x||Number(H)-Number(E),Math.sign(V)===-I){let L=I<0&&-G.L(K);U=(K-=I)-F,V=D-O6(x,E,G.U(K))+(L||G.L(K))}}}return[U,V,M]})(this,...J,...W);return j===8&&(z+=this.J(Y,J[0]),Y=0),{...T0,years:Y,months:z,days:X}},dateFromFields($,Z){let j=y(Z),J=Lj(this,$),W=Hj(this,$,J,j),Y=k9(this,$,W,J,j);return X0(h1(this.P(J,W,Y)),this.id||w)},yearMonthFromFields($,Z){let j=y(Z),J=Lj(this,$),W=Hj(this,$,J,j);return U$(cj(this.P(J,W,1)),this.id||w)},monthDayFromFields($,Z){let j=y(Z),J=!this.id,{monthCode:W,year:Y,month:z}=$,X,G,F,Q,O;if(W!==void 0){[X,G]=SW(W),O=p9($,"day");let K=this.N(X,G,O);if(!K)throw RangeError(y9);if([F,Q]=K,z!==void 0&&z!==Q)throw RangeError(fY);J&&(Q=i0("month",Q,1,H1,1),O=i0("day",O,1,uj(Y!==void 0?Y:F,Q),j))}else{F=Y===void 0&&J?YZ:Lj(this,$),Q=Hj(this,$,F,j),O=k9(this,$,Q,F,j);let K=this.U(F);G=Q===K,X=xj(Q,K);let D=this.N(X,G,O);if(!D)throw RangeError(y9);[F,Q]=D}return G6(h1(this.P(F,Q,O)),this.id||w)},fields($){return Sj(this)&&$.includes("year")?[...$,...Ej]:$},mergeFields($,Z){let j=Object.assign(Object.create(null),$);return Pj(j,Z,WJ),Sj(this)&&(Pj(j,Z,YK),this.id===WZ&&Pj(j,Z,zK,Ej)),j},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,j]=this.h($);return this.j(Z,j)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:c4,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,j]=this.h($),[J,W]=this.I(Z,j);return((Y,z)=>"M"+s0(Y)+(z?"L":""))(J,W)},dayOfWeek:Q7,daysInWeek(){return 7}},aK={dayOfYear:c4,h:X7,q:XZ},rK=Object.assign({},aK,{weekOfYear:CW,yearOfWeek:xW,R($){function Z(D){return(7-D<J?7:0)-D}function j(D){let B=F7(K+D),U=D||1,V=Z(nZ(G+B*U,7));return Q=(B+(V-F)*U)/7}let J=this.id?1:4,W=Q7($),Y=this.dayOfYear($),z=nZ(W-1,7),X=Y-1,G=nZ(z-X,7),F=Z(G),Q,O=Math.floor((X-F)/7)+1,K=$.isoYear;return O?O>j(0)&&(O=1,K++):(O=j(-1),K--),[O,K,Q]}}),tK={dayOfYear:c4,h:Cj,q:eZ,weekOfYear:CW,yearOfWeek:xW,R(){return[]}},MZ=RQ(Object.assign({},g9,rK,{h:X7,ee($){return this.id===r6?K7($):this.id===WZ?MK($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[YZ,$]},K:lj,U(){},L:G7,J:($)=>$*H1,j:uj,X:F7,P:($,Z,j)=>({isoYear:$,isoMonth:Z,isoDay:j}),q:XZ,_:($,Z,j)=>($+=U6(j,H1),(Z+=yj(j,H1))<1?($--,Z+=H1):Z>H1&&($++,Z-=H1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},g9,tK,{h:Cj,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let j=$6.call(this,$);return[xj(Z,j),j===Z]},N($,Z,j){let[J,W,Y]=Cj.call(this,{isoYear:YZ,isoMonth:H1,isoDay:31}),z=$6.call(this,J),X=W===z;(p1($,xj(W,z))||p1(Number(Z),Number(X))||p1(j,Y))===1&&J--;for(let G=0;G<100;G++){let F=J-G,Q=$6.call(this,F),O=O6($,Z,Q);if(Z===(O===Q)&&j<=b9.call(this,F,O))return[F,O]}},K($){let Z=Z6.call(this,$);return Z>Z6.call(this,$-1)&&Z>Z6.call(this,$+1)},U:$6,L:j6,J($,Z){let j=Z+$,J=Math.sign($),W=J<0?-1:0,Y=0;for(let z=Z;z!==j;z+=J)Y+=j6.call(this,z+W);return Y},j:b9,X:Z6,P($,Z,j){return H6(eZ.call(this,$,Z,j))},q:eZ,_($,Z,j){if(j){if(Z+=j,!Number.isSafeInteger(Z))throw RangeError(i6);if(j<0)for(;Z<1;)Z+=j6.call(this,--$);else{let J;for(;Z>(J=j6.call(this,$));)Z-=J,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:j}=this.O($),{C:J}=this.B(Z);return J[j]+1},day($){return this.O($).day}})),c1="numeric",IZ=["timeZoneName"],Jz={month:c1,day:c1},MJ={year:c1,month:c1},IJ=Object.assign({},MJ,{day:c1}),LJ={hour:c1,minute:c1,second:c1},HJ=Object.assign({},IJ,LJ),eK=Object.assign({},HJ,{timeZoneName:"short"}),$O=Object.keys(MJ),ZO=Object.keys(Jz),jO=Object.keys(IJ),JO=Object.keys(LJ),PJ=["dateStyle"],WO=$O.concat(PJ),YO=ZO.concat(PJ),NJ=jO.concat(PJ,["weekday"]),V3=JO.concat(["dayPeriod","timeStyle"]),_J=NJ.concat(V3),zO=_J.concat(IZ),XO=IZ.concat(V3),GO=IZ.concat(NJ),FO=IZ.concat(["day","weekday"],V3),QO=IZ.concat(["year","weekday"],V3),KO={},CJ=[C$(_J,HJ),x6],Wz=[C$(zO,eK),x6,0,($,Z)=>{let j=V0($.timeZone);if(Z&&V0(Z.timeZone)!==j)throw RangeError(EY);return j}],xJ=[C$(_J,HJ,IZ),x0],SJ=[C$(NJ,IJ,XO),x0],fJ=[C$(V3,LJ,GO),($)=>u1($)/G1],AJ=[C$(WO,MJ,FO),x0,1],EJ=[C$(YO,Jz,QO),x0,1],m9;function K1($,Z,j,J,W){function Y(...G){if(!(this instanceof Y))throw TypeError(ZJ);Gz(this,Z(...G))}function z(G,F){return Object.defineProperties(function(...Q){return G.call(this,X(this),...Q)},bj(F))}function X(G){let F=H0(G);if(!F||F.branding!==$)throw TypeError(ZJ);return F}return Object.defineProperties(Y.prototype,{...h9(a0(z,j)),...T$(a0(z,J)),...D6("Temporal."+$)}),Object.defineProperties(Y,{...T$(W),...bj($)}),[Y,(G)=>{let F=Object.create(Y.prototype);return Gz(F,G),F},X]}function Kz($){return $=$.concat("id").sort(),(Z)=>{if(!c9(Z,$))throw TypeError(AY);return Z}}function NZ($){if(H0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(CY);return $}function W8($,Z){let j={};for(let J in $)j[J]=({o:W},Y)=>{let z=H0(Y)||{},{branding:X}=z,G=X===S$||Z.includes(X)?z:E0(Y);return W[J](G)};return j}function wJ($){let Z={};for(let j in $)Z[j]=(J)=>{let{calendar:W}=J;return(Y=W,typeof Y=="string"?MZ(Y):(z=Y,Object.assign(Object.create(SO),{i:z})))[j](J);var Y,z};return Z}function Z$(){throw TypeError(SY)}function M3({calendar:$}){return typeof $=="string"?new cJ($):$}function Yz($,Z){if(Z=Y0(Z),B0($)){let J=H0($);if(J&&J.branding===TZ)return y(Z),J;let W=Dz($);return l4(K8(W||w),!W,$,Z)}let j=r7(MZ,$);return y(Z),j}function Oz($,Z,j){return J=Z.call($,A0(D0(j))),O4(W3(J));var J}function Y8($,Z=Mz){let j=Object.keys(Z).sort(),J={};for(let W of j)J[W]=b(Z[W],$,uY($[W]));return J}function c($,Z){return typeof $=="string"?j8($):Y8($,Z)}function F0($){return c($,bJ)}function F1($){if(B0($)){let Z=H0($);if(Z)switch(Z.branding){case $8:return Z;case A1:return D0(Z.epochNanoseconds)}}return i7($)}function zz($,Z,j){let J=Z.l(F1(j).epochNanoseconds,$);return J?A0(D0(J)):null}function l($){return B0($)?(H0($)||{}).timeZone||wO($):((Z)=>m6(ZW(t(Z))))($)}function r1($,Z){if(B0($)){let j=H0($)||{};switch(j.branding){case e6:return y(Z),j;case f$:return y(Z),e0(j);case A1:return y(Z),r4(F0,j)}return kW($,Z)}return y(Z),t7($)}function kJ($){return $===void 0?void 0:r1($)}function LZ($,Z){if(Z=Y0(Z),B0($)){let J=H0($);return J&&J.branding===VZ?(y(Z),J):u4(F8(I3($)),$,Z)}let j=a7(MZ,$);return y(Z),j}function t1($,Z){if(Z=Y0(Z),B0($)){let J=H0($)||{};switch(J.branding){case f$:return y(Z),J;case S$:return y(Z),z0({...J,...n0});case A1:return y(Z),n4(F0,J)}return wW(Q8(I3($)),$,Z)}let j=n7($);return y(Z),j}function E0($,Z){if(Z=Y0(Z),B0($)){let J=H0($)||{};switch(J.branding){case S$:return y(Z),J;case f$:return y(Z),X0(J);case A1:return y(Z),a4(F0,J)}return d4(Q8(I3($)),$,Z)}let j=v6($);return y(Z),j}function Bz($,Z,j){return r0(Z.call($,$0(X0(j,$))))}function O1($){return(Z)=>typeof Z=="string"?MZ(Z):((j,J)=>{let W=Object.keys(J).sort(),Y={};for(let z of W)Y[z]=b(J[z],j,j[z]);return Y})(Z,$)}function e($){if(B0($)){let Z=H0($);return Z&&Z.branding===Z8?Z:yW($)}return e7($)}function T3($){if($!==void 0){if(B0($)){let Z=H0($)||{};switch(Z.branding){case A1:case S$:return Z;case f$:return X0(Z)}let j=I3($);return{...RW(l,c,Q8(j),$),calendar:j}}return s7($)}}function I3($){return Dz($)||w}function Dz($){let{calendar:Z}=$;if(Z!==void 0)return L0(Z)}function L0($){return B0($)?(H0($)||{}).calendar||oO($):((Z)=>X3($W(t(Z))))($)}function HZ($,Z){if(Z=Y0(Z),B0($)){let j=H0($);if(j&&j.branding===A1)return Y3(Z),j;let J=I3($);return bW(l,c,Q8(J),J,$,Z)}return o7($,Z)}function Xz($){return a0((Z)=>(j)=>Z(RJ(j)),$)}function RJ($){return S0($,F0)}function OO(){let $=a1.prototype,Z=Object.getOwnPropertyDescriptors($),j=Object.getOwnPropertyDescriptors(a1),J=function(W,Y={}){if(!(this instanceof J))return new J(W,Y);dJ.set(this,((z,X={})=>{let G=new a1(z,X),F=G.resolvedOptions(),Q=F.locale,O=v0(Object.keys(X),F),K=y0(UO),D=(...B)=>{let U,V=B.map((M,I)=>{let P=H0(M),A=(P||{}).branding;if(I&&U&&U!==A)throw TypeError(bY);return U=A,P});return U?K(U)(Q,O,...V):[G,...B]};return D.u=G,D})(W,Y))};for(let W in Z){let Y=Z[W],z=W.startsWith("format")&&BO(W);typeof Y.value=="function"?Y.value=W==="constructor"?J:z||DO(W):z&&(Y.get=function(){return z.bind(this)})}return j.prototype.value=Object.create($,Z),Object.defineProperties(J,j),J}function BO($){return function(...Z){let j=dJ.get(this),[J,...W]=j(...Z);return J[$](...W)}}function DO($){return function(...Z){return dJ.get(this).u[$](...Z)}}function UO($){let Z=VO[$];if(!Z)throw TypeError(RY($));return x1(Z,y0(t4))}var VO={Instant:CJ,PlainDateTime:xJ,PlainDate:SJ,PlainTime:fJ,PlainYearMonth:AJ,PlainMonthDay:EJ},TO=x1(CJ),MO=x1(Wz),IO=x1(xJ),LO=x1(SJ),HO=x1(fJ),PO=x1(AJ),NO=x1(EJ),yJ={era:n9,eraYear:qj,year:W3,month:r0,daysInMonth:r0,daysInYear:r0,inLeapYear:dY,monthsInYear:r0},X8={monthCode:t},qJ={day:r0},Uz={dayOfWeek:r0,dayOfYear:r0,weekOfYear:a9,yearOfWeek:qj,daysInWeek:r0},Vz=Object.assign({},yJ,X8,qJ,Uz),z8=new WeakMap,H0=z8.get.bind(z8),Gz=z8.set.bind(z8),_O={...W8(yJ,[VZ]),...W8(Uz,[]),...W8(X8,[VZ,TZ]),...W8(qJ,[TZ])},vJ=wJ(Vz),CO=wJ({...yJ,...X8}),xO=wJ({...X8,...qJ}),L3={calendarId:($)=>V0($.calendar)},SO=a0(($,Z)=>function(j){let{i:J}=this;return $(J[Z]($0(X0(j,J))))},Vz),fO=j3(($)=>(Z)=>Z[$],q.concat("sign")),gJ=j3(($,Z)=>(j)=>j[Z1[Z]],f1),Tz={epochSeconds:M7,epochMilliseconds:x6,epochMicroseconds:I7,epochNanoseconds:L7},H3=b(wj,new Set(["branding"])),[AO,PZ,EO]=K1(TZ,b(nW,L0),{...L3,...xO},{getISOFields:H3,getCalendar:M3,with($,Z,j){return PZ(pW(lO,$,this,NZ(Z),j))},equals:($,Z)=>UW($,Yz(Z)),toPlainDate($,Z){return $0(FY(P3,$,this,Z))},toLocaleString($,Z,j){let[J,W]=NO(Z,j,$);return J.format(W)},toString:X4,toJSON:($)=>X4($),valueOf:Z$},{from:($,Z)=>PZ(Yz($,Z))}),Mz={getOffsetNanosecondsFor:Oz,getPossibleInstantsFor($,Z,j){let J=[...Z.call($,I0(z0(j,w)))].map((Y)=>bO(Y).epochNanoseconds),W=J.length;return W>1&&(J.sort(C0),B4(d0(c0(J[0],J[W-1])))),J}},bJ={getOffsetNanosecondsFor:Oz},[RO,A0,bO]=K1($8,uW,Tz,{add:($,Z)=>A0(D4(0,$,e(Z))),subtract:($,Z)=>A0(D4(1,$,e(Z))),until:($,Z,j)=>d(y4(0,$,F1(Z),j)),since:($,Z,j)=>d(y4(1,$,F1(Z),j)),round:($,Z)=>A0(N7($,Z)),equals:($,Z)=>QW($,F1(Z)),toZonedDateTime($,Z){let j=_1(Z);return G0(o4($,l(j.timeZone),L0(j.calendar)))},toZonedDateTimeISO:($,Z)=>G0(o4($,l(Z))),toLocaleString($,Z,j){let[J,W]=TO(Z,j,$);return J.format(W)},toString:($,Z)=>j4(l,F0,$,Z),toJSON:($)=>j4(l,F0,$),valueOf:Z$},{from:($)=>A0(F1($)),fromEpochSeconds:($)=>A0(OY($)),fromEpochMilliseconds:($)=>A0(BY($)),fromEpochMicroseconds:($)=>A0(DY($)),fromEpochNanoseconds:($)=>A0(UY($)),compare:($,Z)=>b4(F1($),F1(Z))}),[G8,rT]=K1("TimeZone",($)=>{let Z=GW($);return{branding:"TimeZone",id:Z,o:j8(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(t1(Z)).map((j)=>A0(D0(j))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(F1(Z).epochNanoseconds),getOffsetStringFor($,Z){let j=F1(Z).epochNanoseconds,J=Y8(this,bJ).getOffsetNanosecondsFor(j);return L$(J)},getPlainDateTimeFor($,Z,j=w){let J=F1(Z).epochNanoseconds,W=Y8(this,bJ).getOffsetNanosecondsFor(J);return I0(z0(i1(J,W),L0(j)))},getInstantFor($,Z,j){let J=t1(Z),W=ij(j),Y=Y8(this);return A0(D0(q0(Y,J,W)))},getNextTransition:({o:$},Z)=>zz(1,$,Z),getPreviousTransition:({o:$},Z)=>zz(-1,$,Z),equals($,Z){return!!h6(this,l(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=l($);return typeof Z=="string"?new G8(Z):Z}}),wO=Kz(Object.keys(Mz)),[kO,e1]=K1(e6,aW,gJ,{getISOFields:H3,with($,Z,j){return e1(hW(this,NZ(Z),j))},add:($,Z)=>e1(I4(0,$,e(Z))),subtract:($,Z)=>e1(I4(1,$,e(Z))),until:($,Z,j)=>d(p4(0,$,r1(Z),j)),since:($,Z,j)=>d(p4(1,$,r1(Z),j)),round:($,Z)=>e1(x7($,Z)),equals:($,Z)=>VW($,r1(Z)),toZonedDateTime:($,Z)=>G0(QY(l,E0,c,$,Z)),toPlainDateTime:($,Z)=>I0(KY($,E0(Z))),toLocaleString($,Z,j){let[J,W]=HO(Z,j,$);return J.format(W)},toString:G4,toJSON:($)=>G4($),valueOf:Z$},{from:($,Z)=>e1(r1($,Z)),compare:($,Z)=>p6(r1($),r1(Z))}),[yO,$$,qO]=K1(VZ,b(oW,L0),{...L3,...CO},{getISOFields:H3,getCalendar:M3,with($,Z,j){return $$(mW(uO,$,this,NZ(Z),j))},add:($,Z,j)=>$$(M4(Fz,0,$,e(Z),j)),subtract:($,Z,j)=>$$(M4(Fz,1,$,e(Z),j)),until:($,Z,j)=>d(m4(Qz,0,$,LZ(Z),j)),since:($,Z,j)=>d(m4(Qz,1,$,LZ(Z),j)),equals:($,Z)=>DW($,LZ(Z)),toPlainDate($,Z){return $0(GY(P3,$,this,Z))},toLocaleString($,Z,j){let[J,W]=PO(Z,j,$);return J.format(W)},toString:z4,toJSON:($)=>z4($),valueOf:Z$},{from:($,Z)=>$$(LZ($,Z)),compare:($,Z)=>N$(LZ($),LZ(Z))}),[vO,I0]=K1(f$,b(iW,L0),{...L3,...vJ,...gJ},{getISOFields:H3,getCalendar:M3,with($,Z,j){return I0(vW(P3,$,this,NZ(Z),j))},withCalendar:($,Z)=>I0(l6($,L0(Z))),withPlainDate:($,Z)=>I0(IY($,E0(Z))),withPlainTime:($,Z)=>I0(MY($,kJ(Z))),add:($,Z,j)=>I0(V4(E$,0,$,e(Z),j)),subtract:($,Z,j)=>I0(V4(E$,1,$,e(Z),j)),until:($,Z,j)=>d(v4(Q1,0,$,t1(Z),j)),since:($,Z,j)=>d(v4(Q1,1,$,t1(Z),j)),round:($,Z)=>I0(C7($,Z)),equals:($,Z)=>OW($,t1(Z)),toZonedDateTime:($,Z,j)=>G0(ZY(c,$,l(Z),j)),toPlainDate:($)=>$0(X0($)),toPlainTime:($)=>e1(e0($)),toPlainYearMonth($){return $$(jY(F8,$,this))},toPlainMonthDay($){return PZ(JY(K8,$,this))},toLocaleString($,Z,j){let[J,W]=IO(Z,j,$);return J.format(W)},toString:W4,toJSON:($)=>W4($),valueOf:Z$},{from:($,Z)=>I0(t1($,Z)),compare:($,Z)=>k4(t1($),t1(Z))}),[gO,$0,Iz]=K1(S$,b(sW,L0),{...L3,...vJ},{getISOFields:H3,getCalendar:M3,with($,Z,j){return $0(gW(P3,$,this,NZ(Z),j))},withCalendar:($,Z)=>$0(l6($,L0(Z))),add:($,Z,j)=>$0(T4(E$,0,$,e(Z),j)),subtract:($,Z,j)=>$0(T4(E$,1,$,e(Z),j)),until:($,Z,j)=>d(g4(Q1,0,$,E0(Z),j)),since:($,Z,j)=>d(g4(Q1,1,$,E0(Z),j)),equals:($,Z)=>BW($,E0(Z)),toZonedDateTime($,Z){let j=!B0(Z)||Z instanceof G8?{timeZone:Z}:Z;return G0(WY(l,r1,c,$,j))},toPlainDateTime:($,Z)=>I0(YY($,kJ(Z))),toPlainYearMonth($){return $$(zY(F8,$,this))},toPlainMonthDay($){return PZ(XY(K8,$,this))},toLocaleString($,Z,j){let[J,W]=LO(Z,j,$);return J.format(W)},toString:Y4,toJSON:($)=>Y4($),valueOf:Z$},{from:($,Z)=>$0(E0($,Z)),compare:($,Z)=>N$(E0($),E0(Z))}),mJ={fields($,Z,j){return[...Z.call($,j)]}},Lz=Object.assign({dateFromFields($,Z,j,J){return Iz(Z.call($,Object.assign(Object.create(null),j),J))}},mJ),Hz=Object.assign({yearMonthFromFields($,Z,j,J){return qO(Z.call($,Object.assign(Object.create(null),j),J))}},mJ),Pz=Object.assign({monthDayFromFields($,Z,j,J){return EO(Z.call($,Object.assign(Object.create(null),j),J))}},mJ),pJ={mergeFields($,Z,j,J){return _1(Z.call($,Object.assign(Object.create(null),j),Object.assign(Object.create(null),J)))}},mO=Object.assign({},Lz,pJ),pO=Object.assign({},Hz,pJ),hO=Object.assign({},Pz,pJ),hJ={dateAdd($,Z,j,J,W){return Iz(Z.call($,$0(X0(j,$)),d(s(J)),W))}},Nz=Object.assign({},hJ,{dateUntil($,Z,j,J,W,Y){return sO(Z.call($,$0(X0(j,$)),$0(X0(J,$)),Object.assign(Object.create(null),Y,{largestUnit:O3[W]})))}}),cO=Object.assign({},hJ,{day:Bz}),dO=Object.assign({},Nz,{day:Bz}),F8=O1(Hz),Q8=O1(Lz),K8=O1(Pz),uO=O1(pO),P3=O1(mO),lO=O1(hO),E$=O1(hJ),Q1=O1(Nz),Fz=O1(cO),Qz=O1(dO),[iO,d,sO]=K1(Z8,rW,{...fO,blank:d7},{with:($,Z)=>d(cW($,Z)),negated:($)=>d(y6($)),abs:($)=>d(c7($)),add:($,Z,j)=>d(_4(T3,Q1,c,0,$,e(Z),j)),subtract:($,Z,j)=>d(_4(T3,Q1,c,1,$,e(Z),j)),round:($,Z)=>d(h7(T3,Q1,c,$,Z)),total:($,Z)=>P7(T3,Q1,c,$,Z),toLocaleString($,Z,j){return Intl.DurationFormat?new Intl.DurationFormat(Z,j).format(this):E6($)},toString:E6,toJSON:($)=>E6($),valueOf:Z$},{from:($)=>d(e($)),compare:($,Z,j)=>FW(T3,E$,c,e($),e(Z),j)}),_z={toString:($)=>$.id,toJSON:($)=>$.id,..._O,dateAdd:({id:$,o:Z},j,J,W)=>$0(X0(Z.dateAdd(E0(j),e(J),W),$)),dateUntil:({o:$},Z,j,J)=>d(s($.dateUntil(E0(Z),E0(j),B7(J)))),dateFromFields:({id:$,o:Z},j,J)=>$0(d4(Z,j,J,o9($))),yearMonthFromFields:({id:$,o:Z},j,J)=>$$(u4(Z,j,J,i9($))),monthDayFromFields:({id:$,o:Z},j,J)=>PZ(l4(Z,0,j,J,s9($))),fields({o:$},Z){let j=new Set($1),J=[];for(let W of Z){if(t(W),!j.has(W))throw RangeError($J(W));j.delete(W),J.push(W)}return $.fields(J)},mergeFields:({o:$},Z,j)=>$.mergeFields(kj(vj(Z)),kj(vj(j)))},[cJ]=K1("Calendar",($)=>{let Z=_W($);return{branding:"Calendar",id:Z,o:MZ(Z)}},{id:($)=>$.id},_z,{from($){let Z=L0($);return typeof Z=="string"?new cJ(Z):Z}}),oO=Kz(Object.keys(_z).slice(4)),[nO,G0]=K1(A1,b(lW,L0,l),{...Tz,...L3,...Xz(vJ),...Xz(gJ),offset:($)=>L$(RJ($).offsetNanoseconds),offsetNanoseconds:($)=>RJ($).offsetNanoseconds,timeZoneId:($)=>V0($.timeZone),hoursInDay:($)=>S7(c,$)},{getISOFields:($)=>m7(F0,$),getCalendar:M3,getTimeZone:({timeZone:$})=>typeof $=="string"?new G8($):$,with($,Z,j){return G0(qW(P3,c,$,this,NZ(Z),j))},withCalendar:($,Z)=>G0(l6($,L0(Z))),withTimeZone:($,Z)=>G0(LY($,l(Z))),withPlainDate:($,Z)=>G0(TY(c,$,E0(Z))),withPlainTime:($,Z)=>G0(VY(c,$,kJ(Z))),add:($,Z,j)=>G0(U4(E$,c,0,$,e(Z),j)),subtract:($,Z,j)=>G0(U4(E$,c,1,$,e(Z),j)),until:($,Z,j)=>d(s(q4(Q1,c,0,$,HZ(Z),j))),since:($,Z,j)=>d(s(q4(Q1,c,1,$,HZ(Z),j))),round:($,Z)=>G0(_7(c,$,Z)),startOfDay:($)=>G0(f7(c,$)),equals:($,Z)=>KW($,HZ(Z)),toInstant:($)=>A0(tW($)),toPlainDateTime:($)=>I0(n4(F0,$)),toPlainDate:($)=>$0(a4(F0,$)),toPlainTime:($)=>e1(r4(F0,$)),toPlainYearMonth($){return $$(eW(F8,$,this))},toPlainMonthDay($){return PZ($Y(K8,$,this))},toLocaleString($,Z,j={}){let[J,W]=MO(Z,j,$);return J.format(W)},toString:($,Z)=>J4(F0,$,Z),toJSON:($)=>J4(F0,$),valueOf:Z$},{from:($,Z)=>G0(HZ($,Z)),compare:($,Z)=>w4(HZ($),HZ(Z))}),aO=Object.defineProperties({},{...D6("Temporal.Now"),...T$({timeZoneId:()=>S1(),instant:()=>A0(D0(F3())),zonedDateTime:($,Z=S1())=>G0(M0(F3(),l(Z),L0($))),zonedDateTimeISO:($=S1())=>G0(M0(F3(),l($),w)),plainDateTime:($,Z=S1())=>I0(z0(DZ(F0(l(Z))),L0($))),plainDateTimeISO:($=S1())=>I0(z0(DZ(F0(l($))),w)),plainDate:($,Z=S1())=>$0(X0(DZ(F0(l(Z))),L0($))),plainDateISO:($=S1())=>$0(X0(DZ(F0(l($))),w)),plainTimeISO:($=S1())=>e1(e0(DZ(F0(l($)))))})}),_Z=Object.defineProperties({},{...D6("Temporal"),...T$({PlainYearMonth:yO,PlainMonthDay:AO,PlainDate:gO,PlainTime:kO,PlainDateTime:vO,ZonedDateTime:nO,Instant:RO,Calendar:cJ,TimeZone:G8,Duration:iO,Now:aO})}),rO=OO(),dJ=new WeakMap,tO=Object.defineProperties(Object.create(Intl),T$({DateTimeFormat:rO}));var jM="gemi.v1",Cz="/__gemi/socket",uJ="x-gemi-socket",JM=/^[A-Za-z0-9_-]{1,32}$/,WM={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function XM($){return $}function xz(){return{driver:"memory",maxEventBytes:16384,warnEventBytes:4096,path:Cz,allowedOrigins:[],maxConnectionsPerProcess:1e4,maxConnectionsPerIp:100,maxConnectionsPerUser:50,maxChannelsPerSocket:50,maxInboundMessageBytes:16384,backpressureLimit:1048576,idleTimeout:120,heartbeatMs:25000,subscribeRate:{limit:300,windowMs:60000}}}class lJ{deliver=null;hooks;get started(){return this.deliver!==null}publish($,Z){this.deliver?.($,Z)}start($,Z){this.deliver=$,this.hooks=Z}revoke($){this.hooks?.onRevoke?.($)}close(){this.deliver=null,this.hooks=void 0}}import{createHmac as eO,hkdfSync as $B,randomBytes as Sz}from"crypto";function fz($){return eO("sha256",ZB()).update($).digest("base64url").slice(0,22)}var O8=null;function ZB(){let $=process.env.SECRET||void 0;if(O8&&O8.secret===$)return O8.key;let Z=$?Buffer.from($B("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):Sz(32);return O8={secret:$,key:Z},Z}function KM(){return Sz(16).toString("base64url")}var jB=/^[A-Za-z0-9_-]{8,64}$/;function iJ($){return typeof $==="string"&&jB.test($)}function Az($,Z,j,J){let W={op:"ev",t:$,ev:Z};if(j!==void 0)W.d=j;if(J)W.x=J;return JSON.stringify(W)}class Ez extends Error{bytes;limit;constructor($,Z,j){super(`The broadcast "${j}" is ${$} bytes, over the limit of ${Z}. Send ids and a change hint, and let the client fetch the data over HTTP; or raise maxEventBytes in app/config/broadcast.ts.`);this.bytes=$;this.limit=Z;this.name="BroadcastPayloadTooLargeError"}}class g0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=xZ(xz(),$),this.driver=YB(this.config.driver,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 N3(this,B8($,Z[0]),null)}toUser($){return new N3(this,{topic:l$($),pattern:Q0},null)}toOthers($){return new Rz(this,WB($))}broadcastEvent($){let Z=$.broadcastOn(),j=Array.isArray(Z)?Z:[Z],J=$.broadcastAs(),W=$.broadcastWith(),Y=j.map((z)=>this.prepare(B8(z,void 0),J,W,null));for(let{sent:z,frame:X}of Y)this.hand(z,X)}send($,Z,j,J){let{sent:W,frame:Y}=this.prepare($,Z,j,J);this.hand(W,Y)}prepare($,Z,j,J){V5(Z);let W;try{W=Az($.topic,Z,j,J?fz(J):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,W),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(W).d,...J?{except:J}:{}},frame:W}}hand($,Z){CZ(()=>this.publish($,Z))}publish($,Z){let j=(J)=>console.error(`[gemi] The broadcast "${$.event}" on "${$.topic}" could not be published.`,J);try{let J=this.driver.publish($.topic,Z);if(J&&typeof J.catch==="function")J.catch(j)}catch(J){j(J)}}get isStarted(){return this.started}async start($,Z){if(this.started)throw Error("The broadcast driver was already started in this process.");this.started=!0,this.hooks=Z;try{await this.driver.start($,Z)}catch(j){throw this.started=!1,this.hooks=void 0,j}}topicAdded($){return this.driver.topicAdded?.($)}topicRemoved($){return this.driver.topicRemoved?.($)}async close(){this.started=!1,this.hooks=void 0,await this.driver.close()}revoke($){let Z=JB($);CZ(()=>this.sendRevocation(Z))}sendRevocation($){let Z=(j)=>console.error("[gemi] A broadcast revocation could not be sent.",j);try{if(typeof this.driver.revoke==="function"){let j=this.driver.revoke($);if(j&&typeof j.catch==="function")j.catch(Z);return}this.hooks?.onRevoke?.($)}catch(j){Z(j)}}checkSize($,Z){let j=Buffer.byteLength(Z,"utf8");if(j>this.config.maxEventBytes)throw new Ez(j,this.config.maxEventBytes,$);let J=this.config.warnEventBytes;if(J!==!1&&j>J&&!this.warnedAboutSize.has($))this.warnedAboutSize.add($),console.warn(`[gemi] The broadcast "${$}" is ${j} bytes, over ${J}. Broadcasts are change hints: send ids and let the client fetch the data over HTTP. Warned once per event name.`)}}class N3{manager;target;except;constructor($,Z,j){this.manager=$;this.target=Z;this.except=j}emit($,...Z){this.manager.send(this.target,$,Z[0],this.except)}}class Rz{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new N3(this.manager,B8($,Z[0]),this.except)}toUser($){return new N3(this.manager,{topic:l$($),pattern:Q0},this.except)}}function B8($,Z){if(U5($))return{topic:s8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:cZ($,Z??{}),pattern:$};if($===Q0)throw new p('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:s8($)}}function JB($){if($&&typeof $==="object"&&"user"in $)return{user:l$($.user).slice(Q0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:B8($.channel,$.params).topic};throw new p("Broadcast.revoke takes { user } or { channel }.")}function WB($){if($===null||$===void 0)return null;if(typeof $==="string")return iJ($)?$:null;let j=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(uJ);return iJ(j)?j:null}function YB($,Z){if($===void 0||$==="memory")return new lJ;if(typeof $==="function"){if(!Z)throw Error("A broadcast driver factory needs the application to be called with.");return $(Z)}if(typeof $==="object"&&$!==null&&typeof $.publish==="function")return $;throw Error(`Unknown broadcast driver "${String($)}" in app/config/broadcast.ts. Use "memory", or pass a BroadcastDriver.`)}class sJ extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class zB{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1}import{createHash as oJ,createHmac as XB,randomBytes as bz,timingSafeEqual as yz}from"crypto";var C3=600,D8="gemi_oauth",GB=`__Host-${D8}`;function SZ($,Z=D8){if(Z===D8)return $?GB:D8;return $?`__Host-${Z}`:Z}function _3($){return $.toString("base64url")}function qz($){return XB("sha256",t$()).update(`gemi-oauth-state:${$}`).digest()}function wz($,Z){let j=oJ("sha256").update($).digest(),J=oJ("sha256").update(Z).digest();return yz(j,J)&&$.length===Z.length}function U8($,Z=Date.now(),j={}){let J=_3(bz(32)),W=_3(bz(32)),Y=FB(W),z={provider:$,state:J,codeVerifier:W,expiresAt:Z+C3*1000,...j.subject!==void 0?{subject:j.subject}:{},...j.returnTo!==void 0?{returnTo:j.returnTo}:{}};return{state:J,codeVerifier:W,codeChallenge:Y,cookieValue:QB(z)}}function FB($){return _3(oJ("sha256").update($).digest())}function QB($){let Z=_3(Buffer.from(JSON.stringify($)));return`${Z}.${_3(qz(Z))}`}function KB($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let j=$.slice(0,Z),J=Buffer.from($.slice(Z+1),"base64url"),W=qz(j);if(J.length!==W.length||!yz(J,W))return null;try{let Y=JSON.parse(Buffer.from(j,"base64url").toString("utf8"));if(typeof Y?.provider!=="string"||typeof Y?.state!=="string"||typeof Y?.codeVerifier!=="string"||typeof Y?.expiresAt!=="number"||Y.subject!==void 0&&typeof Y.subject!=="string"||Y.returnTo!==void 0&&typeof Y.returnTo!=="string")return null;return Y}catch{return null}}var j$=new Map,kz=1e4;function OB($,Z,j){if(j$.size>=kz){for(let[J,W]of j$)if(W<=j)j$.delete(J);while(j$.size>=kz){let J=j$.keys().next().value;if(J===void 0)break;j$.delete(J)}}j$.set($,Z)}function V8($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let j=KB($.cookieValue);if(!j)return{ok:!1,reason:"invalid_state"};let J=wz(j.state,$.returnedState),W=wz(j.provider,$.provider);if(!J||!W)return{ok:!1,reason:"invalid_state"};if(j.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(j$.has(j.state))return{ok:!1,reason:"invalid_state"};return OB(j.state,j.expiresAt,Z),{ok:!0,payload:j}}var nJ=new WeakMap;function DB($){let Z=nJ.get($);if(!Z)Z=$(BB(32).toString("hex")),nJ.set($,Z),Z.catch(()=>nJ.delete($));return Z}async function aJ($,Z,j){if(typeof j==="string"&&j!=="")return await $.verifyPassword(Z,j);try{await $.verifyPassword(Z,await DB($.hashPassword))}catch{}return!1}async function R$($,Z){let j=Z.user??Z.session?.user;if(!j||!$.onAuthenticated)return;let{password:J,...W}=j;await $.onAuthenticated({...Z,user:W})}class tJ extends Error{}function rJ($){return typeof $==="string"&&$!==""?$:null}function vz($){return sZ($)}var UB=256;function gz($){return typeof $==="string"&&$!==""&&$.length<=UB?$:null}var T8="intended_url";function pz($){if($.cookies.get(T8))$.ctx().setCookie(T8,"",{maxAge:-1})}function mz($){let Z=$.cookies.get(T8);if(!Z)return null;pz($);try{return W1(decodeURIComponent(Z),"")||null}catch{return null}}class eJ extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class hz extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class cz extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}class o extends lZ{async me(){let $=await h0.user();if(!$)throw new Fj;return $}async verifyEmail($=new C){let Z=await $.input(),{userProvider:j}=T(f),J=rJ(Z.get("token"));if(!J)return{email:null};let W=await j.findUserByVerificationToken(J);if(!W)return{email:null};return await j.verifyUser(W.email),{email:W.email}}async signInWithMagicLink($=new C){let Z=T(f),{userProvider:j}=Z,J=rJ($.search.get("token")),W=null;try{W=sZ(decodeURIComponent($.search.get("email")??""))}catch{}if(await e$("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp}),!W||!J||!await Z.verifyMagicLinkToken(W,J))return{error:"Invalid token"};await j.verifyUser(W);let Y=await Z.createOrUpdateSession({email:W});return $.ctx().setCookie("access_token",Y.token,T(f).accessTokenCookieOptions($,Y.expiresAt)),await Z.config.onSignIn(Y,$.search.toJSON()),await R$(Z.config,{session:Y,isNewUser:!1,method:"magic-link",req:$}),{session:Y}}async verifyPinRequest($){let Z=T(f),j=await $.input(),{email:J,pin:W}=j.toJSON(),Y=sZ(J),z=gz(W);if(await e$("verify",Y,$,Z.config.emailCode.verifyLimit),!Y||!z)throw new v({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(Y,z);if(X.status==="too_many_attempts")throw new v({pin:["Too many attempts"]});if(X.status!=="ok")throw new v({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(Y),Y}async signInWithPinV2($=new C){let Z=T(f),j=await this.verifyPinRequest($),J=await Z.createOrUpdateSessionV2({email:j});return $.ctx().setCookie("access_token",J.token,T(f).accessTokenCookieOptions($,J.expiresAt)),await Z.config.onSignIn(J,$.search.toJSON()),await R$(Z.config,{session:J,isNewUser:!1,method:"magic-link",req:$}),J}async signInWithPin($=new C){let Z=T(f),j=await this.verifyPinRequest($),J=await Z.createOrUpdateSession({email:j});return $.ctx().setCookie("access_token",J.token,T(f).accessTokenCookieOptions($,J.expiresAt)),await Z.config.onSignIn(J,$.search.toJSON()),await R$(Z.config,{session:J,isNewUser:!1,method:"magic-link",req:$}),{session:J}}async signInV2($=new eJ){let Z=await $.input(),{email:j,password:J}=Z.toJSON(),W=j.toLowerCase().trim(),Y=T(f),z=await Y.userProvider.findUserByEmailAddress(W,Y.config.verifyEmail),X=typeof J==="string"&&await aJ(Y.config,J,z?.password);if(!z||!X)throw new v({invalid_credentials:["Invalid credentials"]});let G=await Y.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,T(f).accessTokenCookieOptions($,G.expiresAt)),await Y.config.onSignIn(z,$.search.toJSON()),await R$(Y.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:F,...Q}=z;return Q}async signIn($=new eJ){let Z=await $.input(),{email:j,password:J}=Z.toJSON(),W=j.toLowerCase().trim(),Y=T(f),z=await Y.userProvider.findUserByEmailAddress(W,Y.config.verifyEmail),X=typeof J==="string"&&await aJ(Y.config,J,z?.password);if(!z||!X)throw new v({invalid_credentials:["Invalid credentials"]});let G=await Y.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,T(f).accessTokenCookieOptions($,G.expiresAt)),await Y.config.onSignIn(z,$.search.toJSON()),await R$(Y.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:F,...Q}=z;return Q}async signUp(){let $=T(f),{userProvider:Z,config:j}=$,J=new j.signUpRequest,W=await J.input(),{email:Y,password:z,name:X,invitationId:G}=W.toJSON(),F=vz(Y);if(!F)throw new v({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new v({password:["Invalid password"]});if(G!=null&&typeof G!=="string")throw new v({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(F,!1))throw new v({email:["Email address already exists"]});let O=await j.hashPassword(z),K=T(i).detectLocale(J),D;if(G)D=await Z.findInvitation(G,F);let B,U="";if(D)B=await Z.transaction(async()=>{await Z.deleteInvitationById(G);let V=await Z.createUser({email:F,name:X,password:O,emailVerifiedAt:new Date,locale:K});return await Z.createAccount({organizationId:D.organizationId,userId:V.id,organizationRole:D.role}),await j.onUserCreated(V),V});else U=await j.generateEmailVerificationToken(F),B=await Z.transaction(async()=>{let V=await Z.createUser({email:F,name:X,password:O,verificationToken:U,locale:K});return await j.onUserCreated(V),V});return await j.onSignUp(B,U,J.search.toJSON()),B}async signOut($=new C){let Z=z$($),j=T(f),{config:J}=j,W=await j.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",T(f).accessTokenCookieOptions($,new Date(0))),T(f).cookieDomain($))$.ctx().setCookie("access_token","",{...T(f).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(W?.user)VB(W.user),W.user.extension=await J.extendSession(W.user),await J.onSignOut(W.user);return{}}async forgotPassword($=new hz){let Z=await $.input(),j=vz(Z.get("email"));if(!j)return{};let{userProvider:J,config:W}=T(f),Y=await J.findUserByEmailAddress(j,W.verifyEmail);if(!Y)return{};let z=await W.generateForgotPasswordToken(Y);return await J.createPasswordResetToken({user:Y,token:z}),await W.onForgotPassword(Y,z),{}}async resetPassword($=new cz){let{userProvider:Z,config:j}=T(f),J=await $.input(),{password:W,token:Y}=J.toJSON(),z=rJ(Y),X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new v({token:["Invalid token"]});if(_Z.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(_Z.Now.instant()).sign>=0)throw new v({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let F=await Z.findUserByEmailAddress(X.user.email,j.verifyEmail);if(!F)throw new v({email:["User not found"]});let Q=await j.hashPassword(W);return await Z.updateUserPassword({id:F.id,password:Q}),await Z.deleteAllUserSessions(F.id),await j.onResetPassword(F),{}}async changePassword($=new C){let{userProvider:Z,config:j}=T(f),J=await h0.user(),W=await $.input(),{oldPassword:Y,newPassword:z}=W.toJSON();if(typeof z!=="string")throw new v({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(J.email,j.verifyEmail);if(!(typeof Y==="string"&&await aJ(j,Y,X?.password)))throw new v({oldPassword:["Incorrect password"]});let F=await j.hashPassword(z);return await Z.updateUserPassword({id:J.id,password:F}),await Z.deleteAllUserSessions(J.id),{}}async oauthRedirect($=new C){let{provider:Z}=$.params,j=T(f).config.oauthProviders[Z];if(!j)throw Error(`Invalid provider: ${Z}`);let J=s$($.rawRequest),W=W1($.search.get(J1),"");if(W)$.ctx().setCookie(T8,encodeURIComponent(W),{httpOnly:!0,sameSite:"Lax",secure:J,maxAge:600});else pz($);let{state:Y,codeChallenge:z,cookieValue:X}=U8(Z);return $.ctx().setCookie(SZ(J),X,{httpOnly:!0,sameSite:"Lax",secure:J,maxAge:C3}),{destination:await j.getRedirectUrl($,{state:Y,codeChallenge:z,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,j=T(f),{userProvider:J,config:W}=j,Y=W.oauthProviders[Z],z=s$($.rawRequest),X=SZ(z),G=$.cookies.get(X);if(G!==void 0&&G!==null)$.ctx().setCookie(X,"",{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:-1});if(!Y)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 Q=V8({provider:Z,cookieValue:G,returnedState:$.search.get("state")});if("reason"in Q)return console.error(`Authentication error: OAuth callback refused (${Q.reason})`),this.oauthFailure($,Q.reason);if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let O;try{O=await Y.onCallback($,{state:Q.payload.state,codeVerifier:Q.payload.codeVerifier})}catch(H){if(H instanceof sJ)return this.oauthFailure($,H.code);return console.error("Authentication error: OAuth provider callback failed",H),this.oauthFailure($,"provider_error")}let{name:K,username:D,providerId:B,emailVerified:U}=O??{},V=typeof O?.email==="string"?O.email:void 0,M=V?r3(V):null,I=B?await J.findUserBySocialAccount(Z,B):null,P="signin",A=!I&&!M&&!V&&!!B&&Y.createUsersWithoutEmail===!0;if(!I&&A){if(Y.createUsers===!1)return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");try{I=await this.createOAuthUserWithoutEmail({provider:Z,providerId:B,name:K,username:D,locale:T(i).detectLocale($)}),P="signup"}catch(H){let L=await J.findUserBySocialAccount(Z,B);if(!L)throw H;I=L}}if(!I){if(!M)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,V?"invalid_email":B?"missing_email":"no_identity");if(U===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let H=T(i).detectLocale($);try{let L=await this.linkOAuthAccount({provider:Z,providerId:B,email:M,rawEmail:V,name:K,username:D,locale:H,linkExisting:Y.linkByEmail!==!1,createUser:Y.createUsers!==!1});if(L==="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(L==="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(L)I=L.user,P=L.action}catch(L){let m=B?await J.findUserBySocialAccount(Z,B):null;if(!m)throw L;I=m}if(!I)return this.oauthFailure($,"account_conflict")}let x=await j.createOrUpdateSessionV2({email:I.email,id:I.id});if($.ctx().setCookie("access_token",x.token,T(f).accessTokenCookieOptions($,x.expiresAt)),P==="signup")await W.onSignUp(I,"",$.search.toJSON());else await W.onSignIn(I,$.search.toJSON());await R$(j.config,{session:x,user:I,isNewUser:P==="signup",method:"oauth",req:$});let E=mz($)??W.redirectPath,S=W.oauthCompleteProfilePath?W1(W.oauthCompleteProfilePath,""):"";if(S&&!I.email){let H=new URL(S,"http://gemi.invalid");H.searchParams.set(J1,E),E=`${H.pathname}${H.search}${H.hash}`}return{session:x,redirectTo:E}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:j}=T(f);return await Z.transaction(async()=>{let J=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:J.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await j.onUserCreated(J),J})}oauthFailure($,Z){let j=mz($),J=T(f).config.oauthFailurePath;if(J){let W=W1(J,"");if(W){let Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("error",Z),j)Y.searchParams.set(J1,j);M1.external(`${Y.pathname}${Y.search}${Y.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(J)}`)}return{session:null,error:Z,redirectTo:j}}async linkOAuthAccount($){let{provider:Z,providerId:j,email:J,rawEmail:W,name:Y,username:z,locale:X}=$,{userProvider:G,config:F}=T(f),Q=(B)=>({provider:Z,userId:B,email:J,username:z,providerId:j,expiresAt:new Date,accessToken:"",refreshToken:""}),O=await G.findUserByEmailAddress(J,!1),K=W?.trim();if(!O&&K&&K!==J)O=await G.findUserByEmailAddress(K,!1);if(O){if($.linkExisting===!1)return"account_exists";if(!j)return{user:O,action:"signin"};let B=await G.findSocialAccounts(O.id,Z);if(B.some((V)=>V.providerId===j))return{user:O,action:"signin"};if(B.some((V)=>V.providerId))return console.error(`Authentication error: user ${O.id} is already linked to a different ${Z} account`),null;let U=B[0];if(U){if(!await G.claimSocialAccount(U,j))throw Error(`${Z} account link changed concurrently`)}else await G.createSocialAccount(Q(O.id));return{user:O,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await G.transaction(async()=>{let B=await G.createUser({email:J,name:Y,locale:X,emailVerifiedAt:new Date});if(j)await G.createSocialAccount(Q(B.id));return await F.onUserCreated(B),B}),action:"signup"}}async createMagicLinkToken($=new C){let Z=await $.input(),j=sZ(Z.get("email")),J=T(f),{uniformMagicLinkResponse:W,requestLimit:Y}=J.config.emailCode;if(await e$("request",j,$,Y),!j)return{email:null};let{user:z,pin:X,token:G}=await J.createMagicLinkToken(j);if(z)return await J.config.onMagicLinkCreated(z,{email:j,pin:X,token:G}),{email:j};return{email:W?j:null}}async requestEmailCode($=new C){let Z=T(f),j=Z.config.emailCode;if(!j.enabled)throw new P0("Not found",{status:404});let J=await $.input(),W=r3(J.get("email"));if(await e$("request",W,$,j.requestLimit),!W)throw new v({email:["Invalid email"]});let Y=await Z.userProvider.findUserByEmailAddress(W,!1);if(Y||j.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(W,j.length);await j.send({email:W,code:z,token:X,isNewUser:!Y,req:$})}return{ok:!0}}async verifyEmailCode($=new C){let Z=T(f),{userProvider:j,config:J}=Z;if(!J.emailCode.enabled)throw new P0("Not found",{status:404});let W=await $.input(),{email:Y,code:z,name:X}=W.toJSON(),G=r3(Y),F=gz(z);if(await e$("verify",G,$,J.emailCode.verifyLimit),!G||!F)throw new v({code:["invalid_code"]});let Q=await Z.verifyOneTimeCode(G,F,{claim:!1});if(Q.status==="too_many_attempts")throw new v({code:["too_many_attempts"]});if(Q.status!=="ok")throw new v({code:["invalid_code"]});let O=Q.row,K=await j.findUserByEmailAddress(G,!1),D=!1;if(K){if(!await j.claimMagicLinkToken(O.id))throw new v({code:["invalid_code"]});await j.verifyUser(G)}else if(J.emailCode.createUser){let U=T(i).detectLocale($);try{K=await j.transaction(async()=>{if(!await j.claimMagicLinkToken(O.id))throw new tJ;let V=await j.createUser({email:G,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:U});return await J.onUserCreated(V),V}),D=!0}catch(V){if(V instanceof tJ)throw new v({code:["invalid_code"]});throw V}}else throw await j.claimMagicLinkToken(O.id),new v({code:["invalid_code"]});let B=await Z.createOrUpdateSessionV2({email:G,id:K.id});return $.ctx().setCookie("access_token",B.token,T(f).accessTokenCookieOptions($,B.expiresAt)),await J.onSignIn(B,$.search.toJSON()),await R$(Z.config,{session:B,isNewUser:D,method:"email-code",req:$}),{session:B,isNewUser:D}}}function VB($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let j=T();if(typeof j?.bound!=="function"||!j.bound(g0))return;j.make(g0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var dz="gemi_oauth_connection";class M8 extends lZ{async connect($=new C){let Z=String($.params.provider??""),J=T(x3).providers[Z],W=await h0.user(),Y=W1($.search.get(J1),"");if(!J)return this.finish(Y,Z,"unknown_provider");let z=s$($.rawRequest),{state:X,codeChallenge:G,cookieValue:F}=U8(uz(Z),Date.now(),{subject:String(W.id),...Y?{returnTo:Y}:{}});return $.ctx().setCookie(SZ(z,dz),F,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:C3}),M1.external(J.authorizationUrl({state:X,codeChallenge:G,redirectUri:lz($,Z,J.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),j=T(x3),J=await h0.user(),W=s$($.rawRequest),Y=SZ(W,dz),z=$.cookies.get(Y);if(z!==void 0&&z!==null)$.ctx().setCookie(Y,"",{httpOnly:!0,sameSite:"Lax",secure:W,maxAge:-1});let X=V8({provider:uz(Z),cookieValue:z,returnedState:$.search.get("state")}),G="payload"in X?X.payload.returnTo??"":"",F=j.providers[Z];if(!F)return this.finish(G,Z,"unknown_provider");let Q=$.search.get("error");if(Q)return this.finish(G,Z,/^[a-z0-9_]{1,64}$/.test(Q)?Q:"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(J.id))return this.finish(G,Z,"user_mismatch");let O=$.search.get("code");if(!O)return this.finish(G,Z,"missing_code");try{let K=await F.exchangeCode({code:O,codeVerifier:X.payload.codeVerifier,redirectUri:lz($,Z,F.config.redirectUri)}),D=await j.save(J,Z,K);await T(f).config.onConnected({user:J,provider:Z,connection:D,profile:K.profile??null,req:$})}catch(K){if(K instanceof iz)return console.error(`OAuth connection to ${Z} failed: ${K.message}`),this.finish(G,Z,K.providerError??K.code);throw K}return this.finish(G,Z)}finish($,Z,j){let J=$||W1(T(f).config.redirectPath,"/"),W=new URL(J,"http://gemi.invalid");if(W.searchParams.set("connection",Z),j)W.searchParams.set("connection_error",j);throw M1.external(`${W.pathname}${W.search}${W.hash}`),Error("unreachable: Redirect.external throws")}}function uz($){return`connection:${$}`}function lz($,Z,j){if(j)return j;return`${(process.env.HOST_NAME||new URL($.rawRequest.url).origin).replace(/\/$/,"")}/auth/connections/${encodeURIComponent(Z)}/callback`}class sz extends I1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[o,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[o,"oauthCallback"])}}class oz extends I1{middlewares=["cache:private"];routes={"/:provider":this.redirect([M8,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([M8,"callback"]).middleware([d3,"auth"])}}class $2 extends I1{middlewares=["cache:private"];routes={"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[o,"signInWithMagicLink"]),"/oauth":sz,"/connections":oz}}class Z2 extends R0{middlewares=["cache:private"];routes={"/sign-in":this.post(o,"signIn"),"/sign-in-v2":this.post(o,"signInV2"),"/sign-up":this.post(o,"signUp"),"/sign-out":this.post(o,"signOut"),"/forgot-password":this.post(o,"forgotPassword"),"/reset-password":this.post(o,"resetPassword"),"/change-password":this.post(o,"changePassword"),"/verify-email":this.post(o,"verifyEmail"),"/me":this.get(o,"me").middleware(["auth"]),"/magic-link":this.post(o,"createMagicLinkToken"),"/sign-in-with-pin":this.post(o,"signInWithPin"),"/sign-in-with-pin-v2":this.post(o,"signInWithPinV2"),"/email-code":this.post(o,"requestEmailCode"),"/email-code/verify":this.post(o,"verifyEmailCode")}}class j2 extends R0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new C().params.locale;return await T(i).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new C,Z=`/${$.params.scope??""}`,j=$.params.locale,J=T(i),W=j??J.detectLocale($),Y=J.getPageTranslations(W,Z);return $.ctx().setCookie("i18n-locale",W,{expires:new Date(Date.now()+31536000000)}),{[W]:Y}})}}class J2{}class W2 extends J2{async resize($,Z){let{height:j,width:J,quality:W,fit:Y}=Z;return await(await I8("The Sharp image optimization driver"))($).resize(J>0?J:void 0,j>0?j:void 0,{fit:Y}).webp({quality:W>0?W:80,force:!0}).toBuffer()}}function MI($){return $}function nz(){return{driver:new W2}}class Y2 extends R0{routes={"/resize":this.file(async()=>{let $=new C,Z=new URL($.rawRequest.url),j=Z.searchParams.get("url"),J=Number(Z.searchParams.get("w")),W=Number(Z.searchParams.get("h")),Y=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!j)return new Response(JSON.stringify({error:"url query parameter is required"}),{headers:{"Content-Type":"application/json"},status:404});let G=`${j.startsWith("http")?"":`http://localhost:${process.env.PORT||5173}`}${j}`,F=await fetch(G);if(!F.ok)return new Response(JSON.stringify({error:"Image not found",info:G}),{headers:{"Content-Type":"application/json"},status:404});let Q=Buffer.from(await F.arrayBuffer()),O=await T(az).resize(Q,{height:W,width:J,fit:Y,quality:z});F.headers.delete("Content-Type"),F.headers.delete("Content-Length");let K=new Headers(F.headers);return K.set("Content-Type","image/webp"),K.set("Content-Length",`${O.byteLength}`),new Response(new Uint8Array(O),{headers:K})})}}class az{static token="image";driver;constructor($={}){this.driver=$.driver??nz().driver}resize($,Z){return this.driver.resize($,Z)}}class z2 extends R0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(T(rz).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function fI($){return $}function tz(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function ez(){return{partialRendering:!0,localeRouting:"prefix",onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function TB($){return"run"in $}function MB($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function IB($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function LB($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function HB($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function $X($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function X2($,Z="",j=[]){let J={};function W(Y,z,X,G,F){let Q=Y==="/"?"":Y,O=Z==="/"?"":Z,K=(`${O}${Q}`===""?"/":`${O}${Q}`).replaceAll("//","/");if(!J[K])J[K]={};J[K][z.toUpperCase()]={exec:X,middleware:[...j,...G],...F?{source:F}:{}},J[K].OPTIONS={exec:()=>{let B=new C().ctx().headers;return new Response(null,{headers:B,status:204})},middleware:[]}}for(let[Y,z]of Object.entries($)){if(HB(z)){let X=z;for(let G of["GET","POST","PUT","DELETE"])W(Y,G,X.run.bind(X),X.middlewares);continue}if(TB(z)){let X=z,G=X.method,F=X.middlewares,Q=X.run.bind(X);if(W(Y,G,Q,F,X.source),$X(z))W(Y,"HEAD",Q,F,X.source)}if(MB(z))for(let[X,G]of Object.entries(z)){let F=G,Q=F.middlewares,O=F.run.bind(F);if(W(Y,X,O,Q,F.source),X==="get"&&$X(F))W(Y,"HEAD",O,Q,F.source)}if(LB(z)){let X=new z,G=X2(X.routes,`${Z}${Y}`,X.middlewares);for(let[F,Q]of Object.entries(G))J[F.replaceAll("//","/")]=Q}if(IB(z)){let{first:X,second:G}=z;for(let[F,Q]of Object.entries(X)){let O=Q.middlewares,K=Q.run.bind(Q),[D,...B]=Y.split("/").reverse();if(!D.startsWith(":"))throw Error("Resource route must end with a dynamic segment");W(B.reverse().join("/"),F,K,O,Q.source)}for(let[F,Q]of Object.entries(G)){let O=Q.middlewares,K=Q.run.bind(Q);W(Y,F,K,O,Q.source)}}}return Object.fromEntries(Object.entries(J).sort(([Y],[z])=>{let X=Y.split("/").length+Y.split(":").length,G=z.split("/").length+z.split(":").length;return X-G}))}function L8($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function G2($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function F2($){let Z=L8($);return Z.length>1?Z.replace(/\/$/,""):Z}function ZX($,Z){return Z.map((j)=>({...j,path:F2(G2($,j.path))}))}function H8($){let Z={};for(let[j,J]of Object.entries($))if("run"in J){let W=J;if("children"in W){let Y=new W.children,z=H8(Y.routes);for(let[X,{exec:G,middleware:F,segments:Q,features:O,static:K}]of Object.entries(z)){let D=G2(j,X),B=(U)=>W.run.call(W,U,j);Z[L8(D)]={exec:[B,...G],middleware:[...W.middlewares,...F],features:[...W.featureGates,...O],viewPath:W.viewPath,segments:[{path:F2(j),viewPath:W.viewPath,...W.alwaysRuns?{alwaysRun:!0}:{}},...ZX(j,Q)],...K?{static:K}:{}}}}else{let Y=(z)=>W.run.call(W,z,j);Z[L8(j)]={exec:[Y],middleware:W.middlewares,features:W.featureGates,viewPath:W.viewPath,segments:[{path:F2(j),viewPath:W.viewPath}],..."staticOptions"in W&&W.staticOptions?{static:W.staticOptions}:{}}}}else{let W=new J,Y=H8(W.routes);for(let[z,{exec:X,middleware:G,viewPath:F,segments:Q,features:O,static:K}]of Object.entries(Y)){let D=G2(j,z);Z[L8(D)]={exec:X,middleware:[...W.middlewares,...G],features:[...W.featureGates,...O],viewPath:F,segments:ZX(j,Q),...K?{static:K}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([j],[J])=>{let W=j.split("/").length+j.split(":").length,Y=J.split("/").length+J.split(":").length;return W-Y}))}var PB=Object.defineProperty,_=($,Z)=>PB($,"name",{value:Z,configurable:!0}),EZ=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,j,J,W,Y){this.type=$,this.name=Z,this.prefix=j,this.value=J,this.suffix=W,this.modifier=Y}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};_(EZ,"Part");var NB=/[$_\p{ID_Start}]/u,_B=/[$_\u200C\u200D\p{ID_Continue}]/u,K2=".*";function jX($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}_(jX,"isASCII");function D2($,Z=!1){let j=[],J=0;for(;J<$.length;){let W=$[J],Y=_(function(z){if(!Z)throw TypeError(z);j.push({type:"INVALID_CHAR",index:J,value:$[J++]})},"ErrorOrInvalid");if(W==="*"){j.push({type:"ASTERISK",index:J,value:$[J++]});continue}if(W==="+"||W==="?"){j.push({type:"OTHER_MODIFIER",index:J,value:$[J++]});continue}if(W==="\\"){j.push({type:"ESCAPED_CHAR",index:J++,value:$[J++]});continue}if(W==="{"){j.push({type:"OPEN",index:J,value:$[J++]});continue}if(W==="}"){j.push({type:"CLOSE",index:J,value:$[J++]});continue}if(W===":"){let z="",X=J+1;for(;X<$.length;){let G=$.substr(X,1);if(X===J+1&&NB.test(G)||X!==J+1&&_B.test(G)){z+=$[X++];continue}break}if(!z){Y(`Missing parameter name at ${J}`);continue}j.push({type:"NAME",index:J,value:z}),J=X;continue}if(W==="("){let z=1,X="",G=J+1,F=!1;if($[G]==="?"){Y(`Pattern cannot start with "?" at ${G}`);continue}for(;G<$.length;){if(!jX($[G],!1)){Y(`Invalid character '${$[G]}' at ${G}.`),F=!0;break}if($[G]==="\\"){X+=$[G++]+$[G++];continue}if($[G]===")"){if(z--,z===0){G++;break}}else if($[G]==="("&&(z++,$[G+1]!=="?")){Y(`Capturing groups are not allowed at ${G}`),F=!0;break}X+=$[G++]}if(F)continue;if(z){Y(`Unbalanced pattern at ${J}`);continue}if(!X){Y(`Missing pattern at ${J}`);continue}j.push({type:"REGEX",index:J,value:X}),J=G;continue}j.push({type:"CHAR",index:J,value:$[J++]})}return j.push({type:"END",index:J,value:""}),j}_(D2,"lexer");function U2($,Z={}){let j=D2($);Z.delimiter??="/#?",Z.prefixes??="./";let J=`[^${m0(Z.delimiter)}]+?`,W=[],Y=0,z=0,X="",G=new Set,F=_((P)=>{if(z<j.length&&j[z].type===P)return j[z++].value},"tryConsume"),Q=_(()=>F("OTHER_MODIFIER")??F("ASTERISK"),"tryConsumeModifier"),O=_((P)=>{let A=F(P);if(A!==void 0)return A;let{type:x,index:E}=j[z];throw TypeError(`Unexpected ${x} at ${E}, expected ${P}`)},"mustConsume"),K=_(()=>{let P="",A;for(;A=F("CHAR")??F("ESCAPED_CHAR");)P+=A;return P},"consumeText"),D=_((P)=>P,"DefaultEncodePart"),B=Z.encodePart||D,U="",V=_((P)=>{U+=P},"appendToPendingFixedValue"),M=_(()=>{U.length&&(W.push(new EZ(3,"","",B(U),"",3)),U="")},"maybeAddPartFromPendingFixedValue"),I=_((P,A,x,E,S)=>{let H=3;switch(S){case"?":H=1;break;case"*":H=0;break;case"+":H=2;break}if(!A&&!x&&H===3){V(P);return}if(M(),!A&&!x){if(!P)return;W.push(new EZ(3,"","",B(P),"",H));return}let L;x?x==="*"?L=K2:L=x:L=J;let m=2;L===J?(m=1,L=""):L===K2&&(m=0,L="");let u;if(A?u=A:x&&(u=Y++),G.has(u))throw TypeError(`Duplicate name '${u}'.`);G.add(u),W.push(new EZ(m,u,B(P),L,B(E),H))},"addPart");for(;z<j.length;){let P=F("CHAR"),A=F("NAME"),x=F("REGEX");if(!A&&!x&&(x=F("ASTERISK")),A||x){let S=P??"";Z.prefixes.indexOf(S)===-1&&(V(S),S=""),M();let H=Q();I(S,A,x,"",H);continue}let E=P??F("ESCAPED_CHAR");if(E){V(E);continue}if(F("OPEN")){let S=K(),H=F("NAME"),L=F("REGEX");!H&&!L&&(L=F("ASTERISK"));let m=K();O("CLOSE");let u=Q();I(S,H,L,m,u);continue}M(),O("END")}return W}_(U2,"parse");function m0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}_(m0,"escapeString");function O2($){return $&&$.ignoreCase?"ui":"u"}_(O2,"flags");function JX($,Z,j){return V2(U2($,j),Z,j)}_(JX,"stringToRegexp");function b$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}_(b$,"modifierToString");function V2($,Z,j={}){j.delimiter??="/#?",j.prefixes??="./",j.sensitive??=!1,j.strict??=!1,j.end??=!0,j.start??=!0,j.endsWith="";let J=j.start?"^":"";for(let X of $){if(X.type===3){X.modifier===3?J+=m0(X.value):J+=`(?:${m0(X.value)})${b$(X.modifier)}`;continue}Z&&Z.push(X.name);let G=`[^${m0(j.delimiter)}]+?`,F=X.value;if(X.type===1?F=G:X.type===0&&(F=K2),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?J+=`(${F})${b$(X.modifier)}`:J+=`((?:${F})${b$(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){J+=`(?:${m0(X.prefix)}(${F})${m0(X.suffix)})`,J+=b$(X.modifier);continue}J+=`(?:${m0(X.prefix)}`,J+=`((?:${F})(?:`,J+=m0(X.suffix),J+=m0(X.prefix),J+=`(?:${F}))*)${m0(X.suffix)})`,X.modifier===0&&(J+="?")}let W=`[${m0(j.endsWith)}]|$`,Y=`[${m0(j.delimiter)}]`;if(j.end)return j.strict||(J+=`${Y}?`),j.endsWith.length?J+=`(?=${W})`:J+="$",new RegExp(J,O2(j));j.strict||(J+=`(?:${Y}(?=${W}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=j.delimiter.indexOf(X)>-1)}return z||(J+=`(?=${Y}|${W})`),new RegExp(J,O2(j))}_(V2,"partsToRegexp");var W$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},CB={delimiter:".",prefixes:"",sensitive:!0,strict:!0},xB={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function WX($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}_(WX,"isAbsolutePathname");function T2($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}_(T2,"maybeStripPrefix");function YX($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}_(YX,"maybeStripSuffix");function M2($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}_(M2,"treatAsIPv6Hostname");var zX=["ftp","file","http","https","ws","wss"];function I2($){if(!$)return!0;for(let Z of zX)if($.test(Z))return!0;return!1}_(I2,"isSpecialScheme");function XX($,Z){if($=T2($,"#"),Z||$==="")return $;let j=new URL("https://example.com");return j.hash=$,j.hash?j.hash.substring(1,j.hash.length):""}_(XX,"canonicalizeHash");function GX($,Z){if($=T2($,"?"),Z||$==="")return $;let j=new URL("https://example.com");return j.search=$,j.search?j.search.substring(1,j.search.length):""}_(GX,"canonicalizeSearch");function FX($,Z){return Z||$===""?$:M2($)?P2($):H2($)}_(FX,"canonicalizeHostname");function QX($,Z){if(Z||$==="")return $;let j=new URL("https://example.com");return j.password=$,j.password}_(QX,"canonicalizePassword");function KX($,Z){if(Z||$==="")return $;let j=new URL("https://example.com");return j.username=$,j.username}_(KX,"canonicalizeUsername");function OX($,Z,j){if(j||$==="")return $;if(Z&&!zX.includes(Z))return new URL(`${Z}:${$}`).pathname;let J=$[0]=="/";return $=new URL(J?$:"/-"+$,"https://example.com").pathname,J||($=$.substring(2,$.length)),$}_(OX,"canonicalizePathname");function BX($,Z,j){return L2(Z)===$&&($=""),j||$===""?$:N2($)}_(BX,"canonicalizePort");function DX($,Z){return $=YX($,":"),Z||$===""?$:P8($)}_(DX,"canonicalizeProtocol");function L2($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}_(L2,"defaultPortForProtocol");function P8($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}_(P8,"protocolEncodeCallback");function UX($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}_(UX,"usernameEncodeCallback");function VX($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}_(VX,"passwordEncodeCallback");function H2($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}_(H2,"hostnameEncodeCallback");function P2($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}_(P2,"ipv6HostnameEncodeCallback");function N2($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}_(N2,"portEncodeCallback");function TX($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}_(TX,"standardURLPathnameEncodeCallback");function MX($){return $===""?$:new URL(`data:${$}`).pathname}_(MX,"pathURLPathnameEncodeCallback");function IX($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}_(IX,"searchEncodeCallback");function LX($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}_(LX,"hashEncodeCallback");var HX=class{#Y;#J=[];#Z={};#$=0;#W=1;#F=0;#X=0;#B=0;#D=0;#U=!1;constructor($){this.#Y=$}get result(){return this.#Z}parse(){for(this.#J=D2(this.#Y,!0);this.#$<this.#J.length;this.#$+=this.#W){if(this.#W=1,this.#J[this.#$].type==="END"){if(this.#X===0){this.#I(),this.#Q()?this.#j(9,1):this.#K()?this.#j(8,1):this.#j(7,0);continue}else if(this.#X===2){this.#O(5);continue}this.#j(10,0);break}if(this.#B>0)if(this.#x())this.#B-=1;else continue;if(this.#C()){this.#B+=1;continue}switch(this.#X){case 0:this.#L()&&this.#O(1);break;case 1:if(this.#L()){this.#A();let $=7,Z=1;this.#P()?($=2,Z=3):this.#U&&($=2),this.#j($,Z)}break;case 2:this.#T()?this.#O(3):(this.#M()||this.#K()||this.#Q())&&this.#O(5);break;case 3:this.#N()?this.#j(4,1):this.#T()&&this.#j(5,1);break;case 4:this.#T()&&this.#j(5,1);break;case 5:this.#S()?this.#D+=1:this.#f()&&(this.#D-=1),this.#_()&&!this.#D?this.#j(6,1):this.#M()?this.#j(7,0):this.#K()?this.#j(8,1):this.#Q()&&this.#j(9,1);break;case 6:this.#M()?this.#j(7,0):this.#K()?this.#j(8,1):this.#Q()&&this.#j(9,1);break;case 7:this.#K()?this.#j(8,1):this.#Q()&&this.#j(9,1);break;case 8:this.#Q()&&this.#j(9,1);break;case 9:break;case 10:break}}this.#Z.hostname!==void 0&&this.#Z.port===void 0&&(this.#Z.port="")}#j($,Z){switch(this.#X){case 0:break;case 1:this.#Z.protocol=this.#G();break;case 2:break;case 3:this.#Z.username=this.#G();break;case 4:this.#Z.password=this.#G();break;case 5:this.#Z.hostname=this.#G();break;case 6:this.#Z.port=this.#G();break;case 7:this.#Z.pathname=this.#G();break;case 8:this.#Z.search=this.#G();break;case 9:this.#Z.hash=this.#G();break;case 10:break}this.#X!==0&&$!==10&&([1,2,3,4].includes(this.#X)&&[6,7,8,9].includes($)&&(this.#Z.hostname??=""),[1,2,3,4,5,6].includes(this.#X)&&[8,9].includes($)&&(this.#Z.pathname??=this.#U?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#H($,Z)}#H($,Z){this.#X=$,this.#F=this.#$+Z,this.#$+=Z,this.#W=0}#I(){this.#$=this.#F,this.#W=0}#O($){this.#I(),this.#X=$}#V($){return $<0&&($=this.#J.length-$),$<this.#J.length?this.#J[$]:this.#J[this.#J.length-1]}#z($,Z){let j=this.#V($);return j.value===Z&&(j.type==="CHAR"||j.type==="ESCAPED_CHAR"||j.type==="INVALID_CHAR")}#L(){return this.#z(this.#$,":")}#P(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#T(){return this.#z(this.#$,"@")}#N(){return this.#z(this.#$,":")}#_(){return this.#z(this.#$,":")}#M(){return this.#z(this.#$,"/")}#K(){if(this.#z(this.#$,"?"))return!0;if(this.#J[this.#$].value!=="?")return!1;let $=this.#V(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#Q(){return this.#z(this.#$,"#")}#C(){return this.#J[this.#$].type=="OPEN"}#x(){return this.#J[this.#$].type=="CLOSE"}#S(){return this.#z(this.#$,"[")}#f(){return this.#z(this.#$,"]")}#G(){let $=this.#J[this.#$],Z=this.#V(this.#F).index;return this.#Y.substring(Z,$.index)}#A(){let $={};Object.assign($,W$),$.encodePart=P8;let Z=JX(this.#G(),void 0,$);this.#U=I2(Z)}};_(HX,"Parser");var Q2=["protocol","username","password","hostname","port","pathname","search","hash"],J$="*";function B2($,Z){if(typeof $!="string")throw TypeError("parameter 1 is not of type 'string'.");let j=new URL($,Z);return{protocol:j.protocol.substring(0,j.protocol.length-1),username:j.username,password:j.password,hostname:j.hostname,port:j.port,pathname:j.pathname,search:j.search!==""?j.search.substring(1,j.search.length):void 0,hash:j.hash!==""?j.hash.substring(1,j.hash.length):void 0}}_(B2,"extractValues");function B1($,Z){return Z?AZ($):$}_(B1,"processBaseURLString");function fZ($,Z,j){let J;if(typeof Z.baseURL=="string")try{J=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=B1(J.protocol.substring(0,J.protocol.length-1),j)),!j&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=B1(J.username,j)),!j&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=B1(J.password,j)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=B1(J.hostname,j)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=B1(J.port,j)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=B1(J.pathname,j)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=B1(J.search.substring(1,J.search.length),j)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&Z.hash===void 0&&($.hash=B1(J.hash.substring(1,J.hash.length),j))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=DX(Z.protocol,j)),typeof Z.username=="string"&&($.username=KX(Z.username,j)),typeof Z.password=="string"&&($.password=QX(Z.password,j)),typeof Z.hostname=="string"&&($.hostname=FX(Z.hostname,j)),typeof Z.port=="string"&&($.port=BX(Z.port,$.protocol,j)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,J&&!WX($.pathname,j)){let W=J.pathname.lastIndexOf("/");W>=0&&($.pathname=B1(J.pathname.substring(0,W+1),j)+$.pathname)}$.pathname=OX($.pathname,$.protocol,j)}return typeof Z.search=="string"&&($.search=GX(Z.search,j)),typeof Z.hash=="string"&&($.hash=XX(Z.hash,j)),$}_(fZ,"applyInit");function AZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}_(AZ,"escapePatternString");function PX($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}_(PX,"escapeRegexpString");function NX($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let j=".*",J=`[^${PX(Z.delimiter)}]+?`,W=/[$_\u200C\u200D\p{ID_Continue}]/u,Y="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){Y+=AZ(X.value);continue}Y+=`{${AZ(X.value)}}${b$(X.modifier)}`;continue}let G=X.hasCustomName(),F=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),Q=z>0?$[z-1]:null,O=z<$.length-1?$[z+1]:null;if(!F&&G&&X.type===1&&X.modifier===3&&O&&!O.prefix.length&&!O.suffix.length)if(O.type===3){let K=O.value.length>0?O.value[0]:"";F=W.test(K)}else F=!O.hasCustomName();if(!F&&!X.prefix.length&&Q&&Q.type===3){let K=Q.value[Q.value.length-1];F=Z.prefixes.includes(K)}F&&(Y+="{"),Y+=AZ(X.prefix),G&&(Y+=`:${X.name}`),X.type===2?Y+=`(${X.value})`:X.type===1?G||(Y+=`(${J})`):X.type===0&&(!G&&(!Q||Q.type===3||Q.modifier!==3||F||X.prefix!=="")?Y+="*":Y+=`(${j})`),X.type===1&&G&&X.suffix.length&&W.test(X.suffix[0])&&(Y+="\\"),Y+=AZ(X.suffix),F&&(Y+="}"),X.modifier!==3&&(Y+=b$(X.modifier))}return Y}_(NX,"partsToPattern");var _2=class{#Y;#J={};#Z={};#$={};#W={};#F=!1;constructor($={},Z,j){try{let J;if(typeof Z=="string"?J=Z:j=Z,typeof $=="string"){let X=new HX($);if(X.parse(),$=X.result,J===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=J}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(J)throw TypeError("parameter 1 is not of type 'string'.")}typeof j>"u"&&(j={ignoreCase:!1});let W={ignoreCase:j.ignoreCase===!0},Y={pathname:J$,protocol:J$,username:J$,password:J$,hostname:J$,port:J$,search:J$,hash:J$};this.#Y=fZ(Y,$,!0),L2(this.#Y.protocol)===this.#Y.port&&(this.#Y.port="");let z;for(z of Q2){if(!(z in this.#Y))continue;let X={},G=this.#Y[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,W$),X.encodePart=P8;break;case"username":Object.assign(X,W$),X.encodePart=UX;break;case"password":Object.assign(X,W$),X.encodePart=VX;break;case"hostname":Object.assign(X,CB),M2(G)?X.encodePart=P2:X.encodePart=H2;break;case"port":Object.assign(X,W$),X.encodePart=N2;break;case"pathname":I2(this.#J.protocol)?(Object.assign(X,xB,W),X.encodePart=TX):(Object.assign(X,W$,W),X.encodePart=MX);break;case"search":Object.assign(X,W$,W),X.encodePart=IX;break;case"hash":Object.assign(X,W$,W),X.encodePart=LX;break}try{this.#W[z]=U2(G,X),this.#J[z]=V2(this.#W[z],this.#Z[z],X),this.#$[z]=NX(this.#W[z],X),this.#F=this.#F||this.#W[z].some((F)=>F.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#Y[z]}'.`)}}}catch(J){throw TypeError(`Failed to construct 'URLPattern': ${J.message}`)}}get[Symbol.toStringTag](){return"URLPattern"}test($={},Z){let j={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return!1;try{typeof $=="object"?j=fZ(j,$,!1):j=fZ(j,B2($,Z),!1)}catch{return!1}let J;for(J of Q2)if(!this.#J[J].exec(j[J]))return!1;return!0}exec($={},Z){let j={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return;try{typeof $=="object"?j=fZ(j,$,!1):j=fZ(j,B2($,Z),!1)}catch{return null}let J={};Z?J.inputs=[$,Z]:J.inputs=[$];let W;for(W of Q2){let Y=this.#J[W].exec(j[W]);if(!Y)return null;let z={};for(let[X,G]of this.#Z[W].entries())if(typeof G=="string"||typeof G=="number"){let F=Y[X+1];z[G]=F}J[W]={input:j[W]??"",groups:z}}return J}static compareComponent($,Z,j){let J=_((X,G)=>{for(let F of["type","modifier","prefix","value","suffix"]){if(X[F]<G[F])return-1;if(X[F]===G[F])continue;return 1}return 0},"comparePart"),W=new EZ(3,"","","","",3),Y=new EZ(0,"","","","",3),z=_((X,G)=>{let F=0;for(;F<Math.min(X.length,G.length);++F){let Q=J(X[F],G[F]);if(Q)return Q}return X.length===G.length?0:J(X[F]??W,G[F]??W)},"comparePartList");return!Z.#$[$]&&!j.#$[$]?0:Z.#$[$]&&!j.#$[$]?z(Z.#W[$],[Y]):!Z.#$[$]&&j.#$[$]?z([Y],j.#W[$]):z(Z.#W[$],j.#W[$])}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.#F}};_(_2,"URLPattern");function S3($,Z){for(let[j,J]of Object.entries($)){let W=new _2({pathname:j});if(W.test({pathname:Z}))return{routePath:j,params:W.exec({pathname:Z})?.pathname.groups??{},route:J}}return null}var w$={startIndex:0,carriedViews:[]};function _X($,Z){let j=K0($.path,Z);return j.includes("*")?null:j}function SB($,Z){if(!$)return w$;if($.search!==Z.search)return w$;let j=Math.min($.segments.length,Z.segments.length-1),J=0;while(J<j){let W=$.segments[J],Y=Z.segments[J];if(Y.alwaysRun)break;if(W.viewPath!==Y.viewPath)break;let z=_X(W,$.params),X=_X(Y,Z.params);if(z===null||X===null||z!==X)break;J++}if(J===0)return w$;return{startIndex:J,carriedViews:Z.segments.slice(0,J).map(({viewPath:W})=>W)}}function fB($,Z){let[,j,...J]=$.split("/");if(!Z.includes(j))return $;let W=`/${J.join("/")}`;return W==="/"?"/":W.replace(/\/$/,"")}function CX($){let{flatViewRoutes:Z,supportedLocales:j,from:J,origin:W,to:Y}=$;if(!J)return w$;let z;try{z=new URL(J,W)}catch{return w$}if(z.origin!==W)return w$;let X=S3(Z,fB(z.pathname,j));if(!X)return w$;return SB({segments:X.route.segments,params:X.params,search:z.search},Y)}var C2="x-gemi-from";import{createElement as b1,Fragment as $G}from"react";function AB($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function N8($){let Z={};for(let[j,J]of Object.entries($))if("run"in J){let W=J.viewPath;if("children"in J){Z[j]=[W];let Y=new J.children,z=N8(Y.routes);for(let[X,G]of Object.entries(z)){let F=j==="/"?X:`${j}${X}`,Q=X==="/"&&j!=="/"?j:F;Z[Q]=[W,...G]}if(Z[j].length===1)delete Z[j]}else Z[j]=[W]}else{let W=new J,Y=N8(W.routes);for(let[z,X]of Object.entries(Y)){let G=j==="/"?z:`${j}${z}`,F=z==="/"&&j!=="/"?j:G;Z[F]=X}}return Object.fromEntries(Object.entries(Z).map(([j,J])=>[AB(j),J]))}function _8($,Z){let[j,J]=Z,W=$.find(([Y])=>Y===j);if(!W){$.push([j,[...J]]);return}for(let Y of J)_8(W[1],Y)}function C8($){let Z=[];for(let[j,J]of Object.entries($))if("run"in J){let W=J.viewPath;if(W==="__")continue;if(W==="REDIRECT")continue;if(W==="FILE")continue;if("children"in J){let Y=new J.children,z=C8(Y.routes);_8(Z,[W,z])}else _8(Z,[W,[]])}else{let W=new J,Y=C8(W.routes);for(let z of Y)_8(Z,z)}return Z}function x2($){let Z=[];for(let[j,J]of $)Z.push(j,...x2(J).flat());return Array.from(new Set(Z))}class Y$ extends g{static getFacadeAccessor(){return i}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=N.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(N.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??Y$.locale(),$.timeZone??Y$.timeZone())}static setLocale($=Y$.locale(),Z={}){let j=this.getFacadeRoot(),J=$;if(!j.supportedLocales.includes($))J=j.defaultLocale;let W=N.getStore();if(Z.cookie!==!1)W.setCookie("i18n-locale",J,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return W.setLocale(J),J}}class S2{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}var EB=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),RB=new Set(["svg","math"]);function xX($){return $===32||$===9||$===10||$===12||$===13}function SX($){return $>=65&&$<=90||$>=97&&$<=122}function x8($){return $>=65&&$<=90?$+32:$}function fX(){let $="data",Z="",j=!1,J="",W=0,Y=0,z=!1,X=0,G=0,F=()=>$==="data"&&X===0&&G===0,Q=()=>{if(!j&&EB.has(Z)){$="rawText",J=`</${Z}`,W=0,Z="";return}if($="data",Z==="template")if(j)X=Math.max(0,X-1);else X+=1;else if(RB.has(Z)){if(j)G=Math.max(0,G-1);else if(!z)G+=1}Z=""},O=(K)=>{switch($){case"data":if(K===60)$="tagOpen";return;case"tagOpen":if(K===33)$="bang",Y=0;else if(K===47)$="endTagOpen";else if(SX(K))$="tagName",j=!1,z=!1,Z=String.fromCharCode(x8(K));else if(K===63)$="bogus";else if(K===60)$="tagOpen";else $="data";return;case"endTagOpen":if(SX(K))$="tagName",j=!0,z=!1,Z=String.fromCharCode(x8(K));else if(K===62)$="data";else $="bogus";return;case"tagName":if(xX(K)||K===47)$="inTag",z=K===47;else if(K===62)Q();else Z+=String.fromCharCode(x8(K));return;case"inTag":if(K===62){Q();return}if(z=K===47,K===34)$="attrDouble";else if(K===39)$="attrSingle";return;case"attrDouble":if(K===34)$="inTag";z=!1;return;case"attrSingle":if(K===39)$="inTag";z=!1;return;case"bang":if(K===45){if(Y+=1,Y===2)$="comment",Y=0}else if(K===62)$="data";else $="bogus";return;case"bogus":if(K===62)$="data";return;case"comment":if(K===45)Y=Y<2?Y+1:2;else if(K===62&&Y>=2)$="data",Y=0;else Y=0;return;case"rawText":{if(W<J.length){if(x8(K)===J.charCodeAt(W))W+=1;else W=K===60?1:0;return}if(K===62)$="data",Z="";else if(xX(K)||K===47)$="inTag",Z="";else W=K===60?1:0;return}}};return{scanToInsertionPoint(K){for(let D=0;D<K.length;D++){if(F())return D;O(K[D])}return K.length},write(K){for(let D=0;D<K.length;D++)O(K[D])},isSafe:F}}function E1($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function bB($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${E1([$.path,$.variantKey,$.data])})</script>`}function wB($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${E1([$.id,$.locale,$.strings])})</script>`}function f2($,Z,j={},J){let W=new TextEncoder,Y=[],z=!1,X=!1,G=()=>{if(X)return;X=!0,j.onClose?.()};Z.onSettle((B)=>{if(B.status!=="resolved")return;Y.push(bB(B))}),J?.onUse((B)=>{Y.push(wB(B))});let F=$.getReader(),Q=fX(),O=(B,U)=>{B.enqueue(U),j.onChunk?.(U)},K=(B)=>{while(Y.length>0){let U=W.encode(Y.shift());Q.write(U),O(B,U)}},D=(B,U)=>{if(Y.length===0){Q.write(U),O(B,U);return}let V=Q.scanToInsertionPoint(U);if(V>0)O(B,U.subarray(0,V));if(Q.isSafe())K(B);let M=U.subarray(V);if(M.length>0)Q.write(M),O(B,M)};return new ReadableStream({async pull(B){let U;try{U=await F.read()}catch(I){throw G(),I}let{done:V,value:M}=U;if(V){K(B),B.close(),G();return}if(!z){if(z=!0,Q.write(M),O(B,M),j.onShell?.(),Q.isSafe())K(B);return}D(B,M)},cancel(B){return G(),F.cancel(B)}})}var kB=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function S8($){if(!$)return!1;return kB.test($)}async function EX($,Z=()=>{}){let j=N.getStore(),J=j?.req??null,W=null;if(J?.rawRequest?.url)try{W=new URL(J.rawRequest.url).pathname}catch{W=null}return{user:j?.user??null,attributes:await yB($,Z),request:{path:W,routePath:J?.routePath??null,locale:j?.locale??null},anonymousId:AX(),isBot:S8(J?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function RX($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function yB($,Z){if(!$.context)return{};try{let j=N.getStore();return await $.context(j?.req??null)??{}}catch(j){return Z(`The \`context\` hook in app/config/features.ts threw; evaluating with no attributes. ${j instanceof Error?j.message:String(j)}`),{}}}function bX($,Z){return`${$}:${Z}`}function A2($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),j=Number.parseInt(Z.slice(0,8),16);return Math.floor(j/4294967296*1e4)}function wX($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function kX($,Z,j,J){if(J.unavailable)return{value:!1,reason:"unavailable"};if(J.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let Y;try{Y=Z.when(j)}catch(z){return J.warn?.(`The \`when\` for feature "${$}" threw; treating it as off. ${z instanceof Error?z.message:String(z)}`),{value:!1,reason:"error"}}if(typeof Y==="boolean")return{value:Y,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(j.isBot)return{value:!1,reason:"bot"};let W=vB($,Z,j,J.buckets);return wX(W,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function qB($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function vB($,Z,j,J){let W=bX(Z.salt??$,qB(j));if(!J)return A2(W);let Y=J.get(W);if(Y!==void 0)return Y;let z=A2(W);return J.set(W,z),z}class yX 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 E2{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,j,J=()=>{}){this.source=$;this.declared=Z;this.ttlMs=j;this.warn=J}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 yX(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:j}=this.readRows($);return this.snapshot={active:Z,audit:j,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,j=new Map;for(let J of $??[]){let W=typeof J?.key==="string"?J.key:null;if(!W){this.warn("Ignoring a feature row with no `key`.");continue}if(!(W in this.declared)){this.warn(`Feature row "${W}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(W,J.active===!0);let Y=gB(J);if(Y)j.set(W,Y)}return{active:Z,audit:j}}handleFailure($){let Z=$ instanceof Error?$.message:String($),j=Date.now();if(this.lastError=$,this.retryAfter=j+this.ttlMs,j-this.lastFailureLoggedAt>=this.ttlMs)this.lastFailureLoggedAt=j,this.warn(`Could not load feature switches: ${Z}`);if(this.snapshot)return this.snapshot;return this.snapshot={active:new Map,audit:new Map,loadedAt:j,unavailable:!0},this.snapshot}}function gB($){let Z={},j=$.updatedBy;if(typeof j==="string")Z.updatedBy=j;else if(j===null)Z.updatedBy=null;let J=$.updatedAt;if(J instanceof Date||typeof J==="string"||typeof J==="number"){let W=J instanceof Date?J:new Date(J);if(!Number.isNaN(W.getTime()))Z.updatedAt=W}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class mB{}class pB 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 R2 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 qX 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 vX{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 RZ{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new E2($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:j}=await this.switches();return{unavailable:j,features:Object.entries(this.declared).map(([J,W])=>({key:J,describe:W.describe,rollout:W.rollout,targeted:W.when!==void 0,serverOnly:W.serverOnly,salt:W.salt,active:$.get(J),...Z.get(J)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{N.getStore()?.featureEvaluations?.clear()}}async set($,Z,j={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new qX(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let J=hB(j.actor),W=this.config.source;if(typeof W.write!=="function")throw new R2(W.constructor?.name||"an anonymous source");let{actorRecorded:Y}=await W.write($,Z,{actor:J});if(J!==null&&!Y&&!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 vX(this,RX($))}async evaluateIn($,Z,j){let J=this.memoFor(Z),W=J?.get($);if(W)return W;let Y=this.declared[$];if(!Y)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),G=kX($,Y,Z,{active:z,unavailable:X,buckets:j,warn:this.log});return J?.set($,G),this.notify($,G,Z),G}async evaluateAllIn($,Z,j){let J={};for(let[W,Y]of Object.entries(this.declared)){if(j.clientOnly&&Y.serverOnly)continue;J[W]=(await this.evaluateIn(W,$,Z)).value}return J}async switches(){if(!this.config.enabled||Object.keys(this.declared).length===0)return{active:new Map,audit:new Map,unavailable:!1};let $=await this.store.get();return{active:$.active,audit:$.audit,unavailable:$.unavailable}}async switchFor($){if(!this.config.enabled)return{active:!1,unavailable:!1};let Z=await this.store.get();return{active:Z.active.get($),unavailable:Z.unavailable}}async requestContext(){let $=N.getStore();if($?.featureContext)return $.featureContext;let Z=await EX(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=N.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=N.getStore();if(!$)return new Map;return $.featureBuckets??=new Map,$.featureBuckets}notify($,Z,j){if(!this.config.onEvaluate)return;try{this.config.onEvaluate($,Z,j)}catch(J){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${J instanceof Error?J.message:String(J)}`)}}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 hB($){if($===void 0||$===null)return null;if(typeof $==="string"){if($.length>0)return $}else if(typeof $==="object"){let{publicId:Z,id:j}=$;if(typeof Z==="string"&&Z.length>0)return Z;if(typeof j==="string"&&j.length>0||typeof j==="number")return String(j)}throw TypeError("Features.set() was given an `actor` that identifies nobody. Pass a string, or a user with a `publicId` or an `id`.")}function gX($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var cB=50;class bZ{fetcher;entries=new Map;settleListener=null;failListener=null;shellAt=null;settledBacklog=[];shipped=new Set;requestStartedAt=performance.now();renderStartedAt=null;discoveryHintsMuted=!1;constructor($){this.fetcher=$}elapsed(){return Math.round(performance.now()-this.requestStartedAt)}keyFor($,Z){return[$,Z].filter((j)=>j.length>0).join("?")}markRenderStart(){if(this.renderStartedAt===null)this.renderStartedAt=performance.now()}markShell(){if(this.shellAt===null)this.shellAt=this.elapsed()}summarize($){let Z=this.elapsed();return{shellAt:this.shellAt??Z,settledAt:Z,aborted:$,queries:Array.from(this.entries.values(),(j)=>({path:j.path,variantKey:j.variantKey,startedAt:j.startedAt,settledAt:j.settledAt,status:j.status,source:j.source}))}}onQueryFail($){this.failListener=$}muteDiscoveryHints(){this.discoveryHintsMuted=!0}maybeLogLateDiscovery($){if(!$.lateBy||this.discoveryHintsMuted)return;if($.status!=="resolved")return;if(Bun.env.NODE_ENV==="production")return;let Z="";try{let W=JSON.stringify($.data)?.length??0;Z=W>=1024?`${(W/1024).toFixed(1)} kB`:`${W} B`}catch{Z="an unserializable payload"}let j=($.settledAt??0)-$.startedAt,J=$.variantKey?`, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams($.variantKey)))} }`:"";console.warn(`[gemi] useQuery("${$.patternPath}") was discovered ${$.lateBy}ms into the `+`server render \u2014 under a suspended segment, so its fetch (${j}ms, resolved ${Z}) could not overlap the others. It still streamed. If the query belongs on this route, \`Query.prefetch("${$.patternPath}"${J})\` in the view `+"handler starts it at request time \u2014 but note prefetched data is also re-fetched and "+`streamed into every client-side navigation payload for the route, even when the client already holds it, so weigh that bandwidth against the ${Z}. If the data is only needed conditionally (a closed popover, a hidden tab), \`{ lazy: true }\` + \`trigger()\` avoids running it here at all. \`Query.noPrefetch()\` in the handler marks the omission intentional and silences this hint for the route.`)}read($,Z){return this.entries.get(this.keyFor($,Z))}ensure($,Z={},j="render"){let J=Z.params??{},W=new URLSearchParams(gX(Z.search??{}));W.delete("json"),W.sort();let Y=K0($,J),z=W.toString(),X=this.keyFor(Y,z),G=this.entries.get(X);if(G)return G;let F;if(j==="render"&&this.renderStartedAt!==null){let D=Math.round(performance.now()-this.renderStartedAt);if(D>cB)F=D}let Q,O=new Promise((D)=>{Q=D}),K={path:Y,patternPath:$,variantKey:z,lateBy:F,status:"pending",promise:O,source:j,startedAt:this.elapsed()};return this.entries.set(X,K),this.fetcher($,J,W).then((D)=>{K.status="resolved",K.data=D},(D)=>{K.status="rejected",K.error=D}).then(()=>{if(K.settledAt=this.elapsed(),this.maybeLogLateDiscovery(K),K.status==="rejected"&&this.failListener)this.failListener(K);if(this.settleListener)this.settleListener(K);else this.settledBacklog.push(K);Q()}),K}async allSettled(){let $=0;while($!==this.entries.size)$=this.entries.size,await Promise.all(Array.from(this.entries.values(),(Z)=>Z.promise))}snapshotResolved(){let $={};for(let[Z,j]of this.entries){if(j.status!=="resolved")continue;this.shipped.add(Z),$[j.path]??={},$[j.path][j.variantKey]=j.data}return $}onSettle($){this.settleListener=(j)=>{if(this.shipped.has(this.keyFor(j.path,j.variantKey)))return;$(j)};let Z=this.settledBacklog;this.settledBacklog=[];for(let j of Z)this.settleListener(j)}}class R1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,j,J,W){super(typeof J?.message==="string"?J.message:`Request to /api${$} failed with status ${j}`);this.path=$;this.variantKey=Z;this.status=j;this.body=J;this.retryAfter=W;this.name="QueryError"}}function wZ(){let $=JSON.stringify({error:m1("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function b2(){return{status:403,error:{message:"Forbidden"}}}function f3($){let Z=kZ.getStore();return(j,J,W)=>{let Y=new URL($.url).origin,z=[K0(j,J),W.toString()].filter((Q)=>Q.length>0).join("?"),X=new Request(`${Y}/${z}`,{headers:$.headers,signal:$.signal}),G=mX($);if(G)yZ(X,G);let F=new C(X,J);return kZ.run(Z,()=>N.run(F,async()=>{try{let Q=await T(j1).dispatchers(G).api.getRouteData(j);if(i$(Q)){if(!Q.ok)throw new R1(K0(j,J),W.toString(),Q.status,Q.body);return Q.body}if(Q instanceof Response){let O=await Q.json().catch(()=>null);if(!Q.ok)throw new R1(K0(j,J),W.toString(),Q.status,O);return O}return Q}catch(Q){if(Q instanceof R1)throw Q;let O=new R1(K0(j,J),W.toString(),500,{message:Q instanceof Error?Q.message:String(Q)});throw O.cause=Q,O}}))}}var dB=new Set(["script","style","template","title"]),uB=/\shidden([\s=/]|$)/i,lB=/"[^"]*"|'[^']*'/g;function iB($){let Z=0,j=0,J=0,W=0;while(W<$.length){let Y=$.indexOf("<",W),z=Y===-1?$.length:Y;if(z>W){let O=$.slice(W,z).replace(/\s+/g,"").length;if(J>0)j+=O;else Z+=O}if(Y===-1)break;if($.startsWith("<!--",Y)){let O=$.indexOf("-->",Y+4);W=O===-1?$.length:O+3;continue}let X=$.indexOf(">",Y);if(X===-1)break;let G=$.slice(Y+1,X);W=X+1;let F=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(G)?.[1]?.toLowerCase();if(!F)continue;let Q=G.startsWith("/");if(!Q&&dB.has(F)&&!G.endsWith("/")){let O=$.indexOf(`</${F}`,W);W=O===-1?$.length:O;continue}if(F!=="div")continue;if(Q){if(J>0)J-=1}else if(J>0)J+=1;else if(uB.test(G.replace(lB,'""')))J=1}return{shellChars:Z,deferredChars:j}}var sB=1000,oB=64;function nB($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function aB($,Z){if(Z.deferredChars<sB)return null;if(Z.shellChars>=oB)return null;return`[gemi] GET ${$} streams ${nB(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 pX($=console.warn){let Z=new Set;return{shouldObserve(j){return!Z.has(j)},report(j,J){if(Z.has(j))return;let W=aB(j,J);if(!W)return;Z.add(j),$(W)}}}function hX(){let $=new TextDecoder,Z="";return{onChunk(j){Z+=$.decode(j,{stream:!0})},measure(){return Z+=$.decode(),iB(Z)}}}function cX($,Z,j=1e4,J){let W=new TextEncoder,Y=()=>{};return new ReadableStream({start(z){let X=!1,G=(Q)=>{if(X)return;X=!0,clearTimeout(F);try{z.close()}catch{}J?.({aborted:Q})};Y=G,z.enqueue(W.encode(`${JSON.stringify($)}
|
|
14
|
-
`)),Z.onSettle((Q)=>{if(X||Q.status!=="resolved")return;z.enqueue(W.encode(`${JSON.stringify([Q.path,Q.variantKey,Q.data])}
|
|
15
|
-
`))});let F=setTimeout(()=>G(!0),j);Z.allSettled().then(()=>G(!1),()=>G(!1))},cancel(){Y(!1)}})}import{Fragment as yL,createContext as rB,createElement as qL,lazy as vL,use as gL,useContext as mL}from"react";function dX($){return{islands:[],render:$,instances:new WeakMap,count:0}}var A3="gemi-slot",uX="data-slot",lX="data-gemi-slot";var tB=Symbol.for("gemi.staticRender"),iX=globalThis[tB]??=rB(null);import{createHash as nX}from"crypto";var w2='var r=document,i=window,a=history;i.__gemi_nav?.d();var L=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:L.signal,...s}),q=i.__gemi_nav={d:()=>L.abort()},v=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},D=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},R=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")v(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>v(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),v(n,s)});for(let m of n.children)l.observe(m)}}},O=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(O)?.content,C=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},y={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,N=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},Y=(t)=>{let e=r.body,n=t.body,s=D(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),R(e,s)},H=async(t,e)=>{let n=++b,s=!e&&y[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||C(d)!=C(r))throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),Y(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)N(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),y[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=y[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(y[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(O)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();R(r,D(r));_(!0);';var eB="gemi-islands",sL=`'sha256-${nX("sha256").update(k2).digest("base64")}'`;function sX($,Z,j,J){if(!j)return $;let W=J?$.lastIndexOf(Z):$.indexOf(Z);return W===-1?$+j:$.slice(0,W)+j+$.slice(W)}var oX=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),oL=`'sha256-${nX("sha256").update(w2).digest("base64")}'`,$D='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',ZD="gemi-static";function aX($,Z,j,J,W){let Y=new Set,z=[];if(j)z=Z.islands.map((K)=>{let D=K.module?j(K.module):void 0;if(!D)return console.error(`[gemi] island ${K.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(K.load==="eager")for(let B of D.preload)Y.add(B);return{s:D.src,e:K.export,l:K.load}});let X=z.some((K)=>K!==null);if(!X&&!W)return $;let F=(W?`<meta name="${ZD}" content="${oX(W.identity)}"${W.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...Y].map((K)=>`<link rel="modulepreload" href="${oX(K)}"/>`).join(""),Q=W?w2:k2,O=(X?`<script type="application/json" id="${eB}">${E1({i:z})}</script>`:"")+`<script type="module">${J?$D+Q:Q}</script>`;return sX(sX($,"</head>",F,!1),"</body>",O,!0)}function jD($,Z){let j=/<(\/?)template\b[^>]*>/gi;j.lastIndex=Z;let J=0;for(let W=j.exec($);W;W=j.exec($))if(J+=W[1]?-1:1,J===0)return j.lastIndex;return-1}function rX($){let Z=`<template ${lX}="`;for(let j=$.lastIndexOf(Z);j!==-1;j=$.lastIndexOf(Z)){let J=jD($,j);if(J===-1)break;let W=j+Z.length,Y=$.slice(W,$.indexOf('"',W)),z=$.indexOf(">",W)+1,X=$.slice(z,J-11);$=$.slice(0,j)+$.slice(J);let G=`<${A3} ${uX}="${Y}" style="display:contents"></${A3}>`;$=$.split(G).join(`<${A3} style="display:contents">${X}</${A3}>`)}return $}function tX($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function eX($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}var JD=async()=>(await import("./chunk-ycsrpf47.js")).default,y2,E3=async(...$)=>{return y2??=import("react-dom/server.browser").catch((Z)=>{throw y2=void 0,Z}),(await y2).renderToReadableStream(...$)},ZG=1e4,jG="no-locale",WD=`
|
|
16
|
-
!function(){try{var d=document.documentElement,c=d.classList;
|
|
17
|
-
c.remove('light','dark');
|
|
18
|
-
var e=localStorage.getItem('theme');
|
|
19
|
-
if('system'===e||(!e&&'system'===defaultTheme)){
|
|
20
|
-
var t='(prefers-color-scheme: dark)',m=window.matchMedia(t);
|
|
21
|
-
if(m.media!==t||m.matches){d.style.colorScheme='dark';c.add('dark')}
|
|
22
|
-
else{d.style.colorScheme='light';c.add('light')}
|
|
23
|
-
}else if(e){
|
|
24
|
-
c.add(e||'')
|
|
25
|
-
}}catch(e){}}()
|
|
26
|
-
`;async function YD($,Z,j){let J=`${j==="italic"?"italic,":""}wght@${j==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${J}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var g2="/assets";function zD($){return $===g2||$.startsWith(`${g2}/`)}function XD($){let Z=$.filter(zD);if(Z.length>0){let j=Z.length>1;throw Error(`View route path${j?"s":""} ${Z.map((J)=>`"${J}"`).join(", ")} use${j?"":"s"} the reserved "${g2}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function GD($){let Z=T(j1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function q2($){let{status:Z=400,error:j,body:J,...W}=$;return new Response(J??j?.message,{...W,status:Z})}function FD($){let{status:Z=400,data:j,directive:J,headers:W}=$;return new Response(JSON.stringify({data:j,directive:J}),{headers:W,status:Z})}class R3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];staticRoutes=[];root=null;shellReporter=pX();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;constructor($){let Z=ez();this.partialRendering=$.partialRendering??Z.partialRendering,this.localeRouting=$.localeRouting??Z.localeRouting,this.hooks={onRequestStart:$.onRequestStart??Z.onRequestStart,onRequestEnd:$.onRequestEnd??Z.onRequestEnd,onRequestFail:$.onRequestFail??Z.onRequestFail,onStreamComplete:$.onStreamComplete??Z.onStreamComplete};let j={"/":$.rootRouter,"/auth":$2};this.flatViewRoutes=H8(j),XD(Object.keys(this.flatViewRoutes)),this.routeManifest=N8(j),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,J])=>J.at(-1)!=="FILE")),this.componentTree=C8(j),this.flatComponentTree=x2(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,J])=>J.static).map(([J])=>J);for(let J of this.staticRoutes){let W=this.flatViewRoutes[J].static?.layout;if(W&&!this.flatComponentTree.includes(W))this.flatComponentTree.push(W)}this.root=$.root}async passesFeatureGates($){let Z=T(RZ);for(let j of $)if(!await Z.enabled(j))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)f8();return await this.hooks.onRequestEnd($)}completeStream($,Z){let j=(J)=>{k$.error(J?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(J)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(j)}catch(J){j(J)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:j,views:J,routeKey:W}=$,Y=()=>{let G=new Set(Z?.preload??[]);for(let F of J)for(let Q of j?.[F]??[])G.add(Q);return[...G].map((F)=>b1("link",{key:`modulepreload:${F}`,rel:"modulepreload",href:F}))};if(!j)return Y();let z=this.preloadCache.get(j);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(j,z);let X=z.byRoute.get(W);if(!X)X=Y(),z.byRoute.set(W,X);return X}async renderStatic($){let{req:Z,runInRequestScope:j,staticView:J,currentViews:W,data:Y,serverQueries:z,headers:X}=$,G;if(J.layout){if(G=$.viewImportMap[J.layout],!G)throw Error(`The static layout "${J.layout}" was not found. It is a view path: a file at app/views/${J.layout}.tsx whose default export renders the document.`)}let F=await $.getStyles(W,{static:!0,layout:J.layout});z.markRenderStart();let Q=v2(),O=new AbortController,K=setTimeout(()=>O.abort(),ZG),D=(U)=>{if(Bun.env.NODE_ENV!=="production")console.error(U)},B=dX(async(U,V)=>{let M=await E3(U,{signal:O.signal,identifierPrefix:V,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:D});return await M.allReady.catch(()=>{}),await new Response(M).text()});try{let U;if(J.navigation){let I=J.navigation===!0?{}:J.navigation,P=I.version?String(await j(()=>I.version(Z))):"";U={identity:[J.layout??"",$.buildId??"",P].join("|"),prefetch:I.prefetch==="none"?"none":"intent"}}let V=await E3(b1(iX.Provider,{value:B,children:b1($G,{children:[...F,b1(this.root,{data:Y,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:Q,rootLayout:G,key:"root"})]})}),{signal:O.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:D});await V.allReady.catch(()=>{});let M=rX(await new Response(V).text());return new Response(aX(M,B,$.resolveIsland,Bun.env.NODE_ENV!=="production",U),{status:200,headers:X})}finally{clearTimeout(K),j(()=>this.completeStream(Z,z.summarize(O.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:j,csrfTokenHMAC:J,currentPathName:W,headers:Y,i18n:z,params:X,pathname:G,serverQueries:F,userAgent:Q,noStream:O,url:K,user:D,viewData:B,breadcrumbs:U,urlLocaleSegment:V,meta:M,isOgRequest:I,appId:P,features:A,staticView:x}=$,E=G.replace(`/${V}`,""),S={kind:"view",data:{meta:M,pageData:{[E]:B},__csrf:J.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:U,router:{urlLocaleSegment:V,pathname:W,params:X,currentPath:G,searchParams:K.search,is404:!W?!0:!1,domain:Z.domain?GD(Z):null},appId:P,features:A,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},H=this.root,L=this.routeManifest[W];return async(m)=>{let{bootstrapModules:u=[],loaders:k1,getStyles:Z0,viewImportMap:n,cssManifest:k,ogMap:U0,viewModules:y$,clientEntry:q$,modulePreloadManifest:vZ,assetBase:U1,resolveIsland:v$,buildId:g$}=m,a=q$?[]:u,w3=(j0)=>[j0,`window.loaders=${k1}`,...q$?[`import(${JSON.stringify(q$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(I){let j0=null,p$=null;for(let h$ of L??[])if(typeof U0[h$]==="function")p$=h$,j0=U0[h$];if(!j0)return new Response("Not found",{status:404});let iG=Object.values(S.data.pageData)[0];try{await E3(b1(j0,iG[p$]),{onError:()=>{}})}catch(h$){let{fonts:sG,...oG}=h$.satoriOptions,nG=await Promise.all(sG.map((k3)=>{return YD(k3.name,k3.weight,k3.style).then(($F)=>({...k3,data:$F}))})),$5=new Headers(Y);$5.set("Content-Type","image/png");let[aG,rG]=await Promise.all([JD(),I8("Rendering an OG image")]),tG=await aG(h$.jsx,{...oG,fonts:nG}),eG=await rG(Buffer.from(tG)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(eG),{headers:$5})}return new Response("data")}if(x&&W)return await this.renderStatic({req:Z,runInRequestScope:j,staticView:x,currentViews:L,data:S.data,serverQueries:F,headers:Y,getStyles:Z0,viewImportMap:n,viewModules:y$,resolveIsland:v$,buildId:g$});if(S.data.cssManifest=k,S.data.modulePreloadManifest=vZ??{},U1&&U1!=="/")S.data.assetBase=U1;let g8=this.modulePreloadLinks({clientEntry:q$,modulePreloadManifest:vZ,views:L??["404"],routeKey:W??"404"}),m$=await Z0(L);S.data.prefetchedData=F.snapshotResolved(),F.markRenderStart();let V1=new AbortController,gZ=setTimeout(()=>V1.abort(),ZG),T1=S8(Q)||O,R=Bun.env.NODE_ENV!=="production"&&!T1&&W&&this.shellReporter.shouldObserve(W)?hX():null,p0=v2();try{let j0=await E3(b1($G,{children:[...g8,...m$,b1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:WD}}),b1(H,{data:S.data,viewImportMap:n,viewModules:y$,serverQueries:F,dictionarySink:p0,key:"root"})]}),{bootstrapScriptContent:w3(`window.__GEMI_DATA__ = ${E1(S.data)}`),bootstrapModules:a,signal:V1.signal,...T1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(p$){if(Bun.env.NODE_ENV!=="production")console.error(p$)}});if(j0.allReady.catch(()=>{}).finally(()=>clearTimeout(gZ)),T1)await j0.allReady.catch(()=>{});return new Response(f2(j0,F,{onShell:T1?void 0:()=>F.markShell(),onChunk:R?.onChunk,onClose:()=>j(()=>{if(this.completeStream(Z,F.summarize(V1.signal.aborted)),R)this.shellReporter.report(W,R.measure())})},p0),{status:!W?$.refusedStatus??404:200,headers:Y})}catch(j0){if(clearTimeout(gZ),Bun.env.NODE_ENV==="production")throw j(()=>this.completeStream(Z,F.summarize(V1.signal.aborted))),j0;let p$=await E3(b1("div"),{bootstrapScriptContent:w3(`window.error= ${E1(j0.message)}; window.stack_trace=${E1(j0.stack)};window.__GEMI_DATA__ = ${E1(S.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...a]:a});return new Response(f2(p$,F,{onClose:()=>j(()=>this.completeStream(Z,F.summarize(V1.signal.aborted)))}),{status:!W?$.refusedStatus??404:200,headers:Y})}}}viewRefusalStatus($,Z,j){if(X$(Z))return 404;if(Z?.kind===v1){let J=Z.payload?.view?.status;return J===403||J===404?J:null}if(g1(Z)){if(!j.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof R1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let j=new URL($.url),J=j.pathname.endsWith(".json"),W=j.pathname.endsWith(".og"),Y=j.pathname.replace(".json","").replace(".og",""),[,z,...X]=Y.split("/"),G=Y,F=null,Q=null,O=T(i),K=S3(this.flatViewRoutes,Y),D=O.isLocaleAware&&this.localeRouting==="prefix"&&!K?.route.middleware.includes(jG);if(D&&O.supportedLocales.includes(z))G=`/${X.join("/")}`,F=z,Q=z;if(D&&!W&&Q===null&&!(Q===null&&K!==null)){let H=JG(z,O.supportedLocales,O.defaultLocale);if(H){let L=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${H}${L}${J?".json":""}${j.search}`}})}}if(D&&!W){let H=T(i).detectLocale(new C($,{},"view",G));if(Q===null&&H!==O.defaultLocale){let L=j.pathname==="/"?"":j.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${H}${L}${j.search}`}})}}G=G.replace("//","/");let U=[],V=[],M=null,I={},P=null,A=!1,x=[],E;try{let H=S3(this.flatViewRoutes,G);if(Q&&H?.route.middleware.includes(jG))H=null;if(H){if(M=H.routePath,I=H.params,U=H.route.exec,V=H.route.middleware,x=H.route.features,A=V.includes("no-stream"),E=H.route.static,J&&this.partialRendering){let L=$.headers.get(C2),m=CX({flatViewRoutes:this.flatViewRoutes,supportedLocales:T(i).supportedLocales,from:L,origin:j.origin,to:{segments:H.route.segments,params:I,search:j.search}});if(m.startIndex>0)U=U.slice(m.startIndex),P={from:L,carriedViews:m.carriedViews}}}}catch(H){throw H}if(E&&J)return new Response("Not found",{status:404});let S=new C($,I,"view",M);return this.hooks.onRequestStart(S),await N.run(S,async()=>{let H=null,L=N.getStore(),m=kZ.getStore(),u=(k)=>kZ.run(m,()=>N.runWith(L,k));L.serverQueries=new bZ(f3($));let k1=new Set;L.serverQueries.onQueryFail((k)=>{k1.add(k.error);try{u(()=>Promise.resolve(this.hooks.onRequestFail(n,k.error)).catch(()=>{}))}catch{}});let Z0=tX(E);if(Q){let k=Q.replaceAll("/","");Y$.setLocale(k,{cookie:Z0.locale})}else if(O.isLocaleAware&&!D)L.setLocale(O.defaultLocale);else Y$.setLocale(void 0,{cookie:Z0.locale});let n=L.req;if(Z0.session)f8();try{let k=null;try{await T(q1).runMiddleware(V)}catch(R){if(k=this.viewRefusalStatus(n,R,k1),k===null)throw R}if(k!==null||x.length>0&&!await this.passesFeatureGates(x))M=null,U=[],n.routePath="";let U0=T(i),y$=U0.isEnabled,q$=U0.isLocaleAware,vZ=new C($,n.params),U1={defaultLocale:U0.defaultLocale,timeZone:U0.detectTimeZone(vZ)};if(q$){let R=null;if(Q)R=Q.replaceAll("/",""),L.setLocale(R);else if(!D)R=L.locale??U0.defaultLocale;else R=U0.detectLocale(vZ),L.setLocale(R);let p0=y$?U0.getPageTranslations(R,n.routePath):{};U1={...U1,supportedLocales:U0.supportedLocales,currentLocale:R,dictionary:{[R]:p0},defaultLocale:U0.defaultLocale,...D?{}:{localeRouting:"off"}}}await WG(U1.currentLocale??"");let v$;try{v$=await Promise.all(U.map((R)=>R(n)))}catch(R){if(k=this.viewRefusalStatus(n,R,k1),k===null)throw R;M=null,U=[],n.routePath="",v$=[]}let{cookies:g$,headers:a}=L;if(k!==null)a.set("Cache-Control","no-store");H={data:v$,cookies:g$,headers:a,user:L.user,prefetchedData:L.serverQueries.snapshotResolved(),currentPathName:M,params:n.params,urlLocaleSegment:F,meta:L.renderMeta(),appId:T(S2).id,features:await T(RZ).forClient()};let{params:w3,user:g8}=H,m$={},V1={};for(let R of v$??[]){let[p0,j0]=Object.entries(R)?.[0]??[];if(!p0||!j0)continue;V1[`${p0}:${M}`]=j0.breadcrumb,m$[p0]=j0}let gZ=m$.FILE;if(gZ){for(let R of g$)a.append("Set-Cookie",R.toString());try{await this.onRequestEnd(n)}catch(R){k$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}return await r8(gZ,a)}if(J){a.set("Content-Type","application/x-ndjson; charset=utf-8"),a.append("Vary",C2),g$.forEach((p0)=>a.append("Set-Cookie",p0.toString())),await this.hooks.onRequestEnd(n);let R={meta:P&&!L.metadata.touched?null:H.meta,data:{[G]:m$},breadcrumbs:V1,prefetchedData:L.serverQueries.snapshotResolved(),i18n:U1,features:H.features,is404:!M,appId:H.appId,partial:P};return new Response(cX(R,L.serverQueries,void 0,({aborted:p0})=>u(()=>this.completeStream(n,L.serverQueries.summarize(p0)))),{headers:a})}if(a.set("Content-Type","text/html; charset=utf-8"),!A&&!(E&&M))a.append("Vary","User-Agent");let T1=Boolean(E&&M);if(!T1||Z0.session)f8();for(let R of g$)a.append("Set-Cookie",R.toString());if(!T1||Z0.csrf){let R=Bun.CSRF.generate(process.env.SECRET);a.append("Set-Cookie",`csrf_token=${R}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(n,{mintSession:!T1||Z0.session})}catch(R){k$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}if(T1)eX(a,E);return await this.render({req:n,runInRequestScope:u,csrfTokenHMAC:Buffer.from(""),currentPathName:M,headers:a,i18n:U1,params:w3,pathname:j.pathname,serverQueries:L.serverQueries,userAgent:$.headers.get("user-agent"),noStream:A,url:j,user:g8,viewData:m$,breadcrumbs:V1,urlLocaleSegment:F,meta:H.meta,appId:H.appId,features:H.features,isOgRequest:W,staticView:M?E:void 0,refusedStatus:k??void 0})}catch(k){if(k.kind===v1){let U0=J?FD(k.payload.viewData??k.payload.api):q2(k.payload.view);for(let y$ of L.cookies)U0.headers.append("Set-Cookie",y$.toString());return U0}if(!k1.has(k))this.hooks.onRequestFail(n,k);if(g1(k))return console.error(k),J?wZ():q2(b2());if(k instanceof R1&&k.status===403)return J?wZ():q2(b2());throw k}},Z)}}function m2(){let $=JSON.stringify({error:m1("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 FG extends R0{routes={"/api-routes":this.get(()=>{let $=T(E8).flatRoutes,Z=[];for(let[j,J]of Object.entries($))for(let[W,Y]of Object.entries(J)){let{exec:z,middleware:X}=Y;Z.push({path:j,method:W,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=T(R3).flatViewRoutes,Z=[];for(let[j,{middleware:J,viewPath:W}]of Object.entries($))Z.push({path:j,method:"GET",viewPath:W,middleware:J});return Z})}}var QD=new Set([y1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),KD=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,OD=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function BD($,Z,j,J){for(let[W,Y]of Object.entries(j.headers??{})){if(Y===void 0||Y===null)continue;let z=W.toLowerCase();if(QD.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${W}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(J&&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(W,Y)}for(let[W,Y]of Object.entries(j.cookies??{})){if(Y===void 0||Y===null)continue;if(W===y1)throw Error(`dispatchAs: credentials may not set the "${y1}" cookie. The access token stays the initiator's.`);if(!KD.test(W)||!OD.test(Y))throw Error(`dispatchAs: "${W}" is not a cookie a Cookie header can carry.`);Z.push(`${W}=${Y}`)}}function DD($,Z){let j=$.body.getReader(),J=!1,W=()=>{if(J)return;J=!0;try{Z()}catch(z){console.error(z)}},Y=new ReadableStream({async pull(z){let X;try{X=await j.read()}catch(G){W(),z.error(G);return}if(X.done){W();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await j.cancel(z)}finally{W()}}},{highWaterMark:0});return new Response(Y,{status:$.status,statusText:$.statusText,headers:$.headers})}function YG($){let{status:Z=400,data:j,headers:J}=$,W=new Headers({"Content-Type":"application/json",...J});if(!W.has("Cache-Control"))W.set("Cache-Control","no-store");return new Response(JSON.stringify(j),{status:Z,headers:W})}function zG($,Z,j){let J=[];Z?.forEach((z,X)=>J.push([X,z]));let W=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(j??[])];if(J.length===0&&W.length===0)return $;let Y=(z)=>{for(let[X,G]of J){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,G)}for(let X of W)z.append("Set-Cookie",X)};try{return Y($.headers),$}catch{let z=new Headers($.headers);return Y(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}class E8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=tz();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=X2({"/":$.rootRouter,"/auth":Z2,"/__gemi__/services/i18n":j2,"/__gemi__/services/logs":z2,"/__gemi__/services/image":Y2,"/__gemi__/debug":FG})}getRouteHandlerAndParams($){let Z=new URL($.url),j=GG(Z.pathname),J={},W;for(let[Y]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:Y});if(z.test({pathname:j})){W=Y,J=z.exec({pathname:j})?.pathname.groups;break}}catch(z){console.error(z)}return{params:J,path:W}}async runRouteMiddleware($,Z){let J=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await T(q1).runMiddleware(J)}catch(W){if(W.kind===v1)return YG(W.payload.api);else{if(X$(W))return m2();if(this.onRequestFail(Z,W),console.error(W),g1(W))return wZ();throw W}}}async getRouteData($){let Z=this.flatRoutes[$],j=N.getStore(),J=Z[j.req.rawRequest.method].exec??(()=>Promise.resolve({})),W={};try{W=await J()}catch(Y){if(Y.kind===v1)return YG(Y.payload.api);if(X$(Y))return m2();if(this.onRequestFail(j.req,Y),console.error(Y),g1(Y))return wZ();throw Y}return W}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,j){let J=async()=>{try{if(!this.isFrameworkRoute(j))await this.onRequestEnd(Z)}catch(W){k$.error(W?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(W)})}finally{$.destroy()}};if(!$.hasPendingWork()){await J();return}$.whenIdle().then(J).catch((W)=>{console.error(W)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:j,path:J}=this.getRouteHandlerAndParams($),W=this.flatRoutes[J];if(!W||!W[$.method])return new Response(JSON.stringify({error:m1("not_found","Not found",404)}),{status:404});let Y=new C($,j,"api",J);if(!this.isFrameworkRoute(J))this.onRequestStart(Y);return await N.run(Y,async()=>{let z=N.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,Y,J)};try{let F=T(i);if(F.isEnabled){let U=F.detectLocale(Y);z.setLocale(U)}z.setRequest(Y),T(q1).applyDefaultBodyLimit($);let Q=await this.runRouteMiddleware(J,Y);if(Q instanceof Response){let U=zG(Q,z.headers,z.cookies);return await G(),U}let O=await this.getRouteData(J),K=z.headers,D=z.cookies;if(O instanceof Response){let U=zG(O,K,D);if(this.isOpenEndedBody($,U)){let V=DD(U,()=>this.endRequest(z,Y,J));return X=!0,V}return await G(),U}let B=(i$(O)?O:G$.json(O)).toResponse(K,D);return await G(),B}catch(F){if(!X)try{await G()}catch(Q){console.error(Q)}throw F}},Z)}async dispatchAs($,Z,j,J,W){let Y=new URL($.rawRequest.url).origin,z=new URL(`${Y}/api${j}`),X=`/api${j.split(/[?#]/)[0]}`;if(!j.startsWith("/")||z.origin!==Y||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${j}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let G=W?.identity;if(G!==void 0&&(typeof G!=="object"||!G?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let F=new Headers,Q=[],O=G?null:$.cookies.get(y1);if(O)Q.push(`${y1}=${O}`);if(W?.credentials)BD(F,Q,W.credentials,G!==void 0);if(Q.length>0)F.set("Cookie",Q.join("; "));let K=G?null:$.headers.get(y1);if(K)F.set(y1,K);let D=$.headers.get("User-Agent");if(D)F.set("User-Agent",D);let B;if(J instanceof FormData)B=J;else if(J!==void 0)F.set("Content-Type","application/json"),B=JSON.stringify(J);let U=new Request(z,{method:Z,headers:F,body:B,...W?.signal?{signal:W.signal}:{}});if(XG(U,o$($),G?.grant,W?.progress),$.domain)yZ(U,$.domain);let V=G?{user:G.user}:void 0;return N.exit(()=>h3.exit(()=>this.handleApiRequest(U,V)))}}import{timingSafeEqual as UD}from"crypto";var b8="",c2="*",VD=60000,TD=1e4,p2=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,R8=16,QG=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,h2="x-forwarded-host";function KG($){return $.startsWith(":")}function d2($,Z){if($===null)return!1;let j=Buffer.from($,"utf8"),J=Buffer.from(Z,"utf8");return j.length===J.length&&UD(j,J)}function MD($){if(!$)return null;if($===!0)return{header:h2,secret:null};return{header:($.hostHeader??h2).toLowerCase(),secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function ID($){if(!$||$===!0)return;let{hostHeader:Z,secret:j}=$;if(Z!==void 0&&(typeof Z!=="string"||!QG.test(Z)))throw Error(`\`route.domains.trustProxy.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(Z)}.`);if(!j)return;if(typeof j.header!=="string"||!QG.test(j.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${j.header}".`);if(j.header.toLowerCase()===(Z??h2).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof j.value!=="string"||j.value.length<R8)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${R8} characters. A guessable one lets any client name its own host.`)}function D1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function LD($){try{let Z=new URL(`http://${$.trim()}`),j=Z.hostname.toLowerCase().replace(/\.$/,"");return j?Z.port?`${j}:${Z.port}`:j:null}catch{return null}}function HD($){let Z=D1($.root),j=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==j||!Z.split(".").every((Y)=>p2.test(Y)))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<R8)throw Error(`\`route.domains.ask.secret\` must be at least ${R8} characters. A guessable one is worse than leaving \`ask\` out.`);ID($.trustProxy);let J=new Set,W=null;for(let Y of $.groups??[]){let{subdomain:z}=Y;if(J.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(J.add(z),KG(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(W)throw Error(`\`route.domains\` declares two param subdomains, "${W.subdomain}" and "${z}"; a host could match either.`);W=Y;continue}if(Y.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>p2.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!J.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&W&&!W.exists)throw Error(`\`route.domains.ask\` is set, so "${W.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;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){HD($),this.root=D1($.root),this.hostTrust=MD($.trustProxy);for(let Z of $.groups??[])if(KG(Z.subdomain))this.param={...Z,name:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z);this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??VD,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!d2($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}hostOf($){return D1(this.forwardedHost($))??D1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),j=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),J=j==="http"||j==="https"?j:Z.protocol.replace(/:$/,""),W=this.forwardedHost($),Y=W&&D1(W)?LD(W):null;return`${J}://${Y??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let j=await this.match(Z,$);if(j)return j;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:c2,params:{},custom:!0};return null}async allows($,Z){let j=D1($);return j?await this.match(j,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:b8,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let J=$.slice(0,-(this.root.length+1)),W=this.fixed.get(J);if(W)return{host:$,group:W.subdomain,params:{},custom:!1};if(this.param&&p2.test(J)){let Y={[this.param.name]:J};if(this.param.exists&&!await this.param.exists(Y,Z))return null;return{host:$,group:this.param.subdomain,params:Y,custom:!1}}return null}if(!this.custom)return null;let j=await this.resolveCustom($);return j?{host:$,group:this.custom.group,params:j,custom:!0}:null}async resolveCustom($){let Z=Date.now(),j=this.cache.get($);if(j&&j.expiresAt>Z)return this.cache.delete($),this.cache.set($,j),j.value;let J=this.inFlight.get($);if(J)return J;let W=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,W);let Y;try{Y=await W}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=TD)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:Y,expiresAt:Date.now()+this.cacheTtlMs})}return Y}forget($){if($===void 0)this.cache.clear();else{let Z=D1($);if(Z)this.cache.delete(Z)}}}var PD="/__gemi__/domains/ask";class j1{static token="router.domains";resolver;acceptsCustomDomains;groups=new Map;constructor($,Z){this.groups.set(b8,$);let{domains:j}=Z;if(this.acceptsCustomDomains=Boolean(j?.custom),!j){this.resolver=null;return}this.resolver=new u2(j);let J=(W)=>({api:W.api?new E8({...Z.api,...W.api}):$.api,view:W.view?new R3({...Z.view,...W.view}):$.view});for(let W of j.groups??[])this.groups.set(W.subdomain,J(W));if(j.custom?.fallback)this.groups.set(c2,J(j.custom.fallback))}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)OG($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return yZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==PD)return null;if(!d2(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let j=Z.searchParams.get("domain"),J=j?await this.resolver.allows(j,$):!1;return new Response(null,{status:J?200:404})}dispatchers($){return this.groups.get($?.group??b8)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[j,J]of this.groups){if($.has(J.view))continue;$.add(J.view),Z.push({group:j,view:J.view})}return Z}}function w8($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var BG=600000;function DG($,Z){return[n3($,Z),n3($,Z-1)]}class f{static token="auth";config;provider;constructor($={},Z=new Ij){this.config={...xZ(H9($),$),emailCode:Tj($.emailCode)},this.provider=Z}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=T().bound(j1)?T(j1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let j=Z==="root"?T(j1).resolver?.root:D1(Z);if(!j)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let J=$.domain?.host??D1(new URL($.rawRequest.url).host);return J===j||J?.endsWith(`.${j}`)?j:void 0}async getSession($,Z){if(!$)return null;if(!Kj($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let j=await this.userProvider.findSession({token:$,userAgent:Z});if(!j?.user)return null;let J=Date.now(),W=w8(j.expiresAt),Y=w8(j.absoluteExpiresAt);if(W<=J||Y<=J)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(j,J);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,j){let J=N.getStore()?.req;if(!J)return null;let W=Date.now(),Y=Math.floor(W/BG),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await j(X,{token:$,req:J,userAgent:Z}))return null;let F=n3($,Y),Q=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:F,userId:Q,userAgent:Z,...this.freshLifetime(W)}),!0}))z=F}if(!z){for(let F of DG($,Y))if((await this.userProvider.findSession({token:F,userAgent:Z}))?.user){z=F;break}}if(!z)return null;let G=await this.getSession(z,Z);if(G)J.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(J,new Date(G.expiresAt)));return G}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(Kj($)||!this.config.migrateLegacySession){let W=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),W}let j=Math.floor(Date.now()/BG),J=DG($,j);return this.userProvider.withLegacySessionLock($,async()=>{let W=await this.userProvider.findSession({token:$,userAgent:Z});for(let Y of J){if(W?.user)break;W=await this.userProvider.findSession({token:Y,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let Y of J)await this.userProvider.deleteSession({token:Y});return W})}requestCarryingCookie($){let Z=N.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let j=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=j/2)return $;let J=new Date(Math.min(Z+j,new Date($.absoluteExpiresAt).getTime())),W=await this.userProvider.updateSession({token:$.token,expiresAt:J}),Y=this.requestCarryingCookie($.token);if(Y)Y.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(Y,J));if(!W)return $;return{...$,expiresAt:W.expiresAt??J}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let j=await this.createOrUpdateSession({email:$,id:Z.id}),J=new C;if(J.ctx().setCookie("access_token",j.token,this.accessTokenCookieOptions(J,j.expiresAt)),j?.user)j.user.extension=await this.config.extendSession(j.user);return j}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),j=null;if(Z?.user)j=await this.config.extendSession(Z.user),Z.user.extension=j;return Z}async createOrUpdateSession($){let Z=new C,j=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!j)throw new F$;let J=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),W=Q9(j),Y=await this.userProvider.createSessionV2({token:W,userId:j,userAgent:J,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:W,userAgent:J??""});return z?.user?z:Y}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:j,token:J}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:j,token:J}}return{}}async issueOneTimeCode($,Z){await this.userProvider.deleteMagicLinkToken($);let j=await this.config.generateMagicLinkToken($),J=await this.config.generateCode($),W=typeof J==="string"&&J!==""?J:T9(Z);return await this.userProvider.createMagicLinkToken({email:$,token:a3("link",$,j),pin:a3("pin",$,W)}),{email:$,pin:W,token:j}}async verifyOneTimeCode($,Z,j={}){let{expiresInMinutes:J,maxAttempts:W}=this.config.emailCode,Y=await this.userProvider.findMagicLinkTokenByEmail($);if(!Y)return iZ("pin",$,null,Z),{status:"invalid"};let z=w8(Y.createdAt);if(z+J*60000<=Date.now())return iZ("pin",$,null,Z),{status:"expired"};if(!await L9(Y.id,z,W,J))return await this.userProvider.claimMagicLinkToken(Y.id),{status:"too_many_attempts"};if(!iZ("pin",$,Y.pin,Z))return{status:"invalid"};if(j.claim!==!1&&!await this.userProvider.claimMagicLinkToken(Y.id))return{status:"invalid"};return{status:"ok",row:Y}}async verifyMagicLinkToken($,Z){let j=await this.userProvider.findMagicLinkTokenByEmail($),J=iZ("link",$,j?.token,Z);if(!j||!J)return!1;if(w8(j.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(j.id)}}class h0 extends g{static getFacadeAccessor(){return f}static async user(){let $=N.getStore(),Z=$?.user;if(!Z){if(Z=await g3(this.getFacadeRoot(),$?.req),Z)$?.setUser(Z)}if(Z)return Z;throw new F$({redirectTo:c3($?.req,this.getFacadeRoot().config.signInPath)})}static intendedUrl($){let Z=N.getStore()?.req;return W1(Z?.search.get(J1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await h0.user();if(!await $(Z))throw new n$}static async guardSafe($){let Z=await h0.user();try{return await $(Z)}catch(j){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class k8{static ensure($,Z={}){let j=N.getStore();if(j.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return j.serverQueries??=new bZ(f3(j.req.rawRequest)),j.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let j=k8.ensure($,Z[0]);if(await j.promise,j.status==="rejected")throw j.error;return j.data}static prefetch($,...Z){k8.ensure($,Z[0])}static noPrefetch(){let $=N.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new bZ(f3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function UG($,Z,j="/"){let J=new URL($.origin),W=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,Y=new URL(j.startsWith("/")?j:`/${j}`,J),z=ND(W);if(!z)throw Error(`"${W}" 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(Y.hostname=z.hostname,z.port)Y.port=z.port;return Y.toString()}function ND($){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 VG{static absolute($,...Z){return`${process.env.HOST_NAME}${K0(String($),Z[0]??{})}`}static relative($,...Z){return K0(String($),Z[0]??{})}static forDomain($,Z,...j){let J=T(j1).resolver;if(!J)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let W=N.getStore()?.req?.rawRequest,Y=W?J.publicOrigin(W):process.env.HOST_NAME;if(!Y)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` for the protocol.");return UG({root:J.root,origin:Y},$,K0(String(Z),j[0]??{}))}}class TG{name="Meta";static description($){N.getStore().metadata.description($)}static title($){N.getStore().metadata.title($)}static openGraph($){N.getStore().metadata.openGraph($)}static htmlAttributes($){N.getStore().metadata.htmlAttributes($)}static canonical($){N.getStore().metadata.canonical($)}static alternates($){N.getStore().metadata.alternates($)}static fonts($){N.getStore().metadata.fonts($)}}var _D={set($,Z,j){N.getStore().setCookie($,Z,j)},setIfAbsent($,Z,j){if(N.getStore().req.cookies.has($))return!1;return N.getStore().setCookie($,Z,j),!0},delete($,Z){N.getStore().deleteCookie($,Z)}};class w1 extends g{static getFacadeAccessor(){return MG}static get client(){return this.getFacadeRoot().client}static get($){return w1.client.get($)}static set($,Z){return w1.client.set($,Z)}static del(...$){return w1.client.del(...$)}static exists($){return w1.client.exists($)}static incr($){return w1.client.incr($)}static expire($,Z){return w1.client.expire($,Z)}static ttl($){return w1.client.ttl($)}}class IG extends g{static getFacadeAccessor(){return Y1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}}class HG extends g{static getFacadeAccessor(){return LG}static run($,Z,j){return this.getFacadeRoot().run($,Z,j)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class NG extends g{static getFacadeAccessor(){return PG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class _G extends g{static getFacadeAccessor(){return x3}static for($,Z,j){return this.getFacadeRoot().for($,Z,j)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,j){return this.getFacadeRoot().save($,Z,j)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}function ON($){return $}function CG(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function y8($){let Z=new URLSearchParams;for(let[j,J]of $)Z.append(j,String(J));return Z.toString()}function l2($){let Z=new Map;if(!$)return Z;let j;try{j=new URLSearchParams($)}catch{return Z}for(let[J,W]of j){let Y=Number(W);if(W!==""&&Number.isSafeInteger(Y)&&Y>=0)Z.set(J,Y)}return Z}var{SQL:CD}=globalThis.Bun;function xD(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var SD=async($)=>{let Z=new CD($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(j,J,W)=>Z.listen(j,J,W),close:()=>Z.close({timeout:1})}},fD=async($)=>{let Z;try{Z=(await import("./chunk-j0cnsgjq.js")).default}catch(J){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:J})}let j=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(J,W,Y)=>j.listen(J,W,Y),close:()=>j.end({timeout:1}).catch(()=>{})}},xG=($)=>xD()?SD($):fD($);var AD=/^[A-Za-z_][A-Za-z0-9_]*$/;class i2{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let j=Z.headsTable??"gemi_change_heads",J=Z.entriesTable??"gemi_changes",W=Z.notifyChannel??"gemi_changes";for(let z of[j,J,W])if(!AD.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let Y=Z.retain??1000;if(!Number.isInteger(Y)||Y<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Y}.`);this.headsTable=j,this.entriesTable=J,this.notifyChannel=W,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=Y,this.listener=Z.listener??xG}async createTable(){for(let $ of ED(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let j=this.transaction();if(!j){let W=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return W();let Y=this.sqliteTurn.then(W);return this.sqliteTurn=Y.catch(()=>{}),Y}let J=this.append(j,$,Z);return SG(J),J}async append($,Z,j){let J=$.unsafe(`"${this.headsTable}"`),W=$.unsafe(`"${this.entriesTable}"`),[Y]=await $`
|
|
27
|
-
INSERT INTO ${J} (channel, seq) VALUES (${Z}, 1)
|
|
28
|
-
ON CONFLICT (channel) DO UPDATE SET seq = ${J}.seq + 1
|
|
29
|
-
RETURNING seq
|
|
30
|
-
`,z=Number(Y.seq);if(await $`
|
|
31
|
-
INSERT INTO ${W} (channel, seq, data, created_at)
|
|
32
|
-
VALUES (${Z}, ${z}, ${JSON.stringify(j??null)}, ${Date.now()})
|
|
33
|
-
`,z>this.retain)await $`DELETE FROM ${W} WHERE channel = ${Z} AND seq <= ${z-this.retain}`;if(this.dialect==="postgres")await $`SELECT pg_notify(${this.notifyChannel}, ${`${z} ${Z}`})`;return z}async heads($){let Z=new Map($.map((W)=>[W,0]));if($.length===0)return Z;let j=this.sql,J=await j`
|
|
34
|
-
SELECT channel, seq FROM ${j.unsafe(`"${this.headsTable}"`)}
|
|
35
|
-
WHERE channel IN ${j([...$])}
|
|
36
|
-
`;for(let W of J)Z.set(W.channel,Number(W.seq));return Z}async read($,Z,j){let J=this.sql,[W]=await J`
|
|
37
|
-
SELECT seq FROM ${J.unsafe(`"${this.headsTable}"`)} WHERE channel = ${$}
|
|
38
|
-
`,Y=W?Number(W.seq):0;if(Z>Y)return{entries:[],head:Y,gap:!0};if(Z===Y)return{entries:[],head:Y,gap:!1};let z=await J`
|
|
39
|
-
SELECT seq, data FROM ${J.unsafe(`"${this.entriesTable}"`)}
|
|
40
|
-
WHERE channel = ${$} AND seq > ${Z}
|
|
41
|
-
ORDER BY seq
|
|
42
|
-
LIMIT ${j}
|
|
43
|
-
`;if(z.length===0||Number(z[0].seq)!==Z+1)return{entries:[],head:Y,gap:!0};return{entries:z.map((X)=>({seq:Number(X.seq),data:JSON.parse(X.data)})),head:Y,gap:!1}}async listen($,Z){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let j=await this.listener(this.url);try{await j.listen(this.notifyChannel,(J)=>{let W=J.indexOf(" "),Y=Number(J.slice(0,W));if(W>0&&Number.isInteger(Y))$(J.slice(W+1),Y)},Z)}catch(J){throw await j.close(),J}return{close:()=>j.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let $=L1();if($===void 0||O$()!==this.connection)return;return $}}function ED($,Z){return[`CREATE TABLE IF NOT EXISTS "${$}" (
|
|
44
|
-
"channel" TEXT NOT NULL PRIMARY KEY,
|
|
45
|
-
"seq" BIGINT NOT NULL
|
|
46
|
-
)`,`CREATE TABLE IF NOT EXISTS "${Z}" (
|
|
47
|
-
"channel" TEXT NOT NULL,
|
|
48
|
-
"seq" BIGINT NOT NULL,
|
|
49
|
-
"data" TEXT NOT NULL,
|
|
50
|
-
"created_at" BIGINT NOT NULL,
|
|
51
|
-
PRIMARY KEY ("channel", "seq")
|
|
52
|
-
)`]}class s2{logs=new Map;retain;constructor($={}){let Z=$.retain??1000;if(!Number.isInteger(Z)||Z<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Z}.`);this.retain=Z}async publish($,Z){let j=this.logs.get($);if(!j)j={head:0,entries:[]},this.logs.set($,j);let J=++j.head;if(j.entries.push({seq:J,data:Z===void 0?null:structuredClone(Z)}),j.entries.length>this.retain)j.entries.splice(0,j.entries.length-this.retain);return J}async heads($){return new Map($.map((Z)=>[Z,this.logs.get(Z)?.head??0]))}async read($,Z,j){let J=this.logs.get($),W=J?.head??0;if(Z>W)return{entries:[],head:W,gap:!0};if(!J||Z===W)return{entries:[],head:W,gap:!1};let Y=J.entries[0]?.seq??W+1;if(Y>Z+1)return{entries:[],head:W,gap:!0};let z=Z+1-Y;return{entries:J.entries.slice(z,z+j),head:W,gap:!1}}}var bG=new TextEncoder;function fG($,Z){return bG.encode(`id: ${$}
|
|
53
|
-
data: ${JSON.stringify(Z)}
|
|
54
|
-
|
|
55
|
-
`)}function wG($,Z,j,J){let W=Z instanceof Request?Z:Z.rawRequest,Y=J.cursor??W.headers.get("Last-Event-ID")??new URL(W.url).searchParams.get("cursor"),z;try{z=$.subscribe(j,{cursor:Y,signal:W.signal})}catch(K){if(!(K instanceof q8))throw K;return new Response(JSON.stringify({error:"The change feed is at capacity."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":String(J.retryAfter??5)}})}let X=null,G=!1,F=!1,Q=(K)=>{if(X)clearInterval(X);if(X=null,z.close(),F)return;F=!0;try{K.close()}catch{}},O=new ReadableStream({start(K){X=setInterval(()=>{if(RG())return Q(K);try{K.enqueue(bG.encode(AG))}catch{Q(K)}},$.config.keepaliveInterval)},async pull(K){try{if(!G){if(await z.ready(),G=!0,!F)K.enqueue(fG(z.cursor,{type:"ready"}));return}let D=await z.next();if(D.done||F)return Q(K);K.enqueue(fG(z.cursor,D.value))}catch(D){if(!F)console.error("[gemi] A change feed stream failed.",D);Q(K)}},cancel(){if(F=!0,X)clearInterval(X);X=null,z.close()}});return new Response(O,{headers:EG()})}var kG=255,yG=500,RD=30000;class q8 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class a2{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=yG;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=xZ(CG(),$),this.driver=wD(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){n2($);let j=Z===void 0?null:Z;if(L1()!==void 0&&!this.driver.joinsTransaction?.())return CZ(async()=>{this.wake($,await this.driver.publish($,j))}),null;let J=await this.driver.publish($,j);return CZ(()=>this.wake($,J)),J}async head($){return n2($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=o2($);return y8(await this.driver.heads(Z))}subscribe($,Z={}){let j=o2($);if(this.all.size>=this.config.maxSubscriptions)throw new q8(this.config.maxSubscriptions);let J=new qG(this,j,bD(Z.cursor),this.config,Z.signal);this.all.add(J);for(let W of j){let Y=this.followers.get(W);if(!Y)this.followers.set(W,Y=new Set);Y.add(J)}return this.startListening(),this.startPolling(),J}stream($,Z,j={}){return wG(this,$,o2(Z),j)}async close(){if(this.listenState="closed",this.retryTimer)clearTimeout(this.retryTimer);this.retryTimer=null,this.stopPolling();for(let Z of this.all)Z.close();let $=this.listening;this.listening=null,await $?.close(),await this.driver.close?.()}forget($){if(!this.all.delete($))return;for(let Z of $.channels){let j=this.followers.get(Z);if(j?.delete($),j?.size===0)this.followers.delete(Z)}if(this.all.size===0)this.stopPolling()}poll(){return this.polling??=(async()=>{try{let $=[...this.followers.keys()];for(let Z=0;Z<$.length;Z+=500){let j=await this.driver.heads($.slice(Z,Z+500));for(let[J,W]of j)this.wake(J,W)}}catch($){console.error("[gemi] The change feed could not read its channels' heads.",$)}finally{this.polling=null}})(),this.polling}startPolling(){if(this.pollTimer)return;this.pollTimer=setInterval(()=>void this.poll(),this.config.pollInterval),this.pollTimer.unref?.()}stopPolling(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null}wake($,Z){for(let j of this.followers.get($)??[])j.moved($,Z)}resync(){this.poll()}startListening(){if(this.listenState!=="off"||!this.driver.listen)return;this.connect()}async connect(){this.listenState="connecting",this.retryTimer=null;try{let $=await this.driver.listen((Z,j)=>this.wake(Z,j),()=>this.resync());if(this.listenState!=="connecting"){await $.close();return}this.listening=$,this.listenState="listening",this.backoffMs=yG,this.resync()}catch($){if(this.listenState!=="connecting")return;console.error(`[gemi] The change feed could not listen for other instances' changes; retrying in ${this.backoffMs}ms.`,$),this.listenState="retrying",this.retryTimer=setTimeout(()=>void this.connect(),this.backoffMs),this.retryTimer.unref?.(),this.backoffMs=Math.min(this.backoffMs*2,RD)}}}class qG{manager;config;signal;channels;positions=new Map;readTo=new Map;dirty=new Set;pending=[];started=null;wakeUp=null;closed=!1;onAbort=()=>this.close();constructor($,Z,j,J,W){this.manager=$;this.config=J;this.signal=W;this.channels=Z;for(let Y of Z){let z=j.get(Y);if(z!==void 0)this.positions.set(Y,z),this.readTo.set(Y,z),this.dirty.add(Y)}if(W?.aborted)this.close();else W?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return y8(this.positions)}get isClosed(){return this.closed}ready(){return this.started??=(async()=>{let $=this.channels.filter((j)=>!this.positions.has(j));if($.length===0)return;let Z=await this.manager.driver.heads($);for(let j of $){let J=Z.get(j)??0;this.positions.set(j,J),this.readTo.set(j,J)}})(),this.started}async next(){await this.ready();for(;;){if(this.closed)return{done:!0,value:void 0};let $=this.pending.shift();if($)return this.positions.set($.channel,$.seq),{done:!1,value:$};let Z=this.dirty.values().next().value;if(Z!==void 0){await this.read(Z);continue}await this.idle()}}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}close(){if(this.closed)return;this.closed=!0,this.pending.length=0,this.signal?.removeEventListener("abort",this.onAbort),this.manager.forget(this),this.wake()}moved($,Z){let j=this.readTo.get($);if(j!==void 0&&Z===j)return;this.dirty.add($),this.wake()}async read($){let Z=this.readTo.get($)??0;this.dirty.delete($);let{batchSize:j}=this.config,{entries:J,head:W,gap:Y}=await this.manager.driver.read($,Z,j);if(this.closed)return;if(Y){this.readTo.set($,W),this.pending.push({type:"reset",channel:$,seq:W});return}for(let z of J)this.readTo.set($,z.seq),this.pending.push({type:"change",channel:$,seq:z.seq,data:z.data});if(J.length===j)this.dirty.add($)}idle(){return new Promise(($)=>{this.wakeUp=$})}wake(){let $=this.wakeUp;this.wakeUp=null,$?.()}}function n2($){if(typeof $!=="string"||$===""||$.length>kG)throw Error(`A change feed channel is a string of 1 to ${kG} characters; got ${JSON.stringify($)}.`)}function o2($){let Z=[...new Set(typeof $==="string"?[$]:$)];if(Z.length===0)throw Error("A change feed subscription needs at least one channel.");for(let j of Z)n2(j);return Z}function bD($){if($===void 0||$===null)return new Map;if(typeof $==="string")return l2($);let Z=$ instanceof Map?[...$]:Object.entries($);return l2(y8(new Map(Z)))}function wD($,Z){if($==="memory")return new s2;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The change feed driver needs the application it belongs to, and this ChangeFeedManager was built without one. Pass { application }.");if($==="database")return new i2(Z.make(B$));return $(Z)}if(typeof $==="string")throw Error(`Unknown change feed driver "${$}". The changeFeed slice's driver is "memory", "database", a ChangeFeedDriver, or a function returning one.`);return $}class vG extends g{static getFacadeAccessor(){return a2}static publish($,Z){return this.getFacadeRoot().publish($,Z)}static head($){return this.getFacadeRoot().head($)}static cursor($){return this.getFacadeRoot().cursor($)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,j){return this.getFacadeRoot().stream($,Z,j)}}class b3 extends g0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(g0)?$.make(g0):void 0;if(Z instanceof b3)return Z;let j=new b3($,Z);return $.instance(g0,j),j}constructor($,Z){super({driver:"memory",maxEventBytes:Z?.config.maxEventBytes,warnEventBytes:Z?.config.warnEventBytes},{application:$});this.application=$;this.previous=Z;this.channelsFrom=Z}channelsFrom;get channels(){return this.channelsFrom?.channels??null}publish($){this.sent.push($)}sendRevocation($){this.revoked.push($)}restore(){if(this.previous){this.application.instance(g0,this.previous);return}this.application.forget(g0)}assertSent($,Z,j){if(this.matching($,Z,j).length>0)return;throw Error(`Expected ${r2($,Z,j)} to have been broadcast. ${this.summary()}`)}assertNotSent($,Z,j){let J=this.matching($,Z,j);if(J.length===0)return;throw Error(`Expected ${r2($,Z,j)} not to have been broadcast, but it was broadcast ${t2(J.length)}: ${e2(J)}.`)}assertSentTimes($,Z,j,J){let W=this.matching($,j,J);if(W.length===Z)return;throw Error(`Expected ${r2($,j,J)} to have been broadcast ${t2(Z)}, but it was broadcast ${t2(W.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"}: ${e2(this.sent)}.`)}matching($,Z,j){return u$($),this.sent.filter((J)=>(J.pattern===$||T5($,J.topic))&&(Z===void 0||J.event===Z)&&(j===void 0||j(J.data,J)))}summary(){if(this.sent.length===0)return"Nothing was broadcast.";return`Broadcast: ${e2(this.sent)}.`}}function r2($,Z,j){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(j?" matching the predicate":"")}function t2($){return`${$} ${$===1?"time":"times"}`}function e2($){return $.map((Z)=>`${Z.topic} ${Z.event}(${kD(Z.data)})`).join(", ")}function kD($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class gG extends g{static getFacadeAccessor(){return g0}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 b3.install(T())}}class mG extends g{static getFacadeAccessor(){return RZ}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,j){return this.getFacadeRoot().set($,Z,j)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class v8{bound;constructor($){this.bound=$}get name(){return this.bound??O$()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,j=this.connection(Z);return cG(j.sql,(J)=>pG(Z,()=>$(J)),{slowTransactionThreshold:j.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-xhmtph39.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let j=this.connection(),{text:J,values:W}=uG($,dG(j.dialect),Z);return(this.handle()??j.sql).unsafe(J,W)}handle(){let $=L1();if($===void 0)return;return O$()===this.name?$:void 0}connection($=this.name){return hG($),T(B$).connection($)}}var qZ=new v8;class lG extends g{static getFacadeAccessor(){return B$}static connection($){return new v8($)}static get sql(){return qZ.sql}static get dialect(){return qZ.dialect}static query($){return qZ.query($)}static execute($){return qZ.execute($)}static transaction($){return qZ.transaction($)}static schema(){return qZ.schema()}static close(){return this.getFacadeRoot().close()}}export{l0 as Zc,mZ as _c,c8 as $c,d$ as ad,hZ as bd,R0 as cd,g3 as dd,Qj as ed,Kj as fd,Q9 as gd,Y1 as hd,r as id,dZ as jd,h5 as kd,o$ as ld,K9 as md,O9 as nd,Bj as od,Dj as pd,a3 as qd,iZ as rd,cT as sd,H9 as td,VQ as ud,Ij as vd,e8 as wd,d3 as xd,M1 as yd,G$ as zd,LF as Ad,r8 as Bd,I1 as Cd,Y$ as Dd,k8 as Ed,VG as Fd,TG as Gd,_D as Hd,w1 as Id,IG as Jd,HG as Kd,NG as Ld,_G as Md,ON as Nd,CG as Od,y8 as Pd,l2 as Qd,i2 as Rd,s2 as Sd,q8 as Td,a2 as Ud,qG as Vd,vG as Wd,p as Xd,cZ as Yd,jM as Zd,uJ as _d,JM as $d,WM as ae,XM as be,xz as ce,lJ as de,fz as ee,KM as fe,Ez as ge,g0 as he,N3 as ie,Rz as je,gG as ke,bX as le,A2 as me,wX as ne,kX as oe,qB as pe,yX as qe,E2 as re,mB as se,pB as te,R2 as ue,qX as ve,vX as we,RZ as xe,mG as ye,v8 as ze,lG as Ae,sJ as Be,zB as Ce,J2 as De,W2 as Ee,MI as Fe,nz as Ge,az as He,m3 as Ie,q1 as Je,fI as Ke,tz as Le,ez as Me,S2 as Ne,wZ as Oe,b2 as Pe,sL as Qe,oL as Re,g2 as Se,zD as Te,q2 as Ue,FD as Ve,R3 as We,m2 as Xe,YG as Ye,zG as Ze,E8 as _e,j1 as $e,f as af,h0 as bf,p3 as cf,P5 as df,DF as ef,I5 as ff,_5 as gf,o8 as hf,n8 as if,C5 as jf,HF as kf,PF as lf,b5 as mf,k5 as nf,q5 as of,u5 as pf,l5 as qf,i5 as rf,Zj as sf,SF as tf,W0 as uf,J9 as vf,r$ as wf,G9 as xf};
|
|
56
|
-
|
|
57
|
-
//# debugId=DB7C47F41E0C2B0964756E2164756E21
|