gemi 0.124.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.
Files changed (299) hide show
  1. package/dist/ai/AgentController.d.ts +185 -3
  2. package/dist/ai/AgentController.d.ts.map +1 -1
  3. package/dist/ai/client/index.d.ts +1 -1
  4. package/dist/ai/client/index.d.ts.map +1 -1
  5. package/dist/ai/client/index.js +38 -9
  6. package/dist/ai/client/index.js.map +1 -1
  7. package/dist/ai/client/reducer.d.ts.map +1 -1
  8. package/dist/ai/index.d.ts +2 -2
  9. package/dist/ai/index.d.ts.map +1 -1
  10. package/dist/ai/index.js +31 -48
  11. package/dist/ai/index.js.map +6 -15
  12. package/dist/ai/types.d.ts +26 -0
  13. package/dist/ai/types.d.ts.map +1 -1
  14. package/dist/ai/useChat.d.ts +35 -2
  15. package/dist/ai/useChat.d.ts.map +1 -1
  16. package/dist/app/index.js +1 -1
  17. package/dist/auth/AuthController.d.ts.map +1 -1
  18. package/dist/auth/AuthManager.d.ts +11 -0
  19. package/dist/auth/AuthManager.d.ts.map +1 -1
  20. package/dist/auth/AuthServiceProvider.d.ts +2 -0
  21. package/dist/auth/AuthServiceProvider.d.ts.map +1 -1
  22. package/dist/auth/config.d.ts +71 -2
  23. package/dist/auth/config.d.ts.map +1 -1
  24. package/dist/auth/oauth/providers.d.ts +10 -0
  25. package/dist/auth/oauth/providers.d.ts.map +1 -0
  26. package/dist/bun/plugin.js +1 -1
  27. package/dist/bun/preload.js +1 -1
  28. package/dist/{chunk-a3g7y70h.js → chunk-0x1s02r1.js} +3 -3
  29. package/dist/{chunk-a3g7y70h.js.map → chunk-0x1s02r1.js.map} +1 -1
  30. package/dist/{chunk-yzhv93b0.js → chunk-1jcngq6w.js} +3 -3
  31. package/dist/{chunk-yzhv93b0.js.map → chunk-1jcngq6w.js.map} +1 -1
  32. package/dist/{chunk-mrswc6qw.js → chunk-1mxb44n9.js} +2 -2
  33. package/dist/{chunk-mrswc6qw.js.map → chunk-1mxb44n9.js.map} +1 -1
  34. package/dist/{chunk-9tr92nwy.js → chunk-1n40bdxf.js} +2 -2
  35. package/dist/{chunk-9tr92nwy.js.map → chunk-1n40bdxf.js.map} +1 -1
  36. package/dist/chunk-1xmh61fg.js +5 -0
  37. package/dist/{chunk-70nnh0y7.js.map → chunk-1xmh61fg.js.map} +1 -1
  38. package/dist/{chunk-bt9qv2jj.js → chunk-3br5zr7a.js} +3 -3
  39. package/dist/{chunk-bt9qv2jj.js.map → chunk-3br5zr7a.js.map} +1 -1
  40. package/dist/{chunk-w61sphn5.js → chunk-3kxe9geg.js} +3 -3
  41. package/dist/{chunk-w61sphn5.js.map → chunk-3kxe9geg.js.map} +1 -1
  42. package/dist/{chunk-bnt8kx6x.js → chunk-5fh4pvyt.js} +2 -2
  43. package/dist/{chunk-bnt8kx6x.js.map → chunk-5fh4pvyt.js.map} +1 -1
  44. package/dist/{chunk-rpyczdta.js → chunk-6gwxvmjv.js} +3 -3
  45. package/dist/{chunk-rpyczdta.js.map → chunk-6gwxvmjv.js.map} +1 -1
  46. package/dist/{chunk-65s834td.js → chunk-6q6bhkyf.js} +1 -1
  47. package/dist/{chunk-fn2qfwgx.js → chunk-6vz75swk.js} +2 -2
  48. package/dist/{chunk-fn2qfwgx.js.map → chunk-6vz75swk.js.map} +1 -1
  49. package/dist/chunk-6wgh7nk6.js +15 -0
  50. package/dist/{chunk-n0r5xyk2.js.map → chunk-6wgh7nk6.js.map} +6 -5
  51. package/dist/chunk-7vrrgxwm.js +22 -0
  52. package/dist/chunk-7vrrgxwm.js.map +21 -0
  53. package/dist/{chunk-kzsjyvvc.js → chunk-7zj6bk9a.js} +2 -2
  54. package/dist/{chunk-kzsjyvvc.js.map → chunk-7zj6bk9a.js.map} +1 -1
  55. package/dist/{chunk-3hqwz48c.js → chunk-8tvfmy1a.js} +4 -4
  56. package/dist/{chunk-3hqwz48c.js.map → chunk-8tvfmy1a.js.map} +1 -1
  57. package/dist/{chunk-6bgb1nhq.js → chunk-910p6ne6.js} +2 -2
  58. package/dist/{chunk-6bgb1nhq.js.map → chunk-910p6ne6.js.map} +1 -1
  59. package/dist/{chunk-96a1459v.js → chunk-ap3g6rbw.js} +2 -2
  60. package/dist/{chunk-96a1459v.js.map → chunk-ap3g6rbw.js.map} +1 -1
  61. package/dist/{chunk-3j6s5bmx.js → chunk-ayfjjgv2.js} +1 -1
  62. package/dist/chunk-b4x1dt3s.js +10 -0
  63. package/dist/chunk-b4x1dt3s.js.map +43 -0
  64. package/dist/{chunk-f29pktad.js → chunk-b7a22evs.js} +3 -3
  65. package/dist/{chunk-f29pktad.js.map → chunk-b7a22evs.js.map} +1 -1
  66. package/dist/{chunk-qdj8ek8z.js → chunk-bny9s44t.js} +2 -2
  67. package/dist/{chunk-qdj8ek8z.js.map → chunk-bny9s44t.js.map} +1 -1
  68. package/dist/{chunk-1rnh9qrp.js → chunk-by5gwr8x.js} +2 -2
  69. package/dist/{chunk-1rnh9qrp.js.map → chunk-by5gwr8x.js.map} +1 -1
  70. package/dist/{chunk-nn2jeat2.js → chunk-c0qpv8x7.js} +2 -2
  71. package/dist/{chunk-17dndh5z.js.map → chunk-c0qpv8x7.js.map} +1 -1
  72. package/dist/{chunk-f4cmz31h.js → chunk-cpem1j1x.js} +2 -2
  73. package/dist/{chunk-f4cmz31h.js.map → chunk-cpem1j1x.js.map} +1 -1
  74. package/dist/{chunk-019wz697.js → chunk-crnfxn9n.js} +2 -2
  75. package/dist/{chunk-019wz697.js.map → chunk-crnfxn9n.js.map} +1 -1
  76. package/dist/{chunk-s5jxc63j.js → chunk-cwt8e782.js} +3 -3
  77. package/dist/{chunk-s5jxc63j.js.map → chunk-cwt8e782.js.map} +1 -1
  78. package/dist/{chunk-fw7ds23a.js → chunk-dxyxd7b3.js} +2 -2
  79. package/dist/{chunk-fw7ds23a.js.map → chunk-dxyxd7b3.js.map} +1 -1
  80. package/dist/{chunk-qhz0x97z.js → chunk-dy58aztm.js} +2 -2
  81. package/dist/{chunk-qhz0x97z.js.map → chunk-dy58aztm.js.map} +1 -1
  82. package/dist/{chunk-skf89vrv.js → chunk-entpqjyn.js} +2 -2
  83. package/dist/{chunk-skf89vrv.js.map → chunk-entpqjyn.js.map} +1 -1
  84. package/dist/{chunk-7gfdts60.js → chunk-eq5svwca.js} +2 -2
  85. package/dist/{chunk-7gfdts60.js.map → chunk-eq5svwca.js.map} +1 -1
  86. package/dist/{chunk-n1a2zj5z.js → chunk-erzfs4t2.js} +2 -2
  87. package/dist/{chunk-n1a2zj5z.js.map → chunk-erzfs4t2.js.map} +3 -3
  88. package/dist/{chunk-3y294mb8.js → chunk-ex41d03h.js} +2 -2
  89. package/dist/{chunk-3y294mb8.js.map → chunk-ex41d03h.js.map} +1 -1
  90. package/dist/{chunk-v2ggafz1.js → chunk-ey1xrbaz.js} +2 -2
  91. package/dist/{chunk-v2ggafz1.js.map → chunk-ey1xrbaz.js.map} +1 -1
  92. package/dist/chunk-eyptwf54.js +57 -0
  93. package/dist/{chunk-5j50q4g8.js.map → chunk-eyptwf54.js.map} +22 -19
  94. package/dist/{chunk-zsfwcdqn.js → chunk-g52fcwca.js} +2 -2
  95. package/dist/{chunk-zsfwcdqn.js.map → chunk-g52fcwca.js.map} +1 -1
  96. package/dist/{chunk-rttrpjqk.js → chunk-ghcvztxn.js} +2 -2
  97. package/dist/{chunk-rttrpjqk.js.map → chunk-ghcvztxn.js.map} +1 -1
  98. package/dist/{chunk-wbg2tza5.js → chunk-gp00enrk.js} +1 -1
  99. package/dist/{chunk-92sk56n0.js → chunk-h8w9mzjj.js} +6 -6
  100. package/dist/{chunk-92sk56n0.js.map → chunk-h8w9mzjj.js.map} +7 -7
  101. package/dist/{chunk-cfdwsvtx.js → chunk-hff9w6rt.js} +2 -2
  102. package/dist/{chunk-cfdwsvtx.js.map → chunk-hff9w6rt.js.map} +1 -1
  103. package/dist/{chunk-17dndh5z.js → chunk-hxn0s3zh.js} +2 -2
  104. package/dist/{chunk-nn2jeat2.js.map → chunk-hxn0s3zh.js.map} +1 -1
  105. package/dist/{chunk-8m2htvjn.js → chunk-hzen9gh4.js} +2 -2
  106. package/dist/{chunk-8m2htvjn.js.map → chunk-hzen9gh4.js.map} +1 -1
  107. package/dist/{chunk-c4jnxmf2.js → chunk-j10a0m7q.js} +1 -1
  108. package/dist/{chunk-5e22tm7m.js → chunk-j12hpdxk.js} +1 -1
  109. package/dist/{chunk-ykz38t0t.js → chunk-j5rwv09s.js} +2 -2
  110. package/dist/{chunk-ykz38t0t.js.map → chunk-j5rwv09s.js.map} +1 -1
  111. package/dist/{chunk-w4z6x54b.js → chunk-jykkqwcy.js} +3 -3
  112. package/dist/{chunk-w4z6x54b.js.map → chunk-jykkqwcy.js.map} +1 -1
  113. package/dist/{chunk-w3812s34.js → chunk-k1ebt28j.js} +2 -2
  114. package/dist/{chunk-w3812s34.js.map → chunk-k1ebt28j.js.map} +1 -1
  115. package/dist/{chunk-h3p8qzft.js → chunk-kcsa57km.js} +2 -2
  116. package/dist/{chunk-h3p8qzft.js.map → chunk-kcsa57km.js.map} +1 -1
  117. package/dist/{chunk-1qwhty9p.js → chunk-khdkrfxp.js} +2 -2
  118. package/dist/{chunk-1qwhty9p.js.map → chunk-khdkrfxp.js.map} +1 -1
  119. package/dist/{chunk-b5afy6k9.js → chunk-knq4ack4.js} +2 -2
  120. package/dist/{chunk-b5afy6k9.js.map → chunk-knq4ack4.js.map} +1 -1
  121. package/dist/{chunk-121p4g9j.js → chunk-m7pghdcy.js} +2 -2
  122. package/dist/{chunk-121p4g9j.js.map → chunk-m7pghdcy.js.map} +1 -1
  123. package/dist/{chunk-rtawbqec.js → chunk-mmqnq1qh.js} +3 -3
  124. package/dist/{chunk-rtawbqec.js.map → chunk-mmqnq1qh.js.map} +1 -1
  125. package/dist/{chunk-34fkx6kb.js → chunk-n3z83qhq.js} +2 -2
  126. package/dist/{chunk-34fkx6kb.js.map → chunk-n3z83qhq.js.map} +1 -1
  127. package/dist/{chunk-mvkz22p4.js → chunk-npbf06c1.js} +2 -2
  128. package/dist/{chunk-mvkz22p4.js.map → chunk-npbf06c1.js.map} +1 -1
  129. package/dist/{chunk-2affxmkn.js → chunk-p5df4pn7.js} +2 -2
  130. package/dist/{chunk-2affxmkn.js.map → chunk-p5df4pn7.js.map} +1 -1
  131. package/dist/{chunk-y434jc1c.js → chunk-p6jbmcrg.js} +2 -2
  132. package/dist/{chunk-y434jc1c.js.map → chunk-p6jbmcrg.js.map} +1 -1
  133. package/dist/{chunk-jctb7v53.js → chunk-p7mvp5nf.js} +2 -2
  134. package/dist/{chunk-jctb7v53.js.map → chunk-p7mvp5nf.js.map} +1 -1
  135. package/dist/{chunk-jys8y39p.js → chunk-q6ah4yjg.js} +2 -2
  136. package/dist/{chunk-jys8y39p.js.map → chunk-q6ah4yjg.js.map} +1 -1
  137. package/dist/{chunk-pmyh33v5.js → chunk-r923001x.js} +2 -2
  138. package/dist/{chunk-pmyh33v5.js.map → chunk-r923001x.js.map} +1 -1
  139. package/dist/{chunk-mqtfaqx5.js → chunk-rany5zgk.js} +2 -2
  140. package/dist/{chunk-mqtfaqx5.js.map → chunk-rany5zgk.js.map} +1 -1
  141. package/dist/{chunk-30xxc6r7.js → chunk-rmgkc3a2.js} +2 -2
  142. package/dist/{chunk-30xxc6r7.js.map → chunk-rmgkc3a2.js.map} +1 -1
  143. package/dist/{chunk-v8v5qfnh.js → chunk-rvspb96n.js} +3 -3
  144. package/dist/{chunk-v8v5qfnh.js.map → chunk-rvspb96n.js.map} +1 -1
  145. package/dist/{chunk-zsvav1dk.js → chunk-rwmja4zs.js} +2 -2
  146. package/dist/{chunk-zsvav1dk.js.map → chunk-rwmja4zs.js.map} +1 -1
  147. package/dist/{chunk-j7v7dft7.js → chunk-s4semb89.js} +1 -1
  148. package/dist/{chunk-szn2n976.js → chunk-s4xg69r9.js} +2 -2
  149. package/dist/{chunk-szn2n976.js.map → chunk-s4xg69r9.js.map} +1 -1
  150. package/dist/{chunk-4drnyymm.js → chunk-stn0a56e.js} +2 -2
  151. package/dist/{chunk-4drnyymm.js.map → chunk-stn0a56e.js.map} +1 -1
  152. package/dist/{chunk-pe46a5a5.js → chunk-sv125fqq.js} +2 -2
  153. package/dist/{chunk-pe46a5a5.js.map → chunk-sv125fqq.js.map} +1 -1
  154. package/dist/{chunk-dxfhhw5h.js → chunk-t2t63wa0.js} +2 -2
  155. package/dist/{chunk-dxfhhw5h.js.map → chunk-t2t63wa0.js.map} +1 -1
  156. package/dist/{chunk-675kzd7z.js → chunk-t6qpm2j7.js} +2 -2
  157. package/dist/{chunk-675kzd7z.js.map → chunk-t6qpm2j7.js.map} +1 -1
  158. package/dist/chunk-tabsxzg9.js +5 -0
  159. package/dist/chunk-tabsxzg9.js.map +13 -0
  160. package/dist/{chunk-qycwjzsv.js → chunk-vhvvjaj3.js} +3 -3
  161. package/dist/{chunk-qycwjzsv.js.map → chunk-vhvvjaj3.js.map} +1 -1
  162. package/dist/{chunk-sd0c2001.js → chunk-x2j84d06.js} +2 -2
  163. package/dist/{chunk-sd0c2001.js.map → chunk-x2j84d06.js.map} +1 -1
  164. package/dist/{chunk-75ewjc4a.js → chunk-xe2pm36q.js} +2 -2
  165. package/dist/{chunk-75ewjc4a.js.map → chunk-xe2pm36q.js.map} +1 -1
  166. package/dist/{chunk-z5jydj5r.js → chunk-xfvegbxn.js} +2 -2
  167. package/dist/{chunk-z5jydj5r.js.map → chunk-xfvegbxn.js.map} +1 -1
  168. package/dist/{chunk-2n4490pk.js → chunk-y9f2see3.js} +3 -3
  169. package/dist/{chunk-2n4490pk.js.map → chunk-y9f2see3.js.map} +1 -1
  170. package/dist/{chunk-nkzmk7v3.js → chunk-yhht1j7f.js} +2 -2
  171. package/dist/{chunk-nkzmk7v3.js.map → chunk-yhht1j7f.js.map} +1 -1
  172. package/dist/{chunk-nnarmbjv.js → chunk-z5nfve1k.js} +2 -2
  173. package/dist/chunk-z5nfve1k.js.map +10 -0
  174. package/dist/{chunk-fvrmptd0.js → chunk-zq5375wd.js} +3 -3
  175. package/dist/{chunk-fvrmptd0.js.map → chunk-zq5375wd.js.map} +1 -1
  176. package/dist/chunks/{ThemeProvider-CbOx8IRl.js → ThemeProvider-CS2a1snV.js} +27 -1
  177. package/dist/chunks/ThemeProvider-CS2a1snV.js.map +1 -0
  178. package/dist/client/Mutation.d.ts +7 -6
  179. package/dist/client/Mutation.d.ts.map +1 -1
  180. package/dist/client/MutationError.d.ts +53 -1
  181. package/dist/client/MutationError.d.ts.map +1 -1
  182. package/dist/client/QueryResource.d.ts +9 -0
  183. package/dist/client/QueryResource.d.ts.map +1 -1
  184. package/dist/client/auth/useEmailCode.d.ts +3 -3
  185. package/dist/client/auth/useForgotPassword.d.ts +1 -1
  186. package/dist/client/auth/useResetPassword.d.ts +1 -1
  187. package/dist/client/auth/useSignIn.d.ts +1 -1
  188. package/dist/client/auth/useSignOut.d.ts +1 -1
  189. package/dist/client/auth/useSignUp.d.ts +1 -1
  190. package/dist/client/index.d.ts +4 -2
  191. package/dist/client/index.d.ts.map +1 -1
  192. package/dist/client/index.js +136 -9
  193. package/dist/client/index.js.map +1 -1
  194. package/dist/client/useMutation.d.ts +18 -8
  195. package/dist/client/useMutation.d.ts.map +1 -1
  196. package/dist/client/useSetQueryData.d.ts +69 -0
  197. package/dist/client/useSetQueryData.d.ts.map +1 -0
  198. package/dist/config/index.js +1 -1
  199. package/dist/console/run.js +2 -2
  200. package/dist/console/run.js.map +1 -1
  201. package/dist/container/index.js +2 -2
  202. package/dist/container/index.js.map +1 -1
  203. package/dist/database/index.js +2 -2
  204. package/dist/database/index.js.map +1 -1
  205. package/dist/email/index.js +2 -2
  206. package/dist/email/index.js.map +1 -1
  207. package/dist/facades/Auth.d.ts +29 -2
  208. package/dist/facades/Auth.d.ts.map +1 -1
  209. package/dist/facades/RateLimiter.d.ts +16 -1
  210. package/dist/facades/RateLimiter.d.ts.map +1 -1
  211. package/dist/facades/index.js +2 -2
  212. package/dist/facades/index.js.map +1 -1
  213. package/dist/foundation/index.js +2 -2
  214. package/dist/foundation/index.js.map +1 -1
  215. package/dist/http/HttpRequest.d.ts +14 -0
  216. package/dist/http/HttpRequest.d.ts.map +1 -1
  217. package/dist/http/McpRouter.d.ts +121 -2
  218. package/dist/http/McpRouter.d.ts.map +1 -1
  219. package/dist/http/RateLimitExceededError.d.ts +24 -0
  220. package/dist/http/RateLimitExceededError.d.ts.map +1 -0
  221. package/dist/http/RateLimitMiddleware.d.ts +2 -5
  222. package/dist/http/RateLimitMiddleware.d.ts.map +1 -1
  223. package/dist/http/index.d.ts +2 -1
  224. package/dist/http/index.d.ts.map +1 -1
  225. package/dist/http/index.js +2 -2
  226. package/dist/http/index.js.map +1 -1
  227. package/dist/http/refusal.d.ts +6 -1
  228. package/dist/http/refusal.d.ts.map +1 -1
  229. package/dist/http/requestContext.d.ts +3 -1
  230. package/dist/http/requestContext.d.ts.map +1 -1
  231. package/dist/http/requestState.d.ts +57 -0
  232. package/dist/http/requestState.d.ts.map +1 -0
  233. package/dist/i18n/dictionaryRuntime.js +2 -2
  234. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  235. package/dist/i18n/index.js +2 -2
  236. package/dist/i18n/index.js.map +1 -1
  237. package/dist/kernel/index.js +2 -2
  238. package/dist/kernel/index.js.map +1 -1
  239. package/dist/orm/index.js +2 -2
  240. package/dist/orm/index.js.map +1 -1
  241. package/dist/server/Server.d.ts.map +1 -1
  242. package/dist/server/health.d.ts +67 -0
  243. package/dist/server/health.d.ts.map +1 -0
  244. package/dist/server/index.d.ts +1 -0
  245. package/dist/server/index.d.ts.map +1 -1
  246. package/dist/server/index.js +2 -2
  247. package/dist/server/index.js.map +5 -4
  248. package/dist/server/shutdown.d.ts +3 -4
  249. package/dist/server/shutdown.d.ts.map +1 -1
  250. package/dist/services/features/gate.d.ts +11 -0
  251. package/dist/services/features/gate.d.ts.map +1 -0
  252. package/dist/services/index.d.ts +4 -4
  253. package/dist/services/index.d.ts.map +1 -1
  254. package/dist/services/index.js +3 -3
  255. package/dist/services/index.js.map +2 -2
  256. package/dist/services/logging/LogManager.d.ts +1 -0
  257. package/dist/services/logging/LogManager.d.ts.map +1 -1
  258. package/dist/services/logging/config.d.ts +23 -1
  259. package/dist/services/logging/config.d.ts.map +1 -1
  260. package/dist/services/logging/consoleSink.d.ts +25 -0
  261. package/dist/services/logging/consoleSink.d.ts.map +1 -0
  262. package/dist/services/mcp/McpRegistry.d.ts +106 -14
  263. package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
  264. package/dist/services/mcp/http/McpHttpServer.d.ts +41 -2
  265. package/dist/services/mcp/http/McpHttpServer.d.ts.map +1 -1
  266. package/dist/services/mcp/toAgentTools.d.ts +21 -3
  267. package/dist/services/mcp/toAgentTools.d.ts.map +1 -1
  268. package/dist/services/queue/work.js +2 -2
  269. package/dist/services/queue/work.js.map +1 -1
  270. package/dist/services/rate-limiter/RateLimiter.d.ts +12 -0
  271. package/dist/services/rate-limiter/RateLimiter.d.ts.map +1 -1
  272. package/dist/services/router/globalMiddleware.d.ts +4 -3
  273. package/dist/services/router/globalMiddleware.d.ts.map +1 -1
  274. package/dist/stats/route-table.js +1 -1
  275. package/dist/support/index.js +2 -2
  276. package/dist/support/index.js.map +1 -1
  277. package/dist/testing/index.js +1 -1
  278. package/dist/vitest/index.js +1 -1
  279. package/package.json +1 -1
  280. package/skills/gemi-react-best-practices/SKILL.md +1 -1
  281. package/skills/gemi-react-best-practices/rules/query-mutate-over-refetch.md +14 -0
  282. package/skills/gemi-react-best-practices/rules/routing-middleware-dsl.md +2 -1
  283. package/dist/chunk-5j50q4g8.js +0 -57
  284. package/dist/chunk-70nnh0y7.js +0 -5
  285. package/dist/chunk-kc924zjz.js +0 -5
  286. package/dist/chunk-kc924zjz.js.map +0 -12
  287. package/dist/chunk-n0r5xyk2.js +0 -14
  288. package/dist/chunk-nnarmbjv.js.map +0 -10
  289. package/dist/chunk-pya4rqm2.js +0 -5
  290. package/dist/chunk-pya4rqm2.js.map +0 -12
  291. package/dist/chunk-zmf3vhex.js +0 -10
  292. package/dist/chunk-zmf3vhex.js.map +0 -43
  293. package/dist/chunks/ThemeProvider-CbOx8IRl.js.map +0 -1
  294. /package/dist/{chunk-65s834td.js.map → chunk-6q6bhkyf.js.map} +0 -0
  295. /package/dist/{chunk-3j6s5bmx.js.map → chunk-ayfjjgv2.js.map} +0 -0
  296. /package/dist/{chunk-wbg2tza5.js.map → chunk-gp00enrk.js.map} +0 -0
  297. /package/dist/{chunk-c4jnxmf2.js.map → chunk-j10a0m7q.js.map} +0 -0
  298. /package/dist/{chunk-5e22tm7m.js.map → chunk-j12hpdxk.js.map} +0 -0
  299. /package/dist/{chunk-j7v7dft7.js.map → chunk-s4semb89.js.map} +0 -0
