gemi 0.141.0 → 0.143.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 (216) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/app/App.d.ts +4 -3
  4. package/dist/app/App.d.ts.map +1 -1
  5. package/dist/app/index.js +1 -1
  6. package/dist/auth/AuthController.d.ts.map +1 -1
  7. package/dist/auth/config.d.ts +24 -5
  8. package/dist/auth/config.d.ts.map +1 -1
  9. package/dist/bin/gemi.js +2 -2
  10. package/dist/bin/gemi.js.map +3 -3
  11. package/dist/bun/plugin.js +1 -1
  12. package/dist/bun/preload.js +1 -1
  13. package/dist/{chunk-s58hbczk.js → chunk-0839f72f.js} +2 -2
  14. package/dist/{chunk-s58hbczk.js.map → chunk-0839f72f.js.map} +1 -1
  15. package/dist/{chunk-0c553zfq.js → chunk-0t2ym9ap.js} +3 -3
  16. package/dist/{chunk-0c553zfq.js.map → chunk-0t2ym9ap.js.map} +1 -1
  17. package/dist/{chunk-1axhttzr.js → chunk-159c392q.js} +2 -2
  18. package/dist/{chunk-1axhttzr.js.map → chunk-159c392q.js.map} +1 -1
  19. package/dist/{chunk-r6thf4ge.js → chunk-1cn7ets3.js} +3 -3
  20. package/dist/{chunk-r6thf4ge.js.map → chunk-1cn7ets3.js.map} +1 -1
  21. package/dist/{chunk-kddgfct7.js → chunk-1ed75a7b.js} +3 -3
  22. package/dist/{chunk-kddgfct7.js.map → chunk-1ed75a7b.js.map} +1 -1
  23. package/dist/chunk-1rvnk7g8.js +24 -0
  24. package/dist/{chunk-03qkwjvy.js.map → chunk-1rvnk7g8.js.map} +5 -6
  25. package/dist/{chunk-98dxtkbt.js → chunk-1skdsmjx.js} +2 -2
  26. package/dist/{chunk-98dxtkbt.js.map → chunk-1skdsmjx.js.map} +1 -1
  27. package/dist/{chunk-x4g0r9d3.js → chunk-1w5dnkd1.js} +2 -2
  28. package/dist/{chunk-x4g0r9d3.js.map → chunk-1w5dnkd1.js.map} +1 -1
  29. package/dist/{chunk-3wpxqcw7.js → chunk-1x9ghjpt.js} +1 -1
  30. package/dist/{chunk-vtqvq9ca.js → chunk-20d0n391.js} +2 -2
  31. package/dist/{chunk-tbhtx2t0.js.map → chunk-20d0n391.js.map} +1 -1
  32. package/dist/{chunk-y7v30zd8.js → chunk-236be97q.js} +1 -1
  33. package/dist/{chunk-tghh8r2q.js → chunk-2ra5skyk.js} +2 -2
  34. package/dist/{chunk-tghh8r2q.js.map → chunk-2ra5skyk.js.map} +1 -1
  35. package/dist/{chunk-kc2z9z3m.js → chunk-3q7sc68p.js} +2 -2
  36. package/dist/{chunk-kc2z9z3m.js.map → chunk-3q7sc68p.js.map} +1 -1
  37. package/dist/{chunk-t7qp951h.js → chunk-5g7m7g4a.js} +3 -3
  38. package/dist/{chunk-t7qp951h.js.map → chunk-5g7m7g4a.js.map} +1 -1
  39. package/dist/{chunk-5013raxj.js → chunk-5qfzvnyp.js} +3 -3
  40. package/dist/{chunk-5013raxj.js.map → chunk-5qfzvnyp.js.map} +1 -1
  41. package/dist/{chunk-eydahc2f.js → chunk-5xfpqda5.js} +1 -1
  42. package/dist/{chunk-p131vmpy.js → chunk-63q7ycwt.js} +2 -2
  43. package/dist/{chunk-p131vmpy.js.map → chunk-63q7ycwt.js.map} +1 -1
  44. package/dist/{chunk-gy307m19.js → chunk-68f0jpje.js} +2 -2
  45. package/dist/{chunk-gy307m19.js.map → chunk-68f0jpje.js.map} +1 -1
  46. package/dist/{chunk-b9d021hx.js → chunk-78bfmwp0.js} +2 -2
  47. package/dist/{chunk-b9d021hx.js.map → chunk-78bfmwp0.js.map} +1 -1
  48. package/dist/{chunk-j9hf1jyd.js → chunk-83cvkhzn.js} +2 -2
  49. package/dist/{chunk-j9hf1jyd.js.map → chunk-83cvkhzn.js.map} +1 -1
  50. package/dist/{chunk-9yfg4nqq.js → chunk-8ex0y47w.js} +2 -2
  51. package/dist/{chunk-9yfg4nqq.js.map → chunk-8ex0y47w.js.map} +1 -1
  52. package/dist/{chunk-me6mmvbq.js → chunk-8ky8cmde.js} +2 -2
  53. package/dist/{chunk-me6mmvbq.js.map → chunk-8ky8cmde.js.map} +1 -1
  54. package/dist/{chunk-gp4s95kn.js → chunk-9dkpv8ev.js} +2 -2
  55. package/dist/{chunk-gp4s95kn.js.map → chunk-9dkpv8ev.js.map} +1 -1
  56. package/dist/{chunk-v2cv3wcw.js → chunk-9k46m1vf.js} +2 -2
  57. package/dist/{chunk-v2cv3wcw.js.map → chunk-9k46m1vf.js.map} +1 -1
  58. package/dist/chunk-9qfd02h8.js +10 -0
  59. package/dist/{chunk-0540ptgm.js.map → chunk-9qfd02h8.js.map} +4 -4
  60. package/dist/{chunk-e9eh5k8a.js → chunk-9tgcmx4h.js} +2 -2
  61. package/dist/{chunk-e9eh5k8a.js.map → chunk-9tgcmx4h.js.map} +1 -1
  62. package/dist/{chunk-23mcs80p.js → chunk-9xzg05xg.js} +3 -3
  63. package/dist/{chunk-23mcs80p.js.map → chunk-9xzg05xg.js.map} +1 -1
  64. package/dist/{chunk-e9xbdgb2.js → chunk-a37shxb1.js} +2 -2
  65. package/dist/{chunk-e9xbdgb2.js.map → chunk-a37shxb1.js.map} +1 -1
  66. package/dist/chunk-aw8gj99f.js +4 -0
  67. package/dist/chunk-aw8gj99f.js.map +10 -0
  68. package/dist/{chunk-k732d7x5.js → chunk-azd6da5h.js} +2 -2
  69. package/dist/{chunk-k732d7x5.js.map → chunk-azd6da5h.js.map} +1 -1
  70. package/dist/{chunk-1fe07ge4.js → chunk-b4jx4fzq.js} +1 -1
  71. package/dist/chunk-b6mgrrk6.js +5 -0
  72. package/dist/{chunk-5gkzbhts.js.map → chunk-b6mgrrk6.js.map} +1 -1
  73. package/dist/{chunk-6zz3kez5.js → chunk-ce9wm3r9.js} +2 -2
  74. package/dist/{chunk-6zz3kez5.js.map → chunk-ce9wm3r9.js.map} +1 -1
  75. package/dist/{chunk-t6n490ha.js → chunk-ceb4jcrm.js} +2 -2
  76. package/dist/{chunk-t6n490ha.js.map → chunk-ceb4jcrm.js.map} +1 -1
  77. package/dist/{chunk-9b4ypfcw.js → chunk-ej4kf7m5.js} +3 -3
  78. package/dist/{chunk-9b4ypfcw.js.map → chunk-ej4kf7m5.js.map} +1 -1
  79. package/dist/{chunk-b3tmkge9.js → chunk-f2e7n064.js} +2 -2
  80. package/dist/{chunk-b3tmkge9.js.map → chunk-f2e7n064.js.map} +1 -1
  81. package/dist/{chunk-6qydm38w.js → chunk-f5qdyw45.js} +2 -2
  82. package/dist/{chunk-6qydm38w.js.map → chunk-f5qdyw45.js.map} +1 -1
  83. package/dist/{chunk-r1x5ms0y.js → chunk-fpz9e3xx.js} +2 -2
  84. package/dist/{chunk-r1x5ms0y.js.map → chunk-fpz9e3xx.js.map} +1 -1
  85. package/dist/{chunk-mj55jdwp.js → chunk-fsem81ec.js} +1 -1
  86. package/dist/{chunk-b97tpvet.js → chunk-hnsrwr0p.js} +2 -2
  87. package/dist/{chunk-b97tpvet.js.map → chunk-hnsrwr0p.js.map} +1 -1
  88. package/dist/{chunk-dptp6ceg.js → chunk-hyhbk12v.js} +2 -2
  89. package/dist/{chunk-dptp6ceg.js.map → chunk-hyhbk12v.js.map} +1 -1
  90. package/dist/{chunk-eve0hewa.js → chunk-j2k408xc.js} +3 -3
  91. package/dist/{chunk-eve0hewa.js.map → chunk-j2k408xc.js.map} +1 -1
  92. package/dist/{chunk-ct3sgfpj.js → chunk-jmhrpfqn.js} +2 -2
  93. package/dist/{chunk-ct3sgfpj.js.map → chunk-jmhrpfqn.js.map} +1 -1
  94. package/dist/{chunk-qdz4dqbf.js → chunk-kaphqnpp.js} +3 -3
  95. package/dist/{chunk-qdz4dqbf.js.map → chunk-kaphqnpp.js.map} +1 -1
  96. package/dist/chunk-kkqw8bqg.js +117 -0
  97. package/dist/{chunk-akahs8fn.js.map → chunk-kkqw8bqg.js.map} +10 -8
  98. package/dist/{chunk-dzvp8ynr.js → chunk-ktrm6y5j.js} +3 -3
  99. package/dist/{chunk-dzvp8ynr.js.map → chunk-ktrm6y5j.js.map} +1 -1
  100. package/dist/{chunk-vp4x2c0k.js → chunk-kzc6bn8n.js} +2 -2
  101. package/dist/{chunk-vp4x2c0k.js.map → chunk-kzc6bn8n.js.map} +1 -1
  102. package/dist/{chunk-5aj27bgc.js → chunk-m6t5a0me.js} +2 -2
  103. package/dist/{chunk-5aj27bgc.js.map → chunk-m6t5a0me.js.map} +1 -1
  104. package/dist/{chunk-yxhg3wjf.js → chunk-m70hn4eg.js} +2 -2
  105. package/dist/{chunk-yxhg3wjf.js.map → chunk-m70hn4eg.js.map} +1 -1
  106. package/dist/{chunk-rw4z3n9b.js → chunk-m8yd59gg.js} +2 -2
  107. package/dist/{chunk-rw4z3n9b.js.map → chunk-m8yd59gg.js.map} +1 -1
  108. package/dist/{chunk-b4qh3ywd.js → chunk-maqkrbsb.js} +2 -2
  109. package/dist/{chunk-b4qh3ywd.js.map → chunk-maqkrbsb.js.map} +1 -1
  110. package/dist/{chunk-7dwgex81.js → chunk-mfn94b95.js} +2 -2
  111. package/dist/{chunk-7dwgex81.js.map → chunk-mfn94b95.js.map} +1 -1
  112. package/dist/{chunk-jrvg80jw.js → chunk-mkw35cz7.js} +2 -2
  113. package/dist/{chunk-jrvg80jw.js.map → chunk-mkw35cz7.js.map} +1 -1
  114. package/dist/{chunk-7hdfbp2x.js → chunk-mnmr27wd.js} +2 -2
  115. package/dist/{chunk-7hdfbp2x.js.map → chunk-mnmr27wd.js.map} +1 -1
  116. package/dist/{chunk-1cdz01em.js → chunk-n9zycjm1.js} +3 -3
  117. package/dist/{chunk-1cdz01em.js.map → chunk-n9zycjm1.js.map} +1 -1
  118. package/dist/{chunk-d0kw04ym.js → chunk-ncb1qtae.js} +2 -2
  119. package/dist/{chunk-d0kw04ym.js.map → chunk-ncb1qtae.js.map} +1 -1
  120. package/dist/{chunk-c7ecv545.js → chunk-p57nt0pm.js} +2 -2
  121. package/dist/{chunk-c7ecv545.js.map → chunk-p57nt0pm.js.map} +1 -1
  122. package/dist/{chunk-yxjfghq3.js → chunk-p81qeav5.js} +3 -3
  123. package/dist/{chunk-yxjfghq3.js.map → chunk-p81qeav5.js.map} +1 -1
  124. package/dist/{chunk-rwrcsfzv.js → chunk-qt6x2r6a.js} +2 -2
  125. package/dist/{chunk-rwrcsfzv.js.map → chunk-qt6x2r6a.js.map} +1 -1
  126. package/dist/{chunk-qvtmn7mn.js → chunk-r0z27j6t.js} +2 -2
  127. package/dist/{chunk-qvtmn7mn.js.map → chunk-r0z27j6t.js.map} +1 -1
  128. package/dist/{chunk-6d9f4vw0.js → chunk-r567t83k.js} +4 -4
  129. package/dist/{chunk-6d9f4vw0.js.map → chunk-r567t83k.js.map} +1 -1
  130. package/dist/{chunk-pfgbkhmm.js → chunk-rezmtdyt.js} +2 -2
  131. package/dist/{chunk-pfgbkhmm.js.map → chunk-rezmtdyt.js.map} +1 -1
  132. package/dist/{chunk-apfk702c.js → chunk-rvm5mkwm.js} +2 -2
  133. package/dist/{chunk-apfk702c.js.map → chunk-rvm5mkwm.js.map} +1 -1
  134. package/dist/{chunk-eyqsvzej.js → chunk-s29tgy4y.js} +2 -2
  135. package/dist/{chunk-eyqsvzej.js.map → chunk-s29tgy4y.js.map} +1 -1
  136. package/dist/{chunk-dje31gme.js → chunk-sa6a0wy1.js} +2 -2
  137. package/dist/{chunk-dje31gme.js.map → chunk-sa6a0wy1.js.map} +1 -1
  138. package/dist/{chunk-d1whcvyn.js → chunk-sgwgj2q0.js} +1 -1
  139. package/dist/{chunk-8r9kna46.js → chunk-t03nda3s.js} +2 -2
  140. package/dist/{chunk-8r9kna46.js.map → chunk-t03nda3s.js.map} +1 -1
  141. package/dist/{chunk-tbhtx2t0.js → chunk-t2nsn0r2.js} +2 -2
  142. package/dist/{chunk-vtqvq9ca.js.map → chunk-t2nsn0r2.js.map} +1 -1
  143. package/dist/{chunk-7p64zc6a.js → chunk-tkvamktq.js} +2 -2
  144. package/dist/{chunk-7p64zc6a.js.map → chunk-tkvamktq.js.map} +1 -1
  145. package/dist/{chunk-8gfgsmxk.js → chunk-v57ndv0h.js} +2 -2
  146. package/dist/{chunk-8gfgsmxk.js.map → chunk-v57ndv0h.js.map} +1 -1
  147. package/dist/{chunk-e3y72vzw.js → chunk-wffc5k3m.js} +2 -2
  148. package/dist/{chunk-e3y72vzw.js.map → chunk-wffc5k3m.js.map} +1 -1
  149. package/dist/{chunk-pxavt1j3.js → chunk-x0t3t7g3.js} +2 -2
  150. package/dist/{chunk-pxavt1j3.js.map → chunk-x0t3t7g3.js.map} +1 -1
  151. package/dist/{chunk-dvwdehnp.js → chunk-y5yac6n1.js} +2 -2
  152. package/dist/{chunk-dvwdehnp.js.map → chunk-y5yac6n1.js.map} +1 -1
  153. package/dist/{chunk-ks7msv3e.js → chunk-yjszzjyj.js} +2 -2
  154. package/dist/{chunk-ks7msv3e.js.map → chunk-yjszzjyj.js.map} +1 -1
  155. package/dist/{chunk-18y8n1r3.js → chunk-z80v4z8y.js} +2 -2
  156. package/dist/{chunk-18y8n1r3.js.map → chunk-z80v4z8y.js.map} +1 -1
  157. package/dist/config/index.js +1 -1
  158. package/dist/console/run.js +2 -2
  159. package/dist/console/run.js.map +1 -1
  160. package/dist/container/index.js +2 -2
  161. package/dist/container/index.js.map +1 -1
  162. package/dist/database/index.js +2 -2
  163. package/dist/database/index.js.map +1 -1
  164. package/dist/email/index.js +2 -2
  165. package/dist/email/index.js.map +1 -1
  166. package/dist/facades/index.js +2 -2
  167. package/dist/facades/index.js.map +1 -1
  168. package/dist/foundation/index.js +2 -2
  169. package/dist/foundation/index.js.map +1 -1
  170. package/dist/http/RateLimitMiddleware.d.ts.map +1 -1
  171. package/dist/http/clientAddress.d.ts +8 -0
  172. package/dist/http/clientAddress.d.ts.map +1 -0
  173. package/dist/http/index.js +2 -2
  174. package/dist/http/index.js.map +1 -1
  175. package/dist/i18n/dictionaryRuntime.js +2 -2
  176. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  177. package/dist/i18n/index.js +2 -2
  178. package/dist/i18n/index.js.map +1 -1
  179. package/dist/kernel/index.js +2 -2
  180. package/dist/kernel/index.js.map +1 -1
  181. package/dist/orm/index.js +2 -2
  182. package/dist/orm/index.js.map +1 -1
  183. package/dist/server/forwardedFor.d.ts +28 -20
  184. package/dist/server/forwardedFor.d.ts.map +1 -1
  185. package/dist/server/httpProd.d.ts.map +1 -1
  186. package/dist/server/index.js +2 -2
  187. package/dist/server/index.js.map +1 -1
  188. package/dist/services/broadcast/SocketHub.d.ts.map +1 -1
  189. package/dist/services/index.d.ts +1 -1
  190. package/dist/services/index.d.ts.map +1 -1
  191. package/dist/services/index.js +2 -2
  192. package/dist/services/index.js.map +1 -1
  193. package/dist/services/queue/work.js +2 -2
  194. package/dist/services/queue/work.js.map +1 -1
  195. package/dist/services/router/DomainResolver.d.ts +2 -1
  196. package/dist/services/router/DomainResolver.d.ts.map +1 -1
  197. package/dist/services/router/DomainRouter.d.ts +17 -0
  198. package/dist/services/router/DomainRouter.d.ts.map +1 -1
  199. package/dist/services/router/RouteServiceProvider.d.ts.map +1 -1
  200. package/dist/stats/route-table.js +1 -1
  201. package/dist/support/index.js +2 -2
  202. package/dist/support/index.js.map +1 -1
  203. package/dist/vitest/index.js +1 -1
  204. package/package.json +1 -1
  205. package/dist/chunk-03qkwjvy.js +0 -24
  206. package/dist/chunk-0540ptgm.js +0 -10
  207. package/dist/chunk-3v4esxbd.js +0 -4
  208. package/dist/chunk-3v4esxbd.js.map +0 -10
  209. package/dist/chunk-5gkzbhts.js +0 -5
  210. package/dist/chunk-akahs8fn.js +0 -117
  211. /package/dist/{chunk-3wpxqcw7.js.map → chunk-1x9ghjpt.js.map} +0 -0
  212. /package/dist/{chunk-y7v30zd8.js.map → chunk-236be97q.js.map} +0 -0
  213. /package/dist/{chunk-eydahc2f.js.map → chunk-5xfpqda5.js.map} +0 -0
  214. /package/dist/{chunk-1fe07ge4.js.map → chunk-b4jx4fzq.js.map} +0 -0
  215. /package/dist/{chunk-mj55jdwp.js.map → chunk-fsem81ec.js.map} +0 -0
  216. /package/dist/{chunk-d1whcvyn.js.map → chunk-sgwgj2q0.js.map} +0 -0
@@ -1,117 +0,0 @@
1
- // @bun
2
- import{_g as eG}from"./chunk-9b4ypfcw.js";import{sh as tG}from"./chunk-5013raxj.js";import{Ah as K8,Ai as fG,Bh as Y8,Eh as j8,Fh as z8,Gh as uZ,Hh as bQ,Ih as zG,Jh as sW,Kh as h,Qh as C,Rh as f8,Sh as jZ,Th as F8,Uh as J6,Wh as P$,Xh as g,Yh as k4,ki as W6,ri as zZ,th as $3,vi as eX,wi as d$,xh as JG,xi as u$,yh as _9,yi as EG,zh as x9}from"./chunk-eve0hewa.js";import{Di as d1,Ei as Z0,Fi as l1,Gi as S9}from"./chunk-v2cv3wcw.js";import{Hi as v3,Ii as KG,Mi as F5,Ni as p4,Oi as T}from"./chunk-7hdfbp2x.js";import{Ri as nX,Ui as y3}from"./chunk-dzvp8ynr.js";import{$i as TG,Yi as N5}from"./chunk-23mcs80p.js";import{rj as H$,wj as u1}from"./chunk-e9xbdgb2.js";import{Kj as RX}from"./chunk-gy307m19.js";import{Lj as l$,Oj as PG}from"./chunk-98dxtkbt.js";import{Pj as O1}from"./chunk-ks7msv3e.js";import{Qj as e3,Rj as i0,Sj as T1,Tj as oG,Uj as aG,Wj as yZ,Xj as SG,ek as rG}from"./chunk-yxjfghq3.js";import{tk as N1}from"./chunk-8r9kna46.js";import{Dk as BW,yk as eQ}from"./chunk-rwrcsfzv.js";import{Kk as tQ,Pk as n}from"./chunk-rw4z3n9b.js";import{Qk as dZ,Tk as L}from"./chunk-kddgfct7.js";import{$k as GW}from"./chunk-apfk702c.js";import{al as RG}from"./chunk-eyqsvzej.js";import{kl as YW}from"./chunk-9yfg4nqq.js";import{ml as WG}from"./chunk-5aj27bgc.js";import{rl as c4}from"./chunk-tbhtx2t0.js";function s3($){return typeof $==="function"&&$.prototype!==void 0}function l0($){return typeof $==="string"?[$]:$}function n3($,Z){let J=Z?"attachment":"inline",W=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${W}"; filename*=UTF-8''${encodeURIComponent($)}`}function KK($){return"total"in $&&"partial"in $&&"body"in $}function mW(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function oZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":z8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function FK($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(KK($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function X8($,Z){if($ instanceof Response)return $;if(!$)return mW();let J=await FK($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return mW()}let{range:Q}=Z;if(Q){if(z<=0)return oZ(Math.max(z,0));if(!X){if(W instanceof Blob){let F=Y8(Q,z);if(!F)return oZ(z);W=W.slice(F.start,F.end+1),Y=F.start,j=F.end,X=!0}}}let G=Boolean(Q)&&X,K=G?206:J.status,B=new Headers;if(B.set("Accept-Ranges","bytes"),B.set("Content-Type",J.type||"application/octet-stream"),B.set("X-Content-Type-Options","nosniff"),G)B.set("Content-Range",j8(Y,j,z)),B.set("Content-Length",String(j-Y+1));else if(z>=0)B.set("Content-Length",String(z));if(J.name)B.set("Content-Disposition",n3(J.name,J.download));if(J.etag)B.set("ETag",J.etag);if(J.lastModified)B.set("Last-Modified",J.lastModified.toUTCString());for(let[F,O]of Object.entries(J.extraHeaders))B.set(F,O);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:K,headers:B})}return new Response(W,{status:K,headers:B})}class e$ extends Z0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var hW={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function rZ($){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 hW)))return Math.floor(Number(J[1])*(hW[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var aZ=new WeakMap;function cW($){return aZ.has($)}function dW($){return aZ.get($)?.limit??null}function uW($){let Z=aZ.get($);return Z?Z.read>Z.limit:!1}function BK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function G8($,Z){let J=BK($);if(J!==null&&J>Z)throw new e$(Z)}function o3($,Z,J={}){let W=aZ.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};aZ.set($,Y),DK($,Y)}if(J.checkDeclared!==!1)G8($,Z)}function VK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function Q8($,Z){if(Z.stream!==void 0)return Z.stream;let J=VK($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new e$(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function t$($,Z){if(G8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=Q8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:Q,value:G}=await W.read();if(Q)break;Y.push(G),j+=G.byteLength}let z=new Uint8Array(j),X=0;for(let Q of Y)z.set(Q,X),X+=Q.byteLength;return z}function pW($){return $.headers.get("Content-Type")??""}function DK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>Q8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>t$($,Z)}),J("arrayBuffer",{value:async()=>{let W=await t$($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await t$($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await t$($,Z)))}),J("blob",{value:async()=>new Blob([await t$($,Z)],{type:pW($)})}),J("formData",{value:async()=>new Response(await t$($,Z),{headers:{"Content-Type":pW($)}}).formData()}),J("clone",{value:()=>{G8($,Z.limit);let W=Q8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function lW($){return s3($)}class l{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(!lW(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(lW(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=l0($),this}}class nW{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 sW($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(uW($.rawRequest))throw new e$(dW($.rawRequest));throw J}}}class oW{constructor(...$){return new l(...$)}}class aW extends l{__internal_brand="StreamHandler";async run($){let Z=T.getStore(),J=Z?.req?.rawRequest,W=K8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);return await X8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof F8)return oZ(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class rW{constructor(...$){return new aW(...$)}}class tW{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new l("GET",$,"list"),post:new l("POST",$,"store")},this.second={get:new l("GET",$,"show"),put:new l("PUT",$,"update"),delete:new l("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 T0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new l("GET",$,Z)}post($,Z){return new l("POST",$,Z)}put($,Z){return new l("PUT",$,Z)}patch($,Z){return new l("PATCH",$,Z)}delete($,Z){return new l("DELETE",$,Z)}resource($){return new tW($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${iW($)}.`);return OK($,this)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${iW($)}.`);return UK($,this)}file($,Z){return new oW("GET",$,Z)}stream($,Z){return new rW("GET",$,Z)}proxy($,Z={}){return new nW($,Z)}}function iW($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function OK($,Z){let J={stream:new l("POST",$,"stream"),attach:new l("POST",$,"attach"),stop:new l("POST",$,"stop"),upload:new l("POST",$,"upload")};return class extends T0{static __internal_brand="AgentRoute";static controller=$;static handlers=J;constructor(){super();this.middlewares=[...Z?.middlewares??[]]}routes={"/":J.stream,"/attach":J.attach,"/stop":J.stop,"/files":J.upload};static middleware(Y){if(Y.stream)J.stream.middleware(Y.stream);if(Y.attach)J.attach.middleware(Y.attach);if(Y.stop)J.stop.middleware(Y.stop);if(Y.upload)J.upload.middleware(Y.upload);return this}}}function UK($,Z){let J={start:new l("POST",$,"voiceStart"),update:new l("PATCH",$,"voiceUpdate"),end:new l("DELETE",$,"voiceEnd")};return class extends T0{static __internal_brand="VoiceRoute";static controller=$;static handlers=J;constructor(){super();this.middlewares=[...Z?.middlewares??[]]}routes={"/":J.start,"/:sessionId":{patch:J.update,delete:J.end}};static middleware(Y){if(Y.start)J.start.middleware(Y.start);if(Y.update)J.update.middleware(Y.update);if(Y.end)J.end.middleware(Y.end);return this}}}var p1="access_token";function L$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function a3($,Z){let J=L$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var LK=/^[A-Za-z0-9_-]+$/,HK=/^:[A-Za-z_][A-Za-z0-9_]*$/,eW=/^[A-Za-z0-9_-]{1,128}$/,IK=/^[A-Za-z0-9_.:-]+$/;class p extends Error{constructor($){super($);this.name="InvalidChannelError"}}function $9($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function $Z($){if(typeof $!=="string"||$.length===0)throw new p("A channel pattern must be a non-empty string.");if($.length>255)throw new p(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(HK.test(W)){let Y=W.slice(1);if(J.has(Y))throw new p(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new p(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!LK.test(W))throw new p(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function tZ($,Z={}){let J=$Z($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new p(`The channel "${$}" needs the param "${z}".`);let Q=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof Q!=="string"||!eW.test(Q))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 Q}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new p(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new p(`The topic built from "${$}" is longer than 255 characters.`);return Y}function B8($){if($Z($).some((J)=>J.startsWith(":")))throw new p(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function Z9($){if(typeof $!=="string"||$.length===0||$.length>64||!IK.test($))throw new p(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function J9($,Z){if($===Z)return!0;if($===G0)return Z.startsWith(`${G0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&eW.test(W[j]))}var G0="user";function ZZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return tZ(`${G0}.: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 r3 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 o3(this.req.rawRequest,rZ(Z)),{}}}function PK($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}var MK={"body-limit":r3};class c1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:rZ($.bodyLimit)}get aliases(){return{...MK,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!cW($))o3($,this.defaultBodyLimit,{checkDeclared:!1})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new C,J=this.aliases,W=[];for(let[Y,j]of PK($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:W9(z)})}}else if(s3(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:W9(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await TK(W.slice(j+1)),z}return Y})()}}function W9($){return $?.runsOnRefusal===!0}async function TK($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class t3{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...l0($)],this}events(...$){return this}}class X9{static __brand="ChannelRouter";channels={};public(){return new t3("public")}private($){return new t3("private",$)}async authorize($,Z,J={},W={}){try{CK(this)}catch(Q){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",Q),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!Q9(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===G0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=tZ(Z,J??{})}catch(Q){if(Q instanceof p)return{ok:!1,code:"invalid_params"};throw Q}let z=Object.fromEntries(Object.entries(J??{}).map(([Q,G])=>[Q,String(G)])),X=new C($,z,"api",Z);return T.exit(()=>e3.exit(()=>T.run(X,async()=>{let Q=T.getStore();try{if(Y.middlewares.length>0)await L(c1).runMiddleware(Y.middlewares);if(Z===G0){let G=await Y9(X);if(!G)return{ok:!1,code:"denied"};if(j=ZZ(G),Y.visibility==="private"&&Y.authorizer){if(await j9(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await j9(Y.authorizer,X,z):await Y9(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(G){if(xK(G))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,G),{ok:!1,code:"error"}}finally{Q.destroy()}},W.carried)))}}async function NK($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;G9(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function Q9($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function Y9($){if(!T.getStore().user&&L$($)===null)return null;try{return await w0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function j9($,Z,J){if(_K($))return new $().authorize(Z,J);return $(Z,J)}function _K($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function xK($){return $?.kind===d1||u1($)||H$($)}var z9=new WeakSet;function CK($){if(z9.has($))return;G9($),z9.add($)}function G9($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!Q9(Y))throw new p(`The channel "${W}" is not declared with this.public() or this.private().`);let j=$Z(W);if(j[0].startsWith(":"))throw new p(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==G0&&j.length===2&&j[0]===G0)throw new p(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==G0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new p(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===G0?[G0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(SK(J[W].segments,J[Y].segments))throw new p(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function SK($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class V8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class D8{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class O8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}class K9{static __brand="McpRouter";routes={};scopes;param($){return new V8($.as,$.input,$.bind)}fromTool($,Z={}){return new O8($,Z)}fromApiRoute($,Z,J){return new D8($,Z,J)}}function K0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class U8 extends Z0{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 P1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new U8([K0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new U8($,Z)}}var F9=Symbol.for("gemi.HttpResponse");class I${kind;body;status;headers;[F9]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return AK(J),new I$("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 I$.json({error:Z},{...J,status:$})}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null}}}function AK($){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 JZ($){return typeof $==="object"&&$!==null&&$[F9]===!0}function EK($,Z,J={}){return I$.error($,Z,J)}class B9{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return P1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function L8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[Q,G]of Object.entries($.headers??{}))Z.set(Q,G);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",n3(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class V9{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function D9($,Z){if(JZ($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class O9{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=D9(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 U9{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends M1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends M1{routes=J??{}}}else this.children=class extends M1{routes=Z},this.handler=()=>({})}async run($,Z){let J=D9(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 M1{middlewares=[];featureGates=[];routes={};view($,Z){return new O9($,Z)}file($){return new V9($)}redirect($){return new B9($)}layout($,Z,J){return new U9($,Z,J)}}function fK($){return $}function RK(){return{aliases:{},global:[],bodyLimit:null}}var Y1="redirect";function j1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function WZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function bK($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(L(n).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function wK($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function $6($,Z){let J=Z||L(A).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=bK($,!W);if(W||!wK(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(Y1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class L9 extends r{async run($){let Z=T.getStore(),J=Z.req;if(Z.user)return{};let W=await a3(L(A),J);if(!W)throw new P$({redirectTo:$6(J,$)});return Z.setUser(W),{}}}var I8="gemi_same_site",H8="private, no-cache, no-store, max-age=0, must-revalidate";class Z6 extends r{run(){let $=T.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(I8))return{};if(L$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(I8,"1"),new H9(`${W.pathname}${W.search}`)}}class H9 extends Z0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=kK($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":H8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":H8}},viewData:{status:200,data:{},headers:{"Cache-Control":H8},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 kK($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class I9 extends r{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var P9={"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 M9 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={...P9,...this.config.origins[Z]};for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...P9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var qK="Rate limit exceeded";class i1 extends Z0{result;retryAfter;constructor($,Z=qK){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?P8($):{}};this.payload={api:{status:429,data:{error:{...l1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function P8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class z1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(T9("window",W),T9("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new i1(W,typeof J==="function"?J(W):J);return W}}function T9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}class C9 extends r{async run($,Z){let J=yK();if(!J)return{};let W=await J.consume(this.key(),{limit:N9($)??this.config.limit,window:N9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(P8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new i1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=_9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${YZ(this.req)}:${this.req.routePath??"*"}`}}function yK(){try{let $=L();return $.bound(z1)?$.make(z1):null}catch{return null}}function YZ($){let Z=x9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function N9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class A9 extends r{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new M8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new M8;return{}}}class M8 extends Z0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:S9("csrf","Invalid CSRF token",403)}},view:{}}}class E9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class f9{all($,Z){return!0}}class T8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new jZ:new J6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new C,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends r{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof jZ:$ instanceof J6}}function vK($){return new T8($)}async function Y6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await rK($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return aK(z,Z,J,$.url)}async function aK($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:G,value:K}=await Y.read();if(G)break;if(z+K.byteLength>Z){if(!J)throw new W6(W,Z);j.push(K.subarray(0,Z-z)),z=Z;break}j.push(K),z+=K.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),Q=0;for(let G of j)X.set(G,Q),Q+=G.byteLength;return X}async function rK($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function j6($){return new TextDecoder("utf-8").decode($)}var tK={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function M$($){return $.replace(/[&<>"']/g,(Z)=>tK[Z])}var eK={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function N8($){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 eK[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function _8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function R9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(N8($.slice(W)));return}if(Y>W)Z.text(N8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let Q=$.indexOf(">",X+1);if(Q===-1)return;W=Q+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(_8($.slice(Y+2,j).trim())),W=j+1}else{let j=$F($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let Q=z.search(/[\s]|$/),G=_8(z.slice(0,Q));if(G){if(Z.open(G,ZF(z.slice(Q)),X),X)Z.close(G)}W=j+1}}}function $F($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function ZF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[_8(W[1])]=N8(W[2]??W[3]??"");return Z}class J0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var y9="http://www.sitemaps.org/schemas/sitemap/0.9",JF="http://www.w3.org/1999/xhtml",S8=`<?xml version="1.0" encoding="UTF-8"?>
3
- `,b9=`<urlset xmlns="${y9}" xmlns:xhtml="${JF}">
4
- `,w9=`</urlset>
5
- `,T$=50000,eZ=52428800,k9=2048,WF=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),YF=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,jF="application/xml; charset=utf-8",q9=new TextEncoder;function A8($,Z){let J;try{J=new URL($)}catch{throw new J0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new J0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>k9)throw new J0(`Sitemap: ${Z} is over ${k9} characters: "${W.slice(0,80)}\u2026".`);return W}function v9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new J0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!YF.test($))throw new J0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function zF($){let Z=A8($.loc,"loc"),J=`<url><loc>${M$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${M$(v9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!WF.has($.changefreq))throw new J0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);J+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let W=$.priority;if(!Number.isFinite(W)||W<0||W>1)throw new J0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let Y=W.hrefLang?.trim();if(!Y)throw new J0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=A8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${M$(Y)}" href="${M$(j)}"/>`}return`${J}</url>
6
- `}function XF($){let Z=$.maxUrls??T$,J=$.maxBytes??eZ;if(!Number.isInteger(Z)||Z<1||Z>T$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${T$}.`);if(!Number.isInteger(J)||J<1||J>eZ)throw RangeError(`Sitemap: maxBytes must be an integer from 1 to ${eZ}.`);return{maxUrls:Z,maxBytes:J}}function g9($,Z={}){let{maxUrls:J,maxBytes:W}=XF(Z),Y=q9.encode(S8+b9+w9).byteLength,j=[],z=[],X=Y,Q=()=>{j.push(S8+b9+z.join("")+w9),z=[],X=Y};for(let G of $){let K=zF(G),B=q9.encode(K).byteLength;if(Y+B>W)throw new J0(`Sitemap: the entry for ${G.loc} alone is over maxBytes (${W}).`);if(z.length===J||X+B>W)Q();z.push(K),X+=B}if(z.length>0||j.length===0)Q();return j}function m9($){let Z="",J=0;for(let W of $){if(++J>T$)throw new J0(`Sitemap: an index can list at most ${T$} sitemaps.`);let Y=A8(W.loc,"sitemap loc");if(Z+=`<sitemap><loc>${M$(Y)}</loc>`,W.lastmod!=null)Z+=`<lastmod>${M$(v9(W.lastmod,Y))}</lastmod>`;Z+=`</sitemap>
7
- `}return`${S8}<sitemapindex xmlns="${y9}">
8
- ${Z}</sitemapindex>
9
- `}function x8($,Z,J){let W=new Headers(J);if(!W.has("content-type"))W.set("content-type",jF);return new Response($,{status:Z,headers:W})}function QF($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function GF($,Z={}){let J=g9($,Z),W=QF(Z.page);if(W!==null){let j=J[W-1];return j?x8(j,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(J.length===1)return x8(J[0],200,Z.headers);let Y=Z.pageUrl;if(!Y)throw new J0(`Sitemap: the entries need ${J.length} files, so Sitemap.response needs \`pageUrl\` to list them in an index.`);return x8(m9(J.map((j,z)=>({loc:Y(z+1)}))),200,Z.headers)}function C8($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function h9($,Z={}){let J=Z.maxUrls??1/0,W=$.replace(/^\uFEFF/,"").trimStart();if(!W.startsWith("<")){let F=[];for(let O of W.split(/\r?\n/)){if(F.length>=J)break;let V=O.trim()?C8(O):null;if(V)F.push({loc:V})}if(F.length===0&&W.length>0)throw new J0("Sitemap: the document is neither XML nor a list of URLs.");return{kind:"urlset",urls:F}}let Y=null,j=[],z=[],X=[],Q=null,G=null,K="",B=()=>Y==="index"?z.length:j.length;if(R9(W,{stopped:()=>B()>=J,open(F,O){let V=X[X.length-1];if(X.push(F),Y===null){if(F==="urlset")Y="urlset";else if(F==="sitemapindex")Y="index";return}if(Y==="urlset"&&F==="url"&&V==="urlset"||Y==="index"&&F==="sitemap"&&V==="sitemapindex")Q={};else if(Q&&(V==="url"||V==="sitemap")&&(F==="loc"||F==="lastmod"||F==="changefreq"||F==="priority"))G=F,K="";else if(Q&&Y==="urlset"&&V==="url"&&F==="link"){let D=O.href?C8(O.href):null;if(O.rel?.toLowerCase()==="alternate"&&O.hreflang&&D)(Q.alternates??=[]).push({hrefLang:O.hreflang,href:D})}},close(F){let O=X.lastIndexOf(F);if(O===-1)return;if(X.length=O,G&&F===G&&Q)Q[G]=K.trim(),G=null;else if(Q&&(F==="url"||F==="sitemap")){let V=Q;Q=null,G=null;let D=V.loc?C8(V.loc):null;if(!D)return;if(Y==="index"){z.push(V.lastmod?{loc:D,lastmod:V.lastmod}:{loc:D});return}let U={loc:D};if(V.lastmod)U.lastmod=V.lastmod;if(V.changefreq)U.changefreq=V.changefreq;let H=V.priority?Number(V.priority):NaN;if(Number.isFinite(H))U.priority=H;if(V.alternates)U.alternates=V.alternates;j.push(U)}},text(F){if(G)K+=F}}),Y===null)throw new J0("Sitemap: the document has no <urlset> or <sitemapindex>.");return Y==="index"?{kind:Y,sitemaps:z}:{kind:Y,urls:j}}async function*KF($,Z={}){let{maxUrls:J=T$,maxSitemaps:W=50,maxDepth:Y=3,maxSize:j=eZ,onError:z,...X}=Z,Q=[{url:String($),depth:0}],G=new Set,K=0,B=0;while(Q.length>0&&B<J&&K<W){let F=Q.shift(),O=F.url.replace(/#.*$/,"");if(G.has(O))continue;G.add(O),K++;let V;try{let D=await zZ(F.url,{...X,maxSize:j});if(!D.ok)throw D.body?.cancel().catch(()=>{}),new J0(`Sitemap: ${F.url} answered ${D.status}.`,F.url,D.status);let U=j6(await Y6(D,j));V=h9(U,{maxUrls:Math.max(J-B,W-K)})}catch(D){if(F.depth===0||!z||X.signal?.aborted)throw D;z(D,F.url);continue}if(V.kind==="index"){if(F.depth>=Y)continue;Q=V.sitemaps.slice(0,W-K).map((U)=>({url:U.loc,depth:F.depth+1})).concat(Q);continue}for(let D of V.urls)if(yield{...D,sitemap:F.url},++B>=J)return}}var p9={response:GF,chunk:g9,index:m9,parse:h9,read:KF,MAX_URLS:T$,MAX_BYTES:eZ};var FF=512000,BF=new TextEncoder;function c9($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function d9($){let Z="";for(let J=0;J<$.length;J++){let W=$[J];if(W==="%"&&/^[0-9a-fA-F]{2}$/.test($.slice(J+1,J+3)))Z+=`%${$.slice(J+1,J+3).toUpperCase()}`,J+=2;else if(W.charCodeAt(0)>126||W.charCodeAt(0)<=32){let Y=$.codePointAt(J);if(Y>65535)J++;for(let j of BF.encode(String.fromCodePoint(Y)))Z+=`%${j.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=W}return Z}function VF($,Z){let J=$.endsWith("$"),W=J?$.slice(0,-1):$,Y=0,j=0,z=-1,X=0;while(j<Z.length)if(Y<W.length&&W[Y]!=="*"&&W[Y]===Z[j])Y++,j++;else if(Y<W.length&&W[Y]==="*")z=Y++,X=j;else if(Y===W.length&&!J)return!0;else if(z!==-1)Y=z+1,j=++X;else return!1;while(Y<W.length&&W[Y]==="*")Y++;return Y===W.length}class XZ{groups;sitemaps;status;constructor($,Z,J="parsed"){this.groups=$;this.sitemaps=Z;this.status=J}groupsFor($){let Z=c9($)||"*";if(Z!=="*"){let J=this.groups.filter((W)=>W.userAgents.includes(Z));if(J.length>0)return J}return this.groups.filter((J)=>J.userAgents.includes("*"))}isAllowed($,Z="*"){let J;if($ instanceof URL||/^[a-z][a-z0-9+.-]*:/i.test($)){let Y=new URL(String($));J=Y.pathname+Y.search}else J=$.startsWith("/")?$:`/${$}`;if(J==="/robots.txt")return!0;if(this.status==="unavailable")return!0;if(this.status==="unreachable")return!1;J=d9(J);let W=null;for(let Y of this.groupsFor(Z))for(let j of Y.rules){if(!VF(j.path,J))continue;let z=j.path.length,X=j.type==="allow";if(!W||z>W.length||z===W.length&&X)W={length:z,allow:X}}return W?W.allow:!0}crawlDelay($="*"){for(let Z of this.groupsFor($))if(Z.crawlDelay!==void 0)return Z.crawlDelay;return null}}var DF={"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 u9($,Z={}){let J=[],W=[],Y=null,j=!1;for(let z of $.replace(/^\uFEFF/,"").split(/\r\n|\r|\n/)){let X=z.indexOf("#"),Q=(X===-1?z:z.slice(0,X)).trim(),G=Q.indexOf(":");if(G===-1)continue;let K=DF[Q.slice(0,G).trim().toLowerCase()],B=Q.slice(G+1).trim();if(!K)continue;if(K==="sitemap"){if(!B||/\s/.test(B))continue;try{let F=Z.url?new URL(B,Z.url):new URL(B);if(F.protocol==="http:"||F.protocol==="https:")W.push(F.href)}catch{}continue}if(K==="user-agent"){if(!j||!Y)Y={userAgents:[],rules:[]},J.push(Y),j=!0;let F=c9(B);if(F)Y.userAgents.push(F);continue}if(!Y)continue;if(j=!1,K==="crawl-delay"){let F=Number(B);if(Number.isFinite(F)&&F>=0)Y.crawlDelay=F;continue}if(!B)continue;Y.rules.push({type:K,path:d9(B)})}return new XZ(J,W)}async function OF($,Z={}){let{maxSize:J=FF,...W}=Z,Y=new URL("/robots.txt",$),j=await zZ(Y,{...W,maxSize:Number.MAX_SAFE_INTEGER}),z=j.status;if(z===429||z>=500)return j.body?.cancel().catch(()=>{}),new XZ([],[],"unreachable");if(z>=400)return j.body?.cancel().catch(()=>{}),new XZ([],[],"unavailable");let X=await Y6(j,J,!0),Q=j6(X);if(X.byteLength>=J)Q=Q.slice(0,Math.max(0,Q.lastIndexOf(`
10
- `)));return u9(Q,{url:j.url})}function E8($){return $===void 0?[]:typeof $==="string"?[$]:$}function z6($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
11
- `}function l9($){let Z=[];for(let W of $.rules??[]){let Y=E8(W.userAgent);if(Y.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let j=Y.map((X)=>z6("User-agent",X)).join(""),z=[...E8(W.allow).map((X)=>["Allow",X]),...E8(W.disallow).map((X)=>["Disallow",X])];for(let[X,Q]of z){if(!Q.startsWith("/")&&!Q.startsWith("*"))throw TypeError(`Robots: ${X} "${Q}" must start with "/" or "*".`);j+=z6(X,Q)}if(z.length===0)j+=`Disallow:
12
- `;if(W.crawlDelay!==void 0){if(!Number.isFinite(W.crawlDelay)||W.crawlDelay<0)throw TypeError(`Robots: crawlDelay ${W.crawlDelay} is not a number of seconds.`);j+=z6("Crawl-delay",String(W.crawlDelay))}Z.push(j)}let J=($.sitemaps??[]).map((W)=>{let Y;try{Y=new URL(W)}catch{throw TypeError(`Robots: sitemap "${W}" is not an absolute URL.`)}return z6("Sitemap",Y.href)});if(J.length>0)Z.push(J.join(""));return Z.join(`
13
- `)}function UF($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(l9($),{status:200,headers:J})}var i9={response:UF,text:l9,parse:u9,fetch:OF};import{createHmac as s9,randomBytes as LF}from"crypto";var R8="v2.";function b8($){return $.startsWith(R8)}function QZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function n9($){let Z=LF(16).toString("hex"),J=s9("sha256",QZ()).update(`${$}:${Z}`).digest("hex");return`${R8}${J}`}function X6($,Z){let J=s9("sha256",QZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${R8}${J}`}import{createHash as PF,createHmac as MF,randomInt as TF,timingSafeEqual as r9}from"crypto";function o9($,Z){return Math.floor($/Z)*Z}function HF($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function w8($,Z,J,W){return Z*HF(J,W)+$}function IF($){let{current:Z,previous:J,elapsed:W,window:Y,limit:j,cost:z}=$,X=j-z;if(X<0)return Y;let Q=Math.max(0,Y-W);if(J>0){let K=Y*(1-(X-Z)/J);if(K<=Y)return Math.max(0,Math.ceil(K-W))}if(Z<=X)return Q;if(Z<=0)return Q;let G=Y*(1-X/Z);return Q+Math.max(0,Math.ceil(G))}function a9($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:Q}=$;if(Z){let K=w8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-K)),resetAt:Y-j+z,retryAfter:0}}let G=IF({current:J,previous:W,elapsed:j,window:z,limit:X,cost:Q});return{allowed:!1,limit:X,remaining:0,resetAt:Y+G,retryAfter:G}}class k8{}class q8 extends k8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,Y=$.cost??1,j=Date.now(),z=o9(j,W),X=j-z,Q=this.roll(Z,W,z);Q.limit=J;let K=w8(Q.current,Q.previous,X,W)+Y<=J;if(K)Q.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,Q),this.buckets.size>this.maxKeys)this.evict(j);return a9({allowed:K,current:Q.current,previous:Q.previous,now:j,elapsed:X,window:W,limit:J,cost:Y})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,J){let W=this.buckets.get($);if(!W||W.window!==Z)return{window:Z,limit:0,windowStart:J,current:0,previous:0};if(W.windowStart===J)return W;if(W.windowStart+Z===J)return W.previous=W.current,W.current=0,W.windowStart=J,W;return W.previous=0,W.current=0,W.windowStart=J,W}evict($){for(let[W,Y]of this.buckets)if($-Y.windowStart>=Y.window*2)this.buckets.delete(W);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let J=[...this.buckets].map(([W,Y],j)=>({key:W,order:j,spent:Y.limit>0?(Y.current+Y.previous)/Y.limit:0}));J.sort((W,Y)=>W.spent-Y.spent||W.order-Y.order);for(let{key:W}of J){if(this.buckets.size<=Z)break;this.buckets.delete(W)}}}var $5="h1.";function Q6($,Z,J){let W=MF("sha256",QZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${$5}${W}`}function Z3($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith($5),X=Q6($,Z,Y),Q=Buffer.from(z?X:Y),G=Buffer.from(j);if(Q.length!==G.length||Y===""||j==="")return r9(Q,Q),!1;return r9(Q,G)}function Z5($){let Z="";for(let J=0;J<$;J++)Z+=String(TF(0,10));return Z}var J5=320;function J3($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>J5)return null;return Z.toLowerCase()}function G6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>J5)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var t9=null;function W5(){try{let $=L();if(typeof $?.bound==="function"&&$.bound(z1))return $.make(z1)}catch{}return t9??=new z1({driver:new q8,limit:1000,window:60}),t9}function e9($){return $.length<=64?$:`sha256:${PF("sha256").update($).digest("hex")}`}async function GZ($,Z,J,W){let Y=W5(),j=[[`auth:code-${$}:ip:${e9(YZ(J))}`,W.perIp]];if(Z!==null)j.push([`auth:code-${$}:email:${e9(Z)}`,W.perEmail]);for(let[z,X]of j){if(!X)continue;let[Q,G]=X,K=await Y.consume(z,{limit:Q,window:G});if(!K.allowed)throw new i1(K)}}async function Y5($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await W5().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as v8}from"crypto";class y8 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 K6($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let Y=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${Y}, got ${Z}`)}}function NF($={}){for(let Z of["password","magicLink"]){let J=$?.[Z];if(J!==void 0&&typeof J!=="boolean")throw Error(`auth.${Z} must be true or false, got ${JSON.stringify(J)}`)}}function g8($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5;return K6("length",Z,4,12),K6("expiresInMinutes",J,1),K6("linkExpiresInMinutes",W,1),K6("maxAttempts",Y,1),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:W,maxAttempts:Y,requestLimit:{perEmail:$.requestLimit?.perEmail??[5,900],perIp:$.requestLimit?.perIp??[20,900]},verifyLimit:{perEmail:$.verifyLimit?.perEmail??[10,900],perIp:$.verifyLimit?.perIp??[50,900]},uniformMagicLinkResponse:$.uniformMagicLinkResponse??!1,send:$.send??(({email:j,code:z})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${j}: ${z} (set auth.emailCode.send to deliver it)`)})}}async function _F($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function j5($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:J}=$;return{provider:Z,...J!==void 0?{feature:J}:{}}}function z5($){for(let[Z,J]of Object.entries($??{})){if(typeof J?.getRedirectUrl==="function")continue;let W=J;if(typeof W?.provider?.getRedirectUrl!=="function")throw Error(`auth.oauthProviders.${Z} must be an OAuthProvider, or { provider, feature } with an OAuthProvider.`);if(W.feature!==void 0&&(typeof W.feature!=="string"||W.feature===""))throw Error(`auth.oauthProviders.${Z}.feature must be a feature key from app/features.`)}}function bI($){return $}function X5($={}){return NF($),{basePath:"/auth",verifyEmail:!0,password:!0,magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:y8,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:_F,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>v8(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return v8(32).toString("hex")},generateMagicLinkToken:()=>v8(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:g8($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}var xF=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),CF=new Set(["svg","math"]);function Q5($){return $===32||$===9||$===10||$===12||$===13}function G5($){return $>=65&&$<=90||$>=97&&$<=122}function F6($){return $>=65&&$<=90?$+32:$}function K5(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,Q=0,G=()=>$==="data"&&X===0&&Q===0,K=()=>{if(!J&&xF.has(Z)){$="rawText",W=`</${Z}`,Y=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(CF.has(Z)){if(J)Q=Math.max(0,Q-1);else if(!z)Q+=1}Z=""},B=(F)=>{switch($){case"data":if(F===60)$="tagOpen";return;case"tagOpen":if(F===33)$="bang",j=0;else if(F===47)$="endTagOpen";else if(G5(F))$="tagName",J=!1,z=!1,Z=String.fromCharCode(F6(F));else if(F===63)$="bogus";else if(F===60)$="tagOpen";else $="data";return;case"endTagOpen":if(G5(F))$="tagName",J=!0,z=!1,Z=String.fromCharCode(F6(F));else if(F===62)$="data";else $="bogus";return;case"tagName":if(Q5(F)||F===47)$="inTag",z=F===47;else if(F===62)K();else Z+=String.fromCharCode(F6(F));return;case"inTag":if(F===62){K();return}if(z=F===47,F===34)$="attrDouble";else if(F===39)$="attrSingle";return;case"attrDouble":if(F===34)$="inTag";z=!1;return;case"attrSingle":if(F===39)$="inTag";z=!1;return;case"bang":if(F===45){if(j+=1,j===2)$="comment",j=0}else if(F===62)$="data";else $="bogus";return;case"bogus":if(F===62)$="data";return;case"comment":if(F===45)j=j<2?j+1:2;else if(F===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(Y<W.length){if(F6(F)===W.charCodeAt(Y))Y+=1;else Y=F===60?1:0;return}if(F===62)$="data",Z="";else if(Q5(F)||F===47)$="inTag",Z="";else Y=F===60?1:0;return}}};return{scanToInsertionPoint(F){for(let O=0;O<F.length;O++){if(G())return O;B(F[O])}return F.length},write(F){for(let O=0;O<F.length;O++)B(F[O])},isSafe:G}}function X1($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function SF($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${X1([$.path,$.variantKey,$.data])})</script>`}function AF($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${X1([$.id,$.locale,$.strings])})</script>`}function m8($,Z,J={},W){let Y=new TextEncoder,j=[],z=!1,X=!1,Q=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((V)=>{if(V.status!=="resolved")return;j.push(SF(V))}),W?.onUse((V)=>{j.push(AF(V))});let G=$.getReader(),K=K5(),B=(V,D)=>{V.enqueue(D),J.onChunk?.(D)},F=(V)=>{while(j.length>0){let D=Y.encode(j.shift());K.write(D),B(V,D)}},O=(V,D)=>{if(j.length===0){K.write(D),B(V,D);return}let U=K.scanToInsertionPoint(D);if(U>0)B(V,D.subarray(0,U));if(K.isSafe())F(V);let H=D.subarray(U);if(H.length>0)K.write(H),B(V,H)};return new ReadableStream({async pull(V){let D;try{D=await G.read()}catch(M){throw Q(),M}let{done:U,value:H}=D;if(U){F(V),V.close(),Q();return}if(!z){if(z=!0,K.write(H),B(V,H),J.onShell?.(),K.isSafe())F(V);return}O(V,H)},cancel(V){return Q(),G.cancel(V)}})}var EF=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function B6($){if(!$)return!1;return EF.test($)}async function B5($,Z=()=>{}){let J=T.getStore(),W=J?.req??null,Y=null;if(W?.rawRequest?.url)try{Y=new URL(W.rawRequest.url).pathname}catch{Y=null}return{user:J?.user??null,attributes:await fF($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:F5(),isBot:B6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function V5($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function fF($,Z){if(!$.context)return{};try{let J=T.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 D5($,Z){return`${$}:${Z}`}function h8($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function O5($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function U5($,Z,J,W){if(W.unavailable)return{value:!1,reason:"unavailable"};if(W.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let j;try{j=Z.when(J)}catch(z){return W.warn?.(`The \`when\` for feature "${$}" threw; treating it as off. ${z instanceof Error?z.message:String(z)}`),{value:!1,reason:"error"}}if(typeof j==="boolean")return{value:j,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(J.isBot)return{value:!1,reason:"bot"};let Y=bF($,Z,J,W.buckets);return O5(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function RF($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function bF($,Z,J,W){let Y=D5(Z.salt??$,RF(J));if(!W)return h8(Y);let j=W.get(Y);if(j!==void 0)return j;let z=h8(Y);return W.set(Y,z),z}class L5 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 p8{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,W=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=W}async get(){let $=this.snapshot;if($&&Date.now()-$.loadedAt<this.ttlMs)return $;if($){if(Date.now()>=this.retryAfter)this.refresh().catch(()=>{});return $}return await this.refresh()}refresh(){return this.inflight??=this.load().finally(()=>{this.inflight=null}),this.inflight}async invalidate(){await this.inflight?.catch(()=>{});let $=this.generation,Z=await this.refresh();if(this.generation===$)throw new L5(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:J}=this.readRows($);return this.snapshot={active:Z,audit:J,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,J=new Map;for(let W of $??[]){let Y=typeof W?.key==="string"?W.key:null;if(!Y){this.warn("Ignoring a feature row with no `key`.");continue}if(!(Y in this.declared)){this.warn(`Feature row "${Y}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(Y,W.active===!0);let j=wF(W);if(j)J.set(Y,j)}return{active:Z,audit:J}}handleFailure($){let Z=$ instanceof Error?$.message:String($),J=Date.now();if(this.lastError=$,this.retryAfter=J+this.ttlMs,J-this.lastFailureLoggedAt>=this.ttlMs)this.lastFailureLoggedAt=J,this.warn(`Could not load feature switches: ${Z}`);if(this.snapshot)return this.snapshot;return this.snapshot={active:new Map,audit:new Map,loadedAt:J,unavailable:!0},this.snapshot}}function wF($){let Z={},J=$.updatedBy;if(typeof J==="string")Z.updatedBy=J;else if(J===null)Z.updatedBy=null;let W=$.updatedAt;if(W instanceof Date||typeof W==="string"||typeof W==="number"){let Y=W instanceof Date?W:new Date(W);if(!Number.isNaN(Y.getTime()))Z.updatedAt=Y}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class kF{}class qF 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 c8 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 H5 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 I5{manager;ctx;constructor($,Z){this.manager=$;this.ctx=Z}async enabled($){return(await this.explain($)).value}async explain($){return await this.manager.evaluateIn($,this.ctx,new Map)}async all(){return await this.manager.evaluateAllIn(this.ctx,new Map,{clientOnly:!1})}}class s1{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new p8($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:J}=await this.switches();return{unavailable:J,features:Object.entries(this.declared).map(([W,Y])=>({key:W,describe:Y.describe,rollout:Y.rollout,targeted:Y.when!==void 0,serverOnly:Y.serverOnly,salt:Y.salt,active:$.get(W),...Z.get(W)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{T.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new H5(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=yF(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new c8(Y.constructor?.name||"an anonymous source");let{actorRecorded:j}=await Y.write($,Z,{actor:W});if(W!==null&&!j&&!this.warnedAboutActor)this.warnedAboutActor=!0,this.log('Features.set() was given an actor, but the feature source has nowhere to record it. For the database source, add a nullable `updatedBy String?` column to the feature flag model to keep "last changed by".');await this.invalidate()}async enabled($){return(await this.explain($)).value}async explain($){let Z=await this.requestContext();return await this.evaluateIn($,Z,this.requestBuckets())}async all(){let $=await this.requestContext();return await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!1})}async forClient(){if(!this.config.enabled)return{};let $=await this.requestContext(),Z=await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!0});return this.warnIfOversized(Object.keys(Z).length),Z}for($){return new I5(this,V5($))}async evaluateIn($,Z,J){let W=this.memoFor(Z),Y=W?.get($);if(Y)return Y;let j=this.declared[$];if(!j)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),Q=U5($,j,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,Q),this.notify($,Q,Z),Q}async evaluateAllIn($,Z,J){let W={};for(let[Y,j]of Object.entries(this.declared)){if(J.clientOnly&&j.serverOnly)continue;W[Y]=(await this.evaluateIn(Y,$,Z)).value}return W}async switches(){if(!this.config.enabled||Object.keys(this.declared).length===0)return{active:new Map,audit:new Map,unavailable:!1};let $=await this.store.get();return{active:$.active,audit:$.audit,unavailable:$.unavailable}}async switchFor($){if(!this.config.enabled)return{active:!1,unavailable:!1};let Z=await this.store.get();return{active:Z.active.get($),unavailable:Z.unavailable}}async requestContext(){let $=T.getStore();if($?.featureContext)return $.featureContext;let Z=await B5(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=T.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=T.getStore();if(!$)return new Map;return $.featureBuckets??=new Map,$.featureBuckets}notify($,Z,J){if(!this.config.onEvaluate)return;try{this.config.onEvaluate($,Z,J)}catch(W){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${W instanceof Error?W.message:String(W)}`)}}warnIfOversized($){if(this.warnedAboutSize||$<=this.config.maxClientFlags)return;this.warnedAboutSize=!0,this.log(`${$} client-visible features are embedded in every document. Mark the ones only the server reads with \`serverOnly: true\` to keep them out of the payload.`)}}function yF($){if($===void 0||$===null)return null;if(typeof $==="string"){if($.length>0)return $}else if(typeof $==="object"){let{publicId:Z,id:J}=$;if(typeof Z==="string"&&Z.length>0)return Z;if(typeof J==="string"&&J.length>0||typeof J==="number")return String(J)}throw TypeError("Features.set() was given an `actor` that identifies nobody. Pass a string, or a user with a `publicId` or an `id`.")}async function P5($){if($===void 0)return!0;return await L(s1).enabled($)}async function KZ($,Z){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let J=j5($[Z]);if(!J||!await P5(J.feature))return null;return J.provider}async function M5($){let Z=[];for(let J of Object.keys($))if(await KZ($,J))Z.push(J);return Z}function d8($){if($&&typeof $==="object")delete $.password;return $}function vF(){return new Proxy({},{get:($,Z)=>N5(Z)})}var T5=new WeakMap;function _5($){if($&&typeof $==="object"){for(let Z of Object.values($))_5(Z);Object.freeze($)}return $}var gF={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},mF=_5({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:gF});class u8{models;constructor($=vF()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return mF}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??T1(),W=L(N1).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await i0()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||i0())return Y();let z=(T5.get(W)??Promise.resolve()).then(Y,Y);return T5.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return d8(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return d8(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?d8(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 dD}from"crypto";function k0($,Z,J,W,Y){return s0(Z,h5($,Z),J,W,Y)}function s0($,Z,J,W,Y,j){let z=o8(Z,J,W);if(Y&&Z!==z)throw RangeError(Nz($,Z,J,W,j));return z}function h5($,Z){let J=$[Z];if(J===void 0)throw TypeError(_7(Z));return J}function B0($){return $!==null&&/object|function/.test(typeof $)}function v0($,Z=Map){let J=new Z;return(W,...Y)=>{if(J.has(W))return J.get(W);let j=$(W,...Y);return J.set(W,j),j}}function W2($){return C$({name:$},1)}function C$($,Z){return r0((J)=>({value:J,configurable:1,writable:!Z}),$)}function p5($){return r0((Z)=>({get:Z,configurable:1}),$)}function A6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function LZ($,Z){let J={},W=$.length;for(let Y of Z)J[$[--W]]=Y;return J}function r0($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function F3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function hF($,Z,J){let W={};for(let Y=0;Y<$.length;Y++)W[Z[Y]]=J[$[Y]];return W}function m0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function Y2($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function j2($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function c5($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function d5($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function u5($,Z,J){let W={...J};for(let Y=0;Y<Z;Y++)W[$[Y]]=0;return W}function w($,...Z){return(...J)=>$(...Z,...J)}function x5($){return $[0].toUpperCase()+$.substring(1)}function B3($){return $.slice().sort()}function I6($,Z){return String(Z).padStart($,"0")}function n1($,Z){return Math.sign($-Z)}function o8($,Z,J){return Math.min(Math.max($,Z),J)}function x1($,Z){return[Math.floor($/Z),Y3($,Z)]}function Y3($,Z){return($%Z+Z)%Z}function r1($,Z){return[E6($,Z),z2($,Z)]}function E6($,Z){return Math.trunc($/Z)||0}function z2($,Z){return $%Z||0}function V6($){return Math.abs($%1)===0.5}function l5($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let Q=$[J[X]],G=G1[X],K=c/G,[B,F]=r1(Q,K);W+=F*G,Y+=B}let[j,z]=r1(W,c);return[Y+j,z]}function f6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=G1[Y];W[J[Y]]=E6($,j),$=z2($,j)}return W}function i5($){return $===k?K4:[]}function s5($){return $===k?T3:[]}function n5($){return $===k?["year","day"]:[]}function o5($){if($!==void 0)return t($)}function a5($){if($!==void 0)return t0($)}function X2($){if($!==void 0)return V3($)}function t0($){return e5(V3($))}function V3($){return t5(RB($))}function Q2($){if($==null)throw TypeError("Cannot be null or undefined");return $}function r5($,Z){if(Z==null)throw RangeError(_7($));return Z}function S1($){if(!B0($))throw TypeError(Tz);return $}function R6($,Z,J=$){if(typeof Z!==$)throw TypeError(I3(J,Z));return Z}function t5($,Z="number"){if(!Number.isInteger($))throw RangeError(JB(Z,$));return $||0}function e5($,Z="number"){if($<=0)throw RangeError(WB(Z,$));return $}function G2($){if(typeof $=="symbol")throw TypeError(XB);return String($)}function P6($,Z){return B0($)?String($):t($,Z)}function b6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(zB($));return $}function $Y($,Z="number"){if(typeof $=="bigint")throw TypeError(jB(Z));if($=Number($),!Number.isFinite($))throw RangeError(YB(Z,$));return $}function N0($,Z){return Math.trunc($Y($,Z))||0}function ZY($,Z){return t5($Y($,Z),Z)}function C5($,Z){return e5(N0($,Z),Z)}function K2($,Z){let[J,W]=r1(Z,c),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*c),[Y,W]}function BZ($,Z,J=1){return K2($[0]+Z[0]*J,$[1]+Z[1]*J)}function VZ($,Z){return K2($[0],$[1]+Z)}function c0($,Z){return BZ(Z,$,-1)}function x0($,Z){return n1($[0],Z[0])||n1($[1],Z[1])}function JY($,Z,J){return x0($,Z)===-1||x0($,J)===1}function w6($,Z=1){let J=BigInt(c/Z);return[Number($/J),Number($%J)*Z]}function DZ($,Z=1){let J=c/Z,[W,Y]=r1($,J);return[W,Y*Z]}function WY($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=c/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function d0($,Z=1,J){let[W,Y]=$,[j,z]=r1(Y,Z);return W*(c/Z)+(j+(J?z/Z:0))}function F2($,Z,J=x1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(c/Z)+j,z]}function B2($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function V2($){return k0($,"isoYear",K3,G3,1),$.isoYear===K3?k0($,"isoMonth",4,12,1):$.isoYear===G3&&k0($,"isoMonth",1,9,1),$}function o1($){return A1({...$,...a0,isoHour:12}),$}function A1($){let Z=k0($,"isoYear",K3,G3,1),J=Z===K3?1:Z===G3?-1:0;return J&&u0(_0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function u0($){if(!$||JY($,gB,vB))throw RangeError(z4);return $}function t1($){return l5($,5,J1)[1]}function k6($){let[Z,J]=x1($,c);return[f6(J,5,J1),Z]}function YY($){return jY($)[0]}function jY($){return F2($,o0)}function C0($){return HZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function _0($){let Z=C0($);if(Z!==void 0){let[J,W]=r1(Z,y0);return[J,W*K1+($.isoMicrosecond||0)*q$+($.isoNanosecond||0)]}}function D2($,Z){let[J,W]=k6(t1($)-Z);return u0(_0({...$,isoDay:$.isoDay+W,...J}))}function M6(...$){return HZ(...$)/kz}function HZ(...$){let[Z,J]=zY(...$),W=Z.valueOf();if(!isNaN(W))return W-J*y0}function zY($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===K3?1:$===G3?-1:0,Q=new Date;return Q.setUTCHours(W,Y,j,z),Q.setUTCFullYear($,Z-1,J+X),[Q,X]}function $$($,Z){let[J,W]=VZ($,Z);W<0&&(W+=c,J-=1);let[Y,j]=x1(W,K1),[z,X]=x1(j,q$);return q6(J*y0+Y,z,X)}function q6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-yB)/y0)*Math.sign($),Y=new Date($-W*y0);return LZ(B4,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+W,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function XY($){return[$.isoYear,$.isoMonth,$.isoDay]}function QY(){return _1}function O2($,Z){switch(Z){case 2:return U2($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function GY($){return U2($)?366:365}function U2($){return $%4==0&&($%100!=0||$%400==0)}function KY($){let[Z,J]=zY($.isoYear,$.isoMonth,$.isoDay);return Y3(Z.getUTCDay()-J,7)||7}function FY({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function pF($){let Z=C0($);if(Z<hB)return FY($);let J=B2(c7(OZ),Z),{era:W,eraYear:Y}=Tj(J,OZ);return[W,Y]}function y6($){return S$($),v6($,1),$}function S$($){return BY($,1),$}function S5($){return d5(k7,$,BY($))}function BY($,Z){let{isoYear:J}=$,W=k0($,"isoMonth",1,QY(),Z);return{isoYear:J,isoMonth:W,isoDay:k0($,"isoDay",1,O2(J,W),Z)}}function v6($,Z){return LZ(J1,[k0($,"isoHour",0,23,Z),k0($,"isoMinute",0,59,Z),k0($,"isoSecond",0,59,Z),k0($,"isoMillisecond",0,999,Z),k0($,"isoMicrosecond",0,999,Z),k0($,"isoNanosecond",0,999,Z)])}function v($){return $===void 0?0:rz(S1($))}function D3($,Z=0){$=e0($);let J=tz($),W=aB($,Z);return[rz($),W,J]}function L2($){return tz(e0($))}function VY($){return $=e0($),v7($,9,6,1)}function IZ($,Z,J,W=9,Y=0,j=4){Z=e0(Z);let z=v7(Z,W,Y),X=P2(Z),Q=_3(Z,j),G=N3(Z,W,Y,1);return z==null?z=Math.max(J,G):LY(z,G),X=M2(X,G,1),$&&(Q=((K)=>K<4?(K+2)%4:K)(Q)),[z,G,X,Q]}function g6($,Z=6,J){let W=P2($=T2($,S6)),Y=_3($,7),j=N3($,Z);return j=r5(S6,j),W=M2(W,j,void 0,J),[j,W,Y]}function H2($){return g7(e0($))}function DY($,Z){return I2(e0($),Z)}function I2($,Z=4){let J=UY($);return[_3($,4),...OY(N3($,Z),J)]}function OY($,Z){return $!=null?[G1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function P2($){let Z=$[j3];return Z===void 0?1:N0(Z,j3)}function M2($,Z,J,W){let Y=W?c:G1[Z+1];if(Y){let j=G1[Z];if(Y%(($=s0(j3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(I3(j3,$))}else $=s0(j3,$,1,J?1e9:1,1);return $}function UY($){let Z=$[n8];if(Z!==void 0){if(typeof Z!="number"){if(G2(Z)==="auto")return;throw RangeError(I3(n8,Z))}Z=s0(n8,Math.floor(Z),0,9,1)}return Z}function e0($){return $===void 0?{}:S1($)}function T2($,Z){return typeof $=="string"?{[Z]:$}:S1($)}function W0($){if($!==void 0){if(B0($))return Object.assign(Object.create(null),$);throw TypeError(Tz)}}function m6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:cB[Z]})}function N2($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=G2(j),j==="auto")return Y?W:null;let z=e8[j];if(z===void 0&&(z=kB[j]),z===void 0)throw RangeError(Cz($,j,e8));return s0($,z,W,J,1,M3),z}function A$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=G2(Y),z=Z[j];if(z===void 0)throw RangeError(Cz($,j,Z));return z}function LY($,Z){if(Z>$)throw RangeError(CB)}function V0($){return{branding:D4,epochNanoseconds:$}}function U0($,Z,J){return{branding:b1,calendar:J,timeZone:Z,epochNanoseconds:$}}function Y0($,Z=$.calendar){return{branding:v$,calendar:Z,...m0(sz,$)}}function j0($,Z=$.calendar){return{branding:y$,calendar:Z,...m0(q7,$)}}function _$($,Z=$.calendar){return{branding:SZ,calendar:Z,...m0(q7,$)}}function T6($,Z=$.calendar){return{branding:AZ,calendar:Z,...m0(q7,$)}}function $1($){return{branding:V4,...m0(iz,$)}}function o($){return{branding:O4,sign:Z$($),...m0(R7,$)}}function HY($){return YY($.epochNanoseconds)}function h6($){return F2($.epochNanoseconds,K1)[0]}function IY($){return WY($.epochNanoseconds,q$)}function PY($){return WY($.epochNanoseconds)}function MY($){return $.epochNanoseconds}function D0($){return typeof $=="string"?$:t($.id)}function PZ($,Z){return $===Z||D0($)===D0(Z)}function TY($,Z,J,W,Y){let j=x$(W),[z,X]=((U,H)=>{let M=H((U=T2(U,J2))[oz]),P=oB(U);return P=r5(J2,P),[P,M]})(Y,$);if(X3(Math.max(z,j),X))return A5(W,z);if(!X)throw RangeError(X4);let[Q,G,K]=i6(Z,J,X),B=s2(K),F=s6(K),O=n2(K),V=F(G,Q,W),D=O(G,Q,V,z);return X3(z,X)?A5(D,z):((U,H,M,P,x,E,f)=>{let S=Z$(U),[b,I]=_2(P,w7(M,U),M,S,x,E,f),_=x2(H,b,I);return U[m[M]]+_*S})(D,B(V),z,G,Q,B,F)}function A5($,Z){return d0(F0($),G1[Z],1)}function _2($,Z,J,W,Y,j,z){let X=m[J],Q={...Z,[X]:Z[X]+W},G=z($,Y,Z),K=z($,Y,Q);return[j(G),j(K)]}function x2($,Z,J){let W=d0(c0(Z,J));if(!W)throw RangeError(P3);return d0(c0(Z,$))/W}function NY($,Z){let[J,W,Y]=g6(Z,5,1);return V0(c6($.epochNanoseconds,J,W,Y,1))}function _Y($,Z,J){let{epochNanoseconds:W,timeZone:Y,calendar:j}=Z,[z,X,Q]=g6(J);if(z===0&&X===1)return Z;let G=$(Y);if(z===6)W=((K,B,F,O)=>{let V=S0(F,B),[D,U]=K(V),H=F.epochNanoseconds,M=g0(B,D),P=g0(B,U);if(JY(H,M,P))throw RangeError(P3);return wY(x2(H,M,P),O)?P:M})(RY,G,Z,Q);else{let K=G.getOffsetNanosecondsFor(W);W=f$(G,EY($$(W,K),z,X,Q),K,2,0,1)}return U0(W,Y,j)}function xY($,Z){return Y0(EY($,...g6(Z)),$.calendar)}function CY($,Z){let[J,W,Y]=g6(Z,5);var j;return $1((j=Y,C2($,O3(J,W),j)[0]))}function SY($,Z){let J=$(Z.timeZone),W=S0(Z,J),[Y,j]=RY(W),z=d0(c0(g0(J,Y),g0(J,j)),G4,1);if(z<=0)throw RangeError(P3);return z}function AY($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>g0(z,j(S0(X,z))))(bY,$(J),Z);return U0(Y,J,W)}function EY($,Z,J,W){return fY($,O3(Z,J),W)}function fY($,Z,J){let[W,Y]=C2($,Z,J);return A1({...R$($,Y),...W})}function C2($,Z,J){return k6(e1(t1($),Z,J))}function N6($){return e1($,Q4,7)}function O3($,Z){return G1[$]*Z}function RY($){let Z=bY($);return[Z,R$(Z,1)]}function bY($){return qB(6,$)}function cF($,Z,J){let W=Math.min(x$($),6);return TZ(d6(F0($,W),Z,J),W)}function p6($,Z,J,W,Y,j,z,X,Q,G){if(W===0&&Y===1)return $;let K=X3(W,X)?n6(X)&&W<6&&J>=6?uF:dF:lF,[B,F,O]=K($,Z,J,W,Y,j,z,X,Q,G);return O&&W!==7&&(B=((V,D,U,H,M,P,x,E)=>{let f=Z$(V);for(let S=H+1;S<=U;S++){if(S===7&&U!==7)continue;let b=w7(S,V);b[m[S]]+=f;let I=d0(c0(x(E(M,P,b)),D));if(I&&Math.sign(I)!==f)break;V=b}return V})(B,F,J,Math.max(6,W),z,X,Q,G)),B}function c6($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/c)($);return[e1(j,J,W),0]}return d6($,O3(Z,J),W,Y)}function d6($,Z,J,W){let[Y,j]=$;W&&j<0&&(j+=c,Y-=1);let[z,X]=x1(e1(j,Z,J),c);return K2(Y+z,X)}function e1($,Z,J){return wY($/Z,J)*Z}function wY($,Z){return eB[Z]($)}function dF($,Z,J,W,Y,j){let z=Z$($),X=F0($),Q=c6(X,W,Y,j),G=c0(X,Q),K=Math.sign(Q[0]-X[0])===z,B=TZ(Q,Math.min(J,6));return[{...$,...B},BZ(Z,G),K]}function uF($,Z,J,W,Y,j,z,X,Q,G){let K=Z$($),B=d0(F0($,5)),F=O3(W,Y),O=e1(B,F,j),[V,D]=_2(z,{...$,...b7},6,K,X,Q,G),U=O-d0(c0(V,D)),H=0;U&&Math.sign(U)!==K?Z=VZ(V,O):(H+=K,O=e1(U,F,j),Z=VZ(D,O));let M=a6(O);return[{...$,...M,days:$.days+H},Z,Boolean(H)]}function lF($,Z,J,W,Y,j,z,X,Q,G){let K=Z$($),B=m[W],F=w7(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let O=E6($[B],Y)*Y;F[B]=O;let[V,D]=_2(z,F,W,Y*K,X,Q,G),U=O+x2(Z,V,D)*K*Y,H=e1(U,Y,j),M=Math.sign(H-U)===K;return F[B]=H,[F,M?D:V,M]}function S2($,Z,J,W){let[Y,j,z,X]=((G)=>{let K=I2(G=e0(G));return[G.timeZone,...K]})(W),Q=Y!==void 0;return((G,K,B,F,O,V)=>{B=d6(B,O,F,1);let D=K.getOffsetNanosecondsFor(B);return k2($$(B,D),V)+(G?E$(N6(D)):"Z")})(Q,Z(Q?$(Y):g$),J.epochNanoseconds,j,z,X)}function A2($,Z,J){let[W,Y,j,z,X,Q]=((G)=>{G=e0(G);let K=g7(G),B=UY(G),F=tB(G),O=_3(G,4),V=N3(G,4);return[K,rB(G),F,O,...OY(V,B)]})(J);return((G,K,B,F,O,V,D,U,H,M)=>{F=d6(F,H,U,1);let P=G(B).getOffsetNanosecondsFor(F);return k2($$(F,P),M)+E$(N6(P),D)+((x,E)=>E!==1?"["+(E===2?"!":"")+D0(x)+"]":"")(B,V)+q2(K,O)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,Q)}function E2($,Z){let[J,W,Y,j]=((G)=>(G=e0(G),[g7(G),...I2(G)]))(Z);return z=$.calendar,X=J,Q=j,k2(fY($,Y,W),Q)+q2(z,X);var z,X,Q}function f2($,Z){return J=$.calendar,W=$,Y=H2(Z),_6(W)+q2(J,Y);var J,W,Y}function R2($,Z){return kY($.calendar,qY,$,H2(Z))}function b2($,Z){return kY($.calendar,iF,$,H2(Z))}function w2($,Z){let[J,W,Y]=DY(Z);return j=Y,yY(C2($,W,J)[0],j);var j}function u6($,Z){let[J,W,Y]=DY(Z,3);return W>1&&($={...$,...cF($,W,J)}),((j,z)=>{let{sign:X}=j,Q=X===-1?A0(j):j,{hours:G,minutes:K}=Q,[B,F]=F2(F0(Q,3),o0,r1);uY(B);let O=y2(F,z),V=z>=0||!X||O;return(X<0?"-":"")+"P"+E5({Y:N$(Q.years),M:N$(Q.months),W:N$(Q.weeks),D:N$(Q.days)})+(G||K||B||V?"T"+E5({H:N$(G),M:N$(K),S:N$(B,V)+O}):"")})($,Y)}function kY($,Z,J,W){let Y=D0($),j=W>1||W===0&&Y!==k;return W===1?Y===k?Z(J):_6(J):j?_6(J)+vY(Y,W===2):Z(J)}function E5($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function k2($,Z){return _6($)+"T"+yY($,Z)}function _6($){return qY($)+"-"+n0($.isoDay)}function qY($){let{isoYear:Z}=$;return(Z<0||Z>9999?gY(Z)+I6(6,Math.abs(Z)):I6(4,Z))+"-"+n0($.isoMonth)}function iF($){return n0($.isoMonth)+"-"+n0($.isoDay)}function yY($,Z){let J=[n0($.isoHour),n0($.isoMinute)];return Z!==-1&&J.push(n0($.isoSecond)+((W,Y,j,z)=>y2(W*K1+Y*q$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function E$($,Z=0){if(Z===1)return"";let[J,W]=x1(Math.abs($),G4),[Y,j]=x1(W,Q4),[z,X]=x1(j,o0);return gY($)+n0(J)+":"+n0(Y)+(z||X?":"+n0(z)+y2(X):"")}function q2($,Z){if(Z!==1){let J=D0($);if(Z>1||Z===0&&J!==k)return vY(J,Z===2)}return""}function vY($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function y2($,Z){let J=I6(9,$);return J=Z===void 0?J.replace(JV,""):J.slice(0,Z),J?"."+J:""}function gY($){return $<0?"-":"+"}function N$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function sF($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=$$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function mY($,Z){let J=S0(Z,$);return{calendar:Z.calendar,...m0(sz,J),offset:E$(J.offsetNanoseconds),timeZone:Z.timeZone}}function f$($,Z,J,W=0,Y=0,j,z){if(J!==void 0&&W===1&&(W===1||z))return D2(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let Q=((G,K,B,F)=>{let O=_0(K);F&&(B=N6(B));for(let V of G){let D=d0(c0(V,O));if(F&&(D=N6(D)),D===B)return V}})(X,Z,J,j);if(Q!==void 0)return Q;if(W===0)throw RangeError(PB)}return z?_0(Z):g0($,Z,Y,X)}function g0($,Z,J=0,W=$.getPossibleInstantsFor(Z)){if(W.length===1)return W[0];if(J===1)throw RangeError(MB);if(W.length)return W[J===3?1:0];let Y=_0(Z),j=((X,Q)=>{let G=X.getOffsetNanosecondsFor(VZ(Q,-c));return g2(X.getOffsetNanosecondsFor(VZ(Q,c))-G)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor($$(Y,z)))[J===2?0:W.length-1]}function v2($){if(Math.abs($)>=c)throw RangeError(HB);return $}function g2($){if($>c)throw RangeError(IB);return $}function m2($,Z,J){return V0(u0(BZ(Z.epochNanoseconds,((W)=>{if(lY(W))throw RangeError(_B);return F0(W,5)})($?A0(J):J))))}function h2($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...l2(z,X,W,J?A0(Y):Y,j)}}function p2($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return Y0(i2($(j),J,Z?A0(W):W,Y),j)}function c2($,Z,J,W,Y){let{calendar:j}=J;return j0(l6($(j),J,Z?A0(W):W,Y),j)}function d2($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=z3(z,J);Z&&(W=o6(W)),W.sign<0&&(X=z.dateAdd(X,{...O0,months:1}),X=R$(X,-1));let Q=z.dateAdd(X,W,Y);return _$(z3(z,Q),j)}function u2($,Z,J){return $1(hY(Z,$?A0(J):J)[0])}function l2($,Z,J,W,Y){let j=F0(W,5),z=J.epochNanoseconds;if(lY(W)){let X=S0(J,$);z=BZ(g0($,{...l6(Z,X,{...W,...b7},Y),...m0(J1,X)}),j)}else z=BZ(z,j),v(Y);return{epochNanoseconds:u0(z)}}function i2($,Z,J,W){let[Y,j]=hY(Z,J);return A1({...l6($,Z,{...J,...b7,days:J.days+j},W),...Y})}function l6($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);v(W);let Y=J.days+F0(J,5)[0];return Y?o1(R$(Z,Y)):Z}function z3($,Z,J=1){return R$(Z,J-$.day(Z))}function hY($,Z){let[J,W]=F0(Z,5),[Y,j]=k6(t1($)+W);return[Y,J+j]}function R$($,Z){return Z?{...$,...q6(C0($)+Z*y0)}:$}function i6($,Z,J){let W=$(J.calendar);return n6(J)?[J,W,Z(J.timeZone)]:[{...J,...a0},W]}function s2($){return $?MY:_0}function s6($){return $?w(l2,$):i2}function n2($){return $?w(oF,$):aF}function n6($){return $&&$.epochNanoseconds}function X3($,Z){return $<=6-(n6(Z)?1:0)}function o2($,Z,J,W,Y,j,z){let X=$(e0(z).relativeTo),Q=Math.max(x$(Y),x$(j));if(X3(Q,X))return o(MZ(((D,U,H,M)=>{let P=BZ(F0(D),F0(U),M?-1:1);if(!Number.isFinite(P[0]))throw RangeError(z4);return{...O0,...TZ(P,H)}})(Y,j,Q,W)));if(!X)throw RangeError(X4);W&&(j=A0(j));let[G,K,B]=i6(Z,J,X),F=s6(B),O=n2(B),V=F(K,G,Y);return o(O(K,G,F(K,V,j),Q))}function pY($,Z,J,W,Y){let j=x$(W),[z,X,Q,G,K]=((f,S,b)=>{f=T2(f,S6);let I=v7(f),_=b(f[oz]),y=P2(f),D$=_3(f,7),P0=N3(f);if(I===void 0&&P0===void 0)throw RangeError(xB);return P0==null&&(P0=0),I==null&&(I=Math.max(P0,S)),LY(I,P0),y=M2(y,P0,1),[I,P0,y,D$,_]})(Y,j,$),B=Math.max(j,z);if(!n6(K)&&B<=6)return o(MZ(((f,S,b,I,_)=>{let y=c6(F0(f),b,I,_);return{...O0,...TZ(y,S)}})(W,z,X,Q,G)));if(!K)throw RangeError(X4);let[F,O,V]=i6(Z,J,K),D=s2(V),U=s6(V),H=n2(V),M=U(O,F,W),P=H(O,F,M,z),x=W.sign,E=Z$(P);if(x&&E&&x!==E)throw RangeError(P3);return E&&(P=p6(P,D(M),z,X,Q,G,O,F,D,U)),o(P)}function cY($){return $.sign===-1?o6($):$}function o6($){return o(A0($))}function A0($){let Z={};for(let J of m)Z[J]=-1*$[J]||0;return Z}function dY($){return!$.sign}function Z$($,Z=m){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(NB);J=Y}}return J}function MZ($){for(let Z of wB)s0(Z,$[Z],-y5,y5,1);return uY(d0(F0($),o0)),$}function uY($){if(!Number.isSafeInteger($))throw RangeError(TB)}function F0($,Z=6){return l5($,Z,m)}function TZ($,Z=6){let[J,W]=$,Y=f6(W,Z,m);if(Y[m[Z]]+=J*(c/G1[Z]),!Number.isFinite(Y[m[Z]]))throw RangeError(z4);return Y}function a6($,Z=5){return f6($,Z,m)}function lY($){return Boolean(Z$($,lz))}function x$($){let Z=9;for(;Z>0&&!$[m[Z]];Z--);return Z}function nF($,Z){return[$,Z]}function f5($){let Z=Math.floor($/L6)*L6;return[Z,Z+L6]}function iY($){let Z=J$($=P6($));if(!Z)throw RangeError(q0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(q0($));J=NZ(Z.offset)}return Z.timeZone&&e2(Z.timeZone,1),V0(D2(y6(Z),J))}function sY($){let Z=J$(t($));if(!Z)throw RangeError(q0($));if(Z.timeZone)return Jj(Z,Z.offset?NZ(Z.offset):void 0);if(Z.m)throw RangeError(q0($));return Yj(Z)}function nY($,Z){let J=J$(t($));if(!J||!J.timeZone)throw RangeError(q0($));let{offset:W}=J,Y=W?NZ(W):void 0,[,j,z]=D3(Z);return Jj(J,Y,j,z)}function NZ($){let Z=e2($);if(Z===void 0)throw RangeError(q0($));return Z}function oY($){let Z=J$(t($));if(!Z||Z.m)throw RangeError(q0($));return Y0(Wj(Z))}function r6($){let Z=J$(t($));if(!Z||Z.m)throw RangeError(q0($));return j0(Z.p?Wj(Z):Yj(Z))}function aY($,Z){let J=r2(t(Z));if(J)return a2(J),_$(V2(S$(J)));let W=r6(Z);return _$(z3($(W.calendar),W))}function a2($){if($.calendar!==k)throw RangeError(C1($.calendar))}function rY($,Z){let J=t2(t(Z));if(J)return a2(J),T6(S$(J));let W=r6(Z),{calendar:Y}=W,j=$(Y),[z,X,Q]=j.h(W),[G,K]=j.I(z,X),[B,F]=j.N(G,K,Q);return T6(o1(j.P(B,F,Q)),Y)}function tY($){let Z,J=((W)=>{let Y=XV.exec(W);return Y?(t6(Y[10]),Xj(Y)):void 0})(t($));if(!J){if(J=J$($),!J)throw RangeError(q0($));if(!J.p)throw RangeError(q0($));if(J.m)throw RangeError(C1("Z"));a2(J)}if((Z=r2($))&&S5(Z))throw RangeError(q0($));if((Z=t2($))&&S5(Z))throw RangeError(q0($));return $1(v6(J,1))}function eY($){let Z=((J)=>{let W=KV.exec(J);return W?((Y)=>{function j(K,B,F){let O=0,V=0;if(F&&([O,Q]=x1(Q,G1[F])),K!==void 0){if(X)throw RangeError(C1(K));V=((D)=>{let U=parseInt(D);if(!Number.isFinite(U))throw RangeError(C1(D));return U})(K),z=1,B&&(Q=$7(B)*(G1[F]/o0),X=1)}return O+V}let z=0,X=0,Q=0,G={...LZ(m,[j(Y[2]),j(Y[3]),j(Y[4]),j(Y[5]),j(Y[6],Y[7],5),j(Y[8],Y[9],4),j(Y[10],Y[11],3)]),...f6(Q,2,m)};if(!z)throw RangeError(_z(m));return Z7(Y[1])<0&&(G=A0(G)),G})(W):void 0})(t($));if(!Z)throw RangeError(q0($));return o(MZ(Z))}function $j($){let Z=J$($)||r2($)||t2($);return Z?Z.calendar:$}function Zj($){let Z=J$($);return Z&&(Z.timeZone||Z.m&&g$||Z.offset)||$}function Jj($,Z,J=0,W=0){let Y=e6($.timeZone),j=U4(Y);return U0(f$(j,y6($),Z,J,W,!j.v,$.m),Y,U3($.calendar))}function Wj($){return jj(A1(y6($)))}function Yj($){return jj(o1(S$($)))}function jj($){return{...$,calendar:U3($.calendar)}}function J$($){let Z=zV.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:zj(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...Xj(J.slice(5)),...t6(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function r2($){let Z=YV.exec($);return Z?((J)=>({isoYear:zj(J),isoMonth:parseInt(J[4]),isoDay:1,...t6(J[5])}))(Z):void 0}function t2($){let Z=jV.exec($);return Z?((J)=>({isoYear:UZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...t6(J[3])}))(Z):void 0}function e2($,Z){let J=QV.exec($);return J?((W,Y)=>{let j=W[4]||W[5];if(Y&&j)throw RangeError(C1(j));return v2((FZ(W[2])*G4+FZ(W[3])*Q4+FZ(W[4])*o0+$7(W[5]||""))*Z7(W[1]))})(J,Z):void 0}function zj($){let Z=Z7($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(C1(-0));return Z*J}function Xj($){let Z=FZ($[3]);return{...k6($7($[4]||""))[0],isoHour:FZ($[1]),isoMinute:FZ($[2]),isoSecond:Z===60?59:Z}}function t6($){let Z,J,W=[];if($.replace(GV,(Y,j,z)=>{let X=Boolean(j),[Q,G]=z.split("=").reverse();if(G){if(G==="u-ca")W.push(Q),Z||(Z=X);else if(X||/[A-Z]/.test(G))throw RangeError(C1(Y))}else{if(J)throw RangeError(C1(Y));J=Q}return""}),W.length>1&&Z)throw RangeError(C1($));return{timeZone:J,calendar:W[0]||k}}function $7($){return parseInt($.padEnd(9,"0"))}function _Z($){return new RegExp(`^${$}$`,"i")}function Z7($){return $&&$!=="+"?-1:1}function FZ($){return $===void 0?0:parseInt($)}function Qj($){return e6(t($))}function e6($){let Z=J7($);return typeof Z=="number"?E$(Z):Z?((J)=>{if(BV.test(J))throw RangeError(LB);return J.toLowerCase().split("/").map((W,Y)=>(W.length<=3||/\d/.test(W))&&!/etc|yap/.test(W)?W.toUpperCase():W.replace(/baja|dumont|[a-z]+/g,(j,z)=>j.length<=2&&!Y||j==="in"||j==="chat"?j.toUpperCase():j.length>2||!z?x5(j).replace(/island|noronha|murdo|rivadavia|urville/,x5):j)).join("/")})($):g$}function R5($){let Z=J7($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:g$}function J7($){let Z=e2($=$.toUpperCase(),1);return Z!==void 0?Z:$!==g$?FV($):void 0}function W7($,Z){return x0($.epochNanoseconds,Z.epochNanoseconds)}function Y7($,Z){return x0($.epochNanoseconds,Z.epochNanoseconds)}function Gj($,Z,J,W,Y,j){let z=$(e0(j).relativeTo),X=Math.max(x$(W),x$(Y));if(d5(m,W,Y))return 0;if(X3(X,z))return x0(F0(W),F0(Y));if(!z)throw RangeError(X4);let[Q,G,K]=i6(Z,J,z),B=s2(K),F=s6(K);return x0(B(F(G,Q,W)),B(F(G,Q,Y)))}function j7($,Z){return b$($,Z)||$4($,Z)}function b$($,Z){return n1(C0($),C0(Z))}function $4($,Z){return n1(t1($),t1(Z))}function Kj($,Z){return!W7($,Z)}function Fj($,Z){return!Y7($,Z)&&!!Z4($.timeZone,Z.timeZone)&&PZ($.calendar,Z.calendar)}function Bj($,Z){return!j7($,Z)&&PZ($.calendar,Z.calendar)}function Vj($,Z){return!b$($,Z)&&PZ($.calendar,Z.calendar)}function Dj($,Z){return!b$($,Z)&&PZ($.calendar,Z.calendar)}function Oj($,Z){return!b$($,Z)&&PZ($.calendar,Z.calendar)}function Uj($,Z){return!$4($,Z)}function Z4($,Z){if($===Z)return 1;let J=D0($),W=D0(Z);if(J===W)return 1;try{return R5(J)===R5(W)}catch(Y){}}function z7($,Z,J,W){let Y=IZ($,W0(W),3,5),j=J4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return o($?A0(j):j)}function X7($,Z,J,W,Y,j){let z=Y4(W.calendar,Y.calendar),X=W0(j),[Q,G,K,B]=IZ(J,X,5),F=W.epochNanoseconds,O=Y.epochNanoseconds,V=x0(O,F),D;if(V)if(Q<6)D=J4(F,O,Q,G,K,B);else{let U=Z(((M,P)=>{if(!Z4(M,P))throw RangeError(fz);return M})(W.timeZone,Y.timeZone)),H=$(z);D=Hj(H,U,W,Y,V,Q,X),D=p6(D,O,Q,G,K,B,H,W,MY,w(l2,U))}else D=O0;return o(J?A0(D):D)}function Q7($,Z,J,W,Y){let j=Y4(J.calendar,W.calendar),z=W0(Y),[X,Q,G,K]=IZ(Z,z,6),B=_0(J),F=_0(W),O=x0(F,B),V;if(O)if(X<=6)V=J4(B,F,X,Q,G,K);else{let D=$(j);V=Ij(D,J,W,O,X,z),V=p6(V,F,X,Q,G,K,D,J,_0,i2)}else V=O0;return o(Z?A0(V):V)}function G7($,Z,J,W,Y){let j=Y4(J.calendar,W.calendar),z=W0(Y);return Lj(Z,()=>$(j),J,W,...IZ(Z,z,6,9,6),z)}function K7($,Z,J,W,Y){let j=Y4(J.calendar,W.calendar),z=W0(Y),X=IZ(Z,z,9,9,8),Q=$(j);return Lj(Z,()=>Q,z3(Q,J),z3(Q,W),...X,z)}function Lj($,Z,J,W,Y,j,z,X,Q){let G=_0(J),K=_0(W),B;if(x0(K,G))if(Y===6)B=J4(G,K,Y,j,z,X);else{let F=Z();B=F.dateUntil(J,W,Y,Q),j===6&&z===1||(B=p6(B,K,Y,j,z,X,F,J,_0,l6))}else B=O0;return o($?A0(B):B)}function F7($,Z,J,W){let Y=W0(W),[j,z,X,Q]=IZ($,Y,5,5),G=e1(B7(Z,J),O3(z,X),Q),K={...O0,...a6(G,j)};return o($?A0(K):K)}function oF($,Z,J,W,Y,j){let z=x0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?Pj(J.epochNanoseconds,W.epochNanoseconds,Y):Hj(Z,$,J,W,z,Y,j):O0}function aF($,Z,J,W,Y){let j=_0(Z),z=_0(J),X=x0(z,j);return X?W<=6?Pj(j,z,W):Ij($,Z,J,X,W,Y):O0}function Hj($,Z,J,W,Y,j,z){let[X,Q,G]=((F,O,V,D)=>{function U(){return S={...R$(P,E++*-D),...M},b=g0(F,S),x0(x,b)===-D}let H=S0(O,F),M=m0(J1,H),P=S0(V,F),x=V.epochNanoseconds,E=0,f=B7(H,P),S,b;if(Math.sign(f)===-D&&E++,U()&&(D===-1||U()))throw RangeError(P3);let I=d0(c0(b,x));return[H,S,I]})(Z,J,W,Y);var K,B;return{...j===6?(K=X,B=Q,{...O0,days:Mj(K,B)}):$.dateUntil(X,Q,j,z),...a6(G)}}function Ij($,Z,J,W,Y,j){let[z,X,Q]=((G,K,B)=>{let F=K,O=B7(G,K);return Math.sign(O)===-B&&(F=R$(K,-B),O+=c*B),[G,F,O]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...a6(Q)}}function J4($,Z,J,W,Y,j){return{...O0,...TZ(c6(c0($,Z),W,Y,j),J)}}function Pj($,Z,J){return{...O0,...TZ(c0($,Z),J)}}function Mj($,Z){return W4(C0($),C0(Z))}function W4($,Z){return Math.trunc((Z-$)/y0)}function B7($,Z){return t1(Z)-t1($)}function Y4($,Z){if(!PZ($,Z))throw RangeError(S7);return $}function rF($){function Z(Y){return((j,z)=>({...Tj(j,z),F:j.month,day:parseInt(j.day)}))(B2(J,Y),W)}let J=c7($),W=x6($);return{id:$,O:tF(Z),B:eF(Z)}}function tF($){return v0((Z)=>{let J=C0(Z);return $(J)},WeakMap)}function eF($){let Z=$(0).year-mB;return v0((J)=>{let W,Y=HZ(J-Z),j=[],z=[];do Y+=400*y0;while((W=$(Y)).year<=J);do Y+=(1-W.day)*y0,W.year===J&&(j.push(Y),z.push(W.F)),Y-=y0;while((W=$(Y)).year>=J);return{k:j.reverse(),C:wz(z.reverse())}})}function Tj($,Z){let J,W,Y=Nj($);if($.era){let j=cz[Z];j!==void 0&&(J=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),J==="bc"||J==="b"?J="bce":J!=="ad"&&J!=="a"||(J="ce"),W=Y,Y=Aj(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function Nj($){return parseInt($.relatedYear||$.year)}function a8($){let{year:Z,F:J,day:W}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,W]}function Q3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*y0}function D6($){let Z=w5(this,$),J=w5(this,$-1),W=Z.length;if(W>J.length){let Y=Ej(this);if(Y<0)return-Y;for(let j=0;j<W;j++)if(Z[j]!==J[j])return j+1}}function O6($){return W4(Q3.call(this,$),Q3.call(this,$+1))}function b5($,Z){let{k:J}=this.B($),W=Z+1,Y=J;return W>J.length&&(W=1,Y=this.B($+1).k),W4(J[Z-1],Y[W-1])}function U6($){return this.B($).k.length}function w5($,Z){return Object.keys($.B(Z).C)}function _j($){return U3(t($))}function U3($){if(($=$.toLowerCase())!==k&&$!==F4&&x6($)!==x6(c7($).resolvedOptions().calendar))throw RangeError(UB($));return $}function x6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function xj($){return this.R($)[0]}function Cj($){return this.R($)[1]}function V7($){let[Z]=this.h($);return W4(this.q(Z),C0($))+1}function Sj($){let Z=DV.exec($);if(!Z)throw RangeError(DB($));return[parseInt(Z[1]),Boolean(Z[2])]}function C6($,Z,J){return $+(Z||J&&$>=J?1:0)}function r8($,Z){return $-(Z&&$>=Z?1:0)}function Aj($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function t8($){return cz[fj($)]}function Ej($){return fB[fj($)]}function fj($){return x6($.id||k)}function Rj($,Z,J,W){let Y=W$(J,W,Z1,[],gz);if(Y.timeZone!==void 0){let j=J.dateFromFields(Y),z=w$(Y),X=$(Y.timeZone);return{epochNanoseconds:f$(Z(X),{...j,...z},Y.offset!==void 0?NZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...a0}}function bj($,Z,J,W,Y,j){let z=W$(J,Y,Z1,yz,gz),X=$(z.timeZone),[Q,G,K]=D3(j),B=J.dateFromFields(z,m6(j,Q)),F=w$(z,Q);return U0(f$(Z(X),{...B,...F},z.offset!==void 0?NZ(z.offset):void 0,G,K),X,W)}function wj($,Z,J){let W=W$($,Z,Z1,[],R1),Y=v(J);return Y0(A1({...$.dateFromFields(W,m6(J,Y)),...w$(W,Y)}))}function D7($,Z,J,W=[]){let Y=W$($,Z,Z1,W);return $.dateFromFields(Y,J)}function O7($,Z,J,W){let Y=W$($,Z,f7,W);return $.yearMonthFromFields(Y,J)}function U7($,Z,J,W,Y=[]){let j=W$($,J,Z1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=UZ),$.monthDayFromFields(j,W)}function kj($,Z){let J=v(Z);return $1(w$(Q1($,$2,[],1),J))}function qj($){let Z=Q1($,R7);return o(MZ({...O0,...Z}))}function W$($,Z,J,W=[],Y=[]){return Q1(Z,[...$.fields(J),...Y].sort(),W)}function Q1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(QB(X));if(X==="constructor"||X==="__proto__")throw RangeError(x7(X));let Q=$[X];if(Q!==void 0)z=1,v5[X]&&(Q=v5[X](Q,X)),Y[X]=Q;else if(J){if(J.includes(X))throw TypeError(_7(X));Y[X]=pz[X]}j=X}if(W&&!z)throw TypeError(_z(Z));return Y}function w$($,Z){return v6(HV({...pz,...$}),Z)}function yj($,Z,J,W,Y,j){let z=W0(j),{calendar:X,timeZone:Q}=J;return U0(((G,K,B,F,O)=>{let V=L3(G,B,F,Z1,vz,qz),[D,U,H]=D3(O,2);return f$(K,{...G.dateFromFields(V,m6(O,D)),...w$(V,D)},NZ(V.offset),U,H)})($(X),Z(Q),W,Y,z),Q,X)}function vj($,Z,J,W,Y){let j=W0(Y);return Y0(((z,X,Q,G)=>{let K=L3(z,X,Q,Z1,R1),B=v(G);return A1({...z.dateFromFields(K,m6(G,B)),...w$(K,B)})})($(Z.calendar),J,W,j))}function gj($,Z,J,W,Y){let j=W0(Y);return((z,X,Q,G)=>{let K=L3(z,X,Q,Z1);return z.dateFromFields(K,G)})($(Z.calendar),J,W,j)}function mj($,Z,J,W,Y){let j=W0(Y);return _$(((z,X,Q,G)=>{let K=L3(z,X,Q,f7);return z.yearMonthFromFields(K,G)})($(Z.calendar),J,W,j))}function hj($,Z,J,W,Y){let j=W0(Y);return((z,X,Q,G)=>{let K=L3(z,X,Q,Z1);return z.monthDayFromFields(K,G)})($(Z.calendar),J,W,j)}function pj($,Z,J){return $1(((W,Y,j)=>{let z=v(j);return w$({...m0($2,W),...Q1(Y,$2)},z)})($,Z,J))}function cj($,Z){return o((J=$,W=Z,MZ({...J,...Q1(W,R7)})));var J,W}function L3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=Q1(Z,z,j),Q=Q1(J,z);return X=$.mergeFields(X,Q),Q1(X,z,[])}function L7($,Z){let J=W$($,Z,hz);return $.monthDayFromFields(J)}function H7($,Z,J){let W=W$($,Z,mz);return $.yearMonthFromFields(W,J)}function dj($,Z,J,W,Y){Z=m0(J=$.fields(J),Z),W=Q1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=Q1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function l8($,Z){let{era:J,eraYear:W,year:Y}=Z,j=t8($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(KB);if(!j)throw RangeError(GB);let z=j[J];if(z===void 0)throw RangeError(BB(J));let X=Aj(W,z);if(Y!==void 0&&Y!==X)throw RangeError(FB);Y=X}else if(Y===void 0)throw TypeError(VB(j));return Y}function i8($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,Q,G,K)=>{let B=X.U(G),[F,O]=Sj(Q),V=C6(F,O,B);if(O){let D=Ej(X);if(D===void 0)throw RangeError(W3);if(D>0){if(V>D)throw RangeError(W3);if(B===void 0){if(K===1)throw RangeError(W3);V--}}else{if(V!==-D)throw RangeError(W3);if(B===void 0&&K===1)throw RangeError(W3)}}return V})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(Az);Y=z,W=1}else if(Y===void 0)throw TypeError(OB);return s0("month",Y,1,$.L(J),W)}function k5($,Z,J,W,Y){return k0(Z,"day",1,$.j(W,J),Y)}function s8($,Z,J,W){let Y=0,j=[];for(let z of J)Z[z]!==void 0?Y=1:j.push(z);if(Object.assign($,Z),Y)for(let z of W||j)delete $[z]}function uj($){return V0(u0(w6(b6($))))}function lj($,Z,J,W,Y=k){return U0(u0(w6(b6(J))),Z(W),$(Y))}function ij($,Z,J,W,Y=0,j=0,z=0,X=0,Q=0,G=0,K=k){return Y0(A1(y6(r0(N0,LZ(B4,[Z,J,W,Y,j,z,X,Q,G])))),$(K))}function sj($,Z,J,W,Y=k){return j0(o1(S$(r0(N0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function nj($,Z,J,W=k,Y=1){let j=N0(Z),z=N0(J),X=$(W);return _$(V2(S$({isoYear:j,isoMonth:z,isoDay:N0(Y)})),X)}function oj($,Z,J,W=k,Y=UZ){let j=N0(Z),z=N0(J),X=$(W);return T6(o1(S$({isoYear:N0(Y),isoMonth:j,isoDay:z})),X)}function aj($=0,Z=0,J=0,W=0,Y=0,j=0){return $1(v6(r0(N0,LZ(J1,[$,Z,J,W,Y,j])),1))}function rj($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,Q=0,G=0){return o(MZ(r0(ZY,LZ(m,[$,Z,J,W,Y,j,z,X,Q,G]))))}function I7($,Z,J=k){return U0($.epochNanoseconds,Z,J)}function tj($){return V0($.epochNanoseconds)}function P7($,Z){return Y0(S0(Z,$))}function M7($,Z){return j0(S0(Z,$))}function ej($,Z,J){return H7($(Z.calendar),J)}function $z($,Z,J){return L7($(Z.calendar),J)}function T7($,Z){return $1(S0(Z,$))}function Zz($,Z,J,W){let Y=((j,z,X,Q)=>{let G=L2(Q);return g0(j(z),X,G)})($,J,Z,W);return U0(u0(Y),J,Z.calendar)}function Jz($,Z,J){let W=$(Z.calendar);return _$({...Z,...H7(W,J)})}function Wz($,Z,J){return L7($(Z.calendar),J)}function Yz($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):a0;return U0(g0(J(j),{...W,...X}),j,W.calendar)}function jz($,Z=a0){return Y0(A1({...$,...Z}))}function zz($,Z,J){return H7($(Z.calendar),J)}function Xz($,Z,J){return L7($(Z.calendar),J)}function Qz($,Z,J,W){return((Y,j,z)=>dj(Y,j,mz,S1(z),T3))($(Z.calendar),J,W)}function Gz($,Z,J,W){return((Y,j,z)=>dj(Y,j,hz,S1(z),K4))($(Z.calendar),J,W)}function Kz($,Z,J,W,Y){let j=S1(Y),z=Z(j.plainDate),X=$(j.timeZone);return U0(g0(J(X),{...z,...W}),X,z.calendar)}function Fz($,Z){return Y0(A1({...$,...Z}))}function Bz($){return V0(u0(DZ($,o0)))}function Vz($){return V0(u0(DZ($,K1)))}function Dz($){return V0(u0(w6(b6($),q$)))}function Oz($){return V0(u0(w6(b6($))))}function Uz($,Z,J=a0){let W=Z.timeZone,Y=$(W),j={...S0(Z,Y),...J};return U0(f$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function Lz($,Z,J){let W=Z.timeZone,Y=$(W),j={...S0(Z,Y),...J},z=Mz(Z.calendar,J.calendar);return U0(f$(Y,j,j.offsetNanoseconds,2),W,z)}function Hz($,Z=a0){return Y0({...$,...Z})}function Iz($,Z){return Y0({...$,...Z},Mz($.calendar,Z.calendar))}function j4($,Z){return{...$,calendar:Z}}function Pz($,Z){return{...$,timeZone:Z}}function Mz($,Z){if($===Z)return $;let J=D0($),W=D0(Z);if(J===W||J===k)return Z;if(W===k)return $;throw RangeError(S7)}function $B($,Z){return(J)=>J===k?$:J===F4||J===OZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),VV(J))}function k$($,Z,J){let W=new Set(J);return(Y)=>(((j,z)=>{for(let X of z)if(X in j)return 1;return 0})(Y=Y2(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=g$,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function E1($,Z=N7){let[J,,,W]=$;return(Y,j=kV,...z)=>{let X=Z(W&&W(...z),Y,j,J),Q=X.resolvedOptions();return[X,...ZB($,Q,z)]}}function N7($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(SB);J.timeZone=$}return new Y$(Z,J)}function ZB($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,Q)=>{if((Q||z!==k)&&z!==X)throw RangeError(S7)})(D0(j.calendar),Z.calendar,Y),W(j,Z)))}function xZ($){let Z=H3();return $$(Z,$.getOffsetNanosecondsFor(Z))}function H3(){return DZ(Date.now(),K1)}function f1(){return m5||(m5=new Y$().resolvedOptions().timeZone)}var JB=($,Z)=>`Non-integer ${$}: ${Z}`,WB=($,Z)=>`Non-positive ${$}: ${Z}`,YB=($,Z)=>`Non-finite ${$}: ${Z}`,jB=($)=>`Cannot convert bigint to ${$}`,zB=($)=>`Invalid bigint: ${$}`,XB="Cannot convert Symbol to string",Tz="Invalid object",Nz=($,Z,J,W,Y)=>Y?Nz($,Y[Z],Y[J],Y[W]):I3($,Z)+`; must be between ${J}-${W}`,I3=($,Z)=>`Invalid ${$}: ${Z}`,_7=($)=>`Missing ${$}`,x7=($)=>`Invalid field ${$}`,QB=($)=>`Duplicate field ${$}`,_z=($)=>"No valid fields: "+$.join(),xz="Invalid bag",Cz=($,Z,J)=>I3($,Z)+"; must be "+Object.keys(J).join(),Sz="Cannot use valueOf",C7="Invalid calling context",GB="Forbidden era/eraYear",KB="Mismatching era/eraYear",FB="Mismatching year/eraYear",BB=($)=>`Invalid era: ${$}`,VB=($)=>"Missing year"+($?"/era/eraYear":""),DB=($)=>`Invalid monthCode: ${$}`,Az="Mismatching month/monthCode",OB="Missing month/monthCode",q5="Cannot guess year",W3="Invalid leap month",Ez="Invalid protocol",P3="Invalid protocol results",S7="Mismatching Calendars",UB=($)=>`Invalid Calendar: ${$}`,fz="Mismatching TimeZones",LB="Forbidden ICU TimeZone",HB="Out-of-bounds offset",IB="Out-of-bounds TimeZone gap",PB="Invalid TimeZone offset",MB="Ambiguous offset",z4="Out-of-bounds date",TB="Out-of-bounds duration",NB="Cannot mix duration signs",X4="Missing relativeTo",_B="Cannot use large units",xB="Required smallestUnit or largestUnit",CB="smallestUnit > largestUnit",q0=($)=>`Cannot parse: ${$}`,C1=($)=>`Invalid substring: ${$}`,Rz=($)=>`Cannot format ${$}`,bz="Mismatching types for formatting",SB="Cannot specify TimeZone",wz=w(F3,($,Z)=>Z),CZ=w(F3,($,Z,J)=>J),n0=w(I6,2),e8={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},M3=Object.keys(e8),y0=86400000,kz=1000,q$=1000,K1=1e6,o0=1e9,Q4=60000000000,G4=3600000000000,c=86400000000000,G1=[1,q$,K1,o0,Q4,G4,c],R1=M3.slice(0,6),$2=B3(R1),qz=["offset"],yz=["timeZone"],vz=R1.concat(qz),gz=vz.concat(yz),Z2=["era","eraYear"],AB=Z2.concat(["year"]),K4=["year"],A7=["monthCode"],E7=["month"].concat(A7),T3=["day"],f7=E7.concat(K4),mz=A7.concat(K4),Z1=T3.concat(f7),EB=T3.concat(E7),hz=T3.concat(A7),pz=CZ(R1,0),k="iso8601",F4="gregory",OZ="japanese",cz={[F4]:{bce:-1,ce:0},[OZ]:{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}},fB={chinese:13,dangi:13,hebrew:-6},t=w(R6,"string"),dz=w(R6,"boolean"),RB=w(R6,"number"),uz=w(R6,"function"),m=M3.map(($)=>$+"s"),R7=B3(m),bB=m.slice(0,6),lz=m.slice(6),wB=lz.slice(1),kB=wz(m),O0=CZ(m,0),b7=CZ(bB,0),w7=w(u5,m),J1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],k7=["isoDay","isoMonth","isoYear"],B4=J1.concat(k7),q7=B3(k7),iz=B3(J1),sz=B3(B4),a0=CZ(iz,0),qB=w(u5,B4),Y$=Intl.DateTimeFormat,nz="en-GB",y7=1e8,yB=y7*y0,vB=[y7,0],gB=[-y7,0],G3=275760,K3=-271821,mB=1970,UZ=1972,_1=12,hB=HZ(1868,9,8),pB=v0(pF,WeakMap),S6="smallestUnit",J2="unit",j3="roundingIncrement",n8="fractionalSecondDigits",oz="relativeTo",az={constrain:0,reject:1},cB=Object.keys(az),dB={compatible:0,reject:1,earlier:2,later:3},uB={reject:0,use:1,prefer:2,ignore:3},lB={auto:0,never:1,critical:2,always:3},iB={auto:0,never:1,critical:2},sB={auto:0,never:1},nB={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},N3=w(N2,S6),v7=w(N2,"largestUnit"),oB=w(N2,J2),rz=w(A$,"overflow",az),tz=w(A$,"disambiguation",dB),aB=w(A$,"offset",uB),g7=w(A$,"calendarName",lB),rB=w(A$,"timeZoneName",iB),tB=w(A$,"offset",sB),_3=w(A$,"roundingMode",nB),SZ="PlainYearMonth",AZ="PlainMonthDay",y$="PlainDate",v$="PlainDateTime",V4="PlainTime",b1="ZonedDateTime",D4="Instant",O4="Duration",eB=[Math.floor,($)=>V6($)?Math.floor($):Math.round($),Math.ceil,($)=>V6($)?Math.ceil($):Math.round($),Math.trunc,($)=>V6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>V6($)?($=Math.trunc($)||0)+$%2:Math.round($)],g$="UTC",L6=5184000,$V=M6(1847),ZV=M6(new Date().getUTCFullYear()+10),JV=/0+$/,S0=v0(sF,WeakMap),y5=4294967295,U4=v0(($)=>{let Z=J7($);return typeof Z=="object"?new $X(Z):new ez(Z||0)});class ez{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[D2($,this.v)]}l(){}}class $X{constructor($){this.$=((Z)=>{function J(Q){let G=o8(Q,z,X),[K,B]=f5(G),F=Y(K),O=Y(B);return F===O?F:W(j(K,B),F,O,Q)}function W(Q,G,K,B){let F,O;for(;(B===void 0||(F=B<Q[0]?G:B>=Q[1]?K:void 0)===void 0)&&(O=Q[1]-Q[0]);){let V=Q[0]+Math.floor(O/2);Z(V)===K?Q[1]=V:Q[0]=V+1}return F}let Y=v0(Z),j=v0(nF),z=$V,X=ZV;return{G(Q){let G=J(Q-86400),K=J(Q+86400),B=Q-G,F=Q-K;if(G===K)return[B];let O=J(B);return O===J(F)?[Q-O]:G>K?[B,F]:[]},V:J,l(Q,G){let K=o8(Q,z,X),[B,F]=f5(K),O=L6*G,V=G<0?()=>F>z||(z=K,0):()=>B<X||(X=K,0);for(;V();){let D=Y(B),U=Y(F);if(D!==U){let H=j(B,F);W(H,D,U);let M=H[0];if((n1(M,Q)||1)===G)return M}B+=O,F+=O}}}})(((Z)=>(J)=>{let W=B2(Z,J*kz);return M6(Nj(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(YY($))*o0}getPossibleInstantsFor($){let[Z,J]=[M6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*K1+W.isoMicrosecond*q$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>u0(VZ(DZ(Y,o0),J)))}l($,Z){let[J,W]=jY($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return DZ(Y,o0)}}var m7="([+\u2212-])",H6="(?:[.,](\\d{1,9}))?",ZX=`(?:(?:${m7}(\\d{6}))|(\\d{4}))-?(\\d{2})`,h7="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+H6+")?)?",p7=m7+h7,WV=ZX+"-?(\\d{2})(?:[T ]"+h7+"(Z|"+p7+")?)?",JX="\\[(!?)([^\\]]*)\\]",L4=`((?:${JX}){0,9})`,YV=_Z(ZX+L4),jV=_Z("(?:--)?(\\d{2})-?(\\d{2})"+L4),zV=_Z(WV+L4),XV=_Z("T?"+h7+"(?:"+p7+")?"+L4),QV=_Z(p7),GV=new RegExp(JX,"g"),KV=_Z(`${m7}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${H6}H)?(?:(\\d+)${H6}M)?(?:(\\d+)${H6}S)?)?`),FV=v0(($)=>new Y$(nz,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),BV=/^(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$/,VV=v0(rF),c7=v0(($)=>new Y$(nz,{calendar:$,timeZone:g$,era:"short",year:"numeric",month:"short",day:"numeric"})),DV=/^M(\d{2})(L?)$/,OV={era:P6,eraYear:N0,year:N0,month:C5,monthCode:P6,day:C5},UV=CZ(R1,N0),LV=CZ(m,ZY),v5=Object.assign({},OV,UV,LV,{offset:P6}),HV=w(hF,R1,J1),g5={dateAdd($,Z,J){let W=v(J),Y,{years:j,months:z,weeks:X,days:Q}=Z;if(Q+=F0(Z,5)[0],j||z)Y=((G,K,B,F,O)=>{let[V,D,U]=G.h(K);if(B){let[H,M]=G.I(V,D);V+=B,D=C6(H,M,G.U(V)),D=s0("month",D,1,G.L(V),O)}return F&&([V,D]=G._(V,D,F)),U=s0("day",U,1,G.j(V,D),O),G.q(V,D,U)})(this,$,j,z,W);else{if(!X&&!Q)return $;Y=C0($)}return Y+=(7*X+Q)*y0,o1(q6(Y))},dateUntil($,Z,J){if(J<=7){let Q=0,G=Mj({...$,...a0},{...Z,...a0});return J===7&&([Q,G]=r1(G,7)),{...O0,weeks:Q,days:G}}let W=this.h($),Y=this.h(Z),[j,z,X]=((Q,G,K,B,F,O,V)=>{let D=F-G,U=O-K,H=V-B;if(D||U){let M=Math.sign(D||U),P=Q.j(F,O),x=0;if(Math.sign(H)===-M){let E=P;[F,O]=Q._(F,O,-M),D=F-G,U=O-K,P=Q.j(F,O),x=M<0?-E:P}if(H=V-Math.min(B,P)+x,D){let[E,f]=Q.I(G,K),[S,b]=Q.I(F,O);if(U=S-E||Number(b)-Number(f),Math.sign(U)===-M){let I=M<0&&-Q.L(F);D=(F-=M)-G,U=O-C6(E,f,Q.U(F))+(I||Q.L(F))}}}return[D,U,H]})(this,...W,...Y);return J===8&&(z+=this.J(j,W[0]),j=0),{...O0,years:j,months:z,days:X}},dateFromFields($,Z){let J=v(Z),W=l8(this,$),Y=i8(this,$,W,J),j=k5(this,$,Y,W,J);return j0(o1(this.P(W,Y,j)),this.id||k)},yearMonthFromFields($,Z){let J=v(Z),W=l8(this,$),Y=i8(this,$,W,J);return _$(V2(this.P(W,Y,1)),this.id||k)},monthDayFromFields($,Z){let J=v(Z),W=!this.id,{monthCode:Y,year:j,month:z}=$,X,Q,G,K,B;if(Y!==void 0){[X,Q]=Sj(Y),B=h5($,"day");let F=this.N(X,Q,B);if(!F)throw RangeError(q5);if([G,K]=F,z!==void 0&&z!==K)throw RangeError(Az);W&&(K=s0("month",K,1,_1,1),B=s0("day",B,1,O2(j!==void 0?j:G,K),J))}else{G=j===void 0&&W?UZ:l8(this,$),K=i8(this,$,G,J),B=k5(this,$,K,G,J);let F=this.U(G);Q=K===F,X=r8(K,F);let O=this.N(X,Q,B);if(!O)throw RangeError(q5);[G,K]=O}return T6(o1(this.P(G,K,B)),this.id||k)},fields($){return t8(this)&&$.includes("year")?[...$,...Z2]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return s8(J,Z,E7),t8(this)&&(s8(J,Z,AB),this.id===OZ&&s8(J,Z,EB,Z2)),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:V7,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,Y]=this.I(Z,J);return((j,z)=>"M"+n0(j)+(z?"L":""))(W,Y)},dayOfWeek:KY,daysInWeek(){return 7}},IV={dayOfYear:V7,h:XY,q:HZ},PV=Object.assign({},IV,{weekOfYear:xj,yearOfWeek:Cj,R($){function Z(O){return(7-O<W?7:0)-O}function J(O){let V=GY(F+O),D=O||1,U=Z(Y3(Q+V*D,7));return K=(V+(U-G)*D)/7}let W=this.id?1:4,Y=KY($),j=this.dayOfYear($),z=Y3(Y-1,7),X=j-1,Q=Y3(z-X,7),G=Z(Q),K,B=Math.floor((X-G)/7)+1,F=$.isoYear;return B?B>J(0)&&(B=1,F++):(B=J(-1),F--),[B,F,K]}}),MV={dayOfYear:V7,h:a8,q:Q3,weekOfYear:xj,yearOfWeek:Cj,R(){return[]}},EZ=$B(Object.assign({},g5,PV,{h:XY,ee($){return this.id===F4?FY($):this.id===OZ?pB($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[UZ,$]},K:U2,U(){},L:QY,J:($)=>$*_1,j:O2,X:GY,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:HZ,_:($,Z,J)=>($+=E6(J,_1),(Z+=z2(J,_1))<1?($--,Z+=_1):Z>_1&&($++,Z-=_1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},g5,MV,{h:a8,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=D6.call(this,$);return[r8(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=a8.call(this,{isoYear:UZ,isoMonth:_1,isoDay:31}),z=D6.call(this,W),X=Y===z;(n1($,r8(Y,z))||n1(Number(Z),Number(X))||n1(J,j))===1&&W--;for(let Q=0;Q<100;Q++){let G=W-Q,K=D6.call(this,G),B=C6($,Z,K);if(Z===(B===K)&&J<=b5.call(this,G,B))return[G,B]}},K($){let Z=O6.call(this,$);return Z>O6.call(this,$-1)&&Z>O6.call(this,$+1)},U:D6,L:U6,J($,Z){let J=Z+$,W=Math.sign($),Y=W<0?-1:0,j=0;for(let z=Z;z!==J;z+=W)j+=U6.call(this,z+Y);return j},j:b5,X:O6,P($,Z,J){return q6(Q3.call(this,$,Z,J))},q:Q3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(z4);if(J<0)for(;Z<1;)Z+=U6.call(this,--$);else{let W;for(;Z>(W=U6.call(this,$));)Z-=W,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:J}=this.O($),{C:W}=this.B(Z);return W[J]+1},day($){return this.O($).day}})),a1="numeric",fZ=["timeZoneName"],WX={month:a1,day:a1},d7={year:a1,month:a1},u7=Object.assign({},d7,{day:a1}),l7={hour:a1,minute:a1,second:a1},i7=Object.assign({},u7,l7),TV=Object.assign({},i7,{timeZoneName:"short"}),NV=Object.keys(d7),_V=Object.keys(WX),xV=Object.keys(u7),CV=Object.keys(l7),s7=["dateStyle"],SV=NV.concat(s7),AV=_V.concat(s7),n7=xV.concat(s7,["weekday"]),x3=CV.concat(["dayPeriod","timeStyle"]),o7=n7.concat(x3),EV=o7.concat(fZ),fV=fZ.concat(x3),RV=fZ.concat(n7),bV=fZ.concat(["day","weekday"],x3),wV=fZ.concat(["year","weekday"],x3),kV={},a7=[k$(o7,i7),h6],YX=[k$(EV,TV),h6,0,($,Z)=>{let J=D0($.timeZone);if(Z&&D0(Z.timeZone)!==J)throw RangeError(fz);return J}],r7=[k$(o7,i7,fZ),C0],t7=[k$(n7,u7,fV),C0],e7=[k$(x3,l7,RV),($)=>t1($)/K1],$J=[k$(SV,d7,bV),C0,1],ZJ=[k$(AV,WX,wV),C0,1],m5;function V1($,Z,J,W,Y){function j(...Q){if(!(this instanceof j))throw TypeError(C7);QX(this,Z(...Q))}function z(Q,G){return Object.defineProperties(function(...K){return Q.call(this,X(this),...K)},W2(G))}function X(Q){let G=I0(Q);if(!G||G.branding!==$)throw TypeError(C7);return G}return Object.defineProperties(j.prototype,{...p5(r0(z,J)),...C$(r0(z,W)),...A6("Temporal."+$)}),Object.defineProperties(j,{...C$(Y),...W2($)}),[j,(Q)=>{let G=Object.create(j.prototype);return QX(G,Q),G},X]}function FX($){return $=$.concat("id").sort(),(Z)=>{if(!c5(Z,$))throw TypeError(Ez);return Z}}function kZ($){if(I0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(xz);return $}function H4($,Z){let J={};for(let W in $)J[W]=({o:Y},j)=>{let z=I0(j)||{},{branding:X}=z,Q=X===y$||Z.includes(X)?z:f0(j);return Y[W](Q)};return J}function YJ($){let Z={};for(let J in $)Z[J]=(W)=>{let{calendar:Y}=W;return(j=Y,typeof j=="string"?EZ(j):(z=j,Object.assign(Object.create(aV),{i:z})))[J](W);var j,z};return Z}function G$(){throw TypeError(Sz)}function S3({calendar:$}){return typeof $=="string"?new VJ($):$}function jX($,Z){if(Z=W0(Z),B0($)){let W=I0($);if(W&&W.branding===AZ)return v(Z),W;let Y=DX($);return U7(x4(Y||k),!Y,$,Z)}let J=rY(EZ,$);return v(Z),J}function BX($,Z,J){return W=Z.call($,E0(V0(J))),v2(V3(W));var W}function I4($,Z=HX){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=w(Z[Y],$,uz($[Y]));return W}function d($,Z){return typeof $=="string"?U4($):I4($,Z)}function X0($){return d($,WJ)}function F1($){if(B0($)){let Z=I0($);if(Z)switch(Z.branding){case D4:return Z;case b1:return V0(Z.epochNanoseconds)}}return iY($)}function zX($,Z,J){let W=Z.l(F1(J).epochNanoseconds,$);return W?E0(V0(W)):null}function i($){return B0($)?(I0($)||{}).timeZone||JD($):((Z)=>e6(Zj(t(Z))))($)}function j$($,Z){if(B0($)){let J=I0($)||{};switch(J.branding){case V4:return v(Z),J;case v$:return v(Z),$1(J);case b1:return v(Z),T7(X0,J)}return kj($,Z)}return v(Z),tY($)}function jJ($){return $===void 0?void 0:j$($)}function RZ($,Z){if(Z=W0(Z),B0($)){let W=I0($);return W&&W.branding===SZ?(v(Z),W):O7(N4(A3($)),$,Z)}let J=aY(EZ,$);return v(Z),J}function z$($,Z){if(Z=W0(Z),B0($)){let W=I0($)||{};switch(W.branding){case v$:return v(Z),W;case y$:return v(Z),Y0({...W,...a0});case b1:return v(Z),P7(X0,W)}return wj(_4(A3($)),$,Z)}let J=oY($);return v(Z),J}function f0($,Z){if(Z=W0(Z),B0($)){let W=I0($)||{};switch(W.branding){case y$:return v(Z),W;case v$:return v(Z),j0(W);case b1:return v(Z),M7(X0,W)}return D7(_4(A3($)),$,Z)}let J=r6($);return v(Z),J}function VX($,Z,J){return t0(Z.call($,$0(j0(J,$))))}function D1($){return(Z)=>typeof Z=="string"?EZ(Z):((J,W)=>{let Y=Object.keys(W).sort(),j={};for(let z of Y)j[z]=w(W[z],J,J[z]);return j})(Z,$)}function e($){if(B0($)){let Z=I0($);return Z&&Z.branding===O4?Z:qj($)}return eY($)}function C3($){if($!==void 0){if(B0($)){let Z=I0($)||{};switch(Z.branding){case b1:case y$:return Z;case v$:return j0(Z)}let J=A3($);return{...Rj(i,d,_4(J),$),calendar:J}}return sY($)}}function A3($){return DX($)||k}function DX($){let{calendar:Z}=$;if(Z!==void 0)return H0(Z)}function H0($){return B0($)?(I0($)||{}).calendar||LD($):((Z)=>U3($j(t(Z))))($)}function bZ($,Z){if(Z=W0(Z),B0($)){let J=I0($);if(J&&J.branding===b1)return D3(Z),J;let W=A3($);return bj(i,d,_4(W),W,$,Z)}return nY($,Z)}function XX($){return r0((Z)=>(J)=>Z(JJ(J)),$)}function JJ($){return S0($,X0)}function qV(){let $=Y$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(Y$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);DJ.set(this,((z,X={})=>{let Q=new Y$(z,X),G=Q.resolvedOptions(),K=G.locale,B=m0(Object.keys(X),G),F=v0(gV),O=(...V)=>{let D,U=V.map((H,M)=>{let P=I0(H),x=(P||{}).branding;if(M&&D&&D!==x)throw TypeError(bz);return D=x,P});return D?F(D)(K,B,...U):[Q,...V]};return O.u=Q,O})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&yV(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||vV(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function yV($){return function(...Z){let J=DJ.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function vV($){return function(...Z){return DJ.get(this).u[$](...Z)}}function gV($){let Z=mV[$];if(!Z)throw TypeError(Rz($));return E1(Z,v0(N7))}var mV={Instant:a7,PlainDateTime:r7,PlainDate:t7,PlainTime:e7,PlainYearMonth:$J,PlainMonthDay:ZJ},hV=E1(a7),pV=E1(YX),cV=E1(r7),dV=E1(t7),uV=E1(e7),lV=E1($J),iV=E1(ZJ),zJ={era:o5,eraYear:X2,year:V3,month:t0,daysInMonth:t0,daysInYear:t0,inLeapYear:dz,monthsInYear:t0},M4={monthCode:t},XJ={day:t0},OX={dayOfWeek:t0,dayOfYear:t0,weekOfYear:a5,yearOfWeek:X2,daysInWeek:t0},UX=Object.assign({},zJ,M4,XJ,OX),P4=new WeakMap,I0=P4.get.bind(P4),QX=P4.set.bind(P4),sV={...H4(zJ,[SZ]),...H4(OX,[]),...H4(M4,[SZ,AZ]),...H4(XJ,[AZ])},QJ=YJ(UX),nV=YJ({...zJ,...M4}),oV=YJ({...M4,...XJ}),E3={calendarId:($)=>D0($.calendar)},aV=r0(($,Z)=>function(J){let{i:W}=this;return $(W[Z]($0(j0(J,W))))},UX),rV=F3(($)=>(Z)=>Z[$],m.concat("sign")),GJ=F3(($,Z)=>(J)=>J[J1[Z]],R1),LX={epochSeconds:HY,epochMilliseconds:h6,epochMicroseconds:IY,epochNanoseconds:PY},f3=w(Y2,new Set(["branding"])),[tV,wZ,eV]=V1(AZ,w(oj,H0),{...E3,...oV},{getISOFields:f3,getCalendar:S3,with($,Z,J){return wZ(hj(DD,$,this,kZ(Z),J))},equals:($,Z)=>Oj($,jX(Z)),toPlainDate($,Z){return $0(Gz(R3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=iV(Z,J,$);return W.format(Y)},toString:b2,toJSON:($)=>b2($),valueOf:G$},{from:($,Z)=>wZ(jX($,Z))}),HX={getOffsetNanosecondsFor:BX,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,L0(Y0(J,k)))].map((j)=>ZD(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(x0),g2(d0(c0(W[0],W[Y-1])))),W}},WJ={getOffsetNanosecondsFor:BX},[$D,E0,ZD]=V1(D4,uj,LX,{add:($,Z)=>E0(m2(0,$,e(Z))),subtract:($,Z)=>E0(m2(1,$,e(Z))),until:($,Z,J)=>u(z7(0,$,F1(Z),J)),since:($,Z,J)=>u(z7(1,$,F1(Z),J)),round:($,Z)=>E0(NY($,Z)),equals:($,Z)=>Kj($,F1(Z)),toZonedDateTime($,Z){let J=S1(Z);return z0(I7($,i(J.timeZone),H0(J.calendar)))},toZonedDateTimeISO:($,Z)=>z0(I7($,i(Z))),toLocaleString($,Z,J){let[W,Y]=hV(Z,J,$);return W.format(Y)},toString:($,Z)=>S2(i,X0,$,Z),toJSON:($)=>S2(i,X0,$),valueOf:G$},{from:($)=>E0(F1($)),fromEpochSeconds:($)=>E0(Bz($)),fromEpochMilliseconds:($)=>E0(Vz($)),fromEpochMicroseconds:($)=>E0(Dz($)),fromEpochNanoseconds:($)=>E0(Oz($)),compare:($,Z)=>W7(F1($),F1(Z))}),[T4,KP]=V1("TimeZone",($)=>{let Z=Qj($);return{branding:"TimeZone",id:Z,o:U4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(z$(Z)).map((J)=>E0(V0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(F1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=F1(Z).epochNanoseconds,W=I4(this,WJ).getOffsetNanosecondsFor(J);return E$(W)},getPlainDateTimeFor($,Z,J=k){let W=F1(Z).epochNanoseconds,Y=I4(this,WJ).getOffsetNanosecondsFor(W);return L0(Y0($$(W,Y),H0(J)))},getInstantFor($,Z,J){let W=z$(Z),Y=L2(J),j=I4(this);return E0(V0(g0(j,W,Y)))},getNextTransition:({o:$},Z)=>zX(1,$,Z),getPreviousTransition:({o:$},Z)=>zX(-1,$,Z),equals($,Z){return!!Z4(this,i(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=i($);return typeof Z=="string"?new T4(Z):Z}}),JD=FX(Object.keys(HX)),[WD,X$]=V1(V4,aj,GJ,{getISOFields:f3,with($,Z,J){return X$(pj(this,kZ(Z),J))},add:($,Z)=>X$(u2(0,$,e(Z))),subtract:($,Z)=>X$(u2(1,$,e(Z))),until:($,Z,J)=>u(F7(0,$,j$(Z),J)),since:($,Z,J)=>u(F7(1,$,j$(Z),J)),round:($,Z)=>X$(CY($,Z)),equals:($,Z)=>Uj($,j$(Z)),toZonedDateTime:($,Z)=>z0(Kz(i,f0,d,$,Z)),toPlainDateTime:($,Z)=>L0(Fz($,f0(Z))),toLocaleString($,Z,J){let[W,Y]=uV(Z,J,$);return W.format(Y)},toString:w2,toJSON:($)=>w2($),valueOf:G$},{from:($,Z)=>X$(j$($,Z)),compare:($,Z)=>$4(j$($),j$(Z))}),[YD,Q$,jD]=V1(SZ,w(nj,H0),{...E3,...nV},{getISOFields:f3,getCalendar:S3,with($,Z,J){return Q$(mj(VD,$,this,kZ(Z),J))},add:($,Z,J)=>Q$(d2(GX,0,$,e(Z),J)),subtract:($,Z,J)=>Q$(d2(GX,1,$,e(Z),J)),until:($,Z,J)=>u(K7(KX,0,$,RZ(Z),J)),since:($,Z,J)=>u(K7(KX,1,$,RZ(Z),J)),equals:($,Z)=>Dj($,RZ(Z)),toPlainDate($,Z){return $0(Qz(R3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=lV(Z,J,$);return W.format(Y)},toString:R2,toJSON:($)=>R2($),valueOf:G$},{from:($,Z)=>Q$(RZ($,Z)),compare:($,Z)=>b$(RZ($),RZ(Z))}),[zD,L0]=V1(v$,w(ij,H0),{...E3,...QJ,...GJ},{getISOFields:f3,getCalendar:S3,with($,Z,J){return L0(vj(R3,$,this,kZ(Z),J))},withCalendar:($,Z)=>L0(j4($,H0(Z))),withPlainDate:($,Z)=>L0(Iz($,f0(Z))),withPlainTime:($,Z)=>L0(Hz($,jJ(Z))),add:($,Z,J)=>L0(p2(m$,0,$,e(Z),J)),subtract:($,Z,J)=>L0(p2(m$,1,$,e(Z),J)),until:($,Z,J)=>u(Q7(B1,0,$,z$(Z),J)),since:($,Z,J)=>u(Q7(B1,1,$,z$(Z),J)),round:($,Z)=>L0(xY($,Z)),equals:($,Z)=>Bj($,z$(Z)),toZonedDateTime:($,Z,J)=>z0(Zz(d,$,i(Z),J)),toPlainDate:($)=>$0(j0($)),toPlainTime:($)=>X$($1($)),toPlainYearMonth($){return Q$(Jz(N4,$,this))},toPlainMonthDay($){return wZ(Wz(x4,$,this))},toLocaleString($,Z,J){let[W,Y]=cV(Z,J,$);return W.format(Y)},toString:E2,toJSON:($)=>E2($),valueOf:G$},{from:($,Z)=>L0(z$($,Z)),compare:($,Z)=>j7(z$($),z$(Z))}),[XD,$0,IX]=V1(y$,w(sj,H0),{...E3,...QJ},{getISOFields:f3,getCalendar:S3,with($,Z,J){return $0(gj(R3,$,this,kZ(Z),J))},withCalendar:($,Z)=>$0(j4($,H0(Z))),add:($,Z,J)=>$0(c2(m$,0,$,e(Z),J)),subtract:($,Z,J)=>$0(c2(m$,1,$,e(Z),J)),until:($,Z,J)=>u(G7(B1,0,$,f0(Z),J)),since:($,Z,J)=>u(G7(B1,1,$,f0(Z),J)),equals:($,Z)=>Vj($,f0(Z)),toZonedDateTime($,Z){let J=!B0(Z)||Z instanceof T4?{timeZone:Z}:Z;return z0(Yz(i,j$,d,$,J))},toPlainDateTime:($,Z)=>L0(jz($,jJ(Z))),toPlainYearMonth($){return Q$(zz(N4,$,this))},toPlainMonthDay($){return wZ(Xz(x4,$,this))},toLocaleString($,Z,J){let[W,Y]=dV(Z,J,$);return W.format(Y)},toString:f2,toJSON:($)=>f2($),valueOf:G$},{from:($,Z)=>$0(f0($,Z)),compare:($,Z)=>b$(f0($),f0(Z))}),KJ={fields($,Z,J){return[...Z.call($,J)]}},PX=Object.assign({dateFromFields($,Z,J,W){return IX(Z.call($,Object.assign(Object.create(null),J),W))}},KJ),MX=Object.assign({yearMonthFromFields($,Z,J,W){return jD(Z.call($,Object.assign(Object.create(null),J),W))}},KJ),TX=Object.assign({monthDayFromFields($,Z,J,W){return eV(Z.call($,Object.assign(Object.create(null),J),W))}},KJ),FJ={mergeFields($,Z,J,W){return S1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},QD=Object.assign({},PX,FJ),GD=Object.assign({},MX,FJ),KD=Object.assign({},TX,FJ),BJ={dateAdd($,Z,J,W,Y){return IX(Z.call($,$0(j0(J,$)),u(o(W)),Y))}},NX=Object.assign({},BJ,{dateUntil($,Z,J,W,Y,j){return UD(Z.call($,$0(j0(J,$)),$0(j0(W,$)),Object.assign(Object.create(null),j,{largestUnit:M3[Y]})))}}),FD=Object.assign({},BJ,{day:VX}),BD=Object.assign({},NX,{day:VX}),N4=D1(MX),_4=D1(PX),x4=D1(TX),VD=D1(GD),R3=D1(QD),DD=D1(KD),m$=D1(BJ),B1=D1(NX),GX=D1(FD),KX=D1(BD),[OD,u,UD]=V1(O4,rj,{...rV,blank:dY},{with:($,Z)=>u(cj($,Z)),negated:($)=>u(o6($)),abs:($)=>u(cY($)),add:($,Z,J)=>u(o2(C3,B1,d,0,$,e(Z),J)),subtract:($,Z,J)=>u(o2(C3,B1,d,1,$,e(Z),J)),round:($,Z)=>u(pY(C3,B1,d,$,Z)),total:($,Z)=>TY(C3,B1,d,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):u6($)},toString:u6,toJSON:($)=>u6($),valueOf:G$},{from:($)=>u(e($)),compare:($,Z,J)=>Gj(C3,m$,d,e($),e(Z),J)}),_X={toString:($)=>$.id,toJSON:($)=>$.id,...sV,dateAdd:({id:$,o:Z},J,W,Y)=>$0(j0(Z.dateAdd(f0(J),e(W),Y),$)),dateUntil:({o:$},Z,J,W)=>u(o($.dateUntil(f0(Z),f0(J),VY(W)))),dateFromFields:({id:$,o:Z},J,W)=>$0(D7(Z,J,W,n5($))),yearMonthFromFields:({id:$,o:Z},J,W)=>Q$(O7(Z,J,W,i5($))),monthDayFromFields:({id:$,o:Z},J,W)=>wZ(U7(Z,0,J,W,s5($))),fields({o:$},Z){let J=new Set(Z1),W=[];for(let Y of Z){if(t(Y),!J.has(Y))throw RangeError(x7(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(j2(Q2(Z)),j2(Q2(J)))},[VJ]=V1("Calendar",($)=>{let Z=_j($);return{branding:"Calendar",id:Z,o:EZ(Z)}},{id:($)=>$.id},_X,{from($){let Z=H0($);return typeof Z=="string"?new VJ(Z):Z}}),LD=FX(Object.keys(_X).slice(4)),[HD,z0]=V1(b1,w(lj,H0,i),{...LX,...E3,...XX(QJ),...XX(GJ),offset:($)=>E$(JJ($).offsetNanoseconds),offsetNanoseconds:($)=>JJ($).offsetNanoseconds,timeZoneId:($)=>D0($.timeZone),hoursInDay:($)=>SY(d,$)},{getISOFields:($)=>mY(X0,$),getCalendar:S3,getTimeZone:({timeZone:$})=>typeof $=="string"?new T4($):$,with($,Z,J){return z0(yj(R3,d,$,this,kZ(Z),J))},withCalendar:($,Z)=>z0(j4($,H0(Z))),withTimeZone:($,Z)=>z0(Pz($,i(Z))),withPlainDate:($,Z)=>z0(Lz(d,$,f0(Z))),withPlainTime:($,Z)=>z0(Uz(d,$,jJ(Z))),add:($,Z,J)=>z0(h2(m$,d,0,$,e(Z),J)),subtract:($,Z,J)=>z0(h2(m$,d,1,$,e(Z),J)),until:($,Z,J)=>u(o(X7(B1,d,0,$,bZ(Z),J))),since:($,Z,J)=>u(o(X7(B1,d,1,$,bZ(Z),J))),round:($,Z)=>z0(_Y(d,$,Z)),startOfDay:($)=>z0(AY(d,$)),equals:($,Z)=>Fj($,bZ(Z)),toInstant:($)=>E0(tj($)),toPlainDateTime:($)=>L0(P7(X0,$)),toPlainDate:($)=>$0(M7(X0,$)),toPlainTime:($)=>X$(T7(X0,$)),toPlainYearMonth($){return Q$(ej(N4,$,this))},toPlainMonthDay($){return wZ($z(x4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=pV(Z,J,$);return W.format(Y)},toString:($,Z)=>A2(X0,$,Z),toJSON:($)=>A2(X0,$),valueOf:G$},{from:($,Z)=>z0(bZ($,Z)),compare:($,Z)=>Y7(bZ($),bZ(Z))}),ID=Object.defineProperties({},{...A6("Temporal.Now"),...C$({timeZoneId:()=>f1(),instant:()=>E0(V0(H3())),zonedDateTime:($,Z=f1())=>z0(U0(H3(),i(Z),H0($))),zonedDateTimeISO:($=f1())=>z0(U0(H3(),i($),k)),plainDateTime:($,Z=f1())=>L0(Y0(xZ(X0(i(Z))),H0($))),plainDateTimeISO:($=f1())=>L0(Y0(xZ(X0(i($))),k)),plainDate:($,Z=f1())=>$0(j0(xZ(X0(i(Z))),H0($))),plainDateISO:($=f1())=>$0(j0(xZ(X0(i($))),k)),plainTimeISO:($=f1())=>X$($1(xZ(X0(i($)))))})}),qZ=Object.defineProperties({},{...A6("Temporal"),...C$({PlainYearMonth:YD,PlainMonthDay:tV,PlainDate:XD,PlainTime:WD,PlainDateTime:zD,ZonedDateTime:HD,Instant:$D,Calendar:VJ,TimeZone:T4,Duration:OD,Now:ID})}),PD=qV(),DJ=new WeakMap,MD=Object.defineProperties(Object.create(Intl),C$({DateTimeFormat:PD}));var C4="x-gemi-socket";var UP="gemi.v1",xX="/__gemi/socket",LP=/^[A-Za-z0-9_-]{1,32}$/,HP={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function TP($){return $}function CX(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:xX,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 TD,randomBytes as ND}from"crypto";function _D($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(TD("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var xD="__control",OJ=250,CD=1e4,SD=15000;class UJ{config;prefix;controlChannel;instanceId=ND(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??_D(),this.controlChannel=this.prefix+xD,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=b3((async()=>{await $.connect(),await $.subscribe(this.controlChannel,this.onMessage);let J=[...this.wanted];if(await Promise.all(J.map((W)=>$.subscribe(this.prefix+W,this.onMessage))),this.subscriber!==$)throw Error("Replaced.");for(let W of J)this.active.add(W);return $})(),SD,"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 (${SX(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(CD,OJ*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(OJ,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;b3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${SX(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??AD(Math.min(Z,OJ));await b3(J,Z,"subscribe").catch((W)=>{if(Date.now()>=$)throw W})}}sync($,Z){let W=(this.chains.get($)??Promise.resolve()).catch(()=>{}).then(()=>this.reconcile($,Z));this.chains.set($,W);let Y=()=>{if(this.chains.get($)===W)this.chains.delete($)};return W.then(Y,Y),W}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let Y=this.subscriber;this.active.delete($);try{await b3(Y.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(j){if(this.subscriber===Y)this.drop(Y);throw j}return}if(!Z)return;let W=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await b3(W.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(Y){if(this.subscriber===W)this.drop(W);throw Y}if(this.subscriber===W)this.active.add($)}onMessage=($,Z)=>{if(Z===this.controlChannel){this.onControl($);return}if(!Z.startsWith(this.prefix))return;this.deliver?.(Z.slice(this.prefix.length),$)};onControl($){let Z;try{Z=JSON.parse($)}catch{return}if(Z?.op!=="revoke"||Z.from===this.instanceId)return;let J=Z.r;if(J&&typeof J.user==="string")this.hooks?.onRevoke?.({user:J.user});else if(J&&typeof J.topic==="string")this.hooks?.onRevoke?.({topic:J.topic})}}function b3($,Z,J){let W;return Promise.race([$,new Promise((Y,j)=>{W=setTimeout(()=>j(Error(`Redis ${J} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(W))}function AD($){return new Promise((Z)=>setTimeout(Z,$))}function SX($){return $ instanceof Error?$.message:String($)}import{createHmac as ED,hkdfSync as fD,randomBytes as AX}from"crypto";function EX($){return ED("sha256",RD()).update($).digest("base64url").slice(0,22)}var S4=null;function RD(){let $=process.env.SECRET||void 0;if(S4&&S4.secret===$)return S4.key;let Z=$?Buffer.from(fD("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):AX(32);return S4={secret:$,key:Z},Z}function SP(){return AX(16).toString("base64url")}var bD=/^[A-Za-z0-9_-]{8,64}$/;function LJ($){return typeof $==="string"&&bD.test($)}function fX($,Z,J,W){let Y={op:"ev",t:$,ev:Z};if(J!==void 0)Y.d=J;if(W)Y.x=W;return JSON.stringify(Y)}class bX 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 h0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=O1(CX(),$),this.driver=qD(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 w3(this,A4($,Z[0]),null)}toUser($){return new w3(this,{topic:ZZ($),pattern:G0},null)}toOthers($){return new wX(this,kD($))}broadcastEvent($){let Z=$.broadcastOn(),J=Array.isArray(Z)?Z:[Z],W=$.broadcastAs(),Y=$.broadcastWith(),j=J.map((z)=>this.prepare(A4(z,void 0),W,Y,null));for(let{sent:z,frame:X}of j)this.hand(z,X)}send($,Z,J,W){let{sent:Y,frame:j}=this.prepare($,Z,J,W);this.hand(Y,j)}prepare($,Z,J,W){Z9(Z);let Y;try{Y=fX($.topic,Z,J,W?EX(W):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,Y),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(Y).d,...W?{except:W}:{}},frame:Y}}hand($,Z){yZ(()=>this.publish($,Z))}publish($,Z){let J=(W)=>console.error(`[gemi] The broadcast "${$.event}" on "${$.topic}" could not be published.`,W);try{let W=this.driver.publish($.topic,Z);if(W&&typeof W.catch==="function")W.catch(J)}catch(W){J(W)}}get isStarted(){return this.started}async start($,Z){if(this.started)throw Error("The broadcast driver was already started in this process.");this.started=!0,this.hooks=Z;try{await this.driver.start($,Z)}catch(J){throw this.started=!1,this.hooks=void 0,J}}topicAdded($){return this.driver.topicAdded?.($)}topicRemoved($){return this.driver.topicRemoved?.($)}async close(){this.started=!1,this.hooks=void 0,await this.driver.close()}revoke($){let Z=wD($);yZ(()=>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 bX(J,this.config.maxEventBytes,$);let W=this.config.warnEventBytes;if(W!==!1&&J>W&&!this.warnedAboutSize.has($))this.warnedAboutSize.add($),console.warn(`[gemi] The broadcast "${$}" is ${J} bytes, over ${W}. Broadcasts are change hints: send ids and let the client fetch the data over HTTP. Warned once per event name.`)}}class w3{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 wX{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new w3(this.manager,A4($,Z[0]),this.except)}toUser($){return new w3(this.manager,{topic:ZZ($),pattern:G0},this.except)}}function A4($,Z){if($9($))return{topic:B8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:tZ($,Z??{}),pattern:$};if($===G0)throw new p('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:B8($)}}function wD($){if($&&typeof $==="object"&&"user"in $)return{user:ZZ($.user).slice(G0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:A4($.channel,$.params).topic};throw new p("Broadcast.revoke takes { user } or { channel }.")}function kD($){if($===null||$===void 0)return null;if(typeof $==="string")return LJ($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(C4);return LJ(J)?J:null}function qD($,Z){let J=$.driver;if(J===void 0||J==="memory")return new RX;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new UJ({url:Y.url??W.url??process.env.REDIS_URL,options:Y.options??W.options,prefix:Y.prefix,subscribeTimeoutMs:Y.subscribeTimeoutMs,healthCheckMs:Y.healthCheckMs})}if(typeof J==="function"){if(!Z)throw Error("A broadcast driver factory needs the application to be called with.");return J(Z)}if(typeof J==="object"&&J!==null&&typeof J.publish==="function")return J;throw Error(`Unknown broadcast driver "${String(J)}" in app/config/broadcast.ts. Use "memory" or "redis", or pass a BroadcastDriver.`)}class HJ extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class yD{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1}import{createHash as IJ,createHmac as vD,randomBytes as kX,timingSafeEqual as vX}from"crypto";var q3=600,E4="gemi_oauth",gD=`__Host-${E4}`;function vZ($,Z=E4){if(Z===E4)return $?gD:E4;return $?`__Host-${Z}`:Z}function k3($){return $.toString("base64url")}function gX($){return vD("sha256",QZ()).update(`gemi-oauth-state:${$}`).digest()}function qX($,Z){let J=IJ("sha256").update($).digest(),W=IJ("sha256").update(Z).digest();return vX(J,W)&&$.length===Z.length}function f4($,Z=Date.now(),J={}){let W=k3(kX(32)),Y=k3(kX(32)),j=mD(Y),z={provider:$,state:W,codeVerifier:Y,expiresAt:Z+q3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{}};return{state:W,codeVerifier:Y,codeChallenge:j,cookieValue:hD(z)}}function mD($){return k3(IJ("sha256").update($).digest())}function hD($){let Z=k3(Buffer.from(JSON.stringify($)));return`${Z}.${k3(gX(Z))}`}function pD($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let J=$.slice(0,Z),W=Buffer.from($.slice(Z+1),"base64url"),Y=gX(J);if(W.length!==Y.length||!vX(W,Y))return null;try{let j=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof j?.provider!=="string"||typeof j?.state!=="string"||typeof j?.codeVerifier!=="string"||typeof j?.expiresAt!=="number"||j.subject!==void 0&&typeof j.subject!=="string"||j.returnTo!==void 0&&typeof j.returnTo!=="string")return null;return j}catch{return null}}var K$=new Map,yX=1e4;function cD($,Z,J){if(K$.size>=yX){for(let[W,Y]of K$)if(Y<=J)K$.delete(W);while(K$.size>=yX){let W=K$.keys().next().value;if(W===void 0)break;K$.delete(W)}}K$.set($,Z)}function R4($){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 W=qX(J.state,$.returnedState),Y=qX(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(K$.has(J.state))return{ok:!1,reason:"invalid_state"};return cD(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var PJ=new WeakMap;function uD($){let Z=PJ.get($);if(!Z)Z=$(dD(32).toString("hex")),PJ.set($,Z),Z.catch(()=>PJ.delete($));return Z}async function MJ($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await uD($.hashPassword))}catch{}return!1}async function h$($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class NJ extends Error{}function TJ($){return typeof $==="string"&&$!==""?$:null}function mX($){return J3($)}var lD=256;function hX($){return typeof $==="string"&&$!==""&&$.length<=lD?$:null}var b4="intended_url";function cX($){if($.cookies.get(b4))$.ctx().setCookie(b4,"",{maxAge:-1})}function pX($){let Z=$.cookies.get(b4);if(!Z)return null;cX($);try{return j1(decodeURIComponent(Z),"")||null}catch{return null}}class _J extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class dX extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class uX extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}function w1($){if(L(A).config[$]===!1)throw new Z0("Not found",{status:404})}class a extends $3{async me(){let $=await w0.user();if(!$)throw new f8;return $}async verifyEmail($=new C){w1("password");let Z=await $.input(),{userProvider:J}=L(A),W=TJ(Z.get("token"));if(!W)return{email:null};let Y=await J.findUserByVerificationToken(W);if(!Y)return{email:null};return await J.verifyUser(Y.email),{email:Y.email}}async signInWithMagicLink($=new C){let Z=L(A),{userProvider:J}=Z,W=TJ($.search.get("token")),Y=null;try{Y=J3(decodeURIComponent($.search.get("email")??""))}catch{}if(await GZ("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp}),!Y||!W||!await Z.verifyMagicLinkToken(Y,W))return{error:"Invalid token"};await J.verifyUser(Y);let j=await Z.createOrUpdateSession({email:Y});return $.ctx().setCookie("access_token",j.token,L(A).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await h$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){w1("magicLink");let Z=L(A),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=J3(W),z=hX(Y);if(await GZ("verify",j,$,Z.config.emailCode.verifyLimit),!j||!z)throw new h({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new h({pin:["Too many attempts"]});if(X.status!=="ok")throw new h({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new C){let Z=L(A),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,L(A).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await h$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new C){let Z=L(A),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,L(A).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await h$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new _J){w1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=L(A),z=await j.userProvider.findUserByEmailAddress(Y,j.config.verifyEmail),X=typeof W==="string"&&await MJ(j.config,W,z?.password);if(!z||!X)throw new h({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,L(A).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON()),await h$(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...K}=z;return K}async signIn($=new _J){w1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=L(A),z=await j.userProvider.findUserByEmailAddress(Y,j.config.verifyEmail),X=typeof W==="string"&&await MJ(j.config,W,z?.password);if(!z||!X)throw new h({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,L(A).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON()),await h$(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...K}=z;return K}async signUp(){w1("password");let $=L(A),{userProvider:Z,config:J}=$,W=new J.signUpRequest,Y=await W.input(),{email:j,password:z,name:X,invitationId:Q}=Y.toJSON(),G=mX(j);if(!G)throw new h({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new h({password:["Invalid password"]});if(Q!=null&&typeof Q!=="string")throw new h({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(G,!1))throw new h({email:["Email address already exists"]});let B=await J.hashPassword(z),F=L(n).detectLocale(W),O;if(Q)O=await Z.findInvitation(Q,G);let V,D="";if(O)V=await Z.transaction(async()=>{await Z.deleteInvitationById(Q);let U=await Z.createUser({email:G,name:X,password:B,emailVerifiedAt:new Date,locale:F});return await Z.createAccount({organizationId:O.organizationId,userId:U.id,organizationRole:O.role}),await J.onUserCreated(U),U});else D=await J.generateEmailVerificationToken(G),V=await Z.transaction(async()=>{let U=await Z.createUser({email:G,name:X,password:B,verificationToken:D,locale:F});return await J.onUserCreated(U),U});return await J.onSignUp(V,D,W.search.toJSON()),V}async signOut($=new C){let Z=L$($),J=L(A),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",L(A).accessTokenCookieOptions($,new Date(0))),L(A).cookieDomain($))$.ctx().setCookie("access_token","",{...L(A).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)iD(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user);return{}}async forgotPassword($=new dX){w1("password");let Z=await $.input(),J=mX(Z.get("email"));if(!J)return{};let{userProvider:W,config:Y}=L(A),j=await W.findUserByEmailAddress(J,Y.verifyEmail);if(!j)return{};let z=await Y.generateForgotPasswordToken(j);return await W.createPasswordResetToken({user:j,token:z}),await Y.onForgotPassword(j,z),{}}async resetPassword($=new uX){w1("password");let{userProvider:Z,config:J}=L(A),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=TJ(j),X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new h({token:["Invalid token"]});if(qZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(qZ.Now.instant()).sign>=0)throw new h({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let G=await Z.findUserByEmailAddress(X.user.email,J.verifyEmail);if(!G)throw new h({email:["User not found"]});let K=await J.hashPassword(Y);return await Z.updateUserPassword({id:G.id,password:K}),await Z.deleteAllUserSessions(G.id),await J.onResetPassword(G),{}}async changePassword($=new C){w1("password");let{userProvider:Z,config:J}=L(A),W=await w0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(typeof z!=="string")throw new h({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,J.verifyEmail);if(!(typeof j==="string"&&await MJ(J,j,X?.password)))throw new h({oldPassword:["Incorrect password"]});let G=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:G}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new C){let{provider:Z}=$.params,J=L(A).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await KZ(J,Z);if(!Y){if(W)throw new Z0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=WZ($.rawRequest),z=j1($.search.get(Y1),"");if(z)$.ctx().setCookie(b4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else cX($);let{state:X,codeChallenge:Q,cookieValue:G}=f4(Z);return $.ctx().setCookie(vZ(j),G,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:q3}),{destination:await Y.getRedirectUrl($,{state:X,codeChallenge:Q,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,J=L(A),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await KZ(Y.oauthProviders,Z);if(j&&!z)throw new Z0("Not found",{status:404});let X=WZ($.rawRequest),Q=vZ(X),G=$.cookies.get(Q);if(G!==void 0&&G!==null)$.ctx().setCookie(Q,"",{httpOnly:!0,sameSite:"Lax",secure:X,maxAge:-1});if(!z)return this.oauthFailure($,"unknown_provider");let K=$.search.get("error");if(K)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(K)?K:"provider_error");let B=R4({provider:Z,cookieValue:G,returnedState:$.search.get("state")});if("reason"in B)return console.error(`Authentication error: OAuth callback refused (${B.reason})`),this.oauthFailure($,B.reason);if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let F;try{F=await z.onCallback($,{state:B.payload.state,codeVerifier:B.payload.codeVerifier})}catch(I){if(I instanceof HJ)return this.oauthFailure($,I.code);return console.error("Authentication error: OAuth provider callback failed",I),this.oauthFailure($,"provider_error")}let{name:O,username:V,providerId:D,emailVerified:U}=F??{},H=typeof F?.email==="string"?F.email:void 0,M=H?G6(H):null,P=D?await W.findUserBySocialAccount(Z,D):null,x="signin",E=!P&&!M&&!H&&!!D&&z.createUsersWithoutEmail===!0;if(!P&&E){if(z.createUsers===!1)return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");try{P=await this.createOAuthUserWithoutEmail({provider:Z,providerId:D,name:O,username:V,locale:L(n).detectLocale($)}),x="signup"}catch(I){let _=await W.findUserBySocialAccount(Z,D);if(!_)throw I;P=_}}if(!P){if(!M)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,H?"invalid_email":D?"missing_email":"no_identity");if(U===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let I=L(n).detectLocale($);try{let _=await this.linkOAuthAccount({provider:Z,providerId:D,email:M,rawEmail:H,name:O,username:V,locale:I,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(_==="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(_==="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(_)P=_.user,x=_.action}catch(_){let y=D?await W.findUserBySocialAccount(Z,D):null;if(!y)throw _;P=y}if(!P)return this.oauthFailure($,"account_conflict")}let f=await J.createOrUpdateSessionV2({email:P.email,id:P.id});if($.ctx().setCookie("access_token",f.token,L(A).accessTokenCookieOptions($,f.expiresAt)),x==="signup")await Y.onSignUp(P,"",$.search.toJSON());else await Y.onSignIn(P,$.search.toJSON());await h$(J.config,{session:f,user:P,isNewUser:x==="signup",method:"oauth",req:$});let S=pX($)??Y.redirectPath,b=Y.oauthCompleteProfilePath?j1(Y.oauthCompleteProfilePath,""):"";if(b&&!P.email){let I=new URL(b,"http://gemi.invalid");I.searchParams.set(Y1,S),S=`${I.pathname}${I.search}${I.hash}`}return{session:f,redirectTo:S}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=L(A);return await Z.transaction(async()=>{let W=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:W.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await J.onUserCreated(W),W})}oauthFailure($,Z){let J=pX($),W=L(A).config.oauthFailurePath;if(W){let Y=j1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(Y1,J);P1.external(`${j.pathname}${j.search}${j.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(W)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:W,rawEmail:Y,name:j,username:z,locale:X}=$,{userProvider:Q,config:G}=L(A),K=(V)=>({provider:Z,userId:V,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),B=await Q.findUserByEmailAddress(W,!1),F=Y?.trim();if(!B&&F&&F!==W)B=await Q.findUserByEmailAddress(F,!1);if(B){if($.linkExisting===!1)return"account_exists";if(!J)return{user:B,action:"signin"};let V=await Q.findSocialAccounts(B.id,Z);if(V.some((U)=>U.providerId===J))return{user:B,action:"signin"};if(V.some((U)=>U.providerId))return console.error(`Authentication error: user ${B.id} is already linked to a different ${Z} account`),null;let D=V[0];if(D){if(!await Q.claimSocialAccount(D,J))throw Error(`${Z} account link changed concurrently`)}else await Q.createSocialAccount(K(B.id));return{user:B,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await Q.transaction(async()=>{let V=await Q.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await Q.createSocialAccount(K(V.id));return await G.onUserCreated(V),V}),action:"signup"}}async createMagicLinkToken($=new C){w1("magicLink");let Z=await $.input(),J=J3(Z.get("email")),W=L(A),{uniformMagicLinkResponse:Y,requestLimit:j}=W.config.emailCode;if(await GZ("request",J,$,j),!J)return{email:null};let{user:z,pin:X,token:Q}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:Q}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new C){let Z=L(A),J=Z.config.emailCode;if(!J.enabled)throw new Z0("Not found",{status:404});let W=await $.input(),Y=G6(W.get("email"));if(await GZ("request",Y,$,J.requestLimit),!Y)throw new h({email:["Invalid email"]});let j=await Z.userProvider.findUserByEmailAddress(Y,!1);if(j||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(Y,J.length);await J.send({email:Y,code:z,token:X,isNewUser:!j,req:$})}return{ok:!0}}async verifyEmailCode($=new C){let Z=L(A),{userProvider:J,config:W}=Z;if(!W.emailCode.enabled)throw new Z0("Not found",{status:404});let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),Q=G6(j),G=hX(z);if(await GZ("verify",Q,$,W.emailCode.verifyLimit),!Q||!G)throw new h({code:["invalid_code"]});let K=await Z.verifyOneTimeCode(Q,G,{claim:!1});if(K.status==="too_many_attempts")throw new h({code:["too_many_attempts"]});if(K.status!=="ok")throw new h({code:["invalid_code"]});let B=K.row,F=await J.findUserByEmailAddress(Q,!1),O=!1;if(F){if(!await J.claimMagicLinkToken(B.id))throw new h({code:["invalid_code"]});await J.verifyUser(Q)}else if(W.emailCode.createUser){let D=L(n).detectLocale($);try{F=await J.transaction(async()=>{if(!await J.claimMagicLinkToken(B.id))throw new NJ;let U=await J.createUser({email:Q,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:D});return await W.onUserCreated(U),U}),O=!0}catch(U){if(U instanceof NJ)throw new h({code:["invalid_code"]});throw U}}else throw await J.claimMagicLinkToken(B.id),new h({code:["invalid_code"]});let V=await Z.createOrUpdateSessionV2({email:Q,id:F.id});return $.ctx().setCookie("access_token",V.token,L(A).accessTokenCookieOptions($,V.expiresAt)),await W.onSignIn(V,$.search.toJSON()),await h$(Z.config,{session:V,isNewUser:O,method:"email-code",req:$}),{session:V,isNewUser:O}}}function iD($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=L();if(typeof J?.bound!=="function"||!J.bound(h0))return;J.make(h0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var lX="gemi_oauth_connection";class w4 extends $3{async connect($=new C){let Z=String($.params.provider??""),W=L(y3).providers[Z],Y=await w0.user(),j=j1($.search.get(Y1),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=WZ($.rawRequest),{state:X,codeChallenge:Q,cookieValue:G}=f4(iX(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(vZ(z,lX),G,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:q3}),P1.external(W.authorizationUrl({state:X,codeChallenge:Q,redirectUri:sX($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),J=L(y3),W=await w0.user(),Y=WZ($.rawRequest),j=vZ(Y,lX),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=R4({provider:iX(Z),cookieValue:z,returnedState:$.search.get("state")}),Q="payload"in X?X.payload.returnTo??"":"",G=J.providers[Z];if(!G)return this.finish(Q,Z,"unknown_provider");let K=$.search.get("error");if(K)return this.finish(Q,Z,/^[a-z0-9_]{1,64}$/.test(K)?K:"provider_error");if("reason"in X)return console.error(`OAuth connection refused (${X.reason})`),this.finish(Q,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(Q,Z,"user_mismatch");let B=$.search.get("code");if(!B)return this.finish(Q,Z,"missing_code");try{let F=await G.exchangeCode({code:B,codeVerifier:X.payload.codeVerifier,redirectUri:sX($,Z,G.config.redirectUri)}),O=await J.save(W,Z,F);await L(A).config.onConnected({user:W,provider:Z,connection:O,profile:F.profile??null,req:$})}catch(F){if(F instanceof nX)return console.error(`OAuth connection to ${Z} failed: ${F.message}`),this.finish(Q,Z,F.providerError??F.code);throw F}return this.finish(Q,Z)}finish($,Z,J){let W=$||j1(L(A).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw P1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function iX($){return`connection:${$}`}function sX($,Z,J){if(J)return J;return`${v3()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}class oX extends M1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[a,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[a,"oauthCallback"])}}class aX extends M1{middlewares=["cache:private"];routes={"/:provider":this.redirect([w4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([w4,"callback"]).middleware([Z6,"auth"])}}class xJ extends M1{middlewares=["cache:private"];routes={"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[a,"signInWithMagicLink"]),"/oauth":oX,"/connections":aX}}class CJ extends T0{middlewares=["cache:private"];routes={"/sign-in":this.post(a,"signIn"),"/sign-in-v2":this.post(a,"signInV2"),"/sign-up":this.post(a,"signUp"),"/sign-out":this.post(a,"signOut"),"/forgot-password":this.post(a,"forgotPassword"),"/reset-password":this.post(a,"resetPassword"),"/change-password":this.post(a,"changePassword"),"/verify-email":this.post(a,"verifyEmail"),"/me":this.get(a,"me").middleware(["auth"]),"/magic-link":this.post(a,"createMagicLinkToken"),"/sign-in-with-pin":this.post(a,"signInWithPin"),"/sign-in-with-pin-v2":this.post(a,"signInWithPinV2"),"/email-code":this.post(a,"requestEmailCode"),"/email-code/verify":this.post(a,"verifyEmailCode")}}class SJ extends T0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new C().params.locale;return await L(n).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new C,Z=`/${$.params.scope??""}`,J=$.params.locale,W=L(n),Y=J??W.detectLocale($),j=W.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:j}})}}class AJ{}class EJ extends AJ{async resize($,Z){let{height:J,width:W,quality:Y,fit:j}=Z;return await(await k4("The Sharp image optimization driver"))($).resize(W>0?W:void 0,J>0?J:void 0,{fit:j}).webp({quality:Y>0?Y:80,force:!0}).toBuffer()}}function vM($){return $}function rX(){return{driver:new EJ}}class fJ extends T0{routes={"/resize":this.file(async()=>{let $=new C,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),W=Number(Z.searchParams.get("w")),Y=Number(Z.searchParams.get("h")),j=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!J)return new Response(JSON.stringify({error:"url query parameter is required"}),{headers:{"Content-Type":"application/json"},status:404});let Q=`${J.startsWith("http")?"":`http://localhost:${process.env.PORT||5173}`}${J}`,G=await fetch(Q);if(!G.ok)return new Response(JSON.stringify({error:"Image not found",info:Q}),{headers:{"Content-Type":"application/json"},status:404});let K=Buffer.from(await G.arrayBuffer()),B=await L(tX).resize(K,{height:Y,width:W,fit:j,quality:z});G.headers.delete("Content-Type"),G.headers.delete("Content-Length");let F=new Headers(G.headers);return F.set("Content-Type","image/webp"),F.set("Content-Length",`${B.byteLength}`),new Response(new Uint8Array(B),{headers:F})})}}class tX{static token="image";driver;constructor($={}){this.driver=$.driver??rX().driver}resize($,Z){return this.driver.resize($,Z)}}class RJ extends T0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(L(eX).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function sM($){return $}function $Q(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function ZQ(){return{partialRendering:!0,localeRouting:"prefix",theme:{},onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function sD($){return"run"in $}function nD($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function oD($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function aD($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function rD($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function JQ($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function bJ($,Z="",J=[]){let W={};function Y(j,z,X,Q,G){let K=j==="/"?"":j,B=Z==="/"?"":Z,F=(`${B}${K}`===""?"/":`${B}${K}`).replaceAll("//","/");if(!W[F])W[F]={};W[F][z.toUpperCase()]={exec:X,middleware:[...J,...Q],...G?{source:G}:{}},W[F].OPTIONS={exec:()=>{let V=new C().ctx().headers;return new Response(null,{headers:V,status:204})},middleware:[]}}for(let[j,z]of Object.entries($)){if(rD(z)){let X=z;for(let Q of["GET","POST","PUT","DELETE"])Y(j,Q,X.run.bind(X),X.middlewares);continue}if(sD(z)){let X=z,Q=X.method,G=X.middlewares,K=X.run.bind(X);if(Y(j,Q,K,G,X.source),JQ(z))Y(j,"HEAD",K,G,X.source)}if(nD(z))for(let[X,Q]of Object.entries(z)){let G=Q,K=G.middlewares,B=G.run.bind(G);if(Y(j,X,B,K,G.source),X==="get"&&JQ(G))Y(j,"HEAD",B,K,G.source)}if(aD(z)){let X=new z,Q=bJ(X.routes,`${Z}${j}`,X.middlewares);for(let[G,K]of Object.entries(Q))W[G.replaceAll("//","/")]=K}if(oD(z)){let{first:X,second:Q}=z;for(let[G,K]of Object.entries(X)){let B=K.middlewares,F=K.run.bind(K),[O,...V]=j.split("/").reverse();if(!O.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(V.reverse().join("/"),G,F,B,K.source)}for(let[G,K]of Object.entries(Q)){let B=K.middlewares,F=K.run.bind(K);Y(j,G,F,B,K.source)}}}return Object.fromEntries(Object.entries(W).sort(([j],[z])=>{let X=j.split("/").length+j.split(":").length,Q=z.split("/").length+z.split(":").length;return X-Q}))}function q4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function wJ($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function kJ($){let Z=q4($);return Z.length>1?Z.replace(/\/$/,""):Z}function WQ($,Z){return Z.map((J)=>({...J,path:kJ(wJ($,J.path))}))}function y4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W;if("children"in Y){let j=new Y.children,z=y4(j.routes);for(let[X,{exec:Q,middleware:G,segments:K,features:B,static:F}]of Object.entries(z)){let O=wJ(J,X),V=(D)=>Y.run.call(Y,D,J);Z[q4(O)]={exec:[V,...Q],middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...B],viewPath:Y.viewPath,segments:[{path:kJ(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...WQ(J,K)],...F?{static:F}:{}}}}else{let j=(z)=>Y.run.call(Y,z,J);Z[q4(J)]={exec:[j],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:kJ(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new W,j=y4(Y.routes);for(let[z,{exec:X,middleware:Q,viewPath:G,segments:K,features:B,static:F}]of Object.entries(j)){let O=wJ(J,z);Z[q4(O)]={exec:X,middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...B],viewPath:G,segments:WQ(J,K),...F?{static:F}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[W])=>{let Y=J.split("/").length+J.split(":").length,j=W.split("/").length+W.split(":").length;return Y-j}))}var qJ="theme";function YQ($){return $==="light"||$==="dark"||$==="system"}function jQ($){return`!function(o){try{var e=null,d=document.documentElement,c=d.classList,k=document.cookie.split(';'),i,j,v;
14
- for(i=0;i<k.length;i++){j=k[i].indexOf('=');if(j>0&&k[i].slice(0,j).trim()===o.cookie){v=decodeURIComponent(k[i].slice(j+1).trim());break}}
15
- if(v!=='light'&&v!=='dark'&&v!=='system'){try{v=localStorage.getItem('theme')}catch(x){}}
16
- if(v==='light'||v==='dark'||v==='system')e=v;else e=o.default;
17
- if(!e)return;
18
- if(e==='system')e=window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';
19
- c.remove(e==='dark'?'light':'dark');c.add(e);d.style.colorScheme=e}catch(x){}}(${$})`}var tD=Object.defineProperty,N=($,Z)=>tD($,"name",{value:Z,configurable:!0}),hZ=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,J,W,Y,j){this.type=$,this.name=Z,this.prefix=J,this.value=W,this.suffix=Y,this.modifier=j}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};N(hZ,"Part");var eD=/[$_\p{ID_Start}]/u,$O=/[$_\u200C\u200D\p{ID_Continue}]/u,vJ=".*";function zQ($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}N(zQ,"isASCII");function hJ($,Z=!1){let J=[],W=0;for(;W<$.length;){let Y=$[W],j=N(function(z){if(!Z)throw TypeError(z);J.push({type:"INVALID_CHAR",index:W,value:$[W++]})},"ErrorOrInvalid");if(Y==="*"){J.push({type:"ASTERISK",index:W,value:$[W++]});continue}if(Y==="+"||Y==="?"){J.push({type:"OTHER_MODIFIER",index:W,value:$[W++]});continue}if(Y==="\\"){J.push({type:"ESCAPED_CHAR",index:W++,value:$[W++]});continue}if(Y==="{"){J.push({type:"OPEN",index:W,value:$[W++]});continue}if(Y==="}"){J.push({type:"CLOSE",index:W,value:$[W++]});continue}if(Y===":"){let z="",X=W+1;for(;X<$.length;){let Q=$.substr(X,1);if(X===W+1&&eD.test(Q)||X!==W+1&&$O.test(Q)){z+=$[X++];continue}break}if(!z){j(`Missing parameter name at ${W}`);continue}J.push({type:"NAME",index:W,value:z}),W=X;continue}if(Y==="("){let z=1,X="",Q=W+1,G=!1;if($[Q]==="?"){j(`Pattern cannot start with "?" at ${Q}`);continue}for(;Q<$.length;){if(!zQ($[Q],!1)){j(`Invalid character '${$[Q]}' at ${Q}.`),G=!0;break}if($[Q]==="\\"){X+=$[Q++]+$[Q++];continue}if($[Q]===")"){if(z--,z===0){Q++;break}}else if($[Q]==="("&&(z++,$[Q+1]!=="?")){j(`Capturing groups are not allowed at ${Q}`),G=!0;break}X+=$[Q++]}if(G)continue;if(z){j(`Unbalanced pattern at ${W}`);continue}if(!X){j(`Missing pattern at ${W}`);continue}J.push({type:"REGEX",index:W,value:X}),W=Q;continue}J.push({type:"CHAR",index:W,value:$[W++]})}return J.push({type:"END",index:W,value:""}),J}N(hJ,"lexer");function pJ($,Z={}){let J=hJ($);Z.delimiter??="/#?",Z.prefixes??="./";let W=`[^${p0(Z.delimiter)}]+?`,Y=[],j=0,z=0,X="",Q=new Set,G=N((P)=>{if(z<J.length&&J[z].type===P)return J[z++].value},"tryConsume"),K=N(()=>G("OTHER_MODIFIER")??G("ASTERISK"),"tryConsumeModifier"),B=N((P)=>{let x=G(P);if(x!==void 0)return x;let{type:E,index:f}=J[z];throw TypeError(`Unexpected ${E} at ${f}, expected ${P}`)},"mustConsume"),F=N(()=>{let P="",x;for(;x=G("CHAR")??G("ESCAPED_CHAR");)P+=x;return P},"consumeText"),O=N((P)=>P,"DefaultEncodePart"),V=Z.encodePart||O,D="",U=N((P)=>{D+=P},"appendToPendingFixedValue"),H=N(()=>{D.length&&(Y.push(new hZ(3,"","",V(D),"",3)),D="")},"maybeAddPartFromPendingFixedValue"),M=N((P,x,E,f,S)=>{let b=3;switch(S){case"?":b=1;break;case"*":b=0;break;case"+":b=2;break}if(!x&&!E&&b===3){U(P);return}if(H(),!x&&!E){if(!P)return;Y.push(new hZ(3,"","",V(P),"",b));return}let I;E?E==="*"?I=vJ:I=E:I=W;let _=2;I===W?(_=1,I=""):I===vJ&&(_=0,I="");let y;if(x?y=x:E&&(y=j++),Q.has(y))throw TypeError(`Duplicate name '${y}'.`);Q.add(y),Y.push(new hZ(_,y,V(P),I,V(f),b))},"addPart");for(;z<J.length;){let P=G("CHAR"),x=G("NAME"),E=G("REGEX");if(!x&&!E&&(E=G("ASTERISK")),x||E){let S=P??"";Z.prefixes.indexOf(S)===-1&&(U(S),S=""),H();let b=K();M(S,x,E,"",b);continue}let f=P??G("ESCAPED_CHAR");if(f){U(f);continue}if(G("OPEN")){let S=F(),b=G("NAME"),I=G("REGEX");!b&&!I&&(I=G("ASTERISK"));let _=F();B("CLOSE");let y=K();M(S,b,I,_,y);continue}H(),B("END")}return Y}N(pJ,"parse");function p0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}N(p0,"escapeString");function gJ($){return $&&$.ignoreCase?"ui":"u"}N(gJ,"flags");function XQ($,Z,J){return cJ(pJ($,J),Z,J)}N(XQ,"stringToRegexp");function p$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}N(p$,"modifierToString");function cJ($,Z,J={}){J.delimiter??="/#?",J.prefixes??="./",J.sensitive??=!1,J.strict??=!1,J.end??=!0,J.start??=!0,J.endsWith="";let W=J.start?"^":"";for(let X of $){if(X.type===3){X.modifier===3?W+=p0(X.value):W+=`(?:${p0(X.value)})${p$(X.modifier)}`;continue}Z&&Z.push(X.name);let Q=`[^${p0(J.delimiter)}]+?`,G=X.value;if(X.type===1?G=Q:X.type===0&&(G=vJ),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?W+=`(${G})${p$(X.modifier)}`:W+=`((?:${G})${p$(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){W+=`(?:${p0(X.prefix)}(${G})${p0(X.suffix)})`,W+=p$(X.modifier);continue}W+=`(?:${p0(X.prefix)}`,W+=`((?:${G})(?:`,W+=p0(X.suffix),W+=p0(X.prefix),W+=`(?:${G}))*)${p0(X.suffix)})`,X.modifier===0&&(W+="?")}let Y=`[${p0(J.endsWith)}]|$`,j=`[${p0(J.delimiter)}]`;if(J.end)return J.strict||(W+=`${j}?`),J.endsWith.length?W+=`(?=${Y})`:W+="$",new RegExp(W,gJ(J));J.strict||(W+=`(?:${j}(?=${Y}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=J.delimiter.indexOf(X)>-1)}return z||(W+=`(?=${j}|${Y})`),new RegExp(W,gJ(J))}N(cJ,"partsToRegexp");var B$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},ZO={delimiter:".",prefixes:"",sensitive:!0,strict:!0},JO={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function QQ($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}N(QQ,"isAbsolutePathname");function dJ($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}N(dJ,"maybeStripPrefix");function GQ($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}N(GQ,"maybeStripSuffix");function uJ($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}N(uJ,"treatAsIPv6Hostname");var KQ=["ftp","file","http","https","ws","wss"];function lJ($){if(!$)return!0;for(let Z of KQ)if($.test(Z))return!0;return!1}N(lJ,"isSpecialScheme");function FQ($,Z){if($=dJ($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}N(FQ,"canonicalizeHash");function BQ($,Z){if($=dJ($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}N(BQ,"canonicalizeSearch");function VQ($,Z){return Z||$===""?$:uJ($)?nJ($):sJ($)}N(VQ,"canonicalizeHostname");function DQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}N(DQ,"canonicalizePassword");function OQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}N(OQ,"canonicalizeUsername");function UQ($,Z,J){if(J||$==="")return $;if(Z&&!KQ.includes(Z))return new URL(`${Z}:${$}`).pathname;let W=$[0]=="/";return $=new URL(W?$:"/-"+$,"https://example.com").pathname,W||($=$.substring(2,$.length)),$}N(UQ,"canonicalizePathname");function LQ($,Z,J){return iJ(Z)===$&&($=""),J||$===""?$:oJ($)}N(LQ,"canonicalizePort");function HQ($,Z){return $=GQ($,":"),Z||$===""?$:v4($)}N(HQ,"canonicalizeProtocol");function iJ($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}N(iJ,"defaultPortForProtocol");function v4($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}N(v4,"protocolEncodeCallback");function IQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}N(IQ,"usernameEncodeCallback");function PQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}N(PQ,"passwordEncodeCallback");function sJ($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}N(sJ,"hostnameEncodeCallback");function nJ($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}N(nJ,"ipv6HostnameEncodeCallback");function oJ($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}N(oJ,"portEncodeCallback");function MQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}N(MQ,"standardURLPathnameEncodeCallback");function TQ($){return $===""?$:new URL(`data:${$}`).pathname}N(TQ,"pathURLPathnameEncodeCallback");function NQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}N(NQ,"searchEncodeCallback");function _Q($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}N(_Q,"hashEncodeCallback");var xQ=class{#j;#W=[];#Z={};#$=0;#Y=1;#G=0;#X=0;#V=0;#D=0;#O=!1;constructor($){this.#j=$}get result(){return this.#Z}parse(){for(this.#W=hJ(this.#j,!0);this.#$<this.#W.length;this.#$+=this.#Y){if(this.#Y=1,this.#W[this.#$].type==="END"){if(this.#X===0){this.#I(),this.#K()?this.#J(9,1):this.#F()?this.#J(8,1):this.#J(7,0);continue}else if(this.#X===2){this.#B(5);continue}this.#J(10,0);break}if(this.#V>0)if(this.#C())this.#V-=1;else continue;if(this.#x()){this.#V+=1;continue}switch(this.#X){case 0:this.#P()&&this.#B(1);break;case 1:if(this.#P()){this.#E();let $=7,Z=1;this.#T()?($=2,Z=3):this.#O&&($=2),this.#J($,Z)}break;case 2:this.#L()?this.#B(3):(this.#H()||this.#F()||this.#K())&&this.#B(5);break;case 3:this.#N()?this.#J(4,1):this.#L()&&this.#J(5,1);break;case 4:this.#L()&&this.#J(5,1);break;case 5:this.#S()?this.#D+=1:this.#A()&&(this.#D-=1),this.#_()&&!this.#D?this.#J(6,1):this.#H()?this.#J(7,0):this.#F()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 6:this.#H()?this.#J(7,0):this.#F()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 7:this.#F()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 8:this.#K()&&this.#J(9,1);break;case 9:break;case 10:break}}this.#Z.hostname!==void 0&&this.#Z.port===void 0&&(this.#Z.port="")}#J($,Z){switch(this.#X){case 0:break;case 1:this.#Z.protocol=this.#Q();break;case 2:break;case 3:this.#Z.username=this.#Q();break;case 4:this.#Z.password=this.#Q();break;case 5:this.#Z.hostname=this.#Q();break;case 6:this.#Z.port=this.#Q();break;case 7:this.#Z.pathname=this.#Q();break;case 8:this.#Z.search=this.#Q();break;case 9:this.#Z.hash=this.#Q();break;case 10:break}this.#X!==0&&$!==10&&([1,2,3,4].includes(this.#X)&&[6,7,8,9].includes($)&&(this.#Z.hostname??=""),[1,2,3,4,5,6].includes(this.#X)&&[8,9].includes($)&&(this.#Z.pathname??=this.#O?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#M($,Z)}#M($,Z){this.#X=$,this.#G=this.#$+Z,this.#$+=Z,this.#Y=0}#I(){this.#$=this.#G,this.#Y=0}#B($){this.#I(),this.#X=$}#U($){return $<0&&($=this.#W.length-$),$<this.#W.length?this.#W[$]:this.#W[this.#W.length-1]}#z($,Z){let J=this.#U($);return J.value===Z&&(J.type==="CHAR"||J.type==="ESCAPED_CHAR"||J.type==="INVALID_CHAR")}#P(){return this.#z(this.#$,":")}#T(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#L(){return this.#z(this.#$,"@")}#N(){return this.#z(this.#$,":")}#_(){return this.#z(this.#$,":")}#H(){return this.#z(this.#$,"/")}#F(){if(this.#z(this.#$,"?"))return!0;if(this.#W[this.#$].value!=="?")return!1;let $=this.#U(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#K(){return this.#z(this.#$,"#")}#x(){return this.#W[this.#$].type=="OPEN"}#C(){return this.#W[this.#$].type=="CLOSE"}#S(){return this.#z(this.#$,"[")}#A(){return this.#z(this.#$,"]")}#Q(){let $=this.#W[this.#$],Z=this.#U(this.#G).index;return this.#j.substring(Z,$.index)}#E(){let $={};Object.assign($,B$),$.encodePart=v4;let Z=XQ(this.#Q(),void 0,$);this.#O=lJ(Z)}};N(xQ,"Parser");var yJ=["protocol","username","password","hostname","port","pathname","search","hash"],F$="*";function mJ($,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}}N(mJ,"extractValues");function U1($,Z){return Z?mZ($):$}N(U1,"processBaseURLString");function gZ($,Z,J){let W;if(typeof Z.baseURL=="string")try{W=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=U1(W.protocol.substring(0,W.protocol.length-1),J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=U1(W.username,J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=U1(W.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=U1(W.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=U1(W.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=U1(W.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=U1(W.search.substring(1,W.search.length),J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&Z.hash===void 0&&($.hash=U1(W.hash.substring(1,W.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=HQ(Z.protocol,J)),typeof Z.username=="string"&&($.username=OQ(Z.username,J)),typeof Z.password=="string"&&($.password=DQ(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=VQ(Z.hostname,J)),typeof Z.port=="string"&&($.port=LQ(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,W&&!QQ($.pathname,J)){let Y=W.pathname.lastIndexOf("/");Y>=0&&($.pathname=U1(W.pathname.substring(0,Y+1),J)+$.pathname)}$.pathname=UQ($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=BQ(Z.search,J)),typeof Z.hash=="string"&&($.hash=FQ(Z.hash,J)),$}N(gZ,"applyInit");function mZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}N(mZ,"escapePatternString");function CQ($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}N(CQ,"escapeRegexpString");function SQ($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",W=`[^${CQ(Z.delimiter)}]+?`,Y=/[$_\u200C\u200D\p{ID_Continue}]/u,j="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){j+=mZ(X.value);continue}j+=`{${mZ(X.value)}}${p$(X.modifier)}`;continue}let Q=X.hasCustomName(),G=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),K=z>0?$[z-1]:null,B=z<$.length-1?$[z+1]:null;if(!G&&Q&&X.type===1&&X.modifier===3&&B&&!B.prefix.length&&!B.suffix.length)if(B.type===3){let F=B.value.length>0?B.value[0]:"";G=Y.test(F)}else G=!B.hasCustomName();if(!G&&!X.prefix.length&&K&&K.type===3){let F=K.value[K.value.length-1];G=Z.prefixes.includes(F)}G&&(j+="{"),j+=mZ(X.prefix),Q&&(j+=`:${X.name}`),X.type===2?j+=`(${X.value})`:X.type===1?Q||(j+=`(${W})`):X.type===0&&(!Q&&(!K||K.type===3||K.modifier!==3||G||X.prefix!=="")?j+="*":j+=`(${J})`),X.type===1&&Q&&X.suffix.length&&Y.test(X.suffix[0])&&(j+="\\"),j+=mZ(X.suffix),G&&(j+="}"),X.modifier!==3&&(j+=p$(X.modifier))}return j}N(SQ,"partsToPattern");var aJ=class{#j;#W={};#Z={};#$={};#Y={};#G=!1;constructor($={},Z,J){try{let W;if(typeof Z=="string"?W=Z:J=Z,typeof $=="string"){let X=new xQ($);if(X.parse(),$=X.result,W===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=W}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(W)throw TypeError("parameter 1 is not of type 'string'.")}typeof J>"u"&&(J={ignoreCase:!1});let Y={ignoreCase:J.ignoreCase===!0},j={pathname:F$,protocol:F$,username:F$,password:F$,hostname:F$,port:F$,search:F$,hash:F$};this.#j=gZ(j,$,!0),iJ(this.#j.protocol)===this.#j.port&&(this.#j.port="");let z;for(z of yJ){if(!(z in this.#j))continue;let X={},Q=this.#j[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,B$),X.encodePart=v4;break;case"username":Object.assign(X,B$),X.encodePart=IQ;break;case"password":Object.assign(X,B$),X.encodePart=PQ;break;case"hostname":Object.assign(X,ZO),uJ(Q)?X.encodePart=nJ:X.encodePart=sJ;break;case"port":Object.assign(X,B$),X.encodePart=oJ;break;case"pathname":lJ(this.#W.protocol)?(Object.assign(X,JO,Y),X.encodePart=MQ):(Object.assign(X,B$,Y),X.encodePart=TQ);break;case"search":Object.assign(X,B$,Y),X.encodePart=NQ;break;case"hash":Object.assign(X,B$,Y),X.encodePart=_Q;break}try{this.#Y[z]=pJ(Q,X),this.#W[z]=cJ(this.#Y[z],this.#Z[z],X),this.#$[z]=SQ(this.#Y[z],X),this.#G=this.#G||this.#Y[z].some((G)=>G.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#j[z]}'.`)}}}catch(W){throw TypeError(`Failed to construct 'URLPattern': ${W.message}`)}}get[Symbol.toStringTag](){return"URLPattern"}test($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return!1;try{typeof $=="object"?J=gZ(J,$,!1):J=gZ(J,mJ($,Z),!1)}catch{return!1}let W;for(W of yJ)if(!this.#W[W].exec(J[W]))return!1;return!0}exec($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return;try{typeof $=="object"?J=gZ(J,$,!1):J=gZ(J,mJ($,Z),!1)}catch{return null}let W={};Z?W.inputs=[$,Z]:W.inputs=[$];let Y;for(Y of yJ){let j=this.#W[Y].exec(J[Y]);if(!j)return null;let z={};for(let[X,Q]of this.#Z[Y].entries())if(typeof Q=="string"||typeof Q=="number"){let G=j[X+1];z[Q]=G}W[Y]={input:J[Y]??"",groups:z}}return W}static compareComponent($,Z,J){let W=N((X,Q)=>{for(let G of["type","modifier","prefix","value","suffix"]){if(X[G]<Q[G])return-1;if(X[G]===Q[G])continue;return 1}return 0},"comparePart"),Y=new hZ(3,"","","","",3),j=new hZ(0,"","","","",3),z=N((X,Q)=>{let G=0;for(;G<Math.min(X.length,Q.length);++G){let K=W(X[G],Q[G]);if(K)return K}return X.length===Q.length?0:W(X[G]??Y,Q[G]??Y)},"comparePartList");return!Z.#$[$]&&!J.#$[$]?0:Z.#$[$]&&!J.#$[$]?z(Z.#Y[$],[j]):!Z.#$[$]&&J.#$[$]?z([j],J.#Y[$]):z(Z.#Y[$],J.#Y[$])}get protocol(){return this.#$.protocol}get username(){return this.#$.username}get password(){return this.#$.password}get hostname(){return this.#$.hostname}get port(){return this.#$.port}get pathname(){return this.#$.pathname}get search(){return this.#$.search}get hash(){return this.#$.hash}get hasRegExpGroups(){return this.#G}};N(aJ,"URLPattern");function g3($,Z){for(let[J,W]of Object.entries($)){let Y=new aJ({pathname:J});if(Y.test({pathname:Z}))return{routePath:J,params:Y.exec({pathname:Z})?.pathname.groups??{},route:W}}return null}var c$={startIndex:0,carriedViews:[]};function AQ($,Z){let J=K0($.path,Z);return J.includes("*")?null:J}function WO($,Z){if(!$)return c$;if($.search!==Z.search)return c$;let J=Math.min($.segments.length,Z.segments.length-1),W=0;while(W<J){let Y=$.segments[W],j=Z.segments[W];if(j.alwaysRun)break;if(Y.viewPath!==j.viewPath)break;let z=AQ(Y,$.params),X=AQ(j,Z.params);if(z===null||X===null||z!==X)break;W++}if(W===0)return c$;return{startIndex:W,carriedViews:Z.segments.slice(0,W).map(({viewPath:Y})=>Y)}}function YO($,Z){let[,J,...W]=$.split("/");if(!Z.includes(J))return $;let Y=`/${W.join("/")}`;return Y==="/"?"/":Y.replace(/\/$/,"")}function EQ($){let{flatViewRoutes:Z,supportedLocales:J,from:W,origin:Y,to:j}=$;if(!W)return c$;let z;try{z=new URL(W,Y)}catch{return c$}if(z.origin!==Y)return c$;let X=g3(Z,YO(z.pathname,J));if(!X)return c$;return WO({segments:X.route.segments,params:X.params,search:z.search},j)}var rJ="x-gemi-from";import{createElement as q1,Fragment as oQ}from"react";function jO($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function g4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if("children"in W){Z[J]=[Y];let j=new W.children,z=g4(j.routes);for(let[X,Q]of Object.entries(z)){let G=J==="/"?X:`${J}${X}`,K=X==="/"&&J!=="/"?J:G;Z[K]=[Y,...Q]}if(Z[J].length===1)delete Z[J]}else Z[J]=[Y]}else{let Y=new W,j=g4(Y.routes);for(let[z,X]of Object.entries(j)){let Q=J==="/"?z:`${J}${z}`,G=z==="/"&&J!=="/"?J:Q;Z[G]=X}}return Object.fromEntries(Object.entries(Z).map(([J,W])=>[jO(J),W]))}function m4($,Z){let[J,W]=Z,Y=$.find(([j])=>j===J);if(!Y){$.push([J,[...W]]);return}for(let j of W)m4(Y[1],j)}function h4($){let Z=[];for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if(Y==="__")continue;if(Y==="REDIRECT")continue;if(Y==="FILE")continue;if("children"in W){let j=new W.children,z=h4(j.routes);m4(Z,[Y,z])}else m4(Z,[Y,[]])}else{let Y=new W,j=h4(Y.routes);for(let z of j)m4(Z,z)}return Z}function tJ($){let Z=[];for(let[J,W]of $)Z.push(J,...tJ(W).flat());return Array.from(new Set(Z))}function fQ($,Z){let[,J,...W]=$.split("/");if(J===void 0||!Z.includes(J))return{locale:null,pathname:$||"/"};return{locale:J,pathname:`/${W.join("/")}`}}class V$ extends g{static getFacadeAccessor(){return n}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=T.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(T.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??V$.locale(),$.timeZone??V$.timeZone())}static setLocale($=V$.locale(),Z={}){let J=this.getFacadeRoot(),W=$;if(!J.supportedLocales.includes($))W=J.defaultLocale;let Y=T.getStore();if(Z.cookie!==!1)Y.setCookie("i18n-locale",W,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return Y.setLocale(W),W}}class eJ{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function RQ($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var zO=50;class pZ{fetcher;entries=new Map;settleListener=null;failListener=null;shellAt=null;settledBacklog=[];shipped=new Set;requestStartedAt=performance.now();renderStartedAt=null;discoveryHintsMuted=!1;constructor($){this.fetcher=$}elapsed(){return Math.round(performance.now()-this.requestStartedAt)}keyFor($,Z){return[$,Z].filter((J)=>J.length>0).join("?")}markRenderStart(){if(this.renderStartedAt===null)this.renderStartedAt=performance.now()}markShell(){if(this.shellAt===null)this.shellAt=this.elapsed()}summarize($){let Z=this.elapsed();return{shellAt:this.shellAt??Z,settledAt:Z,aborted:$,queries:Array.from(this.entries.values(),(J)=>({path:J.path,variantKey:J.variantKey,startedAt:J.startedAt,settledAt:J.settledAt,status:J.status,source:J.source}))}}onQueryFail($){this.failListener=$}muteDiscoveryHints(){this.discoveryHintsMuted=!0}maybeLogLateDiscovery($){if(!$.lateBy||this.discoveryHintsMuted)return;if($.status!=="resolved")return;if(Bun.env.NODE_ENV==="production")return;let Z="";try{let Y=JSON.stringify($.data)?.length??0;Z=Y>=1024?`${(Y/1024).toFixed(1)} kB`:`${Y} B`}catch{Z="an unserializable payload"}let J=($.settledAt??0)-$.startedAt,W=$.variantKey?`, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams($.variantKey)))} }`:"";console.warn(`[gemi] useQuery("${$.patternPath}") was discovered ${$.lateBy}ms into the `+`server render \u2014 under a suspended segment, so its fetch (${J}ms, resolved ${Z}) could not overlap the others. It still streamed. If the query belongs on this route, \`Query.prefetch("${$.patternPath}"${W})\` in the view `+"handler starts it at request time \u2014 but note prefetched data is also re-fetched and "+`streamed into every client-side navigation payload for the route, even when the client already holds it, so weigh that bandwidth against the ${Z}. If the data is only needed conditionally (a closed popover, a hidden tab), \`{ lazy: true }\` + \`trigger()\` avoids running it here at all. \`Query.noPrefetch()\` in the handler marks the omission intentional and silences this hint for the route.`)}read($,Z){return this.entries.get(this.keyFor($,Z))}ensure($,Z={},J="render"){let W=Z.params??{},Y=new URLSearchParams(RQ(Z.search??{}));Y.delete("json"),Y.sort();let j=K0($,W),z=Y.toString(),X=this.keyFor(j,z),Q=this.entries.get(X);if(Q)return Q;let G;if(J==="render"&&this.renderStartedAt!==null){let O=Math.round(performance.now()-this.renderStartedAt);if(O>zO)G=O}let K,B=new Promise((O)=>{K=O}),F={path:j,patternPath:$,variantKey:z,lateBy:G,status:"pending",promise:B,source:J,startedAt:this.elapsed()};return this.entries.set(X,F),this.fetcher($,W,Y).then((O)=>{F.status="resolved",F.data=O},(O)=>{F.status="rejected",F.error=O}).then(()=>{if(F.settledAt=this.elapsed(),this.maybeLogLateDiscovery(F),F.status==="rejected"&&this.failListener)this.failListener(F);if(this.settleListener)this.settleListener(F);else this.settledBacklog.push(F);K()}),F}async allSettled(){let $=0;while($!==this.entries.size)$=this.entries.size,await Promise.all(Array.from(this.entries.values(),(Z)=>Z.promise))}snapshotResolved(){let $={};for(let[Z,J]of this.entries){if(J.status!=="resolved")continue;this.shipped.add(Z),$[J.path]??={},$[J.path][J.variantKey]=J.data}return $}onSettle($){this.settleListener=(J)=>{if(this.shipped.has(this.keyFor(J.path,J.variantKey)))return;$(J)};let Z=this.settledBacklog;this.settledBacklog=[];for(let J of Z)this.settleListener(J)}}class k1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,J,W,Y){super(typeof W?.message==="string"?W.message:`Request to /api${$} failed with status ${J}`);this.path=$;this.variantKey=Z;this.status=J;this.body=W;this.retryAfter=Y;this.name="QueryError"}}function cZ(){let $=JSON.stringify({error:l1("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function $W(){return{status:403,error:{message:"Forbidden"}}}function m3($){let Z=dZ.getStore();return(J,W,Y)=>{let j=new URL($.url).origin,z=[K0(J,W),Y.toString()].filter((K)=>K.length>0).join("?"),X=new Request(`${j}/${z}`,{headers:$.headers,signal:$.signal}),Q=bQ($);if(Q)uZ(X,Q);let G=new C(X,W);return dZ.run(Z,()=>T.run(G,async()=>{try{let K=L(W1).dispatchers(Q).api,B=await K.runRouteMiddleware(J,G)??await K.getRouteData(J);if(JZ(B)){if(!B.ok)throw new k1(K0(J,W),Y.toString(),B.status,B.body);return B.body}if(B instanceof Response){let F=await B.json().catch(()=>null);if(!B.ok)throw new k1(K0(J,W),Y.toString(),B.status,F);return F}return B}catch(K){if(K instanceof k1)throw K;let B=new k1(K0(J,W),Y.toString(),500,{message:K instanceof Error?K.message:String(K)});throw B.cause=K,B}}))}}var XO=new Set(["script","style","template","title"]),QO=/\shidden([\s=/]|$)/i,GO=/"[^"]*"|'[^']*'/g;function KO($){let Z=0,J=0,W=0,Y=0;while(Y<$.length){let j=$.indexOf("<",Y),z=j===-1?$.length:j;if(z>Y){let B=$.slice(Y,z).replace(/\s+/g,"").length;if(W>0)J+=B;else Z+=B}if(j===-1)break;if($.startsWith("<!--",j)){let B=$.indexOf("-->",j+4);Y=B===-1?$.length:B+3;continue}let X=$.indexOf(">",j);if(X===-1)break;let Q=$.slice(j+1,X);Y=X+1;let G=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(Q)?.[1]?.toLowerCase();if(!G)continue;let K=Q.startsWith("/");if(!K&&XO.has(G)&&!Q.endsWith("/")){let B=$.indexOf(`</${G}`,Y);Y=B===-1?$.length:B;continue}if(G!=="div")continue;if(K){if(W>0)W-=1}else if(W>0)W+=1;else if(QO.test(Q.replace(GO,'""')))W=1}return{shellChars:Z,deferredChars:J}}var FO=1000,BO=64;function VO($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function DO($,Z){if(Z.deferredChars<FO)return null;if(Z.shellChars>=BO)return null;return`[gemi] GET ${$} streams ${VO(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 wQ($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,W){if(Z.has(J))return;let Y=DO(J,W);if(!Y)return;Z.add(J),$(Y)}}}function kQ(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),KO(Z)}}}function qQ($,Z,J=1e4,W){let Y=new TextEncoder,j=()=>{};return new ReadableStream({start(z){let X=!1,Q=(K)=>{if(X)return;X=!0,clearTimeout(G);try{z.close()}catch{}W?.({aborted:K})};j=Q,z.enqueue(Y.encode(`${JSON.stringify($)}
20
- `)),Z.onSettle((K)=>{if(X||K.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([K.path,K.variantKey,K.data])}
21
- `))});let G=setTimeout(()=>Q(!0),J);Z.allSettled().then(()=>Q(!1),()=>Q(!1))},cancel(){j(!1)}})}import{Fragment as mT,createContext as OO,createElement as hT,lazy as pT,use as cT,useContext as dT}from"react";function yQ($){return{islands:[],render:$,instances:new WeakMap,count:0}}var h3="gemi-slot",vQ="data-slot",gQ="data-gemi-slot";var UO=Symbol.for("gemi.staticRender"),mQ=globalThis[UO]??=OO(null);import{createHash as uQ}from"crypto";var ZW='var r=document,i=window,a=history;i.__gemi_nav?.d();var L=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:L.signal,...s}),q=i.__gemi_nav={d:()=>L.abort()},v=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},D=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},R=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")v(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>v(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),v(n,s)});for(let m of n.children)l.observe(m)}}},O=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(O)?.content,C=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},y={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,N=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},Y=(t)=>{let e=r.body,n=t.body,s=D(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),R(e,s)},H=async(t,e)=>{let n=++b,s=!e&&y[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||C(d)!=C(r))throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),Y(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)N(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),y[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=y[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(y[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(O)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();R(r,D(r));_(!0);';import{createHash as LO}from"crypto";import{existsSync as pQ,readFileSync as HO}from"fs";import{join as jW}from"path";var cQ=".script",IO=[".ts",".js"],PO="document-scripts.json",dQ="data-gemi-script",MO=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function TO($){if(typeof $!=="string"||!MO.test($))throw Error(`A static view's \`script\` is a path under app/views without the ".script.ts" suffix, e.g. "site/clicks". Got ${JSON.stringify($)}.`)}function NO($,Z){for(let J of IO){let W=jW($,"views",`${Z}${cQ}${J}`);if(pQ(W))return W}return null}async function hQ($){let Z=await Bun.build({entrypoints:[$],target:"browser",format:"iife",minify:!0,throw:!1});if(!Z.success||!Z.outputs[0]){let W=Z.logs.map((Y)=>String(Y)).join(`
22
- `);throw Error(`The document script ${$} does not bundle.
23
- ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function _O($){return`'sha256-${LO("sha256").update($).digest("base64")}'`}var JW,WW=new Map;function xO(){if(JW===void 0){let $=jW(YW(),"dist","server",PO);JW=pQ($)?JSON.parse(HO($,"utf8")):null}return JW??null}async function zW($){TO($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=xO()?.[$];if(j!==void 0)return j;let z=WW.get($);if(z)return z}let J=jW(YW(),"app"),W=NO(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${cQ}.ts (or .js).`);if(!Z)return hQ(W);let Y=hQ(W);return WW.set($,Y),Y.catch(()=>WW.delete($)),Y}async function aT($){return _O(await zW($))}var CO="gemi-islands",YN=`'sha256-${uQ("sha256").update(GW).digest("base64")}'`;function XW($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var QW=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),jN=`'sha256-${uQ("sha256").update(ZW).digest("base64")}'`,SO='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',AO="gemi-static";function lQ($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((V)=>{let D=V.module?J(V.module):void 0;if(!D)return console.error(`[gemi] island ${V.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(V.load==="eager"){for(let U of D.preload)z.add(U);if(V.preloadDynamic)for(let U of D.dynamicPreload??[])z.add(U)}return{s:D.src,e:V.export,l:V.load}});let Q=X.some((V)=>V!==null),G=j?`<script type="module" ${dQ}="${QW(j.name)}">${j.source}</script>`:"";if(!Q&&!Y)return XW($,"</head>",G,!1);let B=(Y?`<meta name="${AO}" content="${QW(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((V)=>`<link rel="modulepreload" href="${QW(V)}"/>`).join("")+G,F=Y?ZW:GW,O=(Q?`<script type="application/json" id="${CO}">${X1({i:X})}</script>`:"")+`<script type="module">${W?SO+F:F}</script>`;return XW(XW($,"</head>",B,!1),"</body>",O,!0)}function EO($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function iQ($){let Z=`<template ${gQ}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=EO($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let Q=`<${h3} ${vQ}="${j}" style="display:contents"></${h3}>`;$=$.split(Q).join(`<${h3} style="display:contents">${X}</${h3}>`)}return $}function sQ($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function nQ($,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 fO=async()=>(await import("./chunk-r6thf4ge.js")).default,KW,p3=async(...$)=>{return KW??=import("react-dom/server.browser").catch((Z)=>{throw KW=void 0,Z}),(await KW).renderToReadableStream(...$)},aQ=1e4,rQ="no-locale",RO="no-theme";async function bO($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var VW="/assets";function wO($){return $===VW||$.startsWith(`${VW}/`)}function kO($){let Z=$.filter(wO);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${VW}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function qO($){let Z=L(W1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function FW($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function yO($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class c3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];staticRoutes=[];root=null;shellReporter=wQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;theme;constructor($){let Z=ZQ();this.partialRendering=$.partialRendering??Z.partialRendering,this.localeRouting=$.localeRouting??Z.localeRouting,this.theme=$.theme??Z.theme,this.hooks={onNotFound:$.onNotFound??Z.onNotFound,onRequestStart:$.onRequestStart??Z.onRequestStart,onRequestEnd:$.onRequestEnd??Z.onRequestEnd,onRequestFail:$.onRequestFail??Z.onRequestFail,onStreamComplete:$.onStreamComplete??Z.onStreamComplete};let J={"/":$.rootRouter,"/auth":xJ};this.flatViewRoutes=y4(J),kO(Object.keys(this.flatViewRoutes)),this.routeManifest=g4(J),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,W])=>W.at(-1)!=="FILE")),this.componentTree=h4(J),this.flatComponentTree=tJ(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,W])=>W.static).map(([W])=>W);for(let W of this.staticRoutes){let Y=this.flatViewRoutes[W].static?.layout;if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=L(s1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)p4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{d$.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let Q=new Set(Z?.preload??[]);for(let G of W)for(let K of J?.[G]??[])Q.add(K);return[...Q].map((G)=>q1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,Q;if(W.layout){if(Q=$.viewImportMap[W.layout],!Q)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let G=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let K=BW(),B=new AbortController,F=setTimeout(()=>B.abort(),aQ),O=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},V=yQ(async(D,U)=>{let H=await p3(D,{signal:B.signal,identifierPrefix:U,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:O});return await H.allReady.catch(()=>{}),await new Response(H).text()});try{let D,U=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(U)D={name:U,source:await zW(U)};let H;if(W.navigation){let x=W.navigation===!0?{}:W.navigation,E=x.version?String(await J(()=>x.version(Z))):"";H={identity:[W.layout??"",$.buildId??"",D?.name??"",E].join("|"),prefetch:x.prefetch==="none"?"none":"intent"}}let M=await p3(q1(mQ.Provider,{value:V,children:q1(oQ,{children:[...G,q1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:K,rootLayout:Q,key:"root"})]})}),{signal:B.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:O});await M.allReady.catch(()=>{});let P=iQ(await new Response(M).text());return new Response(lQ(P,V,$.resolveIsland,Bun.env.NODE_ENV!=="production",H,D),{status:200,headers:X})}finally{clearTimeout(F),J(()=>this.completeStream(Z,z.summarize(B.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:Q,serverQueries:G,userAgent:K,noStream:B,noTheme:F,url:O,user:V,viewData:D,breadcrumbs:U,urlLocaleSegment:H,meta:M,isOgRequest:P,appId:x,features:E,staticView:f}=$,S=this.theme===!1||F||f?null:{cookie:this.theme.cookie??qJ,default:this.theme.default??null,value:vO(Z,this.theme.cookie??qJ)},b=H?fQ(Q,[H]).pathname:Q,I={kind:"view",data:{meta:M,pageData:{[b]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:V},routeManifest:this.clientRouteManifest,breadcrumbs:U,router:{urlLocaleSegment:H,pathname:Y,params:X,currentPath:Q,searchParams:O.search,is404:!Y?!0:!1,domain:Z.domain?qO(Z):null},appId:x,features:E,theme:S,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},_=this.root,y=this.routeManifest[Y];return async(D$)=>{let{bootstrapModules:P0=[],loaders:v1,getStyles:s,viewImportMap:q,cssManifest:M0,ogMap:i$,viewModules:u3,clientEntry:O$,modulePreloadManifest:g1,assetBase:m1,resolveIsland:s$,buildId:Q0}=D$,sZ=O$?[]:P0,l3=(b0)=>[b0,`window.loaders=${v1}`,...O$?[`import(${JSON.stringify(O$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(P){let b0=null,a$=null;for(let r$ of y??[])if(typeof i$[r$]==="function")a$=r$,b0=i$[r$];if(!b0)return new Response("Not found",{status:404});let ZK=Object.values(I.data.pageData)[0];try{await p3(q1(b0,ZK[a$]),{onError:()=>{}})}catch(r$){let{fonts:JK,...WK}=r$.satoriOptions,YK=await Promise.all(JK.map((i3)=>{return bO(i3.name,i3.weight,i3.style).then((GK)=>({...i3,data:GK}))})),gW=new Headers(j);gW.set("Content-Type","image/png");let[jK,zK]=await Promise.all([fO(),k4("Rendering an OG image")]),XK=await jK(r$.jsx,{...WK,fonts:YK}),QK=await zK(Buffer.from(XK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(QK),{headers:gW})}return new Response("data")}if(f&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:f,currentViews:y,data:I.data,serverQueries:G,headers:j,getStyles:s,viewImportMap:q,viewModules:u3,resolveIsland:s$,buildId:Q0});if(I.data.cssManifest=M0,I.data.modulePreloadManifest=g1??{},m1&&m1!=="/")I.data.assetBase=m1;let n$=this.modulePreloadLinks({clientEntry:O$,modulePreloadManifest:g1,views:y??["404"],routeKey:Y??"404"}),nZ=await s(y??["404"]);I.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let h1=new AbortController,U$=setTimeout(()=>h1.abort(),aQ),R=B6(K)||B,R0=Bun.env.NODE_ENV!=="production"&&!R&&Y&&this.shellReporter.shouldObserve(Y)?kQ():null,o$=BW();try{let b0=await p3(q1(oQ,{children:[...n$,...nZ,...S?[q1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:jQ(X1({cookie:S.cookie,default:S.default}))}})]:[],q1(_,{data:I.data,viewImportMap:q,viewModules:u3,serverQueries:G,dictionarySink:o$,key:"root"})]}),{bootstrapScriptContent:l3(`window.__GEMI_DATA__ = ${X1(I.data)}`),bootstrapModules:sZ,signal:h1.signal,...R?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(a$){if(Bun.env.NODE_ENV!=="production")console.error(a$)}});if(b0.allReady.catch(()=>{}).finally(()=>clearTimeout(U$)),R)await b0.allReady.catch(()=>{});return new Response(m8(b0,G,{onShell:R?void 0:()=>G.markShell(),onChunk:R0?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(h1.signal.aborted)),R0)this.shellReporter.report(Y,R0.measure())})},o$),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(b0){if(clearTimeout(U$),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(h1.signal.aborted))),b0;let a$=await p3(q1("div"),{bootstrapScriptContent:l3(`window.error= ${X1(b0.message)}; window.stack_trace=${X1(b0.stack)};window.__GEMI_DATA__ = ${X1(I.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...sZ]:sZ});return new Response(m8(a$,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(h1.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(H$(Z))return 404;if(Z?.kind===d1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(u1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof k1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),Q=j,G=null,K=null,B=L(n),F=g3(this.flatViewRoutes,j),O=B.isLocaleAware&&this.localeRouting==="prefix"&&!F?.route.middleware.includes(rQ);if(O&&B.supportedLocales.includes(z))Q=`/${X.join("/")}`,G=z,K=z;if(O&&!Y&&K===null&&!(K===null&&F!==null)){let I=tQ(z,B.supportedLocales,B.defaultLocale);if(I){let _=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${I}${_}${W?".json":""}${J.search}`}})}}if(O&&!Y){let I=L(n).detectLocale(new C($,{},"view",Q));if(K===null&&I!==B.defaultLocale){let _=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${I}${_}${J.search}`}})}}Q=Q.replace("//","/");let D=[],U=[],H=null,M={},P=null,x=!1,E=!1,f=[],S;try{let I=g3(this.flatViewRoutes,Q);if(K&&I?.route.middleware.includes(rQ))I=null;if(I){if(H=I.routePath,M=I.params,D=I.route.exec,U=I.route.middleware,f=I.route.features,x=U.includes("no-stream"),E=U.includes(RO),S=I.route.static,W&&this.partialRendering){let _=$.headers.get(rJ),y=EQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:L(n).supportedLocales,from:_,origin:J.origin,to:{segments:I.route.segments,params:M,search:J.search}});if(y.startIndex>0)D=D.slice(y.startIndex),P={from:_,carriedViews:y.carriedViews}}}}catch(I){throw I}if(S&&W)return new Response("Not found",{status:404});let b=new C($,M,"view",H);return this.hooks.onRequestStart(b),await T.run(b,async()=>{let I=null,_=T.getStore(),y=dZ.getStore(),D$=(q)=>dZ.run(y,()=>T.runWith(_,q));_.serverQueries=new pZ(m3($));let P0=new Set;_.serverQueries.onQueryFail((q)=>{P0.add(q.error);try{D$(()=>Promise.resolve(this.hooks.onRequestFail(s,q.error)).catch(()=>{}))}catch{}});let v1=sQ(S);if(K){let q=K.replaceAll("/","");V$.setLocale(q,{cookie:v1.locale})}else if(B.isLocaleAware&&!O)_.setLocale(B.defaultLocale);else V$.setLocale(void 0,{cookie:v1.locale});let s=_.req;if(v1.session)p4();try{let q=null;try{await L(c1).runMiddleware(U)}catch(R){if(q=this.viewRefusalStatus(s,R,P0),q===null)throw R}if(q!==null||f.length>0&&!await this.passesFeatureGates(f))H=null,D=[],s.routePath="";let M0=L(n),i$=M0.isEnabled,u3=M0.isLocaleAware,O$=new C($,s.params),g1={defaultLocale:M0.defaultLocale,timeZone:M0.detectTimeZone(O$)};if(u3){let R=null;if(K)R=K.replaceAll("/",""),_.setLocale(R);else if(!O)R=_.locale??M0.defaultLocale;else R=M0.detectLocale(O$),_.setLocale(R);let R0=i$?M0.getPageTranslations(R,s.routePath):{};g1={...g1,supportedLocales:M0.supportedLocales,currentLocale:R,dictionary:{[R]:R0},defaultLocale:M0.defaultLocale,...O?{}:{localeRouting:"off"}}}await eQ(g1.currentLocale??"");let m1;try{m1=await Promise.all(D.map((R)=>R(s)))}catch(R){if(q=this.viewRefusalStatus(s,R,P0),q===null)throw R;H=null,D=[],s.routePath="",m1=[]}if(H===null)await this.hooks.onNotFound(s,{status:q??404});let{cookies:s$,headers:Q0}=_;if(q!==null)Q0.set("Cache-Control","no-store");I={data:m1,cookies:s$,headers:Q0,user:_.user,prefetchedData:_.serverQueries.snapshotResolved(),currentPathName:H,params:s.params,urlLocaleSegment:G,meta:_.renderMeta(),appId:L(eJ).id,features:await L(s1).forClient()};let{params:sZ,user:l3}=I,n$={},nZ={};for(let R of m1??[]){let[R0,o$]=Object.entries(R)?.[0]??[];if(!R0||!o$)continue;nZ[`${R0}:${H}`]=o$.breadcrumb,n$[R0]=o$}let h1=n$.FILE;if(h1){for(let R of s$)Q0.append("Set-Cookie",R.toString());try{await this.onRequestEnd(s)}catch(R){d$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}return await L8(h1,Q0)}if(W){Q0.set("Content-Type","application/x-ndjson; charset=utf-8"),Q0.append("Vary",rJ),s$.forEach((R0)=>Q0.append("Set-Cookie",R0.toString())),await this.hooks.onRequestEnd(s);let R={meta:P&&!_.metadata.touched?null:I.meta,data:{[Q]:n$},breadcrumbs:nZ,prefetchedData:_.serverQueries.snapshotResolved(),i18n:g1,features:I.features,is404:!H,appId:I.appId,partial:P};return new Response(qQ(R,_.serverQueries,void 0,({aborted:R0})=>D$(()=>this.completeStream(s,_.serverQueries.summarize(R0)))),{headers:Q0})}if(Q0.set("Content-Type","text/html; charset=utf-8"),!x&&!(S&&H))Q0.append("Vary","User-Agent");let U$=Boolean(S&&H);if(!U$||v1.session)p4();for(let R of s$)Q0.append("Set-Cookie",R.toString());if(!U$||v1.csrf){let R=Bun.CSRF.generate(process.env.SECRET);Q0.append("Set-Cookie",`csrf_token=${R}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(s,{mintSession:!U$||v1.session})}catch(R){d$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}if(U$)nQ(Q0,S);return await this.render({req:s,runInRequestScope:D$,csrfTokenHMAC:Buffer.from(""),currentPathName:H,headers:Q0,i18n:g1,params:sZ,pathname:J.pathname,serverQueries:_.serverQueries,userAgent:$.headers.get("user-agent"),noStream:x,noTheme:E,url:J,user:l3,viewData:n$,breadcrumbs:nZ,urlLocaleSegment:G,meta:I.meta,appId:I.appId,features:I.features,isOgRequest:Y,staticView:H?S:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===d1){let M0=W?yO(q.payload.viewData??q.payload.api):FW(q.payload.view);for(let i$ of _.cookies)M0.headers.append("Set-Cookie",i$.toString());return M0}if(!P0.has(q))this.hooks.onRequestFail(s,q);if(u1(q))return console.error(q),W?cZ():FW($W());if(q instanceof k1&&q.status===403)return W?cZ():FW($W());throw q}},Z)}}function vO($,Z){let J=$.cookies?.get(Z);return YQ(J)?J:null}function DW(){let $=JSON.stringify({error:l1("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class YG extends T0{routes={"/api-routes":this.get(()=>{let $=L(d4).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=L(c3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var gO=new Set([p1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),mO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,hO=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function pO($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(gO.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===p1)throw Error(`dispatchAs: credentials may not set the "${p1}" cookie. The access token stays the initiator's.`);if(!mO.test(Y)||!hO.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function cO($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(Q){Y(),z.error(Q);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function $G($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function ZG($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,Q]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,Q)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}class d4{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=$Q();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=bJ({"/":$.rootRouter,"/auth":CJ,"/__gemi__/services/i18n":SJ,"/__gemi__/services/logs":RJ,"/__gemi__/services/image":fJ,"/__gemi__/debug":YG})}getRouteHandlerAndParams($){let Z=new URL($.url),J=WG(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await L(c1).runMiddleware(W)}catch(Y){if(Y.kind===d1)return $G(Y.payload.api);else{if(H$(Y))return DW();if(this.onRequestFail(Z,Y),console.error(Y),u1(Y))return cZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=T.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===d1)return $G(j.payload.api);if(H$(j))return DW();if(this.onRequestFail(J.req,j),console.error(j),u1(j))return cZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){d$.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(!Y||!Y[$.method])return new Response(JSON.stringify({error:l1("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await T.run(j,async()=>{let z=T.getStore(),X=!1,Q=async()=>{X=!0,await this.endRequest(z,j,W)};try{let G=L(n);if(G.isEnabled){let D=G.detectLocale(j);z.setLocale(D)}z.setRequest(j),L(c1).applyDefaultBodyLimit($);let K=await this.runRouteMiddleware(W,j);if(K instanceof Response){let D=ZG(K,z.headers,z.cookies);return await Q(),D}let B=await this.getRouteData(W),F=z.headers,O=z.cookies;if(B instanceof Response){let D=ZG(B,F,O);if(this.isOpenEndedBody($,D)){let U=cO(D,()=>this.endRequest(z,j,W));return X=!0,U}return await Q(),D}let V=(JZ(B)?B:I$.json(B)).toResponse(F,O);return await Q(),V}catch(G){if(!X)try{await Q()}catch(K){console.error(K)}throw G}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let Q=Y?.identity;if(Q!==void 0&&(typeof Q!=="object"||!Q?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,K=[],B=Q?null:$.cookies.get(p1);if(B)K.push(`${p1}=${B}`);if(Y?.credentials)pO(G,K,Y.credentials,Q!==void 0);if(K.length>0)G.set("Cookie",K.join("; "));let F=Q?null:$.headers.get(p1);if(F)G.set(p1,F);let O=$.headers.get("User-Agent");if(O)G.set("User-Agent",O);let V;if(W instanceof FormData)V=W;else if(W!==void 0)G.set("Content-Type","application/json"),V=JSON.stringify(W);let D=new Request(z,{method:Z,headers:G,body:V,...Y?.signal?{signal:Y.signal}:{}});if(JG(D,YZ($),Q?.grant,Y?.progress),$.domain)uZ(D,$.domain);let U=Q?{user:Q.user}:void 0;return T.exit(()=>e3.exit(()=>this.handleApiRequest(D,U)))}}import{timingSafeEqual as dO}from"crypto";import{isIP as uO}from"net";var s4="",LW="*",lO=60000,iO=1e4,UW=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,u4=16,OW=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,l4="x-forwarded-host";function jG($){return $.startsWith(":")}function i4($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&dO(J,W)}function sO($){if(!$)return null;if($===!0)return{header:l4,clientIpHeader:null,secret:null};return{header:($.hostHeader??l4).toLowerCase(),clientIpHeader:$.clientIpHeader?.toLowerCase()??null,secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function nO($){if(!$||$===!0)return;let{hostHeader:Z,clientIpHeader:J,secret:W}=$;if(Z!==void 0&&(typeof Z!=="string"||!OW.test(Z)))throw Error(`\`route.domains.trustProxy.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(Z)}.`);if(J!==void 0){if(typeof J!=="string"||!OW.test(J))throw Error(`\`route.domains.trustProxy.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(J)}.`);if(!W)throw Error("`route.domains.trustProxy.clientIpHeader` needs `secret`: without proof the proxy sent it, any client that reaches the app directly picks its own address.");if(J.toLowerCase()===(Z??l4).toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `hostHeader`.");if(typeof W.header==="string"&&J.toLowerCase()===W.header.toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `secret.header`.")}if(!W)return;if(typeof W.header!=="string"||!OW.test(W.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${W.header}".`);if(W.header.toLowerCase()===(Z??l4).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof W.value!=="string"||W.value.length<u4)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${u4} characters. A guessable one lets any client name its own host.`)}function L1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function oO($){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 aO($){let Z=L1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>UW.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<u4)throw Error(`\`route.domains.ask.secret\` must be at least ${u4} characters. A guessable one is worse than leaving \`ask\` out.`);nO($.trustProxy);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),jG(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>UW.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class HW{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){aO($),this.root=L1($.root),this.hostTrust=sO($.trustProxy);for(let Z of $.groups??[])if(jG(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??lO,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!i4($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.hostTrust;if(!Z?.clientIpHeader||!Z.secret)return null;if(!i4($.headers.get(Z.secret.header),Z.secret.value))return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0]?.trim();return J&&uO(J)?J:null}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return L1(this.forwardedHost($))??L1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&L1(Y)?oO(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:LW,params:{},custom:!0};return null}async allows($,Z){let J=L1($);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:s4,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&UW.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=iO)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=L1($);if(Z)this.cache.delete(Z)}}}var rO="/__gemi__/domains/ask";class W1{static token="router.domains";resolver;acceptsCustomDomains;groups=new Map;constructor($,Z){this.groups.set(s4,$);let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new HW(J);let W=(Y)=>({api:Y.api?new d4({...Z.api,...Y.api}):$.api,view:Y.view?new c3({...Z.view,...Y.view}):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(LW,W(J.custom.fallback))}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)zG($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return uZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==rO)return null;if(!i4(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??s4)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function n4($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var XG=600000;function QG($,Z){return[X6($,Z),X6($,Z-1)]}class A{static token="auth";config;provider;constructor($={},Z=new u8){z5($.oauthProviders),this.config={...O1(X5($),$),emailCode:g8($.emailCode)},this.provider=Z}async oauthProvider($){return await KZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await M5(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=L().bound(W1)?L(W1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?L(W1).resolver?.root:L1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??L1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!b8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=n4(J.expiresAt),j=n4(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=T.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/XG),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let G=X6($,j),K=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:G,userId:K,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=G}if(!z){for(let G of QG($,j))if((await this.userProvider.findSession({token:G,userAgent:Z}))?.user){z=G;break}}if(!z)return null;let Q=await this.getSession(z,Z);if(Q)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(Q.expiresAt)));return Q}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(b8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/XG),W=QG($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=T.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new C;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new P$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=n9(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:Y,userAgent:W??""});return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){await this.userProvider.deleteMagicLinkToken($);let J=await this.config.generateMagicLinkToken($),W=await this.config.generateCode($),Y=typeof W==="string"&&W!==""?W:Z5(Z);return await this.userProvider.createMagicLinkToken({email:$,token:Q6("link",$,J),pin:Q6("pin",$,Y)}),{email:$,pin:Y,token:J}}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.userProvider.findMagicLinkTokenByEmail($);if(!j)return Z3("pin",$,null,Z),{status:"invalid"};let z=n4(j.createdAt);if(z+W*60000<=Date.now())return Z3("pin",$,null,Z),{status:"expired"};if(!await Y5(j.id,z,Y,W))return await this.userProvider.claimMagicLinkToken(j.id),{status:"too_many_attempts"};if(!Z3("pin",$,j.pin,Z))return{status:"invalid"};if(J.claim!==!1&&!await this.userProvider.claimMagicLinkToken(j.id))return{status:"invalid"};return{status:"ok",row:j}}async verifyMagicLinkToken($,Z){let J=await this.userProvider.findMagicLinkTokenByEmail($),W=Z3("link",$,J?.token,Z);if(!J||!W)return!1;if(n4(J.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(J.id)}}class w0 extends g{static getFacadeAccessor(){return A}static async user(){let $=await w0.userOrNull();if($)return $;throw new P$({redirectTo:$6(T.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=T.getStore();if($?.user)return $.user;let Z=await a3(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=T.getStore()?.req;return j1(Z?.search.get(Y1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await w0.user();if(!await $(Z))throw new jZ}static async guardSafe($){let Z=await w0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class o4{static ensure($,Z={}){let J=T.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new pZ(m3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=o4.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){o4.ensure($,Z[0])}static noPrefetch(){let $=T.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new pZ(m3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function GG($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=tO(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function tO($){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 FG{static origin($){return KG($)}static absolute($,...Z){return`${v3()}${K0(String($),Z[0]??{})}`}static relative($,...Z){return K0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=L(W1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=T.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):v3();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return GG({root:W.root,origin:j},$,K0(String(Z),J[0]??{}))}}class BG{name="Meta";static description($){T.getStore().metadata.description($)}static title($){T.getStore().metadata.title($)}static openGraph($){T.getStore().metadata.openGraph($)}static htmlAttributes($){T.getStore().metadata.htmlAttributes($)}static canonical($){T.getStore().metadata.canonical($)}static alternates($){T.getStore().metadata.alternates($)}static fonts($){T.getStore().metadata.fonts($)}}var eO={set($,Z,J){T.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(T.getStore().req.cookies.has($))return!1;return T.getStore().setCookie($,Z,J),!0},delete($,Z){T.getStore().deleteCookie($,Z)}};class y1 extends g{static getFacadeAccessor(){return u$}static get client(){return this.getFacadeRoot().client}static get($){return y1.client.get($)}static set($,Z){return y1.client.set($,Z)}static del(...$){return y1.client.del(...$)}static exists($){return y1.client.exists($)}static incr($){return y1.client.incr($)}static expire($,Z){return y1.client.expire($,Z)}static ttl($){return y1.client.ttl($)}}function Lx($){return $}function VG(){return{store:"memory",ttl:null}}class IW{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var $U="500";class PW{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${ZU(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",$U]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=L(),Z=$.bound(u$)?$.make(u$).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function ZU($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var JU="k:",DG="tag:",WU="t:";class MW{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class TW extends MW{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=O1(VG(),$),this.config.ttl!==null&&this.config.ttl!==void 0)l$(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new UG(this,Z)}async flush(){await this.store.flush()}async storeKey($){return JU+LG($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=DG+Z,W=await this.store.get(J);if(W!==null)return W;let Y=OG();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(DG+Z,OG(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:l$(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new IW(this.config.memory);if($==="redis"){let Z=this.options.application;return new PW({...this.config.redis,client:Z?{send:(J,W)=>Z.make(u$).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class UG extends MW{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){LG($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${WU}${Z.join(",")}:${$}`}}function LG($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function OG(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class HG extends g{static getFacadeAccessor(){return TW}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class IG extends g{static getFacadeAccessor(){return z1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class MG extends g{static getFacadeAccessor(){return PG}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class NG extends g{static getFacadeAccessor(){return TG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class _G extends g{static getFacadeAccessor(){return y3}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 lx($){return $}function xG(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function a4($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function NW($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:YU}=globalThis.Bun;function jU(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var zU=async($)=>{let Z=new YU($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},XU=async($)=>{let Z;try{Z=(await import("./chunk-1fe07ge4.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},CG=($)=>jU()?zU($):XU($);var QU=/^[A-Za-z_][A-Za-z0-9_]*$/;class _W{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!QU.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??CG}async createTable(){for(let $ of GU(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return SG(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
24
- INSERT INTO ${W} (channel, seq) VALUES (${Z}, 1)
25
- ON CONFLICT (channel) DO UPDATE SET seq = ${W}.seq + 1
26
- RETURNING seq
27
- `,z=Number(j.seq);if(await $`
28
- INSERT INTO ${Y} (channel, seq, data, created_at)
29
- VALUES (${Z}, ${z}, ${JSON.stringify(J??null)}, ${Date.now()})
30
- `,z>this.retain)await $`DELETE FROM ${Y} WHERE channel = ${Z} AND seq <= ${z-this.retain}`;if(this.dialect==="postgres")await $`SELECT pg_notify(${this.notifyChannel}, ${`${z} ${Z}`})`;return z}async heads($){let Z=new Map($.map((Y)=>[Y,0]));if($.length===0)return Z;let J=this.sql,W=await J`
31
- SELECT channel, seq FROM ${J.unsafe(`"${this.headsTable}"`)}
32
- WHERE channel IN ${J([...$])}
33
- `;for(let Y of W)Z.set(Y.channel,Number(Y.seq));return Z}async read($,Z,J){let W=this.sql,[Y]=await W`
34
- SELECT seq FROM ${W.unsafe(`"${this.headsTable}"`)} WHERE channel = ${$}
35
- `,j=Y?Number(Y.seq):0;if(Z>j)return{entries:[],head:j,gap:!0};if(Z===j)return{entries:[],head:j,gap:!1};let z=await W`
36
- SELECT seq, data FROM ${W.unsafe(`"${this.entriesTable}"`)}
37
- WHERE channel = ${$} AND seq > ${Z}
38
- ORDER BY seq
39
- LIMIT ${J}
40
- `;if(z.length===0||Number(z[0].seq)!==Z+1)return{entries:[],head:j,gap:!0};return{entries:z.map((X)=>({seq:Number(X.seq),data:JSON.parse(X.data)})),head:j,gap:!1}}async listen($,Z){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let J=await this.listener(this.url);try{await J.listen(this.notifyChannel,(W)=>{let Y=W.indexOf(" "),j=Number(W.slice(0,Y));if(Y>0&&Number.isInteger(j))$(W.slice(Y+1),j)},Z)}catch(W){throw await J.close(),W}return{close:()=>J.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let $=i0();if($===void 0||T1()!==this.connection)return;return $}}function GU($,Z){return[`CREATE TABLE IF NOT EXISTS "${$}" (
41
- "channel" TEXT NOT NULL PRIMARY KEY,
42
- "seq" BIGINT NOT NULL
43
- )`,`CREATE TABLE IF NOT EXISTS "${Z}" (
44
- "channel" TEXT NOT NULL,
45
- "seq" BIGINT NOT NULL,
46
- "data" TEXT NOT NULL,
47
- "created_at" BIGINT NOT NULL,
48
- PRIMARY KEY ("channel", "seq")
49
- )`]}class xW{logs=new Map;retain;constructor($={}){let Z=$.retain??1000;if(!Number.isInteger(Z)||Z<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Z}.`);this.retain=Z}async publish($,Z){let J=this.logs.get($);if(!J)J={head:0,entries:[]},this.logs.set($,J);let W=++J.head;if(J.entries.push({seq:W,data:Z===void 0?null:structuredClone(Z)}),J.entries.length>this.retain)J.entries.splice(0,J.entries.length-this.retain);return W}async heads($){return new Map($.map((Z)=>[Z,this.logs.get(Z)?.head??0]))}async read($,Z,J){let W=this.logs.get($),Y=W?.head??0;if(Z>Y)return{entries:[],head:Y,gap:!0};if(!W||Z===Y)return{entries:[],head:Y,gap:!1};let j=W.entries[0]?.seq??Y+1;if(j>Z+1)return{entries:[],head:Y,gap:!0};let z=Z+1-j;return{entries:W.entries.slice(z,z+J),head:Y,gap:!1}}}var bG=new TextEncoder;function AG($,Z){return bG.encode(`id: ${$}
50
- data: ${JSON.stringify(Z)}
51
-
52
- `)}function wG($,Z,J,W){let Y=Z instanceof Request?Z:Z.rawRequest,j=W.cursor??Y.headers.get("Last-Event-ID")??new URL(Y.url).searchParams.get("cursor"),z;try{z=$.subscribe(J,{cursor:j,signal:Y.signal})}catch(F){if(!(F instanceof r4))throw F;return new Response(JSON.stringify({error:"The change feed is at capacity."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":String(W.retryAfter??5)}})}let X=null,Q=!1,G=!1,K=(F)=>{if(X)clearInterval(X);if(X=null,z.close(),G)return;G=!0;try{F.close()}catch{}},B=new ReadableStream({start(F){X=setInterval(()=>{if(RG())return K(F);try{F.enqueue(bG.encode(EG))}catch{K(F)}},$.config.keepaliveInterval)},async pull(F){try{if(!Q){if(await z.ready(),Q=!0,!G)F.enqueue(AG(z.cursor,{type:"ready"}));return}let O=await z.next();if(O.done||G)return K(F);F.enqueue(AG(z.cursor,O.value))}catch(O){if(!G)console.error("[gemi] A change feed stream failed.",O);K(F)}},cancel(){if(G=!0,X)clearInterval(X);X=null,z.close()}});return new Response(B,{headers:fG()})}var kG=255,qG=500,KU=30000;class r4 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class lZ{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=qG;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=O1(xG(),$),this.driver=BU(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){SW($);let J=Z===void 0?null:Z;if(i0()!==void 0&&!this.driver.joinsTransaction?.())return yZ(async()=>{this.wake($,await this.driver.publish($,J))}),null;let W=await this.driver.publish($,J);return yZ(()=>this.wake($,W)),W}async head($){return SW($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=CW($);return a4(await this.driver.heads(Z))}subscribe($,Z={}){let J=CW($);if(this.all.size>=this.config.maxSubscriptions)throw new r4(this.config.maxSubscriptions);let W=new yG(this,J,FU(Z.cursor),this.config,Z.signal);this.all.add(W);for(let Y of J){let j=this.followers.get(Y);if(!j)this.followers.set(Y,j=new Set);j.add(W)}return this.startListening(),this.startPolling(),W}stream($,Z,J={}){return wG(this,$,CW(Z),J)}async close(){if(this.listenState="closed",this.retryTimer)clearTimeout(this.retryTimer);this.retryTimer=null,this.stopPolling();for(let Z of this.all)Z.close();let $=this.listening;this.listening=null,await $?.close(),await this.driver.close?.()}forget($){if(!this.all.delete($))return;for(let Z of $.channels){let J=this.followers.get(Z);if(J?.delete($),J?.size===0)this.followers.delete(Z)}if(this.all.size===0)this.stopPolling()}poll(){return this.polling??=(async()=>{try{let $=[...this.followers.keys()];for(let Z=0;Z<$.length;Z+=500){let J=await this.driver.heads($.slice(Z,Z+500));for(let[W,Y]of J)this.wake(W,Y)}}catch($){console.error("[gemi] The change feed could not read its channels' heads.",$)}finally{this.polling=null}})(),this.polling}startPolling(){if(this.pollTimer)return;this.pollTimer=setInterval(()=>void this.poll(),this.config.pollInterval),this.pollTimer.unref?.()}stopPolling(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null}wake($,Z){for(let J of this.followers.get($)??[])J.moved($,Z)}resync(){this.poll()}startListening(){if(this.listenState!=="off"||!this.driver.listen)return;this.connect()}async connect(){this.listenState="connecting",this.retryTimer=null;try{let $=await this.driver.listen((Z,J)=>this.wake(Z,J),()=>this.resync());if(this.listenState!=="connecting"){await $.close();return}this.listening=$,this.listenState="listening",this.backoffMs=qG,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,KU)}}}class yG{manager;config;signal;channels;positions=new Map;readTo=new Map;dirty=new Set;pending=[];started=null;wakeUp=null;closed=!1;onAbort=()=>this.close();constructor($,Z,J,W,Y){this.manager=$;this.config=W;this.signal=Y;this.channels=Z;for(let j of Z){let z=J.get(j);if(z!==void 0)this.positions.set(j,z),this.readTo.set(j,z),this.dirty.add(j)}if(Y?.aborted)this.close();else Y?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return a4(this.positions)}get isClosed(){return this.closed}ready(){return this.started??=(async()=>{let $=this.channels.filter((J)=>!this.positions.has(J));if($.length===0)return;let Z=await this.manager.driver.heads($);for(let J of $){let W=Z.get(J)??0;this.positions.set(J,W),this.readTo.set(J,W)}})(),this.started}async next(){await this.ready();for(;;){if(this.closed)return{done:!0,value:void 0};let $=this.pending.shift();if($)return this.positions.set($.channel,$.seq),{done:!1,value:$};let Z=this.dirty.values().next().value;if(Z!==void 0){await this.read(Z);continue}await this.idle()}}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}close(){if(this.closed)return;this.closed=!0,this.pending.length=0,this.signal?.removeEventListener("abort",this.onAbort),this.manager.forget(this),this.wake()}moved($,Z){let J=this.readTo.get($);if(J!==void 0&&Z===J)return;this.dirty.add($),this.wake()}async read($){let Z=this.readTo.get($)??0;this.dirty.delete($);let{batchSize:J}=this.config,{entries:W,head:Y,gap:j}=await this.manager.driver.read($,Z,J);if(this.closed)return;if(j){this.readTo.set($,Y),this.pending.push({type:"reset",channel:$,seq:Y});return}for(let z of W)this.readTo.set($,z.seq),this.pending.push({type:"change",channel:$,seq:z.seq,data:z.data});if(W.length===J)this.dirty.add($)}idle(){return new Promise(($)=>{this.wakeUp=$})}wake(){let $=this.wakeUp;this.wakeUp=null,$?.()}}function SW($){if(typeof $!=="string"||$===""||$.length>kG)throw Error(`A change feed channel is a string of 1 to ${kG} characters; got ${JSON.stringify($)}.`)}function CW($){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)SW(J);return Z}function FU($){if($===void 0||$===null)return new Map;if(typeof $==="string")return NW($);let Z=$ instanceof Map?[...$]:Object.entries($);return NW(a4(new Map(Z)))}function BU($,Z){if($==="memory")return new xW;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 _W(Z.make(N1));return $(Z)}if(typeof $==="string")throw Error(`Unknown change feed driver "${$}". The changeFeed slice's driver is "memory", "database", a ChangeFeedDriver, or a function returning one.`);return $}class vG extends g{static getFacadeAccessor(){return lZ}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 d3 extends h0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(h0)?$.make(h0):void 0;if(Z instanceof d3)return Z;let J=new d3($,Z);return $.instance(h0,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(h0,this.previous);return}this.application.forget(h0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${AW($,Z,J)} to have been broadcast. ${this.summary()}`)}assertNotSent($,Z,J){let W=this.matching($,Z,J);if(W.length===0)return;throw Error(`Expected ${AW($,Z,J)} not to have been broadcast, but it was broadcast ${EW(W.length)}: ${fW(W)}.`)}assertSentTimes($,Z,J,W){let Y=this.matching($,J,W);if(Y.length===Z)return;throw Error(`Expected ${AW($,J,W)} to have been broadcast ${EW(Z)}, but it was broadcast ${EW(Y.length)}. `+this.summary())}assertNothingSent(){if(this.sent.length===0)return;throw Error(`Expected nothing to have been broadcast, but ${this.sent.length} ${this.sent.length===1?"emit was":"emits were"}: ${fW(this.sent)}.`)}matching($,Z,J){return $Z($),this.sent.filter((W)=>(W.pattern===$||J9($,W.topic))&&(Z===void 0||W.event===Z)&&(J===void 0||J(W.data,W)))}summary(){if(this.sent.length===0)return"Nothing was broadcast.";return`Broadcast: ${fW(this.sent)}.`}}function AW($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function EW($){return`${$} ${$===1?"time":"times"}`}function fW($){return $.map((Z)=>`${Z.topic} ${Z.event}(${VU(Z.data)})`).join(", ")}function VU($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class gG extends g{static getFacadeAccessor(){return h0}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 d3.install(L())}}function _C($){return $}function mG(){return{store:"memory",sweepLimit:500}}var RW=["completed","failed","cancelled","timed_out"],H1=["pending","running"];function I1($){return RW.includes($)}class bW{runs=new Map;clock=0;get size(){return this.runs.size}async create($){if(this.runs.has($.id))throw Error(`A run with the id ${$.id} already exists.`);let Z=this.tick(),J={id:$.id,kind:$.kind,subject:$.subject,owner:$.owner,status:$.status,meta:structuredClone($.meta??null),progress:null,result:null,error:null,version:1,createdAt:Z,startedAt:$.status==="running"?Z:null,updatedAt:Z,finishedAt:null,deadlineAt:$.deadlineMs===null?null:Z+$.deadlineMs};return this.runs.set(J.id,J),structuredClone(J)}async get($){let Z=this.runs.get($);return Z?structuredClone(Z):null}async list($){let Z=[];for(let J of this.runs.values()){if($.kind!==void 0&&J.kind!==$.kind)continue;if($.subject!==void 0&&J.subject!==$.subject)continue;if($.owner!==void 0&&J.owner!==$.owner)continue;if($.statuses&&!$.statuses.includes(J.status))continue;Z.push(J)}return Z.reverse().sort((J,W)=>W.createdAt-J.createdAt),Z.slice(0,wW($.limit)).map((J)=>structuredClone(J))}async transition($,Z,J){let W=this.runs.get($);if(!W||!Z.includes(W.status))return null;let Y=structuredClone(J),j=this.tick();if(Y.status!==void 0){if(W.startedAt===null&&Y.status!=="pending")W.startedAt=j;if(I1(Y.status))W.finishedAt=j;W.status=Y.status}if("progress"in Y)W.progress=Y.progress??null;if("result"in Y)W.result=Y.result??null;if("error"in Y)W.error=Y.error??null;return W.version+=1,W.updatedAt=j,structuredClone(W)}async overdue($,Z){let J=[];for(let W of this.runs.values())if(H1.includes(W.status)&&W.deadlineAt!==null&&W.deadlineAt<=$)J.push(W);return J.sort((W,Y)=>W.deadlineAt-Y.deadlineAt),J.slice(0,Math.max(0,Z)).map((W)=>structuredClone(W))}async now(){return this.tick()}async prune($){let Z=this.tick()-$,J=0;for(let[W,Y]of this.runs)if(Y.finishedAt!==null&&Y.finishedAt<=Z)this.runs.delete(W),J++;return J}tick(){return this.clock=Math.max(this.clock,Date.now()),this.clock}}function wW($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class yW{table;sql;dialect;connection;constructor($,Z={}){let J=Z.table??"gemi_runs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The runs table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);this.table=J,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of DU(this.dialect,this.table))await this.sql.unsafe($)}async create($){let Z=this.q(),J=this.clock(Z),W=$.deadlineMs===null?Z`NULL`:Z`${J} + ${this.ms(Z,$.deadlineMs)}`,Y=$.status==="running"?J:Z`NULL`;await Z`
53
- INSERT INTO ${this.name(Z)}
54
- (id, kind, subject, owner, status, meta, version,
55
- created_at, started_at, updated_at, deadline_at)
56
- VALUES
57
- (${$.id}, ${$.kind}, ${$.subject}, ${$.owner}, ${$.status},
58
- ${e4($.meta)}, 1, ${J}, ${Y}, ${J}, ${W})
59
- `;let j=await this.get($.id);if(!j)throw Error(`The run ${$.id} was not found after it was written.`);return j}async get($){let Z=this.q(),J=await Z`SELECT * FROM ${this.name(Z)} WHERE id = ${$}`;return J[0]?qW(J[0]):null}async list($){let Z=this.q(),J=[Z`1 = 1`];if($.kind!==void 0)J.push(Z`kind = ${$.kind}`);if($.subject!==void 0)J.push(Z`subject = ${$.subject}`);if($.owner!==void 0)J.push(Z`owner = ${$.owner}`);if($.statuses!==void 0)J.push($.statuses.length===0?Z`1 = 0`:Z`status IN (${t4(Z,$.statuses)})`);let W=J.reduce((j,z)=>Z`${j} AND ${z}`);return(await Z`
60
- SELECT * FROM ${this.name(Z)}
61
- WHERE ${W}
62
- ORDER BY created_at DESC, id DESC
63
- LIMIT ${wW($.limit)}
64
- `).map(qW)}async transition($,Z,J){if(Z.length===0)return null;let W=this.q(),Y=this.clock(W),j=[W`updated_at = ${Y}`,W`version = version + 1`];if(J.status!==void 0){if(j.push(W`status = ${J.status}`),J.status!=="pending")j.push(W`started_at = COALESCE(started_at, ${Y})`);if(I1(J.status))j.push(W`finished_at = ${Y}`)}if("progress"in J)j.push(W`progress = ${e4(J.progress)}`);if("result"in J)j.push(W`result = ${e4(J.result)}`);if("error"in J)j.push(W`error = ${e4(J.error)}`);let z=j.reduce((Q,G)=>W`${Q}, ${G}`),X=await W`
65
- UPDATE ${this.name(W)} SET ${z}
66
- WHERE id = ${$} AND status IN (${t4(W,Z)})
67
- `;if(pG(X)===0)return null;return this.get($)}async overdue($,Z){let J=this.q();return(await J`
68
- SELECT * FROM ${this.name(J)}
69
- WHERE status IN (${t4(J,H1)})
70
- AND deadline_at IS NOT NULL AND deadline_at <= ${this.ms(J,$)}
71
- ORDER BY deadline_at, id
72
- LIMIT ${Math.max(0,Math.floor(Z))}
73
- `).map(qW)}async now(){let $=this.q(),[Z]=await $`SELECT ${this.clock($)} AS now`;return Number(Z.now)}async prune($){let Z=this.q(),J=await Z`
74
- DELETE FROM ${this.name(Z)}
75
- WHERE status IN (${t4(Z,RW)})
76
- AND finished_at <= ${this.clock(Z)} - ${this.ms(Z,$)}
77
- `;return pG(J)}joinable(){if(this.connection===void 0)return;let $=i0();if($===void 0||T1()!==this.connection)return;return $}q(){return this.joinable()??this.sql}name($){let Z=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Z?`\`${this.table}\``:`"${this.table}"`)}clock($){switch(this.dialect){case"postgres":return $`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return $`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return $`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms($,Z){let J=Math.max(0,Math.round(Z));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${J} AS SIGNED)`:$`CAST(${J} AS BIGINT)`}}function t4($,Z){return Z.map((J)=>$`${J}`).reduce((J,W)=>$`${J}, ${W}`)}function e4($){return $===void 0||$===null?null:JSON.stringify($)}function $8($){if($===null||$===void 0)return null;return JSON.parse(String($))}function kW($){return $===null||$===void 0?null:Number($)}function hG($){return $===null||$===void 0?null:String($)}function qW($){return{id:String($.id),kind:String($.kind),subject:hG($.subject),owner:hG($.owner),status:String($.status),meta:$8($.meta),progress:$8($.progress),result:$8($.result),error:$8($.error),version:Number($.version),createdAt:Number($.created_at),startedAt:kW($.started_at),updatedAt:Number($.updated_at),finishedAt:kW($.finished_at),deadlineAt:kW($.deadline_at)}}function pG($){let Z=$;return Math.max(Number(Z.count??0),Number(Z.affectedRows??0))}function DU($,Z){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
78
- \`id\` VARCHAR(191) NOT NULL,
79
- \`kind\` VARCHAR(191) NOT NULL,
80
- \`subject\` VARCHAR(191) NULL,
81
- \`owner\` VARCHAR(191) NULL,
82
- \`status\` VARCHAR(191) NOT NULL,
83
- \`meta\` LONGTEXT NULL,
84
- \`progress\` LONGTEXT NULL,
85
- \`result\` LONGTEXT NULL,
86
- \`error\` LONGTEXT NULL,
87
- \`version\` INTEGER NOT NULL DEFAULT 1,
88
- \`created_at\` BIGINT NOT NULL,
89
- \`started_at\` BIGINT NULL,
90
- \`updated_at\` BIGINT NOT NULL,
91
- \`finished_at\` BIGINT NULL,
92
- \`deadline_at\` BIGINT NULL,
93
-
94
- INDEX \`${Z}_subject_created_at_idx\`(\`subject\`, \`created_at\`),
95
- INDEX \`${Z}_status_deadline_at_idx\`(\`status\`, \`deadline_at\`),
96
- PRIMARY KEY (\`id\`)
97
- ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let J=$==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',W=$==="sqlite"?"":`,
98
-
99
- CONSTRAINT "${Z}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${Z}" (
100
- ${J}
101
- "kind" TEXT NOT NULL,
102
- "subject" TEXT,
103
- "owner" TEXT,
104
- "status" TEXT NOT NULL,
105
- "meta" TEXT,
106
- "progress" TEXT,
107
- "result" TEXT,
108
- "error" TEXT,
109
- "version" INTEGER NOT NULL DEFAULT 1,
110
- "created_at" BIGINT NOT NULL,
111
- "started_at" BIGINT,
112
- "updated_at" BIGINT NOT NULL,
113
- "finished_at" BIGINT,
114
- "deadline_at" BIGINT${W}
115
- )`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var cG=191,dG=30000;class Z8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class J8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class vW{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=O1(mG(),$),this.store=LU(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(lZ);return this.ownFeed??=new lZ,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){iG("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;iG("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:l$($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return UU(Z),this.change($,H1,{status:"running",progress:Z})}complete($,Z){return this.change($,H1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,H1,{status:"failed",error:lG(Z)})}cancel($,Z){return this.change($,H1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new Z8($);if(I1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(Q)=>{if(Y.signal.aborted)return;await this.progress($,Q)}},X;try{let Q=await Z(z);X=await this.complete($,Q)}catch(Q){if(!(Q instanceof J8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,Q);X=await this.change($,H1,{status:"failed",error:Q instanceof J8?lG(Q):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+l$(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new Z8($);let z=null;for(;;){if(I1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let Q=W-Date.now();if(Q<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await uG(z,Math.min(Q,X??1/0,dG),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new Z8($);if(yield W,I1(W.status))return;for await(let Y of J){let j=OU(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,I1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=l$($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||I1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,H1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(I1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,uG(j,Math.min(z??1/0,dG))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function uG($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>Q(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},Q=(G)=>{X(),W(G)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>Q(!0),()=>Q(!0))})}function OU($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function lG($){if(typeof $==="string")return{message:$};if($ instanceof J8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function iG($,Z){if(typeof Z!=="string"||Z===""||Z.length>cG)throw TypeError(`A run's ${$} is a string of 1 to ${cG} characters; got ${JSON.stringify(Z)}.`)}function UU($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function LU($,Z){if($==="memory")return new bW;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(N1).connection();return new yW(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class sG extends g{static getFacadeAccessor(){return vW}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class nG extends g{static getFacadeAccessor(){return s1}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class W8{bound;constructor($){this.bound=$}get name(){return this.bound??T1()}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 rG(J.sql,(W)=>oG(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-mj55jdwp.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=eG($,tG(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=i0();if($===void 0)return;return T1()===this.name?$:void 0}connection($=this.name){return aG($),L(N1).connection($)}}var iZ=new W8;class $K extends g{static getFacadeAccessor(){return N1}static connection($){return new W8($)}static get sql(){return iZ.sql}static get dialect(){return iZ.dialect}static query($){return iZ.query($)}static execute($){return iZ.execute($)}static transaction($){return iZ.transaction($)}static schema(){return iZ.schema()}static close(){return this.getFacadeRoot().close()}}export{l0 as $d,oZ as ae,X8 as be,e$ as ce,rZ as de,T0 as ee,a3 as fe,R8 as ge,b8 as he,n9 as ie,i1 as je,z1 as ke,r as le,C9 as me,YZ as ne,o9 as oe,a9 as pe,k8 as qe,q8 as re,Q6 as se,Z3 as te,NF as ue,bI as ve,X5 as we,D5 as xe,h8 as ye,O5 as ze,U5 as Ae,RF as Be,L5 as Ce,p8 as De,kF as Ee,qF as Fe,c8 as Ge,H5 as He,I5 as Ie,s1 as Je,P5 as Ke,mF as Le,u8 as Me,I8 as Ne,Z6 as Oe,P1 as Pe,I$ as Qe,EK as Re,L8 as Se,M1 as Te,V$ as Ue,o4 as Ve,FG as We,BG as Xe,eO as Ye,y1 as Ze,Lx as _e,VG as $e,IW as af,PW as bf,TW as cf,UG as df,HG as ef,IG as ff,MG as gf,NG as hf,_G as if,lx as jf,xG as kf,a4 as lf,NW as mf,_W as nf,xW as of,r4 as pf,lZ as qf,yG as rf,vG as sf,p as tf,tZ as uf,C4 as vf,UP as wf,LP as xf,HP as yf,TP as zf,CX as Af,UJ as Bf,EX as Cf,SP as Df,bX as Ef,h0 as Ff,w3 as Gf,wX as Hf,gG as If,_C as Jf,RW as Kf,H1 as Lf,I1 as Mf,bW as Nf,yW as Of,DU as Pf,Z8 as Qf,J8 as Rf,vW as Sf,sG as Tf,nG as Uf,W8 as Vf,$K as Wf,HJ as Xf,yD as Yf,AJ as Zf,EJ as _f,vM as $f,rX as ag,tX as bg,r3 as cg,c1 as dg,sM as eg,$Q as fg,ZQ as gg,eJ as hg,cZ as ig,$W as jg,aT as kg,YN as lg,jN as mg,VW as ng,wO as og,FW as pg,yO as qg,c3 as rg,DW as sg,$G as tg,ZG as ug,d4 as vg,W1 as wg,A as xg,w0 as yg,t3 as zg,X9 as Ag,NK as Bg,Y9 as Cg,G9 as Dg,V8 as Eg,D8 as Fg,O8 as Gg,K9 as Hg,fK as Ig,RK as Jg,L9 as Kg,I9 as Lg,M9 as Mg,A9 as Ng,E9 as Og,f9 as Pg,T8 as Qg,vK as Rg,J0 as Sg,p9 as Tg,XZ as Ug,i9 as Vg};
116
-
117
- //# debugId=DE1DF47F9266F1B864756E2164756E21