@@ -1,57 +0,0 @@
1
- // @bun
2
- import{Cf as oG}from"./chunk-w61sphn5.js";import{Wf as sG}from"./chunk-s5jxc63j.js";import{$f as KG,$g as wG,Ng as i3,Ug as a$,Xf as lZ,Yg as ZX,Zg as k$,_g as PG,ag as hj,bg as cj,bh as kG,cg as i8,dg as p8,gg as h8,hg as c8,ig as yZ,jg as dX,kg as VG,lg as Qj,mg as v,rg as C,sg as Q4,tg as n$,ug as s8,vg as l3,xg as F$,yg as g,zg as L8}from"./chunk-n0r5xyk2.js";import{eh as v1,fh as P0,gh as m1,hh as lj}from"./chunk-n1a2zj5z.js";import{ih as wX,jh as f8,kh as N}from"./chunk-kc924zjz.js";import{nh as az,qh as S3}from"./chunk-v8v5qfnh.js";import{uh as C9,xh as xG}from"./chunk-2n4490pk.js";import{Ph as X$,Uh as g1}from"./chunk-96a1459v.js";import{gi as wz}from"./chunk-skf89vrv.js";import{ji as _G}from"./chunk-mqtfaqx5.js";import{ki as xZ}from"./chunk-pe46a5a5.js";import{Bi as iG,li as c3,mi as L1,ni as O$,oi as uG,pi as lG,ri as CZ,si as bG}from"./chunk-qycwjzsv.js";import{Qi as D$}from"./chunk-mvkz22p4.js";import{Vi as GG,_i as m5}from"./chunk-3y294mb8.js";import{fj as XG,kj as i}from"./chunk-h3p8qzft.js";import{lj as kZ,oj as T}from"./chunk-rpyczdta.js";import{wj as q5}from"./chunk-75ewjc4a.js";import{xj as yG}from"./chunk-nnarmbjv.js";import{Ij as OG}from"./chunk-z5jydj5r.js";import{Nj as E8}from"./chunk-17dndh5z.js";function q3($){return typeof $==="function"&&$.prototype!==void 0}function l0($){return typeof $==="string"?[$]:$}function v3($,Z){let J=Z?"attachment":"inline",j=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${j}"; filename*=UTF-8''${encodeURIComponent($)}`}function YF($){return"total"in $&&"partial"in $&&"body"in $}function jj(){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":c8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function zF($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(YF($))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 d8($,Z){if($ instanceof Response)return $;if(!$)return jj();let J=await zF($),{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 jj()}let{range:G}=Z;if(G){if(z<=0)return mZ(Math.max(z,0));if(!X){if(j instanceof Blob){let K=p8(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",h8(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",v3(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,B]of Object.entries(J.extraHeaders))O.set(K,B);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 Wj={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 Wj)))return Math.floor(Number(J[1])*(Wj[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 zj($){return pZ.has($)}function Xj($){return pZ.get($)?.limit??null}function Gj($){let Z=pZ.get($);return Z?Z.read>Z.limit:!1}function XF($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function l8($,Z){let J=XF($);if(J!==null&&J>Z)throw new d$(Z)}function g3($,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),FF($,W)}if(J.checkDeclared!==!1)l8($,Z)}function GF($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function u8($,Z){if(Z.stream!==void 0)return Z.stream;let J=GF($);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(l8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=u8($,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 Yj($){return $.headers.get("Content-Type")??""}function FF($,Z){let J=(j,W)=>Object.defineProperty($,j,{configurable:!0,...W});J("body",{get:()=>u8($,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:Yj($)})}),J("formData",{value:async()=>new Response(await c$($,Z),{headers:{"Content-Type":Yj($)}}).formData()}),J("clone",{value:()=>{l8($,Z.limit);let j=u8($,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 Fj($){return q3($)}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(!Fj(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(Fj(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=l0($),this}}class Kj{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 Qj($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(Gj($.rawRequest))throw new d$(Xj($.rawRequest));throw J}}}class Oj{constructor(...$){return new j0(...$)}}class Dj extends j0{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,j=i8(J?.headers.get("Range"));if(Z)Z.rangeRequest=j;try{let W=await super.run($);return await d8(W,{range:j,method:J?.method})}catch(W){if(W instanceof s8)return mZ(W.total);throw W}finally{if(Z)Z.rangeRequest=null}}}class Bj{constructor(...$){return new Dj(...$)}}class Uj{__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 b0{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 Uj($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${QF($)}.`);return KF($,this)}file($,Z){return new Oj("GET",$,Z)}stream($,Z){return new Bj("GET",$,Z)}proxy($,Z={}){return new Kj($,Z)}}function QF($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function KF($,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 b0{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 m3($,Z){let J=z$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var OF=/^[A-Za-z0-9_-]+$/,DF=/^:[A-Za-z_][A-Za-z0-9_]*$/,Vj=/^[A-Za-z0-9_-]{1,128}$/,BF=/^[A-Za-z0-9_.:-]+$/;class p extends Error{constructor($){super($);this.name="InvalidChannelError"}}function Tj($){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(DF.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(!OF.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"||!Vj.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 o8($){if(u$($).some((J)=>J.startsWith(":")))throw new p(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function Mj($){if(typeof $!=="string"||$.length===0||$.length>64||!BF.test($))throw new p(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function Ij($,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(":")&&Vj.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 p3 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 g3(this.req.rawRequest,hZ(Z)),{}}}function UF($){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 VF={"body-limit":p3};class q1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:hZ($.bodyLimit)}get aliases(){return{...VF,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!zj($))g3($,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 UF($).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:Lj(z)})}}else if(q3(W)){let z=new W(Z);j.push({run:z.run.bind(z),runsOnRefusal:Lj(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 TF(j.slice(Y+1)),z}return W})()}}function Lj($){return $?.runsOnRefusal===!0}async function TF($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class h3{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...l0($)],this}events(...$){return this}}class _j{static __brand="ChannelRouter";channels={};public(){return new h3("public")}private($){return new h3("private",$)}async authorize($,Z,J={},j={}){try{HF(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(!Cj(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(()=>c3.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 Hj(X);if(!F)return{ok:!1,code:"denied"};if(Y=l$(F),W.visibility==="private"&&W.authorizer){if(await Pj(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 Pj(W.authorizer,X,z):await Hj(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:Y,pattern:Z}}catch(F){if(LF(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 MF($,Z,J={},j={}){let W=typeof $==="function"?new $:$;xj(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 Cj($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function Hj($){if(!N.getStore().user&&z$($)===null)return null;try{return await h0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function Pj($,Z,J){if(IF($))return new $().authorize(Z,J);return $(Z,J)}function IF($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function LF($){return $?.kind===v1||g1($)||X$($)}var Nj=new WeakSet;function HF($){if(Nj.has($))return;xj($),Nj.add($)}function xj($){let Z=Object.entries($.channels),J=[];for(let[j,W]of Z){if(!Cj(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(PF(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 PF($,Z){if($.length!==Z.length)return!1;return $.every((J,j)=>J===Z[j]||J.startsWith(":")||Z[j].startsWith(":"))}class n8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class a8{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class Sj{static __brand="McpRouter";routes={};scopes;param($){return new n8($.as,$.input,$.bind)}fromApiRoute($,Z,J){return new a8($,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 r8 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 r8([K0($,W)||"/",X.toString()].filter(Boolean).join("?"),z??(Y?301:307))}static external($,Z=307){throw new r8($,Z)}}var Aj=Symbol.for("gemi.HttpResponse");class G${kind;body;status;headers;[Aj]=!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 NF(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 NF($){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&&$[Aj]===!0}function _F($,Z,J={}){return G$.error($,Z,J)}class fj{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 t8($,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",v3(W,z));return new Response(j instanceof Blob?j.stream():j,{status:X,headers:Z})}class Ej{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 bj($,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 Rj{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=bj(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 wj{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=bj(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 Rj($,Z)}file($){return new Ej($)}redirect($){return new fj($)}layout($,Z,J){return new wj($,Z,J)}}function CF($){return $}function xF(){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 SF($,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 AF($,Z){let J=(j)=>j.replace(/\/+$/,"")||"/";return J($)===J(Z)}function d3($,Z){let J=Z||T(A).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=SF($,!j);if(j||!AF(new URL(Y,W).pathname,W.pathname))W.searchParams.set(j1,Y)}return j?W.href:`${W.pathname}${W.search}`}class kj extends r{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let j=await m3(T(A),J);if(!j)throw new F$({redirectTo:d3(J,$)});return Z.setUser(j),{}}}var $4="gemi_same_site",e8="private, no-cache, no-store, max-age=0, must-revalidate";class u3 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($4))return{};if(z$(Z))return{};let W=J.headers.get("Sec-Fetch-Site");if(W&&W!=="cross-site")return{};throw j.searchParams.set($4,"1"),new yj(`${j.pathname}${j.search}`)}}class yj extends P0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=fF($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":e8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":e8}},viewData:{status:200,data:{},headers:{"Cache-Control":e8},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 fF($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class qj 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 vj={"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 gj 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={...vj,...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={...vj,...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(mj("window",j),mj("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 mj($,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",...$?uj($):{}};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 dj extends r{async run($,Z){let J=EF();if(!J)return{};let j=await J.consume(this.key(),{limit:pj($)??this.config.limit,window:pj(Z)??this.config.window});if(this.config.headers!==!1){let W=this.req.ctx?.();if(W)for(let[Y,z]of Object.entries(uj(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 $=hj(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${o$(this.req)}:${this.req.routePath??"*"}`}}function EF(){try{let $=T();return $.bound(Y1)?$.make(Y1):null}catch{return null}}function o$($){let Z=cj($.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 uj($){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 pj($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class ij extends r{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new Z4;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new Z4;return{}}}class Z4 extends P0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:lj("csrf","Invalid CSRF token",403)}},view:{}}}class sj{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class oj{all($,Z){return!0}}class J4{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 l3}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 l3}}function bF($){return new J4($)}async function s3($,Z,J=!1){if(!$.body)return new Uint8Array;let[j,W]=await lF($.body),z=j.length>=2&&j[0]===31&&j[1]===139?W.pipeThrough(new DecompressionStream("gzip")):W;return uF(z,Z,J,$.url)}async function uF($,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 i3(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 lF($){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 o3($){return new TextDecoder("utf-8").decode($)}var iF={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function Q$($){return $.replace(/[&<>"']/g,(Z)=>iF[Z])}var sF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function j4($){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 sF[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 W4($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function nj($,Z){let J=$.length,j=0;while(j<J){if(Z.stopped?.())return;let W=$.indexOf("<",j);if(W===-1){Z.text(j4($.slice(j)));return}if(W>j)Z.text(j4($.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(W4($.slice(W+2,Y).trim())),j=Y+1}else{let Y=oF($,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=W4(z.slice(0,G));if(F){if(Z.open(F,nF(z.slice(G)),X),X)Z.close(F)}j=Y+1}}}function oF($,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 nF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let j of $.matchAll(J))Z[W4(j[1])]=j4(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 $9="http://www.sitemaps.org/schemas/sitemap/0.9",aF="http://www.w3.org/1999/xhtml",X4=`<?xml version="1.0" encoding="UTF-8"?>
3
- `,aj=`<urlset xmlns="${$9}" xmlns:xhtml="${aF}">
4
- `,rj=`</urlset>
5
- `,K$=50000,uZ=52428800,tj=2048,rF=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),tF=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,eF="application/xml; charset=utf-8",ej=new TextEncoder;function G4($,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>tj)throw new W0(`Sitemap: ${Z} is over ${tj} characters: "${j.slice(0,80)}\u2026".`);return j}function Z9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new W0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!tF.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 $Q($){let Z=G4($.loc,"loc"),J=`<url><loc>${Q$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${Q$(Z9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!rF.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=G4(j.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${Q$(W)}" href="${Q$(Y)}"/>`}return`${J}</url>
6
- `}function ZQ($){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 J9($,Z={}){let{maxUrls:J,maxBytes:j}=ZQ(Z),W=ej.encode(X4+aj+rj).byteLength,Y=[],z=[],X=W,G=()=>{Y.push(X4+aj+z.join("")+rj),z=[],X=W};for(let F of $){let Q=$Q(F),O=ej.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 j9($){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=G4(j.loc,"sitemap loc");if(Z+=`<sitemap><loc>${Q$(W)}</loc>`,j.lastmod!=null)Z+=`<lastmod>${Q$(Z9(j.lastmod,W))}</lastmod>`;Z+=`</sitemap>
7
- `}return`${X4}<sitemapindex xmlns="${$9}">
8
- ${Z}</sitemapindex>
9
- `}function Y4($,Z,J){let j=new Headers(J);if(!j.has("content-type"))j.set("content-type",eF);return new Response($,{status:Z,headers:j})}function JQ($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function jQ($,Z={}){let J=J9($,Z),j=JQ(Z.page);if(j!==null){let Y=J[j-1];return Y?Y4(Y,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(J.length===1)return Y4(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 Y4(j9(J.map((Y,z)=>({loc:W(z+1)}))),200,Z.headers)}function z4($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function W9($,Z={}){let J=Z.maxUrls??1/0,j=$.replace(/^\uFEFF/,"").trimStart();if(!j.startsWith("<")){let K=[];for(let B of j.split(/\r?\n/)){if(K.length>=J)break;let D=B.trim()?z4(B):null;if(D)K.push({loc:D})}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(nj(j,{stopped:()=>O()>=J,open(K,B){let D=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"&&D==="urlset"||W==="index"&&K==="sitemap"&&D==="sitemapindex")G={};else if(G&&(D==="url"||D==="sitemap")&&(K==="loc"||K==="lastmod"||K==="changefreq"||K==="priority"))F=K,Q="";else if(G&&W==="urlset"&&D==="url"&&K==="link"){let U=B.href?z4(B.href):null;if(B.rel?.toLowerCase()==="alternate"&&B.hreflang&&U)(G.alternates??=[]).push({hrefLang:B.hreflang,href:U})}},close(K){let B=X.lastIndexOf(K);if(B===-1)return;if(X.length=B,F&&K===F&&G)G[F]=Q.trim(),F=null;else if(G&&(K==="url"||K==="sitemap")){let D=G;G=null,F=null;let U=D.loc?z4(D.loc):null;if(!U)return;if(W==="index"){z.push(D.lastmod?{loc:U,lastmod:D.lastmod}:{loc:U});return}let V={loc:U};if(D.lastmod)V.lastmod=D.lastmod;if(D.changefreq)V.changefreq=D.changefreq;let M=D.priority?Number(D.priority):NaN;if(Number.isFinite(M))V.priority=M;if(D.alternates)V.alternates=D.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*WQ($,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(),B=K.url.replace(/#.*$/,"");if(F.has(B))continue;F.add(B),Q++;let D;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=o3(await s3(U,Y));D=W9(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(D.kind==="index"){if(K.depth>=W)continue;G=D.sitemaps.slice(0,j-Q).map((V)=>({url:V.loc,depth:K.depth+1})).concat(G);continue}for(let U of D.urls)if(yield{...U,sitemap:K.url},++O>=J)return}}var Y9={response:jQ,chunk:J9,index:j9,parse:W9,read:WQ,MAX_URLS:K$,MAX_BYTES:uZ};var YQ=512000,zQ=new TextEncoder;function z9($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function X9($){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 zQ.encode(String.fromCodePoint(W)))Z+=`%${Y.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=j}return Z}function XQ($,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=z9($)||"*";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=X9(J);let j=null;for(let W of this.groupsFor(Z))for(let Y of W.rules){if(!XQ(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 GQ={"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 G9($,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=GQ[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=z9(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:X9(O)})}return new r$(J,j)}async function FQ($,Z={}){let{maxSize:J=YQ,...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 s3(Y,J,!0),G=o3(X);if(X.byteLength>=J)G=G.slice(0,Math.max(0,G.lastIndexOf(`
10
- `)));return G9(G,{url:Y.url})}function F4($){return $===void 0?[]:typeof $==="string"?[$]:$}function n3($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
11
- `}function F9($){let Z=[];for(let j of $.rules??[]){let W=F4(j.userAgent);if(W.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let Y=W.map((X)=>n3("User-agent",X)).join(""),z=[...F4(j.allow).map((X)=>["Allow",X]),...F4(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+=n3(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+=n3("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 n3("Sitemap",W.href)});if(J.length>0)Z.push(J.join(""));return Z.join(`
13
- `)}function QQ($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(F9($),{status:200,headers:J})}var Q9={response:QQ,text:F9,parse:G9,fetch:FQ};import{createHmac as K9,randomBytes as KQ}from"crypto";var K4="v2.";function O4($){return $.startsWith(K4)}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 O9($){let Z=KQ(16).toString("hex"),J=K9("sha256",t$()).update(`${$}:${Z}`).digest("hex");return`${K4}${J}`}function a3($,Z){let J=K9("sha256",t$()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${K4}${J}`}import{createHash as BQ,createHmac as UQ,randomInt as VQ,timingSafeEqual as U9}from"crypto";function D9($,Z){return Math.floor($/Z)*Z}function OQ($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function D4($,Z,J,j){return Z*OQ(J,j)+$}function DQ($){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 B9($){let{allowed:Z,current:J,previous:j,now:W,elapsed:Y,window:z,limit:X,cost:G}=$;if(Z){let Q=D4(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=DQ({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 B4{}class U4 extends B4{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=D9(Y,j),X=Y-z,G=this.roll(Z,j,z);G.limit=J;let Q=D4(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 B9({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 M9="h1.";function r3($,Z,J){let j=UQ("sha256",t$()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${M9}${j}`}function iZ($,Z,J,j){let W=typeof j==="string"?j:"",Y=typeof J==="string"?J:"",z=Y.startsWith(M9),X=r3($,Z,W),G=Buffer.from(z?X:W),F=Buffer.from(Y);if(G.length!==F.length||W===""||Y==="")return U9(G,G),!1;return U9(G,F)}function I9($){let Z="";for(let J=0;J<$;J++)Z+=String(VQ(0,10));return Z}var L9=320;function sZ($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>L9)return null;return Z.toLowerCase()}function t3($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>L9)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var V9=null;function H9(){try{let $=T();if(typeof $?.bound==="function"&&$.bound(Y1))return $.make(Y1)}catch{}return V9??=new Y1({driver:new U4,limit:1000,window:60}),V9}function T9($){return $.length<=64?$:`sha256:${BQ("sha256").update($).digest("hex")}`}async function e$($,Z,J,j){let W=H9(),Y=[[`auth:code-${$}:ip:${T9(o$(J))}`,j.perIp]];if(Z!==null)Y.push([`auth:code-${$}:email:${T9(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 P9($,Z,J,j=10){let W=Math.max(86400,Math.ceil(j*60*(J+1)));return(await H9().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:W})).allowed}import{randomBytes as T4}from"crypto";class V4 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 e3($,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 M4($={}){let Z=$.length??6,J=$.expiresInMinutes??10,j=$.linkExpiresInMinutes??10080,W=$.maxAttempts??5;return e3("length",Z,4,12),e3("expiresInMinutes",J,1),e3("linkExpiresInMinutes",j,1),e3("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 TQ($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function eT($){return $}function N9($={}){return{basePath:"/auth",verifyEmail:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:V4,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:TQ,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>T4(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return T4(32).toString("hex")},generateMagicLinkToken:()=>T4(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:M4($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}function I4($){if($&&typeof $==="object")delete $.password;return $}function MQ(){return new Proxy({},{get:($,Z)=>C9(Z)})}var _9=new WeakMap;function x9($){if($&&typeof $==="object"){for(let Z of Object.values($))x9(Z);Object.freeze($)}return $}var IQ={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},LQ=x9({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:IQ});class L4{models;constructor($=MQ()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return LQ}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??O$(),j=T(D$).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=(_9.get(j)??Promise.resolve()).then(W,W);return _9.set(j,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return I4(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return I4(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?I4(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 _D}from"crypto";function R0($,Z,J,j,W){return i0(Z,c9($,Z),J,j,W)}function i0($,Z,J,j,W,Y){let z=C4(Z,J,j);if(W&&Z!==z)throw RangeError(CY($,Z,J,j,Y));return z}function c9($,Z){let J=$[Z];if(J===void 0)throw TypeError($2(Z));return J}function D0($){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 w4($){return T$({name:$},1)}function T$($,Z){return a0((J)=>({value:J,configurable:1,writable:!Z}),$)}function d9($){return a0((Z)=>({get:Z,configurable:1}),$)}function U6($){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 HQ($,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 k4($,Z){let J={};for(let j in Z)$.has(j)||(J[j]=Z[j]);return J}function y4($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function u9($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function l9($,Z,J){for(let j of $)if(Z[j]!==J[j])return 0;return 1}function i9($,Z,J){let j={...J};for(let W=0;W<Z;W++)j[$[W]]=0;return j}function R($,...Z){return(...J)=>$(...Z,...J)}function S9($){return $[0].toUpperCase()+$.substring(1)}function j3($){return $.slice().sort()}function z6($,Z){return String(Z).padStart($,"0")}function p1($,Z){return Math.sign($-Z)}function C4($,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[V6($,Z),q4($,Z)]}function V6($,Z){return Math.trunc($/Z)||0}function q4($,Z){return $%Z||0}function $6($){return Math.abs($%1)===0.5}function s9($,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 T6($,Z,J){let j={};for(let W=Z;W>=0;W--){let Y=X1[W];j[J[W]]=V6($,Y),$=q4($,Y)}return j}function o9($){return $===w?r6:[]}function n9($){return $===w?D3:[]}function a9($){return $===w?["year","day"]:[]}function r9($){if($!==void 0)return t($)}function t9($){if($!==void 0)return r0($)}function v4($){if($!==void 0)return W3($)}function r0($){return ZW(W3($))}function W3($){return $W(OK($))}function g4($){if($==null)throw TypeError("Cannot be null or undefined");return $}function e9($,Z){if(Z==null)throw RangeError($2($));return Z}function _1($){if(!D0($))throw TypeError(_Y);return $}function M6($,Z,J=$){if(typeof Z!==$)throw TypeError(Q3(J,Z));return Z}function $W($,Z="number"){if(!Number.isInteger($))throw RangeError(vQ(Z,$));return $||0}function ZW($,Z="number"){if($<=0)throw RangeError(gQ(Z,$));return $}function m4($){if(typeof $=="symbol")throw TypeError(cQ);return String($)}function X6($,Z){return D0($)?String($):t($,Z)}function I6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(hQ($));return $}function JW($,Z="number"){if(typeof $=="bigint")throw TypeError(pQ(Z));if($=Number($),!Number.isFinite($))throw RangeError(mQ(Z,$));return $}function N0($,Z){return Math.trunc(JW($,Z))||0}function jW($,Z){return $W(JW($,Z),Z)}function A9($,Z){return ZW(N0($,Z),Z)}function p4($,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 p4($[0]+Z[0]*J,$[1]+Z[1]*J)}function JZ($,Z){return p4($[0],$[1]+Z)}function c0($,Z){return ZZ(Z,$,-1)}function C0($,Z){return p1($[0],Z[0])||p1($[1],Z[1])}function WW($,Z,J){return C0($,Z)===-1||C0($,J)===1}function L6($,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 YW($,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 h4($,Z,J=P1){let[j,W]=$,[Y,z]=J(W,Z);return[j*(h/Z)+Y,z]}function c4($,Z){let J=$.formatToParts(Z),j={};for(let W of J)j[W.type]=W.value;return j}function d4($){return R0($,"isoYear",Z3,$3,1),$.isoYear===Z3?R0($,"isoMonth",4,12,1):$.isoYear===$3&&R0($,"isoMonth",1,9,1),$}function h1($){return C1({...$,...n0,isoHour:12}),$}function C1($){let Z=R0($,"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(!$||WW($,IK,MK))throw RangeError(s6);return $}function u1($){return s9($,5,Z1)[1]}function H6($){let[Z,J]=P1($,h);return[T6(J,5,Z1),Z]}function zW($){return XW($)[0]}function XW($){return h4($,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 u4($,Z){let[J,j]=H6(u1($)-Z);return u0(_0({...$,isoDay:$.isoDay+j,...J}))}function G6(...$){return XZ(...$)/qY}function XZ(...$){let[Z,J]=GW(...$),j=Z.valueOf();if(!isNaN(j))return j-J*k0}function GW($,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 P6(J*k0+W,z,X)}function P6($,Z=0,J=0){let j=Math.ceil(Math.max(0,Math.abs($)-TK)/k0)*Math.sign($),W=new Date($-j*k0);return zZ(e6,[W.getUTCFullYear(),W.getUTCMonth()+1,W.getUTCDate()+j,W.getUTCHours(),W.getUTCMinutes(),W.getUTCSeconds(),W.getUTCMilliseconds(),Z,J])}function FW($){return[$.isoYear,$.isoMonth,$.isoDay]}function QW(){return H1}function l4($,Z){switch(Z){case 2:return i4($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function KW($){return i4($)?366:365}function i4($){return $%4==0&&($%100!=0||$%400==0)}function OW($){let[Z,J]=GW($.isoYear,$.isoMonth,$.isoDay);return nZ(Z.getUTCDay()-J,7)||7}function DW({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function PQ($){let Z=x0($);if(Z<HK)return DW($);let J=c4(M2(WZ),Z),{era:j,eraYear:W}=_7(J,WZ);return[j,W]}function N6($){return M$($),_6($,1),$}function M$($){return BW($,1),$}function f9($){return l9(Q2,$,BW($))}function BW($,Z){let{isoYear:J}=$,j=R0($,"isoMonth",1,QW(),Z);return{isoYear:J,isoMonth:j,isoDay:R0($,"isoDay",1,l4(J,j),Z)}}function _6($,Z){return zZ(Z1,[R0($,"isoHour",0,23,Z),R0($,"isoMinute",0,59,Z),R0($,"isoSecond",0,59,Z),R0($,"isoMillisecond",0,999,Z),R0($,"isoMicrosecond",0,999,Z),R0($,"isoNanosecond",0,999,Z)])}function y($){return $===void 0?0:eY(_1($))}function Y3($,Z=0){$=t0($);let J=$z($),j=bK($,Z);return[eY($),j,J]}function s4($){return $z(t0($))}function UW($){return $=t0($),D2($,9,6,1)}function GZ($,Z,J,j=9,W=0,Y=4){Z=t0(Z);let z=D2(Z,j,W),X=a4(Z),G=U3(Z,Y),F=B3(Z,j,W,1);return z==null?z=Math.max(J,F):IW(z,F),X=r4(X,F,1),$&&(G=((Q)=>Q<4?(Q+2)%4:Q)(G)),[z,F,X,G]}function C6($,Z=6,J){let j=a4($=t4($,B6)),W=U3($,7),Y=B3($,Z);return Y=e9(B6,Y),j=r4(j,Y,void 0,J),[Y,j,W]}function o4($){return B2(t0($))}function VW($,Z){return n4(t0($),Z)}function n4($,Z=4){let J=MW($);return[U3($,4),...TW(B3($,Z),J)]}function TW($,Z){return $!=null?[X1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function a4($){let Z=$[aZ];return Z===void 0?1:N0(Z,aZ)}function r4($,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 MW($){let Z=$[_4];if(Z!==void 0){if(typeof Z!="number"){if(m4(Z)==="auto")return;throw RangeError(Q3(_4,Z))}Z=i0(_4,Math.floor(Z),0,9,1)}return Z}function t0($){return $===void 0?{}:_1($)}function t4($,Z){return typeof $=="string"?{[Z]:$}:_1($)}function Y0($){if($!==void 0){if(D0($))return Object.assign(Object.create(null),$);throw TypeError(_Y)}}function x6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:NK[Z]})}function e4($,Z,J=9,j=0,W){let Y=Z[$];if(Y===void 0)return W?j:void 0;if(Y=m4(Y),Y==="auto")return W?j:null;let z=f4[Y];if(z===void 0&&(z=UK[Y]),z===void 0)throw RangeError(AY($,Y,f4));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=m4(W),z=Z[Y];if(z===void 0)throw RangeError(AY($,Y,Z));return z}function IW($,Z){if(Z>$)throw RangeError(XK)}function B0($){return{branding:Z8,epochNanoseconds:$}}function M0($,Z,J){return{branding:f1,calendar:J,timeZone:Z,epochNanoseconds:$}}function z0($,Z=$.calendar){return{branding:A$,calendar:Z,...v0(nY,$)}}function X0($,Z=$.calendar){return{branding:S$,calendar:Z,...v0(K2,$)}}function U$($,Z=$.calendar){return{branding:VZ,calendar:Z,...v0(K2,$)}}function F6($,Z=$.calendar){return{branding:TZ,calendar:Z,...v0(K2,$)}}function e0($){return{branding:$8,...v0(oY,$)}}function s($){return{branding:J8,sign:s1($),...v0(X2,$)}}function LW($){return zW($.epochNanoseconds)}function S6($){return h4($.epochNanoseconds,G1)[0]}function HW($){return YW($.epochNanoseconds,x$)}function PW($){return YW($.epochNanoseconds)}function NW($){return $.epochNanoseconds}function V0($){return typeof $=="string"?$:t($.id)}function FZ($,Z){return $===Z||V0($)===V0(Z)}function _W($,Z,J,j,W){let Y=V$(j),[z,X]=((V,M)=>{let I=M((V=t4(V,R4))[rY]),P=EK(V);return P=e9(R4,P),[P,I]})(W,$);if(tZ(Math.max(z,Y),X))return E9(j,z);if(!X)throw RangeError(o6);let[G,F,Q]=w6(Z,J,X),O=NJ(Q),K=k6(Q),B=_J(Q),D=K(F,G,j),U=B(F,G,D,z);return tZ(z,X)?E9(U,z):((V,M,I,P,f,x,E)=>{let S=s1(V),[H,L]=$J(P,F2(I,V),I,S,f,x,E),m=ZJ(M,H,L);return V[q[I]]+m*S})(U,O(D),z,F,G,O,K)}function E9($,Z){return d0(O0($),X1[Z],1)}function $J($,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 ZJ($,Z,J){let j=d0(c0(Z,J));if(!j)throw RangeError(K3);return d0(c0(Z,$))/j}function CW($,Z){let[J,j,W]=C6(Z,5,1);return B0(f6($.epochNanoseconds,J,j,W,1))}function xW($,Z,J){let{epochNanoseconds:j,timeZone:W,calendar:Y}=Z,[z,X,G]=C6(J);if(z===0&&X===1)return Z;let F=$(W);if(z===6)j=((Q,O,K,B)=>{let D=S0(K,O),[U,V]=Q(D),M=K.epochNanoseconds,I=q0(O,U),P=q0(O,V);if(WW(M,I,P))throw RangeError(K3);return yW(ZJ(M,I,P),B)?P:I})(wW,F,Z,G);else{let Q=F.getOffsetNanosecondsFor(j);j=H$(F,bW(i1(j,Q),z,X,G),Q,2,0,1)}return M0(j,W,Y)}function SW($,Z){return z0(bW($,...C6(Z)),$.calendar)}function AW($,Z){let[J,j,W]=C6(Z,5);var Y;return e0((Y=W,JJ($,z3(J,j),Y)[0]))}function fW($,Z){let J=$(Z.timeZone),j=S0(Z,J),[W,Y]=wW(j),z=d0(c0(q0(J,W),q0(J,Y)),a6,1);if(z<=0)throw RangeError(K3);return z}function EW($,Z){let{timeZone:J,calendar:j}=Z,W=((Y,z,X)=>q0(z,Y(S0(X,z))))(kW,$(J),Z);return M0(W,J,j)}function bW($,Z,J,j){return RW($,z3(Z,J),j)}function RW($,Z,J){let[j,W]=JJ($,Z,J);return C1({...P$($,W),...j})}function JJ($,Z,J){return H6(l1(u1($),Z,J))}function Q6($){return l1($,n6,7)}function z3($,Z){return X1[$]*Z}function wW($){let Z=kW($);return[Z,P$(Z,1)]}function kW($){return VK(6,$)}function NQ($,Z,J){let j=Math.min(V$($),6);return KZ(E6(O0($,j),Z,J),j)}function A6($,Z,J,j,W,Y,z,X,G,F){if(j===0&&W===1)return $;let Q=tZ(j,X)?y6(X)&&j<6&&J>=6?CQ:_Q:xQ,[O,K,B]=Q($,Z,J,j,W,Y,z,X,G,F);return B&&j!==7&&(O=((D,U,V,M,I,P,f,x)=>{let E=s1(D);for(let S=M+1;S<=V;S++){if(S===7&&V!==7)continue;let H=F2(S,D);H[q[S]]+=E;let L=d0(c0(f(x(I,P,H)),U));if(L&&Math.sign(L)!==E)break;D=H}return D})(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 E6($,z3(Z,J),j,W)}function E6($,Z,J,j){let[W,Y]=$;j&&Y<0&&(Y+=h,W-=1);let[z,X]=P1(l1(Y,Z,J),h);return p4(W+z,X)}function l1($,Z,J){return yW($/Z,J)*Z}function yW($,Z){return kK[Z]($)}function _Q($,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 CQ($,Z,J,j,W,Y,z,X,G,F){let Q=s1($),O=d0(O0($,5)),K=z3(j,W),B=l1(O,K,Y),[D,U]=$J(z,{...$,...G2},6,Q,X,G,F),V=B-d0(c0(D,U)),M=0;V&&Math.sign(V)!==Q?Z=JZ(D,B):(M+=Q,B=l1(V,K,Y),Z=JZ(U,B));let I=v6(B);return[{...$,...I,days:$.days+M},Z,Boolean(M)]}function xQ($,Z,J,j,W,Y,z,X,G,F){let Q=s1($),O=q[j],K=F2(j,$);j===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let B=V6($[O],W)*W;K[O]=B;let[D,U]=$J(z,K,j,W*Q,X,G,F),V=B+ZJ(Z,D,U)*Q*W,M=l1(V,W,Y),I=Math.sign(M-V)===Q;return K[O]=M,[K,I?U:D,I]}function jJ($,Z,J,j){let[W,Y,z,X]=((F)=>{let Q=n4(F=t0(F));return[F.timeZone,...Q]})(j),G=W!==void 0;return((F,Q,O,K,B,D)=>{O=E6(O,B,K,1);let U=Q.getOffsetNanosecondsFor(O);return QJ(i1(O,U),D)+(F?L$(Q6(U)):"Z")})(G,Z(G?$(W):f$),J.epochNanoseconds,Y,z,X)}function WJ($,Z,J){let[j,W,Y,z,X,G]=((F)=>{F=t0(F);let Q=B2(F),O=MW(F),K=wK(F),B=U3(F,4),D=B3(F,4);return[Q,RK(F),K,B,...TW(D,O)]})(J);return((F,Q,O,K,B,D,U,V,M,I)=>{K=E6(K,M,V,1);let P=F(O).getOffsetNanosecondsFor(K);return QJ(i1(K,P),I)+L$(Q6(P),U)+((f,x)=>x!==1?"["+(x===2?"!":"")+V0(f)+"]":"")(O,D)+KJ(Q,B)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,j,W,Y,z,X,G)}function YJ($,Z){let[J,j,W,Y]=((F)=>(F=t0(F),[B2(F),...n4(F)]))(Z);return z=$.calendar,X=J,G=Y,QJ(RW($,W,j),G)+KJ(z,X);var z,X,G}function zJ($,Z){return J=$.calendar,j=$,W=o4(Z),K6(j)+KJ(J,W);var J,j,W}function XJ($,Z){return qW($.calendar,vW,$,o4(Z))}function GJ($,Z){return qW($.calendar,SQ,$,o4(Z))}function FJ($,Z){let[J,j,W]=VW(Z);return Y=W,gW(JJ($,j,J)[0],Y);var Y}function b6($,Z){let[J,j,W]=VW(Z,3);return j>1&&($={...$,...NQ($,j,J)}),((Y,z)=>{let{sign:X}=Y,G=X===-1?A0(Y):Y,{hours:F,minutes:Q}=G,[O,K]=h4(O0(G,3),o0,d1);iW(O);let B=OJ(K,z),D=z>=0||!X||B;return(X<0?"-":"")+"P"+b9({Y:B$(G.years),M:B$(G.months),W:B$(G.weeks),D:B$(G.days)})+(F||Q||O||D?"T"+b9({H:B$(F),M:B$(Q),S:B$(O,D)+B}):"")})($,W)}function qW($,Z,J,j){let W=V0($),Y=j>1||j===0&&W!==w;return j===1?W===w?Z(J):K6(J):Y?K6(J)+mW(W,j===2):Z(J)}function b9($){let Z=[];for(let J in $){let j=$[J];j&&Z.push(j,J)}return Z.join("")}function QJ($,Z){return K6($)+"T"+gW($,Z)}function K6($){return vW($)+"-"+s0($.isoDay)}function vW($){let{isoYear:Z}=$;return(Z<0||Z>9999?pW(Z)+z6(6,Math.abs(Z)):z6(4,Z))+"-"+s0($.isoMonth)}function SQ($){return s0($.isoMonth)+"-"+s0($.isoDay)}function gW($,Z){let J=[s0($.isoHour),s0($.isoMinute)];return Z!==-1&&J.push(s0($.isoSecond)+((j,W,Y,z)=>OJ(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($),a6),[W,Y]=P1(j,n6),[z,X]=P1(Y,o0);return pW($)+s0(J)+":"+s0(W)+(z||X?":"+s0(z)+OJ(X):"")}function KJ($,Z){if(Z!==1){let J=V0($);if(Z>1||Z===0&&J!==w)return mW(J,Z===2)}return""}function mW($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function OJ($,Z){let J=z6(9,$);return J=Z===void 0?J.replace(vK,""):J.slice(0,Z),J?"."+J:""}function pW($){return $<0?"-":"+"}function B$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function AQ($,Z){let{epochNanoseconds:J}=$,j=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),W=i1(J,j);return{calendar:$.calendar,...W,offsetNanoseconds:j}}function hW($,Z){let J=S0(Z,$);return{calendar:Z.calendar,...v0(nY,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 u4(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&j!==3){let G=((F,Q,O,K)=>{let B=_0(Q);K&&(O=Q6(O));for(let D of F){let U=d0(c0(D,B));if(K&&(U=Q6(U)),U===O)return D}})(X,Z,J,Y);if(G!==void 0)return G;if(j===0)throw RangeError(ZK)}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(JK);if(j.length)return j[J===3?1:0];let W=_0(Z),Y=((X,G)=>{let F=X.getOffsetNanosecondsFor(JZ(G,-h));return BJ(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 DJ($){if(Math.abs($)>=h)throw RangeError(eQ);return $}function BJ($){if($>h)throw RangeError($K);return $}function UJ($,Z,J){return B0(u0(ZZ(Z.epochNanoseconds,((j)=>{if(sW(j))throw RangeError(YK);return O0(j,5)})($?A0(J):J))))}function VJ($,Z,J,j,W,Y=Object.create(null)){let z=Z(j.timeZone),X=$(j.calendar);return{...j,...HJ(z,X,j,J?A0(W):W,Y)}}function TJ($,Z,J,j,W=Object.create(null)){let{calendar:Y}=J;return z0(PJ($(Y),J,Z?A0(j):j,W),Y)}function MJ($,Z,J,j,W){let{calendar:Y}=J;return X0(R6($(Y),J,Z?A0(j):j,W),Y)}function IJ($,Z,J,j,W=Object.create(null)){let Y=J.calendar,z=$(Y),X=rZ(z,J);Z&&(j=q6(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 LJ($,Z,J){return e0(cW(Z,$?A0(J):J)[0])}function HJ($,Z,J,j,W){let Y=O0(j,5),z=J.epochNanoseconds;if(sW(j)){let X=S0(J,$);z=ZZ(q0($,{...R6(Z,X,{...j,...G2},W),...v0(Z1,X)}),Y)}else z=ZZ(z,Y),y(W);return{epochNanoseconds:u0(z)}}function PJ($,Z,J,j){let[W,Y]=cW(Z,J);return C1({...R6($,Z,{...J,...G2,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 cW($,Z){let[J,j]=O0(Z,5),[W,Y]=H6(u1($)+j);return[W,J+Y]}function P$($,Z){return Z?{...$,...P6(x0($)+Z*k0)}:$}function w6($,Z,J){let j=$(J.calendar);return y6(J)?[J,j,Z(J.timeZone)]:[{...J,...n0},j]}function NJ($){return $?NW:_0}function k6($){return $?R(HJ,$):PJ}function _J($){return $?R(EQ,$):bQ}function y6($){return $&&$.epochNanoseconds}function tZ($,Z){return $<=6-(y6(Z)?1:0)}function CJ($,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(s6);return{...T0,...KZ(P,M)}})(W,Y,G,j)));if(!X)throw RangeError(o6);j&&(Y=A0(Y));let[F,Q,O]=w6(Z,J,X),K=k6(O),B=_J(O),D=K(Q,F,W);return s(B(Q,F,K(Q,D,Y),G))}function dW($,Z,J,j,W){let Y=V$(j),[z,X,G,F,Q]=((E,S,H)=>{E=t4(E,B6);let L=D2(E),m=H(E[rY]),u=a4(E),k1=U3(E,7),Z0=B3(E);if(L===void 0&&Z0===void 0)throw RangeError(zK);return Z0==null&&(Z0=0),L==null&&(L=Math.max(Z0,S)),IW(L,Z0),u=r4(u,Z0,1),[L,Z0,u,k1,m]})(W,Y,$),O=Math.max(Y,z);if(!y6(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(o6);let[K,B,D]=w6(Z,J,Q),U=NJ(D),V=k6(D),M=_J(D),I=V(B,K,j),P=M(B,K,I,z),f=j.sign,x=s1(P);if(f&&x&&f!==x)throw RangeError(K3);return x&&(P=A6(P,U(I),z,X,G,F,B,K,U,V)),s(P)}function uW($){return $.sign===-1?q6($):$}function q6($){return s(A0($))}function A0($){let Z={};for(let J of q)Z[J]=-1*$[J]||0;return Z}function lW($){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(WK);J=W}}return J}function QZ($){for(let Z of BK)i0(Z,$[Z],-g9,g9,1);return iW(d0(O0($),o0)),$}function iW($){if(!Number.isSafeInteger($))throw RangeError(jK)}function O0($,Z=6){return s9($,Z,q)}function KZ($,Z=6){let[J,j]=$,W=T6(j,Z,q);if(W[q[Z]]+=J*(h/X1[Z]),!Number.isFinite(W[q[Z]]))throw RangeError(s6);return W}function v6($,Z=5){return T6($,Z,q)}function sW($){return Boolean(s1($,sY))}function V$($){let Z=9;for(;Z>0&&!$[q[Z]];Z--);return Z}function fQ($,Z){return[$,Z]}function R9($){let Z=Math.floor($/W6)*W6;return[Z,Z+W6]}function oW($){let Z=o1($=X6($));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&&fJ(Z.timeZone,1),B0(u4(N6(Z),J))}function nW($){let Z=o1(t($));if(!Z)throw RangeError(w0($));if(Z.timeZone)return W7(Z,Z.offset?OZ(Z.offset):void 0);if(Z.m)throw RangeError(w0($));return z7(Z)}function aW($,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 W7(J,W,Y,z)}function OZ($){let Z=fJ($);if(Z===void 0)throw RangeError(w0($));return Z}function rW($){let Z=o1(t($));if(!Z||Z.m)throw RangeError(w0($));return z0(Y7(Z))}function g6($){let Z=o1(t($));if(!Z||Z.m)throw RangeError(w0($));return X0(Z.p?Y7(Z):z7(Z))}function tW($,Z){let J=SJ(t(Z));if(J)return xJ(J),U$(d4(M$(J)));let j=g6(Z);return U$(rZ($(j.calendar),j))}function xJ($){if($.calendar!==w)throw RangeError(N1($.calendar))}function eW($,Z){let J=AJ(t(Z));if(J)return xJ(J),F6(M$(J));let j=g6(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 F6(h1(Y.P(O,K,G)),W)}function $7($){let Z,J=((j)=>{let W=cK.exec(j);return W?(m6(W[10]),F7(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"));xJ(J)}if((Z=SJ($))&&f9(Z))throw RangeError(w0($));if((Z=AJ($))&&f9(Z))throw RangeError(w0($));return e0(_6(J,1))}function Z7($){let Z=((J)=>{let j=lK.exec(J);return j?((W)=>{function Y(Q,O,K){let B=0,D=0;if(K&&([B,G]=P1(G,X1[K])),Q!==void 0){if(X)throw RangeError(N1(Q));D=((U)=>{let V=parseInt(U);if(!Number.isFinite(V))throw RangeError(N1(U));return V})(Q),z=1,O&&(G=EJ(O)*(X1[K]/o0),X=1)}return B+D}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)]),...T6(G,2,q)};if(!z)throw RangeError(xY(q));return bJ(W[1])<0&&(F=A0(F)),F})(j):void 0})(t($));if(!Z)throw RangeError(w0($));return s(QZ(Z))}function J7($){let Z=o1($)||SJ($)||AJ($);return Z?Z.calendar:$}function j7($){let Z=o1($);return Z&&(Z.timeZone||Z.m&&f$||Z.offset)||$}function W7($,Z,J=0,j=0){let W=p6($.timeZone),Y=j8(W);return M0(H$(Y,N6($),Z,J,j,!Y.v,$.m),W,X3($.calendar))}function Y7($){return X7(C1(N6($)))}function z7($){return X7(h1(M$($)))}function X7($){return{...$,calendar:X3($.calendar)}}function o1($){let Z=hK.exec($);return Z?((J)=>{let j=J[10],W=(j||"").toUpperCase()==="Z";return{isoYear:G7(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...F7(J.slice(5)),...m6(J[16]),p:Boolean(J[6]),m:W,offset:W?void 0:j}})(Z):void 0}function SJ($){let Z=mK.exec($);return Z?((J)=>({isoYear:G7(J),isoMonth:parseInt(J[4]),isoDay:1,...m6(J[5])}))(Z):void 0}function AJ($){let Z=pK.exec($);return Z?((J)=>({isoYear:YZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...m6(J[3])}))(Z):void 0}function fJ($,Z){let J=dK.exec($);return J?((j,W)=>{let Y=j[4]||j[5];if(W&&Y)throw RangeError(N1(Y));return DJ(($Z(j[2])*a6+$Z(j[3])*n6+$Z(j[4])*o0+EJ(j[5]||""))*bJ(j[1]))})(J,Z):void 0}function G7($){let Z=bJ($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(N1(-0));return Z*J}function F7($){let Z=$Z($[3]);return{...H6(EJ($[4]||""))[0],isoHour:$Z($[1]),isoMinute:$Z($[2]),isoSecond:Z===60?59:Z}}function m6($){let Z,J,j=[];if($.replace(uK,(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 EJ($){return parseInt($.padEnd(9,"0"))}function DZ($){return new RegExp(`^${$}$`,"i")}function bJ($){return $&&$!=="+"?-1:1}function $Z($){return $===void 0?0:parseInt($)}function Q7($){return p6(t($))}function p6($){let Z=RJ($);return typeof Z=="number"?L$(Z):Z?((J)=>{if(sK.test(J))throw RangeError(tQ);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?S9(Y).replace(/island|noronha|murdo|rivadavia|urville/,S9):Y)).join("/")})($):f$}function w9($){let Z=RJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:f$}function RJ($){let Z=fJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==f$?iK($):void 0}function wJ($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function kJ($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function K7($,Z,J,j,W,Y){let z=$(t0(Y).relativeTo),X=Math.max(V$(j),V$(W));if(l9(q,j,W))return 0;if(tZ(X,z))return C0(O0(j),O0(W));if(!z)throw RangeError(o6);let[G,F,Q]=w6(Z,J,z),O=NJ(Q),K=k6(Q);return C0(O(K(F,G,j)),O(K(F,G,W)))}function yJ($,Z){return N$($,Z)||h6($,Z)}function N$($,Z){return p1(x0($),x0(Z))}function h6($,Z){return p1(u1($),u1(Z))}function O7($,Z){return!wJ($,Z)}function D7($,Z){return!kJ($,Z)&&!!c6($.timeZone,Z.timeZone)&&FZ($.calendar,Z.calendar)}function B7($,Z){return!yJ($,Z)&&FZ($.calendar,Z.calendar)}function U7($,Z){return!N$($,Z)&&FZ($.calendar,Z.calendar)}function V7($,Z){return!N$($,Z)&&FZ($.calendar,Z.calendar)}function T7($,Z){return!N$($,Z)&&FZ($.calendar,Z.calendar)}function M7($,Z){return!h6($,Z)}function c6($,Z){if($===Z)return 1;let J=V0($),j=V0(Z);if(J===j)return 1;try{return w9(J)===w9(j)}catch(W){}}function qJ($,Z,J,j){let W=GZ($,Y0(j),3,5),Y=d6(Z.epochNanoseconds,J.epochNanoseconds,...W);return s($?A0(Y):Y)}function vJ($,Z,J,j,W,Y){let z=l6(j.calendar,W.calendar),X=Y0(Y),[G,F,Q,O]=GZ(J,X,5),K=j.epochNanoseconds,B=W.epochNanoseconds,D=C0(B,K),U;if(D)if(G<6)U=d6(K,B,G,F,Q,O);else{let V=Z(((I,P)=>{if(!c6(I,P))throw RangeError(RY);return I})(j.timeZone,W.timeZone)),M=$(z);U=L7(M,V,j,W,D,G,X),U=A6(U,B,G,F,Q,O,M,j,NW,R(HJ,V))}else U=T0;return s(J?A0(U):U)}function gJ($,Z,J,j,W){let Y=l6(J.calendar,j.calendar),z=Y0(W),[X,G,F,Q]=GZ(Z,z,6),O=_0(J),K=_0(j),B=C0(K,O),D;if(B)if(X<=6)D=d6(O,K,X,G,F,Q);else{let U=$(Y);D=H7(U,J,j,B,X,z),D=A6(D,K,X,G,F,Q,U,J,_0,PJ)}else D=T0;return s(Z?A0(D):D)}function mJ($,Z,J,j,W){let Y=l6(J.calendar,j.calendar),z=Y0(W);return I7(Z,()=>$(Y),J,j,...GZ(Z,z,6,9,6),z)}function pJ($,Z,J,j,W){let Y=l6(J.calendar,j.calendar),z=Y0(W),X=GZ(Z,z,9,9,8),G=$(Y);return I7(Z,()=>G,rZ(G,J),rZ(G,j),...X,z)}function I7($,Z,J,j,W,Y,z,X,G){let F=_0(J),Q=_0(j),O;if(C0(Q,F))if(W===6)O=d6(F,Q,W,Y,z,X);else{let K=Z();O=K.dateUntil(J,j,W,G),Y===6&&z===1||(O=A6(O,Q,W,Y,z,X,K,J,_0,R6))}else O=T0;return s($?A0(O):O)}function hJ($,Z,J,j){let W=Y0(j),[Y,z,X,G]=GZ($,W,5,5),F=l1(cJ(Z,J),z3(z,X),G),Q={...T0,...v6(F,Y)};return s($?A0(Q):Q)}function EQ($,Z,J,j,W,Y){let z=C0(j.epochNanoseconds,J.epochNanoseconds);return z?W<6?P7(J.epochNanoseconds,j.epochNanoseconds,W):L7(Z,$,J,j,z,W,Y):T0}function bQ($,Z,J,j,W){let Y=_0(Z),z=_0(J),X=C0(z,Y);return X?j<=6?P7(Y,z,j):H7($,Z,J,X,j,W):T0}function L7($,Z,J,j,W,Y,z){let[X,G,F]=((K,B,D,U)=>{function V(){return S={...P$(P,x++*-U),...I},H=q0(K,S),C0(f,H)===-U}let M=S0(B,K),I=v0(Z1,M),P=S0(D,K),f=D.epochNanoseconds,x=0,E=cJ(M,P),S,H;if(Math.sign(E)===-U&&x++,V()&&(U===-1||V()))throw RangeError(K3);let L=d0(c0(H,f));return[M,S,L]})(Z,J,j,W);var Q,O;return{...Y===6?(Q=X,O=G,{...T0,days:N7(Q,O)}):$.dateUntil(X,G,Y,z),...v6(F)}}function H7($,Z,J,j,W,Y){let[z,X,G]=((F,Q,O)=>{let K=Q,B=cJ(F,Q);return Math.sign(B)===-O&&(K=P$(Q,-O),B+=h*O),[F,K,B]})(Z,J,j);return{...$.dateUntil(z,X,W,Y),...v6(G)}}function d6($,Z,J,j,W,Y){return{...T0,...KZ(f6(c0($,Z),j,W,Y),J)}}function P7($,Z,J){return{...T0,...KZ(c0($,Z),J)}}function N7($,Z){return u6(x0($),x0(Z))}function u6($,Z){return Math.trunc((Z-$)/k0)}function cJ($,Z){return u1(Z)-u1($)}function l6($,Z){if(!FZ($,Z))throw RangeError(j2);return $}function RQ($){function Z(W){return((Y,z)=>({..._7(Y,z),F:Y.month,day:parseInt(Y.day)}))(c4(J,W),j)}let J=M2($),j=O6($);return{id:$,O:wQ(Z),B:kQ(Z)}}function wQ($){return y0((Z)=>{let J=x0(Z);return $(J)},WeakMap)}function kQ($){let Z=$(0).year-LK;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:yY(z.reverse())}})}function _7($,Z){let J,j,W=C7($);if($.era){let Y=uY[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=E7(j,Y[J]||0))}return{era:J,eraYear:j,year:W}}function C7($){return parseInt($.relatedYear||$.year)}function x4($){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 Z6($){let Z=y9(this,$),J=y9(this,$-1),j=Z.length;if(j>J.length){let W=b7(this);if(W<0)return-W;for(let Y=0;Y<j;Y++)if(Z[Y]!==J[Y])return Y+1}}function J6($){return u6(eZ.call(this,$),eZ.call(this,$+1))}function k9($,Z){let{k:J}=this.B($),j=Z+1,W=J;return j>J.length&&(j=1,W=this.B($+1).k),u6(J[Z-1],W[j-1])}function j6($){return this.B($).k.length}function y9($,Z){return Object.keys($.B(Z).C)}function x7($){return X3(t($))}function X3($){if(($=$.toLowerCase())!==w&&$!==t6&&O6($)!==O6(M2($).resolvedOptions().calendar))throw RangeError(rQ($));return $}function O6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function S7($){return this.R($)[0]}function A7($){return this.R($)[1]}function dJ($){let[Z]=this.h($);return u6(this.q(Z),x0($))+1}function f7($){let Z=nK.exec($);if(!Z)throw RangeError(nQ($));return[parseInt(Z[1]),Boolean(Z[2])]}function D6($,Z,J){return $+(Z||J&&$>=J?1:0)}function S4($,Z){return $-(Z&&$>=Z?1:0)}function E7($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function A4($){return uY[R7($)]}function b7($){return KK[R7($)]}function R7($){return O6($.id||w)}function w7($,Z,J,j){let W=n1(J,j,$1,[],pY);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 k7($,Z,J,j,W,Y){let z=n1(J,W,$1,gY,pY),X=$(z.timeZone),[G,F,Q]=Y3(Y),O=J.dateFromFields(z,x6(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 y7($,Z,J){let j=n1($,Z,$1,[],A1),W=y(J);return z0(C1({...$.dateFromFields(j,x6(J,W)),..._$(j,W)}))}function uJ($,Z,J,j=[]){let W=n1($,Z,$1,j);return $.dateFromFields(W,J)}function lJ($,Z,J,j){let W=n1($,Z,z2,j);return $.yearMonthFromFields(W,J)}function iJ($,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 q7($,Z){let J=y(Z);return e0(_$(z1($,E4,[],1),J))}function v7($){let Z=z1($,X2);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(dQ(X));if(X==="constructor"||X==="__proto__")throw RangeError(Z2(X));let G=$[X];if(G!==void 0)z=1,m9[X]&&(G=m9[X](G,X)),W[X]=G;else if(J){if(J.includes(X))throw TypeError($2(X));W[X]=dY[X]}Y=X}if(j&&!z)throw TypeError(xY(Z));return W}function _$($,Z){return _6(eK({...dY,...$}),Z)}function g7($,Z,J,j,W,Y){let z=Y0(Y),{calendar:X,timeZone:G}=J;return M0(((F,Q,O,K,B)=>{let D=G3(F,O,K,$1,mY,vY),[U,V,M]=Y3(B,2);return H$(Q,{...F.dateFromFields(D,x6(B,U)),..._$(D,U)},OZ(D.offset),V,M)})($(X),Z(G),j,W,z),G,X)}function m7($,Z,J,j,W){let Y=Y0(W);return z0(((z,X,G,F)=>{let Q=G3(z,X,G,$1,A1),O=y(F);return C1({...z.dateFromFields(Q,x6(F,O)),..._$(Q,O)})})($(Z.calendar),J,j,Y))}function p7($,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 h7($,Z,J,j,W){let Y=Y0(W);return U$(((z,X,G,F)=>{let Q=G3(z,X,G,z2);return z.yearMonthFromFields(Q,F)})($(Z.calendar),J,j,Y))}function c7($,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 d7($,Z,J){return e0(((j,W,Y)=>{let z=y(Y);return _$({...v0(E4,j),...z1(W,E4)},z)})($,Z,J))}function u7($,Z){return s((J=$,j=Z,QZ({...J,...z1(j,X2)})));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 sJ($,Z){let J=n1($,Z,cY);return $.monthDayFromFields(J)}function oJ($,Z,J){let j=n1($,Z,hY);return $.yearMonthFromFields(j,J)}function l7($,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 H4($,Z){let{era:J,eraYear:j,year:W}=Z,Y=A4($);if(J!==void 0||j!==void 0){if(J===void 0||j===void 0)throw TypeError(lQ);if(!Y)throw RangeError(uQ);let z=Y[J];if(z===void 0)throw RangeError(sQ(J));let X=E7(j,z);if(W!==void 0&&W!==X)throw RangeError(iQ);W=X}else if(W===void 0)throw TypeError(oQ(Y));return W}function P4($,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,B]=f7(G),D=D6(K,B,O);if(B){let U=b7(X);if(U===void 0)throw RangeError(oZ);if(U>0){if(D>U)throw RangeError(oZ);if(O===void 0){if(Q===1)throw RangeError(oZ);D--}}else{if(D!==-U)throw RangeError(oZ);if(O===void 0&&Q===1)throw RangeError(oZ)}}return D})($,Y,J,j);if(W!==void 0&&W!==z)throw RangeError(EY);W=z,j=1}else if(W===void 0)throw TypeError(aQ);return i0("month",W,1,$.L(J),j)}function q9($,Z,J,j,W){return R0(Z,"day",1,$.j(j,J),W)}function N4($,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 i7($){return B0(u0(L6(I6($))))}function s7($,Z,J,j,W=w){return M0(u0(L6(I6(J))),Z(j),$(W))}function o7($,Z,J,j,W=0,Y=0,z=0,X=0,G=0,F=0,Q=w){return z0(C1(N6(a0(N0,zZ(e6,[Z,J,j,W,Y,z,X,G,F])))),$(Q))}function n7($,Z,J,j,W=w){return X0(h1(M$(a0(N0,{isoYear:Z,isoMonth:J,isoDay:j}))),$(W))}function a7($,Z,J,j=w,W=1){let Y=N0(Z),z=N0(J),X=$(j);return U$(d4(M$({isoYear:Y,isoMonth:z,isoDay:N0(W)})),X)}function r7($,Z,J,j=w,W=YZ){let Y=N0(Z),z=N0(J),X=$(j);return F6(h1(M$({isoYear:N0(W),isoMonth:Y,isoDay:z})),X)}function t7($=0,Z=0,J=0,j=0,W=0,Y=0){return e0(_6(a0(N0,zZ(Z1,[$,Z,J,j,W,Y])),1))}function e7($=0,Z=0,J=0,j=0,W=0,Y=0,z=0,X=0,G=0,F=0){return s(QZ(a0(jW,zZ(q,[$,Z,J,j,W,Y,z,X,G,F]))))}function nJ($,Z,J=w){return M0($.epochNanoseconds,Z,J)}function $Y($){return B0($.epochNanoseconds)}function aJ($,Z){return z0(S0(Z,$))}function rJ($,Z){return X0(S0(Z,$))}function ZY($,Z,J){return oJ($(Z.calendar),J)}function JY($,Z,J){return sJ($(Z.calendar),J)}function tJ($,Z){return e0(S0(Z,$))}function jY($,Z,J,j){let W=((Y,z,X,G)=>{let F=s4(G);return q0(Y(z),X,F)})($,J,Z,j);return M0(u0(W),J,Z.calendar)}function WY($,Z,J){let j=$(Z.calendar);return U$({...Z,...oJ(j,J)})}function YY($,Z,J){return sJ($(Z.calendar),J)}function zY($,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 XY($,Z=n0){return z0(C1({...$,...Z}))}function GY($,Z,J){return oJ($(Z.calendar),J)}function FY($,Z,J){return sJ($(Z.calendar),J)}function QY($,Z,J,j){return((W,Y,z)=>l7(W,Y,hY,_1(z),D3))($(Z.calendar),J,j)}function KY($,Z,J,j){return((W,Y,z)=>l7(W,Y,cY,_1(z),r6))($(Z.calendar),J,j)}function OY($,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 DY($,Z){return z0(C1({...$,...Z}))}function BY($){return B0(u0(jZ($,o0)))}function UY($){return B0(u0(jZ($,G1)))}function VY($){return B0(u0(L6(I6($),x$)))}function TY($){return B0(u0(L6(I6($))))}function MY($,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 IY($,Z,J){let j=Z.timeZone,W=$(j),Y={...S0(Z,W),...J},z=NY(Z.calendar,J.calendar);return M0(H$(W,Y,Y.offsetNanoseconds,2),j,z)}function LY($,Z=n0){return z0({...$,...Z})}function HY($,Z){return z0({...$,...Z},NY($.calendar,Z.calendar))}function i6($,Z){return{...$,calendar:Z}}function PY($,Z){return{...$,timeZone:Z}}function NY($,Z){if($===Z)return $;let J=V0($),j=V0(Z);if(J===j||J===w)return Z;if(j===w)return $;throw RangeError(j2)}function yQ($,Z){return(J)=>J===w?$:J===t6||J===WZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),oK(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=k4(j,W),$)||Object.assign(W,Z),J&&(W.timeZone=f$,["full","long"].includes(W.timeStyle)&&(W.timeStyle="medium")),W)}function x1($,Z=eJ){let[J,,,j]=$;return(W,Y=UO,...z)=>{let X=Z(j&&j(...z),W,Y,J),G=X.resolvedOptions();return[X,...qQ($,G,z)]}}function eJ($,Z,J,j){if(J=j(J),$){if(J.timeZone!==void 0)throw TypeError(GK);J.timeZone=$}return new a1(Z,J)}function qQ($,Z,J){let[,j,W]=$;return J.map((Y)=>(Y.calendar&&((z,X,G)=>{if((G||z!==w)&&z!==X)throw RangeError(j2)})(V0(Y.calendar),Z.calendar,W),j(Y,Z)))}function BZ($){let Z=F3();return i1(Z,$.getOffsetNanosecondsFor(Z))}function F3(){return jZ(Date.now(),G1)}function S1(){return h9||(h9=new a1().resolvedOptions().timeZone)}var vQ=($,Z)=>`Non-integer ${$}: ${Z}`,gQ=($,Z)=>`Non-positive ${$}: ${Z}`,mQ=($,Z)=>`Non-finite ${$}: ${Z}`,pQ=($)=>`Cannot convert bigint to ${$}`,hQ=($)=>`Invalid bigint: ${$}`,cQ="Cannot convert Symbol to string",_Y="Invalid object",CY=($,Z,J,j,W)=>W?CY($,W[Z],W[J],W[j]):Q3($,Z)+`; must be between ${J}-${j}`,Q3=($,Z)=>`Invalid ${$}: ${Z}`,$2=($)=>`Missing ${$}`,Z2=($)=>`Invalid field ${$}`,dQ=($)=>`Duplicate field ${$}`,xY=($)=>"No valid fields: "+$.join(),SY="Invalid bag",AY=($,Z,J)=>Q3($,Z)+"; must be "+Object.keys(J).join(),fY="Cannot use valueOf",J2="Invalid calling context",uQ="Forbidden era/eraYear",lQ="Mismatching era/eraYear",iQ="Mismatching year/eraYear",sQ=($)=>`Invalid era: ${$}`,oQ=($)=>"Missing year"+($?"/era/eraYear":""),nQ=($)=>`Invalid monthCode: ${$}`,EY="Mismatching month/monthCode",aQ="Missing month/monthCode",v9="Cannot guess year",oZ="Invalid leap month",bY="Invalid protocol",K3="Invalid protocol results",j2="Mismatching Calendars",rQ=($)=>`Invalid Calendar: ${$}`,RY="Mismatching TimeZones",tQ="Forbidden ICU TimeZone",eQ="Out-of-bounds offset",$K="Out-of-bounds TimeZone gap",ZK="Invalid TimeZone offset",JK="Ambiguous offset",s6="Out-of-bounds date",jK="Out-of-bounds duration",WK="Cannot mix duration signs",o6="Missing relativeTo",YK="Cannot use large units",zK="Required smallestUnit or largestUnit",XK="smallestUnit > largestUnit",w0=($)=>`Cannot parse: ${$}`,N1=($)=>`Invalid substring: ${$}`,wY=($)=>`Cannot format ${$}`,kY="Mismatching types for formatting",GK="Cannot specify TimeZone",yY=R(J3,($,Z)=>Z),UZ=R(J3,($,Z,J)=>J),s0=R(z6,2),f4={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},O3=Object.keys(f4),k0=86400000,qY=1000,x$=1000,G1=1e6,o0=1e9,n6=60000000000,a6=3600000000000,h=86400000000000,X1=[1,x$,G1,o0,n6,a6,h],A1=O3.slice(0,6),E4=j3(A1),vY=["offset"],gY=["timeZone"],mY=A1.concat(vY),pY=mY.concat(gY),b4=["era","eraYear"],FK=b4.concat(["year"]),r6=["year"],W2=["monthCode"],Y2=["month"].concat(W2),D3=["day"],z2=Y2.concat(r6),hY=W2.concat(r6),$1=D3.concat(z2),QK=D3.concat(Y2),cY=D3.concat(W2),dY=UZ(A1,0),w="iso8601",t6="gregory",WZ="japanese",uY={[t6]:{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}},KK={chinese:13,dangi:13,hebrew:-6},t=R(M6,"string"),lY=R(M6,"boolean"),OK=R(M6,"number"),iY=R(M6,"function"),q=O3.map(($)=>$+"s"),X2=j3(q),DK=q.slice(0,6),sY=q.slice(6),BK=sY.slice(1),UK=yY(q),T0=UZ(q,0),G2=UZ(DK,0),F2=R(i9,q),Z1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],Q2=["isoDay","isoMonth","isoYear"],e6=Z1.concat(Q2),K2=j3(Q2),oY=j3(Z1),nY=j3(e6),n0=UZ(oY,0),VK=R(i9,e6),a1=Intl.DateTimeFormat,aY="en-GB",O2=1e8,TK=O2*k0,MK=[O2,0],IK=[-O2,0],$3=275760,Z3=-271821,LK=1970,YZ=1972,H1=12,HK=XZ(1868,9,8),PK=y0(PQ,WeakMap),B6="smallestUnit",R4="unit",aZ="roundingIncrement",_4="fractionalSecondDigits",rY="relativeTo",tY={constrain:0,reject:1},NK=Object.keys(tY),_K={compatible:0,reject:1,earlier:2,later:3},CK={reject:0,use:1,prefer:2,ignore:3},xK={auto:0,never:1,critical:2,always:3},SK={auto:0,never:1,critical:2},AK={auto:0,never:1},fK={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},B3=R(e4,B6),D2=R(e4,"largestUnit"),EK=R(e4,R4),eY=R(I$,"overflow",tY),$z=R(I$,"disambiguation",_K),bK=R(I$,"offset",CK),B2=R(I$,"calendarName",xK),RK=R(I$,"timeZoneName",SK),wK=R(I$,"offset",AK),U3=R(I$,"roundingMode",fK),VZ="PlainYearMonth",TZ="PlainMonthDay",S$="PlainDate",A$="PlainDateTime",$8="PlainTime",f1="ZonedDateTime",Z8="Instant",J8="Duration",kK=[Math.floor,($)=>$6($)?Math.floor($):Math.round($),Math.ceil,($)=>$6($)?Math.ceil($):Math.round($),Math.trunc,($)=>$6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>$6($)?($=Math.trunc($)||0)+$%2:Math.round($)],f$="UTC",W6=5184000,yK=G6(1847),qK=G6(new Date().getUTCFullYear()+10),vK=/0+$/,S0=y0(AQ,WeakMap),g9=4294967295,j8=y0(($)=>{let Z=RJ($);return typeof Z=="object"?new Jz(Z):new Zz(Z||0)});class Zz{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[u4($,this.v)]}l(){}}class Jz{constructor($){this.$=((Z)=>{function J(G){let F=C4(G,z,X),[Q,O]=R9(F),K=W(Q),B=W(O);return K===B?K:j(Y(Q,O),K,B,G)}function j(G,F,Q,O){let K,B;for(;(O===void 0||(K=O<G[0]?F:O>=G[1]?Q:void 0)===void 0)&&(B=G[1]-G[0]);){let D=G[0]+Math.floor(B/2);Z(D)===Q?G[1]=D:G[0]=D+1}return K}let W=y0(Z),Y=y0(fQ),z=yK,X=qK;return{G(G){let F=J(G-86400),Q=J(G+86400),O=G-F,K=G-Q;if(F===Q)return[O];let B=J(O);return B===J(K)?[G-B]:F>Q?[O,K]:[]},V:J,l(G,F){let Q=C4(G,z,X),[O,K]=R9(Q),B=W6*F,D=F<0?()=>K>z||(z=Q,0):()=>O<X||(X=Q,0);for(;D();){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+=B,K+=B}}}})(((Z)=>(J)=>{let j=c4(Z,J*qY);return G6(C7(j),parseInt(j.month),parseInt(j.day),parseInt(j.hour),parseInt(j.minute),parseInt(j.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(zW($))*o0}getPossibleInstantsFor($){let[Z,J]=[G6((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]=XW($),W=this.$.l(J+(Z>0||j?1:0),Z);if(W!==void 0)return jZ(W,o0)}}var U2="([+\u2212-])",Y6="(?:[.,](\\d{1,9}))?",jz=`(?:(?:${U2}(\\d{6}))|(\\d{4}))-?(\\d{2})`,V2="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+Y6+")?)?",T2=U2+V2,gK=jz+"-?(\\d{2})(?:[T ]"+V2+"(Z|"+T2+")?)?",Wz="\\[(!?)([^\\]]*)\\]",W8=`((?:${Wz}){0,9})`,mK=DZ(jz+W8),pK=DZ("(?:--)?(\\d{2})-?(\\d{2})"+W8),hK=DZ(gK+W8),cK=DZ("T?"+V2+"(?:"+T2+")?"+W8),dK=DZ(T2),uK=new RegExp(Wz,"g"),lK=DZ(`${U2}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${Y6}H)?(?:(\\d+)${Y6}M)?(?:(\\d+)${Y6}S)?)?`),iK=y0(($)=>new a1(aY,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),sK=/^(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$/,oK=y0(RQ),M2=y0(($)=>new a1(aY,{calendar:$,timeZone:f$,era:"short",year:"numeric",month:"short",day:"numeric"})),nK=/^M(\d{2})(L?)$/,aK={era:X6,eraYear:N0,year:N0,month:A9,monthCode:X6,day:A9},rK=UZ(A1,N0),tK=UZ(q,jW),m9=Object.assign({},aK,rK,tK,{offset:X6}),eK=R(HQ,A1,Z1),p9={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,B)=>{let[D,U,V]=F.h(Q);if(O){let[M,I]=F.I(D,U);D+=O,U=D6(M,I,F.U(D)),U=i0("month",U,1,F.L(D),B)}return K&&([D,U]=F._(D,U,K)),V=i0("day",V,1,F.j(D,U),B),F.q(D,U,V)})(this,$,Y,z,j);else{if(!X&&!G)return $;W=x0($)}return W+=(7*X+G)*k0,h1(P6(W))},dateUntil($,Z,J){if(J<=7){let G=0,F=N7({...$,...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,B,D)=>{let U=K-F,V=B-Q,M=D-O;if(U||V){let I=Math.sign(U||V),P=G.j(K,B),f=0;if(Math.sign(M)===-I){let x=P;[K,B]=G._(K,B,-I),U=K-F,V=B-Q,P=G.j(K,B),f=I<0?-x:P}if(M=D-Math.min(O,P)+f,U){let[x,E]=G.I(F,Q),[S,H]=G.I(K,B);if(V=S-x||Number(H)-Number(E),Math.sign(V)===-I){let L=I<0&&-G.L(K);U=(K-=I)-F,V=B-D6(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=H4(this,$),W=P4(this,$,j,J),Y=q9(this,$,W,j,J);return X0(h1(this.P(j,W,Y)),this.id||w)},yearMonthFromFields($,Z){let J=y(Z),j=H4(this,$),W=P4(this,$,j,J);return U$(d4(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]=f7(W),O=c9($,"day");let K=this.N(X,G,O);if(!K)throw RangeError(v9);if([F,Q]=K,z!==void 0&&z!==Q)throw RangeError(EY);j&&(Q=i0("month",Q,1,H1,1),O=i0("day",O,1,l4(Y!==void 0?Y:F,Q),J))}else{F=Y===void 0&&j?YZ:H4(this,$),Q=P4(this,$,F,J),O=q9(this,$,Q,F,J);let K=this.U(F);G=Q===K,X=S4(Q,K);let B=this.N(X,G,O);if(!B)throw RangeError(v9);[F,Q]=B}return F6(h1(this.P(F,Q,O)),this.id||w)},fields($){return A4(this)&&$.includes("year")?[...$,...b4]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return N4(J,Z,Y2),A4(this)&&(N4(J,Z,FK),this.id===WZ&&N4(J,Z,QK,b4)),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:dJ,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:OW,daysInWeek(){return 7}},$O={dayOfYear:dJ,h:FW,q:XZ},ZO=Object.assign({},$O,{weekOfYear:S7,yearOfWeek:A7,R($){function Z(B){return(7-B<j?7:0)-B}function J(B){let D=KW(K+B),U=B||1,V=Z(nZ(G+D*U,7));return Q=(D+(V-F)*U)/7}let j=this.id?1:4,W=OW($),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]}}),JO={dayOfYear:dJ,h:x4,q:eZ,weekOfYear:S7,yearOfWeek:A7,R(){return[]}},MZ=yQ(Object.assign({},p9,ZO,{h:FW,ee($){return this.id===t6?DW($):this.id===WZ?PK($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[YZ,$]},K:i4,U(){},L:QW,J:($)=>$*H1,j:l4,X:KW,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:XZ,_:($,Z,J)=>($+=V6(J,H1),(Z+=q4(J,H1))<1?($--,Z+=H1):Z>H1&&($++,Z-=H1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},p9,JO,{h:x4,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=Z6.call(this,$);return[S4(Z,J),J===Z]},N($,Z,J){let[j,W,Y]=x4.call(this,{isoYear:YZ,isoMonth:H1,isoDay:31}),z=Z6.call(this,j),X=W===z;(p1($,S4(W,z))||p1(Number(Z),Number(X))||p1(J,Y))===1&&j--;for(let G=0;G<100;G++){let F=j-G,Q=Z6.call(this,F),O=D6($,Z,Q);if(Z===(O===Q)&&J<=k9.call(this,F,O))return[F,O]}},K($){let Z=J6.call(this,$);return Z>J6.call(this,$-1)&&Z>J6.call(this,$+1)},U:Z6,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:k9,X:J6,P($,Z,J){return P6(eZ.call(this,$,Z,J))},q:eZ,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(s6);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"],Yz={month:c1,day:c1},I2={year:c1,month:c1},L2=Object.assign({},I2,{day:c1}),H2={hour:c1,minute:c1,second:c1},P2=Object.assign({},L2,H2),jO=Object.assign({},P2,{timeZoneName:"short"}),WO=Object.keys(I2),YO=Object.keys(Yz),zO=Object.keys(L2),XO=Object.keys(H2),N2=["dateStyle"],GO=WO.concat(N2),FO=YO.concat(N2),_2=zO.concat(N2,["weekday"]),V3=XO.concat(["dayPeriod","timeStyle"]),C2=_2.concat(V3),QO=C2.concat(IZ),KO=IZ.concat(V3),OO=IZ.concat(_2),DO=IZ.concat(["day","weekday"],V3),BO=IZ.concat(["year","weekday"],V3),UO={},x2=[C$(C2,P2),S6],zz=[C$(QO,jO),S6,0,($,Z)=>{let J=V0($.timeZone);if(Z&&V0(Z.timeZone)!==J)throw RangeError(RY);return J}],S2=[C$(C2,P2,IZ),x0],A2=[C$(_2,L2,KO),x0],f2=[C$(V3,H2,OO),($)=>u1($)/G1],E2=[C$(GO,I2,DO),x0,1],b2=[C$(FO,Yz,BO),x0,1],h9;function K1($,Z,J,j,W){function Y(...G){if(!(this instanceof Y))throw TypeError(J2);Qz(this,Z(...G))}function z(G,F){return Object.defineProperties(function(...Q){return G.call(this,X(this),...Q)},w4(F))}function X(G){let F=H0(G);if(!F||F.branding!==$)throw TypeError(J2);return F}return Object.defineProperties(Y.prototype,{...d9(a0(z,J)),...T$(a0(z,j)),...U6("Temporal."+$)}),Object.defineProperties(Y,{...T$(W),...w4($)}),[Y,(G)=>{let F=Object.create(Y.prototype);return Qz(F,G),F},X]}function Dz($){return $=$.concat("id").sort(),(Z)=>{if(!u9(Z,$))throw TypeError(bY);return Z}}function NZ($){if(H0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(SY);return $}function Y8($,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 k2($){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(bO),{i:z})))[J](j);var Y,z};return Z}function Z$(){throw TypeError(fY)}function M3({calendar:$}){return typeof $=="string"?new d2($):$}function Xz($,Z){if(Z=Y0(Z),D0($)){let j=H0($);if(j&&j.branding===TZ)return y(Z),j;let W=Vz($);return iJ(O8(W||w),!W,$,Z)}let J=eW(MZ,$);return y(Z),J}function Bz($,Z,J){return j=Z.call($,f0(B0(J))),DJ(W3(j));var j}function z8($,Z=Lz){let J=Object.keys(Z).sort(),j={};for(let W of J)j[W]=R(Z[W],$,iY($[W]));return j}function c($,Z){return typeof $=="string"?j8($):z8($,Z)}function F0($){return c($,w2)}function F1($){if(D0($)){let Z=H0($);if(Z)switch(Z.branding){case Z8:return Z;case f1:return B0(Z.epochNanoseconds)}}return oW($)}function Gz($,Z,J){let j=Z.l(F1(J).epochNanoseconds,$);return j?f0(B0(j)):null}function l($){return D0($)?(H0($)||{}).timeZone||vO($):((Z)=>p6(j7(t(Z))))($)}function r1($,Z){if(D0($)){let J=H0($)||{};switch(J.branding){case $8:return y(Z),J;case A$:return y(Z),e0(J);case f1:return y(Z),tJ(F0,J)}return q7($,Z)}return y(Z),$7($)}function y2($){return $===void 0?void 0:r1($)}function LZ($,Z){if(Z=Y0(Z),D0($)){let j=H0($);return j&&j.branding===VZ?(y(Z),j):lJ(Q8(I3($)),$,Z)}let J=tW(MZ,$);return y(Z),J}function t1($,Z){if(Z=Y0(Z),D0($)){let j=H0($)||{};switch(j.branding){case A$:return y(Z),j;case S$:return y(Z),z0({...j,...n0});case f1:return y(Z),aJ(F0,j)}return y7(K8(I3($)),$,Z)}let J=rW($);return y(Z),J}function E0($,Z){if(Z=Y0(Z),D0($)){let j=H0($)||{};switch(j.branding){case S$:return y(Z),j;case A$:return y(Z),X0(j);case f1:return y(Z),rJ(F0,j)}return uJ(K8(I3($)),$,Z)}let J=g6($);return y(Z),J}function Uz($,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]=R(j[z],J,J[z]);return Y})(Z,$)}function e($){if(D0($)){let Z=H0($);return Z&&Z.branding===J8?Z:v7($)}return Z7($)}function T3($){if($!==void 0){if(D0($)){let Z=H0($)||{};switch(Z.branding){case f1:case S$:return Z;case A$:return X0(Z)}let J=I3($);return{...w7(l,c,K8(J),$),calendar:J}}return nW($)}}function I3($){return Vz($)||w}function Vz($){let{calendar:Z}=$;if(Z!==void 0)return L0(Z)}function L0($){return D0($)?(H0($)||{}).calendar||tO($):((Z)=>X3(J7(t(Z))))($)}function HZ($,Z){if(Z=Y0(Z),D0($)){let J=H0($);if(J&&J.branding===f1)return Y3(Z),J;let j=I3($);return k7(l,c,K8(j),j,$,Z)}return aW($,Z)}function Fz($){return a0((Z)=>(J)=>Z(R2(J)),$)}function R2($){return S0($,F0)}function VO(){let $=a1.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(a1),j=function(W,Y={}){if(!(this instanceof j))return new j(W,Y);u2.set(this,((z,X={})=>{let G=new a1(z,X),F=G.resolvedOptions(),Q=F.locale,O=v0(Object.keys(X),F),K=y0(IO),B=(...D)=>{let U,V=D.map((M,I)=>{let P=H0(M),f=(P||{}).branding;if(I&&U&&U!==f)throw TypeError(kY);return U=f,P});return U?K(U)(Q,O,...V):[G,...D]};return B.u=G,B})(W,Y))};for(let W in Z){let Y=Z[W],z=W.startsWith("format")&&TO(W);typeof Y.value=="function"?Y.value=W==="constructor"?j:z||MO(W):z&&(Y.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(j,J),j}function TO($){return function(...Z){let J=u2.get(this),[j,...W]=J(...Z);return j[$](...W)}}function MO($){return function(...Z){return u2.get(this).u[$](...Z)}}function IO($){let Z=LO[$];if(!Z)throw TypeError(wY($));return x1(Z,y0(eJ))}var LO={Instant:x2,PlainDateTime:S2,PlainDate:A2,PlainTime:f2,PlainYearMonth:E2,PlainMonthDay:b2},HO=x1(x2),PO=x1(zz),NO=x1(S2),_O=x1(A2),CO=x1(f2),xO=x1(E2),SO=x1(b2),q2={era:r9,eraYear:v4,year:W3,month:r0,daysInMonth:r0,daysInYear:r0,inLeapYear:lY,monthsInYear:r0},G8={monthCode:t},v2={day:r0},Tz={dayOfWeek:r0,dayOfYear:r0,weekOfYear:t9,yearOfWeek:v4,daysInWeek:r0},Mz=Object.assign({},q2,G8,v2,Tz),X8=new WeakMap,H0=X8.get.bind(X8),Qz=X8.set.bind(X8),AO={...Y8(q2,[VZ]),...Y8(Tz,[]),...Y8(G8,[VZ,TZ]),...Y8(v2,[TZ])},g2=k2(Mz),fO=k2({...q2,...G8}),EO=k2({...G8,...v2}),L3={calendarId:($)=>V0($.calendar)},bO=a0(($,Z)=>function(J){let{i:j}=this;return $(j[Z]($0(X0(J,j))))},Mz),RO=J3(($)=>(Z)=>Z[$],q.concat("sign")),m2=J3(($,Z)=>(J)=>J[Z1[Z]],A1),Iz={epochSeconds:LW,epochMilliseconds:S6,epochMicroseconds:HW,epochNanoseconds:PW},H3=R(k4,new Set(["branding"])),[wO,PZ,kO]=K1(TZ,R(r7,L0),{...L3,...EO},{getISOFields:H3,getCalendar:M3,with($,Z,J){return PZ(c7(nO,$,this,NZ(Z),J))},equals:($,Z)=>T7($,Xz(Z)),toPlainDate($,Z){return $0(KY(P3,$,this,Z))},toLocaleString($,Z,J){let[j,W]=SO(Z,J,$);return j.format(W)},toString:GJ,toJSON:($)=>GJ($),valueOf:Z$},{from:($,Z)=>PZ(Xz($,Z))}),Lz={getOffsetNanosecondsFor:Bz,getPossibleInstantsFor($,Z,J){let j=[...Z.call($,I0(z0(J,w)))].map((Y)=>qO(Y).epochNanoseconds),W=j.length;return W>1&&(j.sort(C0),BJ(d0(c0(j[0],j[W-1])))),j}},w2={getOffsetNanosecondsFor:Bz},[yO,f0,qO]=K1(Z8,i7,Iz,{add:($,Z)=>f0(UJ(0,$,e(Z))),subtract:($,Z)=>f0(UJ(1,$,e(Z))),until:($,Z,J)=>d(qJ(0,$,F1(Z),J)),since:($,Z,J)=>d(qJ(1,$,F1(Z),J)),round:($,Z)=>f0(CW($,Z)),equals:($,Z)=>O7($,F1(Z)),toZonedDateTime($,Z){let J=_1(Z);return G0(nJ($,l(J.timeZone),L0(J.calendar)))},toZonedDateTimeISO:($,Z)=>G0(nJ($,l(Z))),toLocaleString($,Z,J){let[j,W]=HO(Z,J,$);return j.format(W)},toString:($,Z)=>jJ(l,F0,$,Z),toJSON:($)=>jJ(l,F0,$),valueOf:Z$},{from:($)=>f0(F1($)),fromEpochSeconds:($)=>f0(BY($)),fromEpochMilliseconds:($)=>f0(UY($)),fromEpochMicroseconds:($)=>f0(VY($)),fromEpochNanoseconds:($)=>f0(TY($)),compare:($,Z)=>wJ(F1($),F1(Z))}),[F8,GM]=K1("TimeZone",($)=>{let Z=Q7($);return{branding:"TimeZone",id:Z,o:j8(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(t1(Z)).map((J)=>f0(B0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(F1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=F1(Z).epochNanoseconds,j=z8(this,w2).getOffsetNanosecondsFor(J);return L$(j)},getPlainDateTimeFor($,Z,J=w){let j=F1(Z).epochNanoseconds,W=z8(this,w2).getOffsetNanosecondsFor(j);return I0(z0(i1(j,W),L0(J)))},getInstantFor($,Z,J){let j=t1(Z),W=s4(J),Y=z8(this);return f0(B0(q0(Y,j,W)))},getNextTransition:({o:$},Z)=>Gz(1,$,Z),getPreviousTransition:({o:$},Z)=>Gz(-1,$,Z),equals($,Z){return!!c6(this,l(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=l($);return typeof Z=="string"?new F8(Z):Z}}),vO=Dz(Object.keys(Lz)),[gO,e1]=K1($8,t7,m2,{getISOFields:H3,with($,Z,J){return e1(d7(this,NZ(Z),J))},add:($,Z)=>e1(LJ(0,$,e(Z))),subtract:($,Z)=>e1(LJ(1,$,e(Z))),until:($,Z,J)=>d(hJ(0,$,r1(Z),J)),since:($,Z,J)=>d(hJ(1,$,r1(Z),J)),round:($,Z)=>e1(AW($,Z)),equals:($,Z)=>M7($,r1(Z)),toZonedDateTime:($,Z)=>G0(OY(l,E0,c,$,Z)),toPlainDateTime:($,Z)=>I0(DY($,E0(Z))),toLocaleString($,Z,J){let[j,W]=CO(Z,J,$);return j.format(W)},toString:FJ,toJSON:($)=>FJ($),valueOf:Z$},{from:($,Z)=>e1(r1($,Z)),compare:($,Z)=>h6(r1($),r1(Z))}),[mO,$$,pO]=K1(VZ,R(a7,L0),{...L3,...fO},{getISOFields:H3,getCalendar:M3,with($,Z,J){return $$(h7(oO,$,this,NZ(Z),J))},add:($,Z,J)=>$$(IJ(Kz,0,$,e(Z),J)),subtract:($,Z,J)=>$$(IJ(Kz,1,$,e(Z),J)),until:($,Z,J)=>d(pJ(Oz,0,$,LZ(Z),J)),since:($,Z,J)=>d(pJ(Oz,1,$,LZ(Z),J)),equals:($,Z)=>V7($,LZ(Z)),toPlainDate($,Z){return $0(QY(P3,$,this,Z))},toLocaleString($,Z,J){let[j,W]=xO(Z,J,$);return j.format(W)},toString:XJ,toJSON:($)=>XJ($),valueOf:Z$},{from:($,Z)=>$$(LZ($,Z)),compare:($,Z)=>N$(LZ($),LZ(Z))}),[hO,I0]=K1(A$,R(o7,L0),{...L3,...g2,...m2},{getISOFields:H3,getCalendar:M3,with($,Z,J){return I0(m7(P3,$,this,NZ(Z),J))},withCalendar:($,Z)=>I0(i6($,L0(Z))),withPlainDate:($,Z)=>I0(HY($,E0(Z))),withPlainTime:($,Z)=>I0(LY($,y2(Z))),add:($,Z,J)=>I0(TJ(E$,0,$,e(Z),J)),subtract:($,Z,J)=>I0(TJ(E$,1,$,e(Z),J)),until:($,Z,J)=>d(gJ(Q1,0,$,t1(Z),J)),since:($,Z,J)=>d(gJ(Q1,1,$,t1(Z),J)),round:($,Z)=>I0(SW($,Z)),equals:($,Z)=>B7($,t1(Z)),toZonedDateTime:($,Z,J)=>G0(jY(c,$,l(Z),J)),toPlainDate:($)=>$0(X0($)),toPlainTime:($)=>e1(e0($)),toPlainYearMonth($){return $$(WY(Q8,$,this))},toPlainMonthDay($){return PZ(YY(O8,$,this))},toLocaleString($,Z,J){let[j,W]=NO(Z,J,$);return j.format(W)},toString:YJ,toJSON:($)=>YJ($),valueOf:Z$},{from:($,Z)=>I0(t1($,Z)),compare:($,Z)=>yJ(t1($),t1(Z))}),[cO,$0,Hz]=K1(S$,R(n7,L0),{...L3,...g2},{getISOFields:H3,getCalendar:M3,with($,Z,J){return $0(p7(P3,$,this,NZ(Z),J))},withCalendar:($,Z)=>$0(i6($,L0(Z))),add:($,Z,J)=>$0(MJ(E$,0,$,e(Z),J)),subtract:($,Z,J)=>$0(MJ(E$,1,$,e(Z),J)),until:($,Z,J)=>d(mJ(Q1,0,$,E0(Z),J)),since:($,Z,J)=>d(mJ(Q1,1,$,E0(Z),J)),equals:($,Z)=>U7($,E0(Z)),toZonedDateTime($,Z){let J=!D0(Z)||Z instanceof F8?{timeZone:Z}:Z;return G0(zY(l,r1,c,$,J))},toPlainDateTime:($,Z)=>I0(XY($,y2(Z))),toPlainYearMonth($){return $$(GY(Q8,$,this))},toPlainMonthDay($){return PZ(FY(O8,$,this))},toLocaleString($,Z,J){let[j,W]=_O(Z,J,$);return j.format(W)},toString:zJ,toJSON:($)=>zJ($),valueOf:Z$},{from:($,Z)=>$0(E0($,Z)),compare:($,Z)=>N$(E0($),E0(Z))}),p2={fields($,Z,J){return[...Z.call($,J)]}},Pz=Object.assign({dateFromFields($,Z,J,j){return Hz(Z.call($,Object.assign(Object.create(null),J),j))}},p2),Nz=Object.assign({yearMonthFromFields($,Z,J,j){return pO(Z.call($,Object.assign(Object.create(null),J),j))}},p2),_z=Object.assign({monthDayFromFields($,Z,J,j){return kO(Z.call($,Object.assign(Object.create(null),J),j))}},p2),h2={mergeFields($,Z,J,j){return _1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),j)))}},dO=Object.assign({},Pz,h2),uO=Object.assign({},Nz,h2),lO=Object.assign({},_z,h2),c2={dateAdd($,Z,J,j,W){return Hz(Z.call($,$0(X0(J,$)),d(s(j)),W))}},Cz=Object.assign({},c2,{dateUntil($,Z,J,j,W,Y){return rO(Z.call($,$0(X0(J,$)),$0(X0(j,$)),Object.assign(Object.create(null),Y,{largestUnit:O3[W]})))}}),iO=Object.assign({},c2,{day:Uz}),sO=Object.assign({},Cz,{day:Uz}),Q8=O1(Nz),K8=O1(Pz),O8=O1(_z),oO=O1(uO),P3=O1(dO),nO=O1(lO),E$=O1(c2),Q1=O1(Cz),Kz=O1(iO),Oz=O1(sO),[aO,d,rO]=K1(J8,e7,{...RO,blank:lW},{with:($,Z)=>d(u7($,Z)),negated:($)=>d(q6($)),abs:($)=>d(uW($)),add:($,Z,J)=>d(CJ(T3,Q1,c,0,$,e(Z),J)),subtract:($,Z,J)=>d(CJ(T3,Q1,c,1,$,e(Z),J)),round:($,Z)=>d(dW(T3,Q1,c,$,Z)),total:($,Z)=>_W(T3,Q1,c,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):b6($)},toString:b6,toJSON:($)=>b6($),valueOf:Z$},{from:($)=>d(e($)),compare:($,Z,J)=>K7(T3,E$,c,e($),e(Z),J)}),xz={toString:($)=>$.id,toJSON:($)=>$.id,...AO,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),UW(j)))),dateFromFields:({id:$,o:Z},J,j)=>$0(uJ(Z,J,j,a9($))),yearMonthFromFields:({id:$,o:Z},J,j)=>$$(lJ(Z,J,j,o9($))),monthDayFromFields:({id:$,o:Z},J,j)=>PZ(iJ(Z,0,J,j,n9($))),fields({o:$},Z){let J=new Set($1),j=[];for(let W of Z){if(t(W),!J.has(W))throw RangeError(Z2(W));J.delete(W),j.push(W)}return $.fields(j)},mergeFields:({o:$},Z,J)=>$.mergeFields(y4(g4(Z)),y4(g4(J)))},[d2]=K1("Calendar",($)=>{let Z=x7($);return{branding:"Calendar",id:Z,o:MZ(Z)}},{id:($)=>$.id},xz,{from($){let Z=L0($);return typeof Z=="string"?new d2(Z):Z}}),tO=Dz(Object.keys(xz).slice(4)),[eO,G0]=K1(f1,R(s7,L0,l),{...Iz,...L3,...Fz(g2),...Fz(m2),offset:($)=>L$(R2($).offsetNanoseconds),offsetNanoseconds:($)=>R2($).offsetNanoseconds,timeZoneId:($)=>V0($.timeZone),hoursInDay:($)=>fW(c,$)},{getISOFields:($)=>hW(F0,$),getCalendar:M3,getTimeZone:({timeZone:$})=>typeof $=="string"?new F8($):$,with($,Z,J){return G0(g7(P3,c,$,this,NZ(Z),J))},withCalendar:($,Z)=>G0(i6($,L0(Z))),withTimeZone:($,Z)=>G0(PY($,l(Z))),withPlainDate:($,Z)=>G0(IY(c,$,E0(Z))),withPlainTime:($,Z)=>G0(MY(c,$,y2(Z))),add:($,Z,J)=>G0(VJ(E$,c,0,$,e(Z),J)),subtract:($,Z,J)=>G0(VJ(E$,c,1,$,e(Z),J)),until:($,Z,J)=>d(s(vJ(Q1,c,0,$,HZ(Z),J))),since:($,Z,J)=>d(s(vJ(Q1,c,1,$,HZ(Z),J))),round:($,Z)=>G0(xW(c,$,Z)),startOfDay:($)=>G0(EW(c,$)),equals:($,Z)=>D7($,HZ(Z)),toInstant:($)=>f0($Y($)),toPlainDateTime:($)=>I0(aJ(F0,$)),toPlainDate:($)=>$0(rJ(F0,$)),toPlainTime:($)=>e1(tJ(F0,$)),toPlainYearMonth($){return $$(ZY(Q8,$,this))},toPlainMonthDay($){return PZ(JY(O8,$,this))},toLocaleString($,Z,J={}){let[j,W]=PO(Z,J,$);return j.format(W)},toString:($,Z)=>WJ(F0,$,Z),toJSON:($)=>WJ(F0,$),valueOf:Z$},{from:($,Z)=>G0(HZ($,Z)),compare:($,Z)=>kJ(HZ($),HZ(Z))}),$D=Object.defineProperties({},{...U6("Temporal.Now"),...T$({timeZoneId:()=>S1(),instant:()=>f0(B0(F3())),zonedDateTime:($,Z=S1())=>G0(M0(F3(),l(Z),L0($))),zonedDateTimeISO:($=S1())=>G0(M0(F3(),l($),w)),plainDateTime:($,Z=S1())=>I0(z0(BZ(F0(l(Z))),L0($))),plainDateTimeISO:($=S1())=>I0(z0(BZ(F0(l($))),w)),plainDate:($,Z=S1())=>$0(X0(BZ(F0(l(Z))),L0($))),plainDateISO:($=S1())=>$0(X0(BZ(F0(l($))),w)),plainTimeISO:($=S1())=>e1(e0(BZ(F0(l($)))))})}),_Z=Object.defineProperties({},{...U6("Temporal"),...T$({PlainYearMonth:mO,PlainMonthDay:wO,PlainDate:cO,PlainTime:gO,PlainDateTime:hO,ZonedDateTime:eO,Instant:yO,Calendar:d2,TimeZone:F8,Duration:aO,Now:$D})}),ZD=VO(),u2=new WeakMap,JD=Object.defineProperties(Object.create(Intl),T$({DateTimeFormat:ZD}));var DM="gemi.v1",Sz="/__gemi/socket",l2="x-gemi-socket",BM=/^[A-Za-z0-9_-]{1,32}$/,UM={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function MM($){return $}function Az(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:Sz,allowedOrigins:[],maxConnectionsPerProcess:1e4,maxConnectionsPerIp:100,maxConnectionsPerUser:50,maxChannelsPerSocket:50,maxInboundMessageBytes:16384,backpressureLimit:1048576,idleTimeout:120,heartbeatMs:25000,subscribeRate:{limit:300,windowMs:60000}}}import{hkdfSync as jD,randomBytes as WD}from"crypto";function YD($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(jD("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var zD="__control",i2=250,XD=1e4,GD=15000;class s2{config;prefix;controlChannel;instanceId=WD(9).toString("base64url");subscribeTimeoutMs;healthCheckMs;publisher=null;subscriber=null;ready=null;deliver=null;hooks;wanted=new Set;active=new Set;chains=new Map;connectedOnce=!1;reconnectAttempt=0;reconnectTimer=null;healthTimer=null;closed=!1;constructor($={}){this.config=$;this.prefix=$.prefix??YD(),this.controlChannel=this.prefix+zD,this.subscribeTimeoutMs=$.subscribeTimeoutMs??5000,this.healthCheckMs=$.healthCheckMs??30000}get connected(){return this.subscriber!==null&&this.ready===null}publish($,Z){return this.send(this.prefix+$,Z)}async revoke($){this.hooks?.onRevoke?.($);let Z={op:"revoke",from:this.instanceId,r:$};try{await this.send(this.controlChannel,JSON.stringify(Z))}catch(J){throw Error(`The broadcast revocation ${JSON.stringify($)} could not reach the other instances.`,{cause:J})}}async start($,Z){this.closed=!1,this.deliver=$,this.hooks=Z,this.connectSubscriber(),this.startHealthCheck();try{await this.whenReady()}catch{console.warn("[gemi] Broadcast: Redis is not reachable yet; sockets get events once it is.")}}topicAdded($){return this.wanted.add($),this.sync($,!0)}topicRemoved($){return this.wanted.delete($),this.sync($,!1)}async close(){if(this.closed=!0,this.deliver=null,this.hooks=void 0,this.reconnectTimer)clearTimeout(this.reconnectTimer);if(this.reconnectTimer=null,this.healthTimer)clearInterval(this.healthTimer);this.healthTimer=null;let $=[this.subscriber,this.publisher];this.subscriber=null,this.publisher=null,this.ready=null,this.wanted.clear(),this.active.clear(),this.chains.clear();for(let Z of $){if(!Z)continue;Z.onclose=null;try{Z.close()}catch{}}}async send($,Z){let J=this.publisherClient();try{await J.publish($,Z)}catch{if(this.closed)throw Error("The broadcast driver is closed.");this.dropPublisher(J),await this.publisherClient().publish($,Z)}}dropPublisher($){if(this.publisher!==$)return;this.publisher=null,$.onclose=null;try{$.close()}catch{}}publisherClient(){if(this.publisher)return this.publisher;let $=this.createClient("publisher");return $.onclose=()=>{if(this.publisher===$)this.publisher=null},this.publisher=$,$}createClient($){if(this.config.createClient)return this.config.createClient($);let Z=globalThis.Bun?.RedisClient;if(typeof Z!=="function")throw Error("The redis broadcast driver needs Bun's built-in Redis client. Run the app under Bun.");let J=$==="subscriber"?{...this.config.options,autoReconnect:!1}:{...this.config.options};return new Z(this.config.url,J)}connectSubscriber(){if(this.closed||this.ready)return;let $;try{$=this.createClient("subscriber")}catch(J){console.error("[gemi] Broadcast: the Redis subscriber could not be created.",J),this.scheduleReconnect();return}this.subscriber=$,this.active.clear(),$.onclose=()=>this.lost($);let Z=N3((async()=>{await $.connect(),await $.subscribe(this.controlChannel,this.onMessage);let J=[...this.wanted];if(await Promise.all(J.map((j)=>$.subscribe(this.prefix+j,this.onMessage))),this.subscriber!==$)throw Error("Replaced.");for(let j of J)this.active.add(j);return $})(),GD,"connect");this.ready=Z,Z.then(()=>{if(this.subscriber!==$)return;this.ready=null,this.reconnectAttempt=0;for(let J of this.active)if(!this.wanted.has(J))this.sync(J,!1).catch(()=>{});if(this.connectedOnce)this.hooks?.onGap?.();this.connectedOnce=!0},(J)=>{if(this.subscriber!==$||this.closed)return;console.warn(`[gemi] Broadcast: the Redis subscriber could not connect (${fz(J)}); retrying.`),this.drop($)})}lost($){if(this.subscriber!==$||this.closed)return;if(this.ready===null)console.warn("[gemi] Broadcast: the Redis subscriber connection dropped; reconnecting.");this.drop($)}drop($){if(this.subscriber!==$)return;this.subscriber=null,this.ready=null,this.active.clear(),$.onclose=null;try{$.close()}catch{}this.scheduleReconnect()}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let $=Math.min(XD,i2*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(i2,Math.floor(Math.random()*$));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connectSubscriber()},Z),this.reconnectTimer.unref?.()}startHealthCheck(){if(this.healthCheckMs<=0||this.healthTimer)return;this.healthTimer=setInterval(()=>{let $=this.subscriber;if(!$||this.ready)return;N3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${fz(Z)}); reconnecting.`),this.drop($)})},this.healthCheckMs),this.healthTimer.unref?.()}async whenReady(){if(this.closed)throw Error("The broadcast driver is closed.");let $=Date.now()+this.subscribeTimeoutMs;for(;;){if(this.subscriber&&!this.ready)return this.subscriber;let Z=$-Date.now();if(Z<=0)throw Error("Redis did not answer in time.");let J=this.ready??FD(Math.min(Z,i2));await N3(J,Z,"subscribe").catch((j)=>{if(Date.now()>=$)throw j})}}sync($,Z){let j=(this.chains.get($)??Promise.resolve()).catch(()=>{}).then(()=>this.reconcile($,Z));this.chains.set($,j);let W=()=>{if(this.chains.get($)===j)this.chains.delete($)};return j.then(W,W),j}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let W=this.subscriber;this.active.delete($);try{await N3(W.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(Y){if(this.subscriber===W)this.drop(W);throw Y}return}if(!Z)return;let j=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await N3(j.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(W){if(this.subscriber===j)this.drop(j);throw W}if(this.subscriber===j)this.active.add($)}onMessage=($,Z)=>{if(Z===this.controlChannel){this.onControl($);return}if(!Z.startsWith(this.prefix))return;this.deliver?.(Z.slice(this.prefix.length),$)};onControl($){let Z;try{Z=JSON.parse($)}catch{return}if(Z?.op!=="revoke"||Z.from===this.instanceId)return;let J=Z.r;if(J&&typeof J.user==="string")this.hooks?.onRevoke?.({user:J.user});else if(J&&typeof J.topic==="string")this.hooks?.onRevoke?.({topic:J.topic})}}function N3($,Z,J){let j;return Promise.race([$,new Promise((W,Y)=>{j=setTimeout(()=>Y(Error(`Redis ${J} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(j))}function FD($){return new Promise((Z)=>setTimeout(Z,$))}function fz($){return $ instanceof Error?$.message:String($)}import{createHmac as QD,hkdfSync as KD,randomBytes as Ez}from"crypto";function bz($){return QD("sha256",OD()).update($).digest("base64url").slice(0,22)}var D8=null;function OD(){let $=process.env.SECRET||void 0;if(D8&&D8.secret===$)return D8.key;let Z=$?Buffer.from(KD("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):Ez(32);return D8={secret:$,key:Z},Z}function NM(){return Ez(16).toString("base64url")}var DD=/^[A-Za-z0-9_-]{8,64}$/;function o2($){return typeof $==="string"&&DD.test($)}function Rz($,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 kz 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(Az(),$),this.driver=VD(this.config,Z.application)}get channels(){if(this.channelRouter===void 0)this.channelRouter=this.options.channels?new this.options.channels:null;return this.channelRouter}to($,...Z){return new _3(this,B8($,Z[0]),null)}toUser($){return new _3(this,{topic:l$($),pattern:Q0},null)}toOthers($){return new yz(this,UD($))}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){Mj(Z);let W;try{W=Rz($.topic,Z,J,j?bz(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=BD($);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 kz(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 _3{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 yz{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new _3(this.manager,B8($,Z[0]),this.except)}toUser($){return new _3(this.manager,{topic:l$($),pattern:Q0},this.except)}}function B8($,Z){if(Tj($))return{topic:o8($.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:o8($)}}function BD($){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 UD($){if($===null||$===void 0)return null;if(typeof $==="string")return o2($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(l2);return o2(J)?J:null}function VD($,Z){let J=$.driver;if(J===void 0||J==="memory")return new wz;if(J==="redis"){let j=Z?.config.get("redis",{})??{},W=$.redis??{};return new s2({url:W.url??j.url??process.env.REDIS_URL,options:W.options??j.options,prefix:W.prefix,subscribeTimeoutMs:W.subscribeTimeoutMs,healthCheckMs:W.healthCheckMs})}if(typeof J==="function"){if(!Z)throw Error("A broadcast driver factory needs the application to be called with.");return J(Z)}if(typeof J==="object"&&J!==null&&typeof J.publish==="function")return J;throw Error(`Unknown broadcast driver "${String(J)}" in app/config/broadcast.ts. Use "memory" or "redis", or pass a BroadcastDriver.`)}class n2 extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class TD{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1}import{createHash as a2,createHmac as MD,randomBytes as qz,timingSafeEqual as mz}from"crypto";var x3=600,U8="gemi_oauth",ID=`__Host-${U8}`;function SZ($,Z=U8){if(Z===U8)return $?ID:U8;return $?`__Host-${Z}`:Z}function C3($){return $.toString("base64url")}function pz($){return MD("sha256",t$()).update(`gemi-oauth-state:${$}`).digest()}function vz($,Z){let J=a2("sha256").update($).digest(),j=a2("sha256").update(Z).digest();return mz(J,j)&&$.length===Z.length}function V8($,Z=Date.now(),J={}){let j=C3(qz(32)),W=C3(qz(32)),Y=LD(W),z={provider:$,state:j,codeVerifier:W,expiresAt:Z+x3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{}};return{state:j,codeVerifier:W,codeChallenge:Y,cookieValue:HD(z)}}function LD($){return C3(a2("sha256").update($).digest())}function HD($){let Z=C3(Buffer.from(JSON.stringify($)));return`${Z}.${C3(pz(Z))}`}function PD($){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=pz(J);if(j.length!==W.length||!mz(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,gz=1e4;function ND($,Z,J){if(J$.size>=gz){for(let[j,W]of J$)if(W<=J)J$.delete(j);while(J$.size>=gz){let j=J$.keys().next().value;if(j===void 0)break;J$.delete(j)}}J$.set($,Z)}function T8($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=PD($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let j=vz(J.state,$.returnedState),W=vz(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 ND(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var r2=new WeakMap;function CD($){let Z=r2.get($);if(!Z)Z=$(_D(32).toString("hex")),r2.set($,Z),Z.catch(()=>r2.delete($));return Z}async function t2($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await CD($.hashPassword))}catch{}return!1}async function b$($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:j,...W}=J;await $.onAuthenticated({...Z,user:W})}class $5 extends Error{}function e2($){return typeof $==="string"&&$!==""?$:null}function hz($){return sZ($)}var xD=256;function cz($){return typeof $==="string"&&$!==""&&$.length<=xD?$:null}var M8="intended_url";function uz($){if($.cookies.get(M8))$.ctx().setCookie(M8,"",{maxAge:-1})}function dz($){let Z=$.cookies.get(M8);if(!Z)return null;uz($);try{return W1(decodeURIComponent(Z),"")||null}catch{return null}}class Z5 extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class lz extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class iz extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}class o extends lZ{async me(){let $=await h0.user();if(!$)throw new Q4;return $}async verifyEmail($=new C){let Z=await $.input(),{userProvider:J}=T(A),j=e2(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(A),{userProvider:J}=Z,j=e2($.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(A).accessTokenCookieOptions($,Y.expiresAt)),await Z.config.onSignIn(Y,$.search.toJSON()),await b$(Z.config,{session:Y,isNewUser:!1,method:"magic-link",req:$}),{session:Y}}async verifyPinRequest($){let Z=T(A),J=await $.input(),{email:j,pin:W}=J.toJSON(),Y=sZ(j),z=cz(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(A),J=await this.verifyPinRequest($),j=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",j.token,T(A).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await b$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),j}async signInWithPin($=new C){let Z=T(A),J=await this.verifyPinRequest($),j=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",j.token,T(A).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await b$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async signInV2($=new Z5){let Z=await $.input(),{email:J,password:j}=Z.toJSON(),W=J.toLowerCase().trim(),Y=T(A),z=await Y.userProvider.findUserByEmailAddress(W,Y.config.verifyEmail),X=typeof j==="string"&&await t2(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(A).accessTokenCookieOptions($,G.expiresAt)),await Y.config.onSignIn(z,$.search.toJSON()),await b$(Y.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:F,...Q}=z;return Q}async signIn($=new Z5){let Z=await $.input(),{email:J,password:j}=Z.toJSON(),W=J.toLowerCase().trim(),Y=T(A),z=await Y.userProvider.findUserByEmailAddress(W,Y.config.verifyEmail),X=typeof j==="string"&&await t2(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(A).accessTokenCookieOptions($,G.expiresAt)),await Y.config.onSignIn(z,$.search.toJSON()),await b$(Y.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:F,...Q}=z;return Q}async signUp(){let $=T(A),{userProvider:Z,config:J}=$,j=new J.signUpRequest,W=await j.input(),{email:Y,password:z,name:X,invitationId:G}=W.toJSON(),F=hz(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),B;if(G)B=await Z.findInvitation(G,F);let D,U="";if(B)D=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:B.organizationId,userId:V.id,organizationRole:B.role}),await J.onUserCreated(V),V});else U=await J.generateEmailVerificationToken(F),D=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(D,U,j.search.toJSON()),D}async signOut($=new C){let Z=z$($),J=T(A),{config:j}=J,W=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",T(A).accessTokenCookieOptions($,new Date(0))),T(A).cookieDomain($))$.ctx().setCookie("access_token","",{...T(A).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(W?.user)SD(W.user),W.user.extension=await j.extendSession(W.user),await j.onSignOut(W.user);return{}}async forgotPassword($=new lz){let Z=await $.input(),J=hz(Z.get("email"));if(!J)return{};let{userProvider:j,config:W}=T(A),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 iz){let{userProvider:Z,config:J}=T(A),j=await $.input(),{password:W,token:Y}=j.toJSON(),z=e2(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(A),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 t2(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(A).config.oauthProviders[Z];if(!J)throw Error(`Invalid provider: ${Z}`);let j=s$($.rawRequest),W=W1($.search.get(j1),"");if(W)$.ctx().setCookie(M8,encodeURIComponent(W),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else uz($);let{state:Y,codeChallenge:z,cookieValue:X}=V8(Z);return $.ctx().setCookie(SZ(j),X,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:x3}),{destination:await J.getRedirectUrl($,{state:Y,codeChallenge:z,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,J=T(A),{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=T8({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 n2)return this.oauthFailure($,H.code);return console.error("Authentication error: OAuth provider callback failed",H),this.oauthFailure($,"provider_error")}let{name:K,username:B,providerId:D,emailVerified:U}=O??{},V=typeof O?.email==="string"?O.email:void 0,M=V?t3(V):null,I=D?await j.findUserBySocialAccount(Z,D):null,P="signin",f=!I&&!M&&!V&&!!D&&Y.createUsersWithoutEmail===!0;if(!I&&f){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:D,name:K,username:B,locale:T(i).detectLocale($)}),P="signup"}catch(H){let L=await j.findUserBySocialAccount(Z,D);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":D?"missing_email":"no_identity");if(U===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let H=T(i).detectLocale($);try{let L=await this.linkOAuthAccount({provider:Z,providerId:D,email:M,rawEmail:V,name:K,username:B,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=D?await j.findUserBySocialAccount(Z,D):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(A).accessTokenCookieOptions($,x.expiresAt)),P==="signup")await W.onSignUp(I,"",$.search.toJSON());else await W.onSignIn(I,$.search.toJSON());await b$(J.config,{session:x,user:I,isNewUser:P==="signup",method:"oauth",req:$});let E=dz($)??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(A);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=dz($),j=T(A).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(A),Q=(D)=>({provider:Z,userId:D,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 D=await G.findSocialAccounts(O.id,Z);if(D.some((V)=>V.providerId===J))return{user:O,action:"signin"};if(D.some((V)=>V.providerId))return console.error(`Authentication error: user ${O.id} is already linked to a different ${Z} account`),null;let U=D[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 D=await G.createUser({email:j,name:Y,locale:X,emailVerifiedAt:new Date});if(J)await G.createSocialAccount(Q(D.id));return await F.onUserCreated(D),D}),action:"signup"}}async createMagicLinkToken($=new C){let Z=await $.input(),J=sZ(Z.get("email")),j=T(A),{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(A),J=Z.config.emailCode;if(!J.enabled)throw new P0("Not found",{status:404});let j=await $.input(),W=t3(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(A),{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=t3(Y),F=cz(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),B=!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 $5;let V=await J.createUser({email:G,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:U});return await j.onUserCreated(V),V}),B=!0}catch(V){if(V instanceof $5)throw new v({code:["invalid_code"]});throw V}}else throw await J.claimMagicLinkToken(O.id),new v({code:["invalid_code"]});let D=await Z.createOrUpdateSessionV2({email:G,id:K.id});return $.ctx().setCookie("access_token",D.token,T(A).accessTokenCookieOptions($,D.expiresAt)),await j.onSignIn(D,$.search.toJSON()),await b$(Z.config,{session:D,isNewUser:B,method:"email-code",req:$}),{session:D,isNewUser:B}}}function SD($){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 sz="gemi_oauth_connection";class I8 extends lZ{async connect($=new C){let Z=String($.params.provider??""),j=T(S3).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}=V8(oz(Z),Date.now(),{subject:String(W.id),...Y?{returnTo:Y}:{}});return $.ctx().setCookie(SZ(z,sz),F,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:x3}),M1.external(j.authorizationUrl({state:X,codeChallenge:G,redirectUri:nz($,Z,j.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),J=T(S3),j=await h0.user(),W=s$($.rawRequest),Y=SZ(W,sz),z=$.cookies.get(Y);if(z!==void 0&&z!==null)$.ctx().setCookie(Y,"",{httpOnly:!0,sameSite:"Lax",secure:W,maxAge:-1});let X=T8({provider:oz(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:nz($,Z,F.config.redirectUri)}),B=await J.save(j,Z,K);await T(A).config.onConnected({user:j,provider:Z,connection:B,profile:K.profile??null,req:$})}catch(K){if(K instanceof az)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(A).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 oz($){return`connection:${$}`}function nz($,Z,J){if(J)return J;return`${(process.env.HOST_NAME||new URL($.rawRequest.url).origin).replace(/\/$/,"")}/auth/connections/${encodeURIComponent(Z)}/callback`}class rz extends I1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[o,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[o,"oauthCallback"])}}class tz extends I1{middlewares=["cache:private"];routes={"/:provider":this.redirect([I8,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([I8,"callback"]).middleware([u3,"auth"])}}class J5 extends I1{middlewares=["cache:private"];routes={"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[o,"signInWithMagicLink"]),"/oauth":rz,"/connections":tz}}class j5 extends b0{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 W5 extends b0{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 Y5{}class z5 extends Y5{async resize($,Z){let{height:J,width:j,quality:W,fit:Y}=Z;return await(await L8("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 bI($){return $}function ez(){return{driver:new z5}}class X5 extends b0{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($X).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 $X{static token="image";driver;constructor($={}){this.driver=$.driver??ez().driver}resize($,Z){return this.driver.resize($,Z)}}class G5 extends b0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(T(ZX).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function hI($){return $}function JX(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function jX(){return{partialRendering:!0,localeRouting:"prefix",onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function AD($){return"run"in $}function fD($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function ED($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function bD($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function RD($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function WX($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function F5($,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 D=new C().ctx().headers;return new Response(null,{headers:D,status:204})},middleware:[]}}for(let[Y,z]of Object.entries($)){if(RD(z)){let X=z;for(let G of["GET","POST","PUT","DELETE"])W(Y,G,X.run.bind(X),X.middlewares);continue}if(AD(z)){let X=z,G=X.method,F=X.middlewares,Q=X.run.bind(X);if(W(Y,G,Q,F,X.source),WX(z))W(Y,"HEAD",Q,F,X.source)}if(fD(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"&&WX(F))W(Y,"HEAD",O,Q,F.source)}if(bD(z)){let X=new z,G=F5(X.routes,`${Z}${Y}`,X.middlewares);for(let[F,Q]of Object.entries(G))j[F.replaceAll("//","/")]=Q}if(ED(z)){let{first:X,second:G}=z;for(let[F,Q]of Object.entries(X)){let O=Q.middlewares,K=Q.run.bind(Q),[B,...D]=Y.split("/").reverse();if(!B.startsWith(":"))throw Error("Resource route must end with a dynamic segment");W(D.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 H8($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function Q5($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function K5($){let Z=H8($);return Z.length>1?Z.replace(/\/$/,""):Z}function YX($,Z){return Z.map((J)=>({...J,path:K5(Q5($,J.path))}))}function P8($){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=P8(Y.routes);for(let[X,{exec:G,middleware:F,segments:Q,features:O,static:K}]of Object.entries(z)){let B=Q5(J,X),D=(U)=>W.run.call(W,U,J);Z[H8(B)]={exec:[D,...G],middleware:[...W.middlewares,...F],features:[...W.featureGates,...O],viewPath:W.viewPath,segments:[{path:K5(J),viewPath:W.viewPath,...W.alwaysRuns?{alwaysRun:!0}:{}},...YX(J,Q)],...K?{static:K}:{}}}}else{let Y=(z)=>W.run.call(W,z,J);Z[H8(J)]={exec:[Y],middleware:W.middlewares,features:W.featureGates,viewPath:W.viewPath,segments:[{path:K5(J),viewPath:W.viewPath}],..."staticOptions"in W&&W.staticOptions?{static:W.staticOptions}:{}}}}else{let W=new j,Y=P8(W.routes);for(let[z,{exec:X,middleware:G,viewPath:F,segments:Q,features:O,static:K}]of Object.entries(Y)){let B=Q5(J,z);Z[H8(B)]={exec:X,middleware:[...W.middlewares,...G],features:[...W.featureGates,...O],viewPath:F,segments:YX(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 wD=Object.defineProperty,_=($,Z)=>wD($,"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 kD=/[$_\p{ID_Start}]/u,yD=/[$_\u200C\u200D\p{ID_Continue}]/u,D5=".*";function zX($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}_(zX,"isASCII");function V5($,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&&kD.test(G)||X!==j+1&&yD.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(!zX($[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}_(V5,"lexer");function T5($,Z={}){let J=V5($);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 f=F(P);if(f!==void 0)return f;let{type:x,index:E}=J[z];throw TypeError(`Unexpected ${x} at ${E}, expected ${P}`)},"mustConsume"),K=_(()=>{let P="",f;for(;f=F("CHAR")??F("ESCAPED_CHAR");)P+=f;return P},"consumeText"),B=_((P)=>P,"DefaultEncodePart"),D=Z.encodePart||B,U="",V=_((P)=>{U+=P},"appendToPendingFixedValue"),M=_(()=>{U.length&&(W.push(new EZ(3,"","",D(U),"",3)),U="")},"maybeAddPartFromPendingFixedValue"),I=_((P,f,x,E,S)=>{let H=3;switch(S){case"?":H=1;break;case"*":H=0;break;case"+":H=2;break}if(!f&&!x&&H===3){V(P);return}if(M(),!f&&!x){if(!P)return;W.push(new EZ(3,"","",D(P),"",H));return}let L;x?x==="*"?L=D5:L=x:L=j;let m=2;L===j?(m=1,L=""):L===D5&&(m=0,L="");let u;if(f?u=f:x&&(u=Y++),G.has(u))throw TypeError(`Duplicate name '${u}'.`);G.add(u),W.push(new EZ(m,u,D(P),L,D(E),H))},"addPart");for(;z<J.length;){let P=F("CHAR"),f=F("NAME"),x=F("REGEX");if(!f&&!x&&(x=F("ASTERISK")),f||x){let S=P??"";Z.prefixes.indexOf(S)===-1&&(V(S),S=""),M();let H=Q();I(S,f,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}_(T5,"parse");function m0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}_(m0,"escapeString");function B5($){return $&&$.ignoreCase?"ui":"u"}_(B5,"flags");function XX($,Z,J){return M5(T5($,J),Z,J)}_(XX,"stringToRegexp");function R$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}_(R$,"modifierToString");function M5($,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)})${R$(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=D5),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?j+=`(${F})${R$(X.modifier)}`:j+=`((?:${F})${R$(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){j+=`(?:${m0(X.prefix)}(${F})${m0(X.suffix)})`,j+=R$(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,B5(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,B5(J))}_(M5,"partsToRegexp");var W$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},qD={delimiter:".",prefixes:"",sensitive:!0,strict:!0},vD={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function GX($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}_(GX,"isAbsolutePathname");function I5($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}_(I5,"maybeStripPrefix");function FX($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}_(FX,"maybeStripSuffix");function L5($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}_(L5,"treatAsIPv6Hostname");var QX=["ftp","file","http","https","ws","wss"];function H5($){if(!$)return!0;for(let Z of QX)if($.test(Z))return!0;return!1}_(H5,"isSpecialScheme");function KX($,Z){if($=I5($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}_(KX,"canonicalizeHash");function OX($,Z){if($=I5($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}_(OX,"canonicalizeSearch");function DX($,Z){return Z||$===""?$:L5($)?_5($):N5($)}_(DX,"canonicalizeHostname");function BX($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}_(BX,"canonicalizePassword");function UX($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}_(UX,"canonicalizeUsername");function VX($,Z,J){if(J||$==="")return $;if(Z&&!QX.includes(Z))return new URL(`${Z}:${$}`).pathname;let j=$[0]=="/";return $=new URL(j?$:"/-"+$,"https://example.com").pathname,j||($=$.substring(2,$.length)),$}_(VX,"canonicalizePathname");function TX($,Z,J){return P5(Z)===$&&($=""),J||$===""?$:C5($)}_(TX,"canonicalizePort");function MX($,Z){return $=FX($,":"),Z||$===""?$:N8($)}_(MX,"canonicalizeProtocol");function P5($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}_(P5,"defaultPortForProtocol");function N8($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}_(N8,"protocolEncodeCallback");function IX($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}_(IX,"usernameEncodeCallback");function LX($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}_(LX,"passwordEncodeCallback");function N5($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}_(N5,"hostnameEncodeCallback");function _5($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}_(_5,"ipv6HostnameEncodeCallback");function C5($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}_(C5,"portEncodeCallback");function HX($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}_(HX,"standardURLPathnameEncodeCallback");function PX($){return $===""?$:new URL(`data:${$}`).pathname}_(PX,"pathURLPathnameEncodeCallback");function NX($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}_(NX,"searchEncodeCallback");function _X($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}_(_X,"hashEncodeCallback");var CX=class{#Y;#j=[];#Z={};#$=0;#W=1;#F=0;#X=0;#D=0;#B=0;#U=!1;constructor($){this.#Y=$}get result(){return this.#Z}parse(){for(this.#j=V5(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.#D>0)if(this.#x())this.#D-=1;else continue;if(this.#C()){this.#D+=1;continue}switch(this.#X){case 0:this.#L()&&this.#O(1);break;case 1:if(this.#L()){this.#f();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.#B+=1:this.#A()&&(this.#B-=1),this.#_()&&!this.#B?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.#$,"[")}#A(){return this.#z(this.#$,"]")}#G(){let $=this.#j[this.#$],Z=this.#V(this.#F).index;return this.#Y.substring(Z,$.index)}#f(){let $={};Object.assign($,W$),$.encodePart=N8;let Z=XX(this.#G(),void 0,$);this.#U=H5(Z)}};_(CX,"Parser");var O5=["protocol","username","password","hostname","port","pathname","search","hash"],j$="*";function U5($,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}}_(U5,"extractValues");function D1($,Z){return Z?fZ($):$}_(D1,"processBaseURLString");function AZ($,Z,J){let j;if(typeof Z.baseURL=="string")try{j=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=D1(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=D1(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=D1(j.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=D1(j.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=D1(j.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=D1(j.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=D1(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=D1(j.hash.substring(1,j.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=MX(Z.protocol,J)),typeof Z.username=="string"&&($.username=UX(Z.username,J)),typeof Z.password=="string"&&($.password=BX(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=DX(Z.hostname,J)),typeof Z.port=="string"&&($.port=TX(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,j&&!GX($.pathname,J)){let W=j.pathname.lastIndexOf("/");W>=0&&($.pathname=D1(j.pathname.substring(0,W+1),J)+$.pathname)}$.pathname=VX($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=OX(Z.search,J)),typeof Z.hash=="string"&&($.hash=KX(Z.hash,J)),$}_(AZ,"applyInit");function fZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}_(fZ,"escapePatternString");function xX($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}_(xX,"escapeRegexpString");function SX($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",j=`[^${xX(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+=fZ(X.value);continue}Y+=`{${fZ(X.value)}}${R$(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+=fZ(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+=fZ(X.suffix),F&&(Y+="}"),X.modifier!==3&&(Y+=R$(X.modifier))}return Y}_(SX,"partsToPattern");var x5=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 CX($);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=AZ(Y,$,!0),P5(this.#Y.protocol)===this.#Y.port&&(this.#Y.port="");let z;for(z of O5){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=N8;break;case"username":Object.assign(X,W$),X.encodePart=IX;break;case"password":Object.assign(X,W$),X.encodePart=LX;break;case"hostname":Object.assign(X,qD),L5(G)?X.encodePart=_5:X.encodePart=N5;break;case"port":Object.assign(X,W$),X.encodePart=C5;break;case"pathname":H5(this.#j.protocol)?(Object.assign(X,vD,W),X.encodePart=HX):(Object.assign(X,W$,W),X.encodePart=PX);break;case"search":Object.assign(X,W$,W),X.encodePart=NX;break;case"hash":Object.assign(X,W$,W),X.encodePart=_X;break}try{this.#W[z]=T5(G,X),this.#j[z]=M5(this.#W[z],this.#Z[z],X),this.#$[z]=SX(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=AZ(J,$,!1):J=AZ(J,U5($,Z),!1)}catch{return!1}let j;for(j of O5)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=AZ(J,$,!1):J=AZ(J,U5($,Z),!1)}catch{return null}let j={};Z?j.inputs=[$,Z]:j.inputs=[$];let W;for(W of O5){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}};_(x5,"URLPattern");function A3($,Z){for(let[J,j]of Object.entries($)){let W=new x5({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 AX($,Z){let J=K0($.path,Z);return J.includes("*")?null:J}function gD($,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=AX(W,$.params),X=AX(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 mD($,Z){let[,J,...j]=$.split("/");if(!Z.includes(J))return $;let W=`/${j.join("/")}`;return W==="/"?"/":W.replace(/\/$/,"")}function fX($){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=A3(Z,mD(z.pathname,J));if(!X)return w$;return gD({segments:X.route.segments,params:X.params,search:z.search},Y)}var S5="x-gemi-from";import{createElement as R1,Fragment as WG}from"react";function pD($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function _8($){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=_8(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=_8(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])=>[pD(J),j]))}function C8($,Z){let[J,j]=Z,W=$.find(([Y])=>Y===J);if(!W){$.push([J,[...j]]);return}for(let Y of j)C8(W[1],Y)}function x8($){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=x8(Y.routes);C8(Z,[W,z])}else C8(Z,[W,[]])}else{let W=new j,Y=x8(W.routes);for(let z of Y)C8(Z,z)}return Z}function A5($){let Z=[];for(let[J,j]of $)Z.push(J,...A5(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 f5{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}var hD=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),cD=new Set(["svg","math"]);function EX($){return $===32||$===9||$===10||$===12||$===13}function bX($){return $>=65&&$<=90||$>=97&&$<=122}function S8($){return $>=65&&$<=90?$+32:$}function RX(){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&&hD.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(cD.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(bX(K))$="tagName",J=!1,z=!1,Z=String.fromCharCode(S8(K));else if(K===63)$="bogus";else if(K===60)$="tagOpen";else $="data";return;case"endTagOpen":if(bX(K))$="tagName",J=!0,z=!1,Z=String.fromCharCode(S8(K));else if(K===62)$="data";else $="bogus";return;case"tagName":if(EX(K)||K===47)$="inTag",z=K===47;else if(K===62)Q();else Z+=String.fromCharCode(S8(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(S8(K)===j.charCodeAt(W))W+=1;else W=K===60?1:0;return}if(K===62)$="data",Z="";else if(EX(K)||K===47)$="inTag",Z="";else W=K===60?1:0;return}}};return{scanToInsertionPoint(K){for(let B=0;B<K.length;B++){if(F())return B;O(K[B])}return K.length},write(K){for(let B=0;B<K.length;B++)O(K[B])},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 dD($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${E1([$.path,$.variantKey,$.data])})</script>`}function uD($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${E1([$.id,$.locale,$.strings])})</script>`}function E5($,Z,J={},j){let W=new TextEncoder,Y=[],z=!1,X=!1,G=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((D)=>{if(D.status!=="resolved")return;Y.push(dD(D))}),j?.onUse((D)=>{Y.push(uD(D))});let F=$.getReader(),Q=RX(),O=(D,U)=>{D.enqueue(U),J.onChunk?.(U)},K=(D)=>{while(Y.length>0){let U=W.encode(Y.shift());Q.write(U),O(D,U)}},B=(D,U)=>{if(Y.length===0){Q.write(U),O(D,U);return}let V=Q.scanToInsertionPoint(U);if(V>0)O(D,U.subarray(0,V));if(Q.isSafe())K(D);let M=U.subarray(V);if(M.length>0)Q.write(M),O(D,M)};return new ReadableStream({async pull(D){let U;try{U=await F.read()}catch(I){throw G(),I}let{done:V,value:M}=U;if(V){K(D),D.close(),G();return}if(!z){if(z=!0,Q.write(M),O(D,M),J.onShell?.(),Q.isSafe())K(D);return}B(D,M)},cancel(D){return G(),F.cancel(D)}})}var lD=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function A8($){if(!$)return!1;return lD.test($)}async function kX($,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 iD($,Z),request:{path:W,routePath:j?.routePath??null,locale:J?.locale??null},anonymousId:wX(),isBot:A8(j?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function yX($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function iD($,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 qX($,Z){return`${$}:${Z}`}function b5($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function vX($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function gX($,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=oD($,Z,J,j.buckets);return vX(W,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function sD($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function oD($,Z,J,j){let W=qX(Z.salt??$,sD(J));if(!j)return b5(W);let Y=j.get(W);if(Y!==void 0)return Y;let z=b5(W);return j.set(W,z),z}class mX 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 R5{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 mX(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=nD(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 nD($){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 aD{}class rD 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 w5 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 pX 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 hX{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 bZ{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new R5($.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 pX(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let j=tD(J.actor),W=this.config.source;if(typeof W.write!=="function")throw new w5(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 hX(this,yX($))}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=gX($,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 kX(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 tD($){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 cX($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var eD=50;class RZ{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(cX(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 B=Math.round(performance.now()-this.renderStartedAt);if(B>eD)F=B}let Q,O=new Promise((B)=>{Q=B}),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((B)=>{K.status="resolved",K.data=B},(B)=>{K.status="rejected",K.error=B}).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 b1 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 k5(){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=dX($);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 b1(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 b1(K0(J,j),W.toString(),Q.status,O);return O}return Q}catch(Q){if(Q instanceof b1)throw Q;let O=new b1(K0(J,j),W.toString(),500,{message:Q instanceof Error?Q.message:String(Q)});throw O.cause=Q,O}}))}}var $B=new Set(["script","style","template","title"]),ZB=/\shidden([\s=/]|$)/i,JB=/"[^"]*"|'[^']*'/g;function jB($){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&&$B.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(ZB.test(G.replace(JB,'""')))j=1}return{shellChars:Z,deferredChars:J}}var WB=1000,YB=64;function zB($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function XB($,Z){if(Z.deferredChars<WB)return null;if(Z.shellChars>=YB)return null;return`[gemi] GET ${$} streams ${zB(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 uX($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,j){if(Z.has(J))return;let W=XB(J,j);if(!W)return;Z.add(J),$(W)}}}function lX(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),jB(Z)}}}function iX($,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 oL,createContext as GB,createElement as nL,lazy as aL,use as rL,useContext as tL}from"react";function sX($){return{islands:[],render:$,instances:new WeakMap,count:0}}var E3="gemi-slot",oX="data-slot",nX="data-gemi-slot";var FB=Symbol.for("gemi.staticRender"),aX=globalThis[FB]??=GB(null);import{createHash as eX}from"crypto";var y5='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 QB="gemi-islands",zH=`'sha256-${eX("sha256").update(q5).digest("base64")}'`;function rX($,Z,J,j){if(!J)return $;let W=j?$.lastIndexOf(Z):$.indexOf(Z);return W===-1?$+J:$.slice(0,W)+J+$.slice(W)}var tX=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),XH=`'sha256-${eX("sha256").update(y5).digest("base64")}'`,KB='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',OB="gemi-static";function $G($,Z,J,j,W){let Y=new Set,z=[];if(J)z=Z.islands.map((K)=>{let B=K.module?J(K.module):void 0;if(!B)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 D of B.preload)Y.add(D);return{s:B.src,e:K.export,l:K.load}});let X=z.some((K)=>K!==null);if(!X&&!W)return $;let F=(W?`<meta name="${OB}" content="${tX(W.identity)}"${W.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...Y].map((K)=>`<link rel="modulepreload" href="${tX(K)}"/>`).join(""),Q=W?y5:q5,O=(X?`<script type="application/json" id="${QB}">${E1({i:z})}</script>`:"")+`<script type="module">${j?KB+Q:Q}</script>`;return rX(rX($,"</head>",F,!1),"</body>",O,!0)}function DB($,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 ZG($){let Z=`<template ${nX}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let j=DB($,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=`<${E3} ${oX}="${Y}" style="display:contents"></${E3}>`;$=$.split(G).join(`<${E3} style="display:contents">${X}</${E3}>`)}return $}function JG($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function jG($,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 BB=async()=>(await import("./chunk-yzhv93b0.js")).default,v5,b3=async(...$)=>{return v5??=import("react-dom/server.browser").catch((Z)=>{throw v5=void 0,Z}),(await v5).renderToReadableStream(...$)},YG=1e4,zG="no-locale",UB=`
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 VB($,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 p5="/assets";function TB($){return $===p5||$.startsWith(`${p5}/`)}function MB($){let Z=$.filter(TB);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 "${p5}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function IB($){let Z=T(J1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function g5($){let{status:Z=400,error:J,body:j,...W}=$;return new Response(j??J?.message,{...W,status:Z})}function LB($){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=uX();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;constructor($){let Z=jX();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":J5};this.flatViewRoutes=P8(J),MB(Object.keys(this.flatViewRoutes)),this.routeManifest=_8(J),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,j])=>j.at(-1)!=="FILE")),this.componentTree=x8(J),this.flatComponentTree=A5(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(bZ);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)=>R1("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=m5(),O=new AbortController,K=setTimeout(()=>O.abort(),YG),B=(U)=>{if(Bun.env.NODE_ENV!=="production")console.error(U)},D=sX(async(U,V)=>{let M=await b3(U,{signal:O.signal,identifierPrefix:V,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:B});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 b3(R1(aX.Provider,{value:D,children:R1(WG,{children:[...F,R1(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:B});await V.allReady.catch(()=>{});let M=ZG(await new Response(V).text());return new Response($G(M,D,$.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:B,viewData:D,breadcrumbs:U,urlLocaleSegment:V,meta:M,isOgRequest:I,appId:P,features:f,staticView:x}=$,E=G.replace(`/${V}`,""),S={kind:"view",data:{meta:M,pageData:{[E]:D},__csrf:j.toString("base64"),prefetchedData:{},i18n:z,auth:{user:B},routeManifest:this.clientRouteManifest,breadcrumbs:U,router:{urlLocaleSegment:V,pathname:W,params:X,currentPath:G,searchParams:K.search,is404:!W?!0:!1,domain:Z.domain?IB(Z):null},appId:P,features:f,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,k3=(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 aG=Object.values(S.data.pageData)[0];try{await b3(R1(J0,aG[p$]),{onError:()=>{}})}catch(h$){let{fonts:rG,...tG}=h$.satoriOptions,eG=await Promise.all(rG.map((y3)=>{return VB(y3.name,y3.weight,y3.style).then((WF)=>({...y3,data:WF}))})),Jj=new Headers(Y);Jj.set("Content-Type","image/png");let[$F,ZF]=await Promise.all([BB(),L8("Rendering an OG image")]),JF=await $F(h$.jsx,{...tG,fonts:eG}),jF=await ZF(Buffer.from(JF)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(jF),{headers:Jj})}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 m8=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(),YG),T1=A8(Q)||O,b=Bun.env.NODE_ENV!=="production"&&!T1&&W&&this.shellReporter.shouldObserve(W)?lX():null,p0=m5();try{let J0=await b3(R1(WG,{children:[...m8,...m$,R1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:UB}}),R1(H,{data:S.data,viewImportMap:n,viewModules:y$,serverQueries:F,dictionarySink:p0,key:"root"})]}),{bootstrapScriptContent:k3(`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(E5(J0,F,{onShell:T1?void 0:()=>F.markShell(),onChunk:b?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,F.summarize(V1.signal.aborted)),b)this.shellReporter.report(W,b.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 b3(R1("div"),{bootstrapScriptContent:k3(`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(E5(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 b1&&(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=A3(this.flatViewRoutes,Y),B=O.isLocaleAware&&this.localeRouting==="prefix"&&!K?.route.middleware.includes(zG);if(B&&O.supportedLocales.includes(z))G=`/${X.join("/")}`,F=z,Q=z;if(B&&!W&&Q===null&&!(Q===null&&K!==null)){let H=XG(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(B&&!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,f=!1,x=[],E;try{let H=A3(this.flatViewRoutes,G);if(Q&&H?.route.middleware.includes(zG))H=null;if(H){if(M=H.routePath,I=H.params,U=H.route.exec,V=H.route.middleware,x=H.route.features,f=V.includes("no-stream"),E=H.route.static,j&&this.partialRendering){let L=$.headers.get(S5),m=fX({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 RZ(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=JG(E);if(Q){let k=Q.replaceAll("/","");Y$.setLocale(k,{cookie:Z0.locale})}else if(O.isLocaleAware&&!B)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(b){if(k=this.viewRefusalStatus(n,b,k1),k===null)throw b}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 b=null;if(Q)b=Q.replaceAll("/",""),L.setLocale(b);else if(!B)b=L.locale??U0.defaultLocale;else b=U0.detectLocale(vZ),L.setLocale(b);let p0=y$?U0.getPageTranslations(b,n.routePath):{};U1={...U1,supportedLocales:U0.supportedLocales,currentLocale:b,dictionary:{[b]:p0},defaultLocale:U0.defaultLocale,...B?{}:{localeRouting:"off"}}}await GG(U1.currentLocale??"");let v$;try{v$=await Promise.all(U.map((b)=>b(n)))}catch(b){if(k=this.viewRefusalStatus(n,b,k1),k===null)throw b;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(f5).id,features:await T(bZ).forClient()};let{params:k3,user:m8}=H,m$={},V1={};for(let b of v$??[]){let[p0,J0]=Object.entries(b)?.[0]??[];if(!p0||!J0)continue;V1[`${p0}:${M}`]=J0.breadcrumb,m$[p0]=J0}let gZ=m$.FILE;if(gZ){for(let b of g$)a.append("Set-Cookie",b.toString());try{await this.onRequestEnd(n)}catch(b){k$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}return await t8(gZ,a)}if(j){a.set("Content-Type","application/x-ndjson; charset=utf-8"),a.append("Vary",S5),g$.forEach((p0)=>a.append("Set-Cookie",p0.toString())),await this.hooks.onRequestEnd(n);let b={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(iX(b,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"),!f&&!(E&&M))a.append("Vary","User-Agent");let T1=Boolean(E&&M);if(!T1||Z0.session)f8();for(let b of g$)a.append("Set-Cookie",b.toString());if(!T1||Z0.csrf){let b=Bun.CSRF.generate(process.env.SECRET);a.append("Set-Cookie",`csrf_token=${b}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(n,{mintSession:!T1||Z0.session})}catch(b){k$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}if(T1)jG(a,E);return await this.render({req:n,runInRequestScope:u,csrfTokenHMAC:Buffer.from(""),currentPathName:M,headers:a,i18n:U1,params:k3,pathname:J.pathname,serverQueries:L.serverQueries,userAgent:$.headers.get("user-agent"),noStream:f,url:J,user:m8,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?LB(k.payload.viewData??k.payload.api):g5(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():g5(k5());if(k instanceof b1&&k.status===403)return j?wZ():g5(k5());throw k}},Z)}}function h5(){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 DG extends b0{routes={"/api-routes":this.get(()=>{let $=T(b8).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 HB=new Set([y1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),PB=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,NB=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function _B($,Z,J,j){for(let[W,Y]of Object.entries(J.headers??{})){if(Y===void 0||Y===null)continue;let z=W.toLowerCase();if(HB.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(!PB.test(W)||!NB.test(Y))throw Error(`dispatchAs: "${W}" is not a cookie a Cookie header can carry.`);Z.push(`${W}=${Y}`)}}function CB($,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 FG($){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 QG($,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 b8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=JX();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=F5({"/":$.rootRouter,"/auth":j5,"/__gemi__/services/i18n":W5,"/__gemi__/services/logs":G5,"/__gemi__/services/image":X5,"/__gemi__/debug":DG})}getRouteHandlerAndParams($){let Z=new URL($.url),J=OG(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 FG(W.payload.api);else{if(X$(W))return h5();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 FG(Y.payload.api);if(X$(Y))return h5();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=QG(Q,z.headers,z.cookies);return await G(),U}let O=await this.getRouteData(j),K=z.headers,B=z.cookies;if(O instanceof Response){let U=QG(O,K,B);if(this.isOpenEndedBody($,U)){let V=CB(U,()=>this.endRequest(z,Y,j));return X=!0,V}return await G(),U}let D=(i$(O)?O:G$.json(O)).toResponse(K,B);return await G(),D}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)_B(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 B=$.headers.get("User-Agent");if(B)F.set("User-Agent",B);let D;if(j instanceof FormData)D=j;else if(j!==void 0)F.set("Content-Type","application/json"),D=JSON.stringify(j);let U=new Request(z,{method:Z,headers:F,body:D,...W?.signal?{signal:W.signal}:{}});if(KG(U,o$($),G?.grant,W?.progress),$.domain)yZ(U,$.domain);let V=G?{user:G.user}:void 0;return N.exit(()=>c3.exit(()=>this.handleApiRequest(U,V)))}}import{timingSafeEqual as xB}from"crypto";var w8="",u5="*",SB=60000,AB=1e4,c5=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,R8=16,BG=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,d5="x-forwarded-host";function UG($){return $.startsWith(":")}function l5($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),j=Buffer.from(Z,"utf8");return J.length===j.length&&xB(J,j)}function fB($){if(!$)return null;if($===!0)return{header:d5,secret:null};return{header:($.hostHeader??d5).toLowerCase(),secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function EB($){if(!$||$===!0)return;let{hostHeader:Z,secret:J}=$;if(Z!==void 0&&(typeof Z!=="string"||!BG.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"||!BG.test(J.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${J.header}".`);if(J.header.toLowerCase()===(Z??d5).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 B1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function bB($){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 RB($){let Z=B1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((Y)=>c5.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.`);EB($.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),UG(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)=>c5.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 i5{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){RB($),this.root=B1($.root),this.hostTrust=fB($.trustProxy);for(let Z of $.groups??[])if(UG(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??SB,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!l5($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}hostOf($){return B1(this.forwardedHost($))??B1(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&&B1(W)?bB(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:u5,params:{},custom:!0};return null}async allows($,Z){let J=B1($);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:w8,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&&c5.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>=AB)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=B1($);if(Z)this.cache.delete(Z)}}}var wB="/__gemi__/domains/ask";class J1{static token="router.domains";resolver;acceptsCustomDomains;groups=new Map;constructor($,Z){this.groups.set(w8,$);let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new i5(J);let j=(W)=>({api:W.api?new b8({...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(u5,j(J.custom.fallback))}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)VG($,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!==wB)return null;if(!l5(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??w8)}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 k8($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var TG=600000;function MG($,Z){return[a3($,Z),a3($,Z-1)]}class A{static token="auth";config;provider;constructor($={},Z=new L4){this.config={...xZ(N9($),$),emailCode:M4($.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:B1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let j=$.domain?.host??B1(new URL($.rawRequest.url).host);return j===J||j?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!O4($))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=k8(J.expiresAt),Y=k8(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/TG),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=a3($,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 MG($,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(O4($)||!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()/TG),j=MG($,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=O9(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:I9(Z);return await this.userProvider.createMagicLinkToken({email:$,token:r3("link",$,J),pin:r3("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=k8(Y.createdAt);if(z+j*60000<=Date.now())return iZ("pin",$,null,Z),{status:"expired"};if(!await P9(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(k8(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 A}static async user(){let $=N.getStore(),Z=$?.user;if(!Z){if(Z=await m3(this.getFacadeRoot(),$?.req),Z)$?.setUser(Z)}if(Z)return Z;throw new F$({redirectTo:d3($?.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 y8{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 RZ(f3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=y8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){y8.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 RZ(f3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function IG($,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=kB(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 kB($){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 LG{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 IG({root:j.root,origin:Y},$,K0(String(Z),J[0]??{}))}}class HG{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 yB={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 PG}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 NG extends g{static getFacadeAccessor(){return Y1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}}class CG extends g{static getFacadeAccessor(){return _G}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class SG extends g{static getFacadeAccessor(){return xG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class AG extends g{static getFacadeAccessor(){return S3}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 CN($){return $}function fG(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function q8($){let Z=new URLSearchParams;for(let[J,j]of $)Z.append(J,String(j));return Z.toString()}function s5($){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:qB}=globalThis.Bun;function vB(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var gB=async($)=>{let Z=new qB($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,j,W)=>Z.listen(J,j,W),close:()=>Z.close({timeout:1})}},mB=async($)=>{let Z;try{Z=(await import("./chunk-65s834td.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(()=>{})}},EG=($)=>vB()?gB($):mB($);var pB=/^[A-Za-z_][A-Za-z0-9_]*$/;class o5{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(!pB.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??EG}async createTable(){for(let $ of hB(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 bG(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 hB($,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 n5{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 qG=new TextEncoder;function RG($,Z){return qG.encode(`id: ${$}
53
- data: ${JSON.stringify(Z)}
54
-
55
- `)}function vG($,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 v8))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(yG())return Q(K);try{K.enqueue(qG.encode(wG))}catch{Q(K)}},$.config.keepaliveInterval)},async pull(K){try{if(!G){if(await z.ready(),G=!0,!F)K.enqueue(RG(z.cursor,{type:"ready"}));return}let B=await z.next();if(B.done||F)return Q(K);K.enqueue(RG(z.cursor,B.value))}catch(B){if(!F)console.error("[gemi] A change feed stream failed.",B);Q(K)}},cancel(){if(F=!0,X)clearInterval(X);X=null,z.close()}});return new Response(O,{headers:kG()})}var gG=255,mG=500,cB=30000;class v8 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class t5{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=mG;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=xZ(fG(),$),this.driver=uB(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){r5($);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 r5($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=a5($);return q8(await this.driver.heads(Z))}subscribe($,Z={}){let J=a5($);if(this.all.size>=this.config.maxSubscriptions)throw new v8(this.config.maxSubscriptions);let j=new pG(this,J,dB(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 vG(this,$,a5(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=mG,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,cB)}}}class pG{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 q8(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 r5($){if(typeof $!=="string"||$===""||$.length>gG)throw Error(`A change feed channel is a string of 1 to ${gG} characters; got ${JSON.stringify($)}.`)}function a5($){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)r5(J);return Z}function dB($){if($===void 0||$===null)return new Map;if(typeof $==="string")return s5($);let Z=$ instanceof Map?[...$]:Object.entries($);return s5(q8(new Map(Z)))}function uB($,Z){if($==="memory")return new n5;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 o5(Z.make(D$));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 hG extends g{static getFacadeAccessor(){return t5}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 w3 extends g0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(g0)?$.make(g0):void 0;if(Z instanceof w3)return Z;let J=new w3($,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 ${e5($,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 ${e5($,Z,J)} not to have been broadcast, but it was broadcast ${$j(j.length)}: ${Zj(j)}.`)}assertSentTimes($,Z,J,j){let W=this.matching($,J,j);if(W.length===Z)return;throw Error(`Expected ${e5($,J,j)} to have been broadcast ${$j(Z)}, but it was broadcast ${$j(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"}: ${Zj(this.sent)}.`)}matching($,Z,J){return u$($),this.sent.filter((j)=>(j.pattern===$||Ij($,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: ${Zj(this.sent)}.`}}function e5($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function $j($){return`${$} ${$===1?"time":"times"}`}function Zj($){return $.map((Z)=>`${Z.topic} ${Z.event}(${lB(Z.data)})`).join(", ")}function lB($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class cG 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 w3.install(T())}}class dG extends g{static getFacadeAccessor(){return bZ}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 g8{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 iG(J.sql,(j)=>uG(Z,()=>$(j)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-c4jnxmf2.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:j,values:W}=oG($,sG(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 lG($),T(D$).connection($)}}var qZ=new g8;class nG extends g{static getFacadeAccessor(){return D$}static connection($){return new g8($)}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,d8 as $c,d$ as ad,hZ as bd,b0 as cd,m3 as dd,K4 as ed,O4 as fd,O9 as gd,Y1 as hd,r as id,dZ as jd,dj as kd,o$ as ld,D9 as md,B9 as nd,B4 as od,U4 as pd,r3 as qd,iZ as rd,eT as sd,N9 as td,LQ as ud,L4 as vd,$4 as wd,u3 as xd,M1 as yd,G$ as zd,_F as Ad,t8 as Bd,I1 as Cd,Y$ as Dd,y8 as Ed,LG as Fd,HG as Gd,yB as Hd,w1 as Id,NG as Jd,CG as Kd,SG as Ld,AG as Md,CN as Nd,fG as Od,q8 as Pd,s5 as Qd,o5 as Rd,n5 as Sd,v8 as Td,t5 as Ud,pG as Vd,hG as Wd,p as Xd,cZ as Yd,DM as Zd,l2 as _d,BM as $d,UM as ae,MM as be,Az as ce,s2 as de,bz as ee,NM as fe,kz as ge,g0 as he,_3 as ie,yz as je,cG as ke,qX as le,b5 as me,vX as ne,gX as oe,sD as pe,mX as qe,R5 as re,aD as se,rD as te,w5 as ue,pX as ve,hX as we,bZ as xe,dG as ye,g8 as ze,nG as Ae,n2 as Be,TD as Ce,Y5 as De,z5 as Ee,bI as Fe,ez as Ge,$X as He,p3 as Ie,q1 as Je,hI as Ke,JX as Le,jX as Me,f5 as Ne,wZ as Oe,k5 as Pe,zH as Qe,XH as Re,p5 as Se,TB as Te,g5 as Ue,LB as Ve,R3 as We,h5 as Xe,FG as Ye,QG as Ze,b8 as _e,J1 as $e,A as af,h0 as bf,h3 as cf,_j as df,MF as ef,Hj as ff,xj as gf,n8 as hf,a8 as if,Sj as jf,CF as kf,xF as lf,kj as mf,qj as nf,gj as of,ij as pf,sj as qf,oj as rf,J4 as sf,bF as tf,W0 as uf,Y9 as vf,r$ as wf,Q9 as xf};
56
-
57
- //# debugId=C3092A80409FE77364756E2164756E21