gemi 0.136.0 → 0.137.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 (220) hide show
  1. package/dist/ai/Agent.d.ts +48 -5
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentController.d.ts +42 -2
  4. package/dist/ai/AgentController.d.ts.map +1 -1
  5. package/dist/ai/index.d.ts +3 -1
  6. package/dist/ai/index.d.ts.map +1 -1
  7. package/dist/ai/index.js +85 -18
  8. package/dist/ai/index.js.map +5 -4
  9. package/dist/ai/memory/AgentMemories.d.ts +226 -0
  10. package/dist/ai/memory/AgentMemories.d.ts.map +1 -0
  11. package/dist/ai/memory/AgentMemoryStore.d.ts +182 -0
  12. package/dist/ai/memory/AgentMemoryStore.d.ts.map +1 -0
  13. package/dist/ai/memory/DatabaseAgentMemoryStore.d.ts +76 -0
  14. package/dist/ai/memory/DatabaseAgentMemoryStore.d.ts.map +1 -0
  15. package/dist/ai/memory/contextBlock.d.ts +32 -0
  16. package/dist/ai/memory/contextBlock.d.ts.map +1 -0
  17. package/dist/ai/memory/index.d.ts +6 -0
  18. package/dist/ai/memory/index.d.ts.map +1 -0
  19. package/dist/ai/memory/runMemory.d.ts +355 -0
  20. package/dist/ai/memory/runMemory.d.ts.map +1 -0
  21. package/dist/ai/memory/safety.d.ts +34 -0
  22. package/dist/ai/memory/safety.d.ts.map +1 -0
  23. package/dist/ai/memory/search.d.ts +23 -0
  24. package/dist/ai/memory/search.d.ts.map +1 -0
  25. package/dist/app/index.js +1 -1
  26. package/dist/bun/plugin.js +1 -1
  27. package/dist/bun/preload.js +1 -1
  28. package/dist/{chunk-rnp5k8m3.js → chunk-038xtqpm.js} +2 -2
  29. package/dist/{chunk-rnp5k8m3.js.map → chunk-038xtqpm.js.map} +1 -1
  30. package/dist/{chunk-5pdgh9a1.js → chunk-26yghzet.js} +2 -2
  31. package/dist/{chunk-5pdgh9a1.js.map → chunk-26yghzet.js.map} +1 -1
  32. package/dist/{chunk-ha15x5ns.js → chunk-27xv8kty.js} +2 -2
  33. package/dist/{chunk-ha15x5ns.js.map → chunk-27xv8kty.js.map} +1 -1
  34. package/dist/{chunk-k2xeskp6.js → chunk-3jkem5gq.js} +2 -2
  35. package/dist/{chunk-k2xeskp6.js.map → chunk-3jkem5gq.js.map} +1 -1
  36. package/dist/{chunk-q15f5g86.js → chunk-46bwknb5.js} +3 -3
  37. package/dist/{chunk-q15f5g86.js.map → chunk-46bwknb5.js.map} +1 -1
  38. package/dist/{chunk-8sde8337.js → chunk-4jc7wbet.js} +2 -2
  39. package/dist/{chunk-8sde8337.js.map → chunk-4jc7wbet.js.map} +1 -1
  40. package/dist/{chunk-3dpmkxp7.js → chunk-4zjtbgnr.js} +2 -2
  41. package/dist/{chunk-3dpmkxp7.js.map → chunk-4zjtbgnr.js.map} +1 -1
  42. package/dist/{chunk-feajsgns.js → chunk-5benn2ys.js} +3 -3
  43. package/dist/{chunk-feajsgns.js.map → chunk-5benn2ys.js.map} +1 -1
  44. package/dist/{chunk-rzqft8q8.js → chunk-6qzyq0g5.js} +2 -2
  45. package/dist/{chunk-rzqft8q8.js.map → chunk-6qzyq0g5.js.map} +1 -1
  46. package/dist/{chunk-6qty7at2.js → chunk-78zfqt54.js} +2 -2
  47. package/dist/{chunk-6qty7at2.js.map → chunk-78zfqt54.js.map} +1 -1
  48. package/dist/{chunk-ysc7ykss.js → chunk-7d26eqv1.js} +2 -2
  49. package/dist/{chunk-ysc7ykss.js.map → chunk-7d26eqv1.js.map} +1 -1
  50. package/dist/{chunk-6fr6j338.js → chunk-7t7jh8t2.js} +2 -2
  51. package/dist/{chunk-6fr6j338.js.map → chunk-7t7jh8t2.js.map} +1 -1
  52. package/dist/{chunk-xvvsc58s.js → chunk-7vxeqxxr.js} +2 -2
  53. package/dist/{chunk-xvvsc58s.js.map → chunk-7vxeqxxr.js.map} +1 -1
  54. package/dist/{chunk-zyhmn3hy.js → chunk-80fjsb26.js} +3 -3
  55. package/dist/{chunk-zyhmn3hy.js.map → chunk-80fjsb26.js.map} +1 -1
  56. package/dist/{chunk-xymr3asa.js → chunk-85k70cme.js} +3 -3
  57. package/dist/{chunk-xymr3asa.js.map → chunk-85k70cme.js.map} +1 -1
  58. package/dist/{chunk-ka991yx4.js → chunk-8dmhbj4m.js} +2 -2
  59. package/dist/{chunk-ka991yx4.js.map → chunk-8dmhbj4m.js.map} +1 -1
  60. package/dist/{chunk-8ryrjtn0.js → chunk-8ef5c93d.js} +2 -2
  61. package/dist/{chunk-8ryrjtn0.js.map → chunk-8ef5c93d.js.map} +1 -1
  62. package/dist/{chunk-t33yh84d.js → chunk-8p4t8x9c.js} +2 -2
  63. package/dist/{chunk-t33yh84d.js.map → chunk-8p4t8x9c.js.map} +1 -1
  64. package/dist/{chunk-7nxnyw7x.js → chunk-965gfa41.js} +2 -2
  65. package/dist/{chunk-7nxnyw7x.js.map → chunk-965gfa41.js.map} +1 -1
  66. package/dist/{chunk-swwkdm75.js → chunk-974p7em0.js} +2 -2
  67. package/dist/{chunk-swwkdm75.js.map → chunk-974p7em0.js.map} +1 -1
  68. package/dist/{chunk-krk880my.js → chunk-9s203ks3.js} +2 -2
  69. package/dist/{chunk-krk880my.js.map → chunk-9s203ks3.js.map} +1 -1
  70. package/dist/{chunk-0eamc2tr.js → chunk-9wc53ywv.js} +2 -2
  71. package/dist/{chunk-0eamc2tr.js.map → chunk-9wc53ywv.js.map} +1 -1
  72. package/dist/{chunk-hb9hm8za.js → chunk-a2fhbstt.js} +3 -3
  73. package/dist/{chunk-hb9hm8za.js.map → chunk-a2fhbstt.js.map} +1 -1
  74. package/dist/{chunk-cxsvzqd4.js → chunk-aj2sr77y.js} +2 -2
  75. package/dist/{chunk-cxsvzqd4.js.map → chunk-aj2sr77y.js.map} +1 -1
  76. package/dist/{chunk-0gg4e94v.js → chunk-an1nja68.js} +2 -2
  77. package/dist/{chunk-0gg4e94v.js.map → chunk-an1nja68.js.map} +1 -1
  78. package/dist/{chunk-jy9dkgt0.js → chunk-ant9ck0r.js} +2 -2
  79. package/dist/{chunk-jy9dkgt0.js.map → chunk-ant9ck0r.js.map} +1 -1
  80. package/dist/chunk-atmw5c0q.js +28 -0
  81. package/dist/chunk-atmw5c0q.js.map +27 -0
  82. package/dist/{chunk-sa6cxt3g.js → chunk-bg0e39dk.js} +2 -2
  83. package/dist/{chunk-sa6cxt3g.js.map → chunk-bg0e39dk.js.map} +1 -1
  84. package/dist/{chunk-1awxdnb6.js → chunk-c0m8pcbd.js} +1 -1
  85. package/dist/{chunk-65j32dtn.js → chunk-c6c7p43e.js} +2 -2
  86. package/dist/{chunk-65j32dtn.js.map → chunk-c6c7p43e.js.map} +1 -1
  87. package/dist/{chunk-x9bk5s21.js → chunk-c83e4ghx.js} +2 -2
  88. package/dist/{chunk-x9bk5s21.js.map → chunk-c83e4ghx.js.map} +1 -1
  89. package/dist/{chunk-jgx8ggbz.js → chunk-cedmppcy.js} +2 -2
  90. package/dist/{chunk-jgx8ggbz.js.map → chunk-cedmppcy.js.map} +1 -1
  91. package/dist/{chunk-wrsf2abe.js → chunk-chyt9th4.js} +2 -2
  92. package/dist/{chunk-wrsf2abe.js.map → chunk-chyt9th4.js.map} +1 -1
  93. package/dist/{chunk-qfra7gah.js → chunk-d368es1y.js} +2 -2
  94. package/dist/{chunk-qfra7gah.js.map → chunk-d368es1y.js.map} +1 -1
  95. package/dist/{chunk-dt95z6et.js → chunk-d492ae5e.js} +2 -2
  96. package/dist/{chunk-dt95z6et.js.map → chunk-d492ae5e.js.map} +1 -1
  97. package/dist/{chunk-beb265c9.js → chunk-e440f645.js} +2 -2
  98. package/dist/{chunk-beb265c9.js.map → chunk-e440f645.js.map} +1 -1
  99. package/dist/{chunk-njpnstck.js → chunk-eqzxvfvt.js} +2 -2
  100. package/dist/{chunk-njpnstck.js.map → chunk-eqzxvfvt.js.map} +1 -1
  101. package/dist/{chunk-99a4e6zf.js → chunk-f9w78tbd.js} +2 -2
  102. package/dist/{chunk-99a4e6zf.js.map → chunk-f9w78tbd.js.map} +1 -1
  103. package/dist/chunk-fjw51b91.js +10 -0
  104. package/dist/{chunk-3gx7wcrt.js.map → chunk-fjw51b91.js.map} +3 -3
  105. package/dist/chunk-fs4ntgdr.js +5 -0
  106. package/dist/{chunk-47e7fbsp.js.map → chunk-fs4ntgdr.js.map} +1 -1
  107. package/dist/{chunk-gng5e7pd.js → chunk-fwmmy0jn.js} +1 -1
  108. package/dist/{chunk-mw7ft5bs.js → chunk-g22q8j2s.js} +2 -2
  109. package/dist/{chunk-mw7ft5bs.js.map → chunk-g22q8j2s.js.map} +1 -1
  110. package/dist/{chunk-z9xxthp1.js → chunk-ghbzre7k.js} +3 -3
  111. package/dist/{chunk-z9xxthp1.js.map → chunk-ghbzre7k.js.map} +1 -1
  112. package/dist/{chunk-x5hj0mqp.js → chunk-gq4fr0zn.js} +3 -3
  113. package/dist/{chunk-x5hj0mqp.js.map → chunk-gq4fr0zn.js.map} +1 -1
  114. package/dist/{chunk-x51tegk3.js → chunk-gqcmnyc8.js} +2 -2
  115. package/dist/{chunk-x51tegk3.js.map → chunk-gqcmnyc8.js.map} +1 -1
  116. package/dist/{chunk-x16ckgq1.js → chunk-h0ydk8cc.js} +2 -2
  117. package/dist/{chunk-x16ckgq1.js.map → chunk-h0ydk8cc.js.map} +1 -1
  118. package/dist/{chunk-m9vwg9j1.js → chunk-jys3n8xv.js} +3 -3
  119. package/dist/{chunk-m9vwg9j1.js.map → chunk-jys3n8xv.js.map} +1 -1
  120. package/dist/{chunk-3h37f124.js → chunk-kpb8xvrv.js} +2 -2
  121. package/dist/{chunk-3h37f124.js.map → chunk-kpb8xvrv.js.map} +1 -1
  122. package/dist/{chunk-mpqvmge4.js → chunk-kzdkpz04.js} +1 -1
  123. package/dist/{chunk-0rhf4g12.js → chunk-md6wfc1h.js} +3 -3
  124. package/dist/{chunk-0rhf4g12.js.map → chunk-md6wfc1h.js.map} +1 -1
  125. package/dist/{chunk-s025aycr.js → chunk-n2czjpz9.js} +2 -2
  126. package/dist/{chunk-s025aycr.js.map → chunk-n2czjpz9.js.map} +1 -1
  127. package/dist/{chunk-ff60bzvf.js → chunk-n7576zsr.js} +3 -3
  128. package/dist/{chunk-ff60bzvf.js.map → chunk-n7576zsr.js.map} +1 -1
  129. package/dist/{chunk-s782bzeq.js → chunk-nbfksexg.js} +2 -2
  130. package/dist/{chunk-s782bzeq.js.map → chunk-nbfksexg.js.map} +1 -1
  131. package/dist/{chunk-p82868xx.js → chunk-p1y58p84.js} +2 -2
  132. package/dist/{chunk-p82868xx.js.map → chunk-p1y58p84.js.map} +1 -1
  133. package/dist/{chunk-zv5qyrqg.js → chunk-p2c7z2nr.js} +2 -2
  134. package/dist/{chunk-zv5qyrqg.js.map → chunk-p2c7z2nr.js.map} +1 -1
  135. package/dist/{chunk-vnw91fe1.js → chunk-pv2mtg8n.js} +2 -2
  136. package/dist/{chunk-vnw91fe1.js.map → chunk-pv2mtg8n.js.map} +1 -1
  137. package/dist/{chunk-jx5zx48j.js → chunk-qfhcec6q.js} +2 -2
  138. package/dist/{chunk-jx5zx48j.js.map → chunk-qfhcec6q.js.map} +1 -1
  139. package/dist/{chunk-6hz63ts4.js → chunk-qk6vmvr2.js} +4 -4
  140. package/dist/{chunk-6hz63ts4.js.map → chunk-qk6vmvr2.js.map} +1 -1
  141. package/dist/{chunk-w1cksc5z.js → chunk-qvx8473q.js} +3 -3
  142. package/dist/{chunk-w1cksc5z.js.map → chunk-qvx8473q.js.map} +1 -1
  143. package/dist/{chunk-4278e429.js → chunk-rqb52m93.js} +2 -2
  144. package/dist/{chunk-4278e429.js.map → chunk-rqb52m93.js.map} +1 -1
  145. package/dist/{chunk-py1twqh8.js → chunk-skmdmqv7.js} +2 -2
  146. package/dist/{chunk-py1twqh8.js.map → chunk-skmdmqv7.js.map} +1 -1
  147. package/dist/{chunk-04tkpna8.js → chunk-t0p6zb29.js} +2 -2
  148. package/dist/{chunk-04tkpna8.js.map → chunk-t0p6zb29.js.map} +1 -1
  149. package/dist/{chunk-53rr32zm.js → chunk-ted0qjps.js} +1 -1
  150. package/dist/{chunk-hj88dcss.js → chunk-v4dp93qv.js} +3 -3
  151. package/dist/{chunk-hj88dcss.js.map → chunk-v4dp93qv.js.map} +1 -1
  152. package/dist/{chunk-33hdxe7v.js → chunk-vmr4d6hc.js} +1 -1
  153. package/dist/{chunk-3g5q0cj5.js → chunk-vz5rrcnh.js} +2 -2
  154. package/dist/{chunk-3g5q0cj5.js.map → chunk-vz5rrcnh.js.map} +1 -1
  155. package/dist/{chunk-pm8wjatv.js → chunk-w17p2k8g.js} +3 -3
  156. package/dist/{chunk-pm8wjatv.js.map → chunk-w17p2k8g.js.map} +1 -1
  157. package/dist/{chunk-j5g7qc5f.js → chunk-wbvb1hcx.js} +2 -2
  158. package/dist/{chunk-j5g7qc5f.js.map → chunk-wbvb1hcx.js.map} +1 -1
  159. package/dist/{chunk-t8xs9ptb.js → chunk-x1j7e46e.js} +2 -2
  160. package/dist/{chunk-t8xs9ptb.js.map → chunk-x1j7e46e.js.map} +1 -1
  161. package/dist/{chunk-jx2mgvvt.js → chunk-xwmy6fby.js} +3 -3
  162. package/dist/{chunk-jx2mgvvt.js.map → chunk-xwmy6fby.js.map} +1 -1
  163. package/dist/{chunk-z61dj480.js → chunk-y6gr3stt.js} +3 -3
  164. package/dist/{chunk-z61dj480.js.map → chunk-y6gr3stt.js.map} +1 -1
  165. package/dist/{chunk-4t41m5f1.js → chunk-yhp70t40.js} +2 -2
  166. package/dist/{chunk-4t41m5f1.js.map → chunk-yhp70t40.js.map} +1 -1
  167. package/dist/{chunk-zypmy8yq.js → chunk-z0jazehw.js} +2 -2
  168. package/dist/{chunk-zypmy8yq.js.map → chunk-z0jazehw.js.map} +1 -1
  169. package/dist/{chunk-541s0vkt.js → chunk-z19rwc6x.js} +5 -5
  170. package/dist/{chunk-541s0vkt.js.map → chunk-z19rwc6x.js.map} +1 -1
  171. package/dist/{chunk-gqgpwb88.js → chunk-z969a4nt.js} +2 -2
  172. package/dist/{chunk-gqgpwb88.js.map → chunk-z969a4nt.js.map} +1 -1
  173. package/dist/{chunk-hf492gg2.js → chunk-zj8y4ak5.js} +1 -1
  174. package/dist/{chunk-qpwb3gnh.js → chunk-zvzvgrrn.js} +2 -2
  175. package/dist/{chunk-qpwb3gnh.js.map → chunk-zvzvgrrn.js.map} +1 -1
  176. package/dist/config/index.js +1 -1
  177. package/dist/console/run.js +2 -2
  178. package/dist/console/run.js.map +1 -1
  179. package/dist/container/index.js +2 -2
  180. package/dist/container/index.js.map +1 -1
  181. package/dist/database/index.js +2 -2
  182. package/dist/database/index.js.map +1 -1
  183. package/dist/email/index.js +2 -2
  184. package/dist/email/index.js.map +1 -1
  185. package/dist/facades/index.js +2 -2
  186. package/dist/facades/index.js.map +1 -1
  187. package/dist/foundation/index.js +2 -2
  188. package/dist/foundation/index.js.map +1 -1
  189. package/dist/http/index.js +2 -2
  190. package/dist/http/index.js.map +1 -1
  191. package/dist/i18n/dictionaryRuntime.js +2 -2
  192. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  193. package/dist/i18n/index.js +2 -2
  194. package/dist/i18n/index.js.map +1 -1
  195. package/dist/kernel/index.js +2 -2
  196. package/dist/kernel/index.js.map +1 -1
  197. package/dist/orm/index.js +2 -2
  198. package/dist/orm/index.js.map +1 -1
  199. package/dist/server/index.js +2 -2
  200. package/dist/server/index.js.map +1 -1
  201. package/dist/services/index.js +2 -2
  202. package/dist/services/index.js.map +1 -1
  203. package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
  204. package/dist/services/queue/work.js +2 -2
  205. package/dist/services/queue/work.js.map +1 -1
  206. package/dist/stats/route-table.js +1 -1
  207. package/dist/support/index.js +2 -2
  208. package/dist/support/index.js.map +1 -1
  209. package/dist/vitest/index.js +1 -1
  210. package/package.json +1 -1
  211. package/dist/chunk-2cnawkke.js +0 -22
  212. package/dist/chunk-2cnawkke.js.map +0 -21
  213. package/dist/chunk-3gx7wcrt.js +0 -10
  214. package/dist/chunk-47e7fbsp.js +0 -5
  215. /package/dist/{chunk-1awxdnb6.js.map → chunk-c0m8pcbd.js.map} +0 -0
  216. /package/dist/{chunk-gng5e7pd.js.map → chunk-fwmmy0jn.js.map} +0 -0
  217. /package/dist/{chunk-mpqvmge4.js.map → chunk-kzdkpz04.js.map} +0 -0
  218. /package/dist/{chunk-53rr32zm.js.map → chunk-ted0qjps.js.map} +0 -0
  219. /package/dist/{chunk-33hdxe7v.js.map → chunk-vmr4d6hc.js.map} +0 -0
  220. /package/dist/{chunk-hf492gg2.js.map → chunk-zj8y4ak5.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ng as sQ}from"./chunk-ff60bzvf.js";import{fh as iQ}from"./chunk-feajsgns.js";import{Dh as C,Eh as A8,Fh as WZ,Gh as Q8,Hh as e3,Jh as L$,Kh as v,Lh as b4,Zh as $6,ei as YZ,gh as tZ,ii as aX,ji as h$,kh as aG,ki as p$,lh as TW,li as NQ,mh as MW,nh as G8,ni as _Q,oh as J8,rh as W8,sh as Y8,th as cZ,uh as CG,vh as $Q,wh as u9,xh as h}from"./chunk-0rhf4g12.js";import{qi as d1,ri as Y0,si as l1,ti as _W}from"./chunk-zv5qyrqg.js";import{Ai as g4,Bi as N,ui as q3,vi as YQ,zi as G5}from"./chunk-4t41m5f1.js";import{Ei as lX,Hi as k3}from"./chunk-hj88dcss.js";import{Li as P5,Oi as UQ}from"./chunk-z61dj480.js";import{ej as D$,jj as u1}from"./chunk-vnw91fe1.js";import{xj as AX}from"./chunk-jy9dkgt0.js";import{Bj as OQ,yj as c$}from"./chunk-ysc7ykss.js";import{Cj as O1}from"./chunk-jx5zx48j.js";import{Dj as a3,Ej as i0,Fj as x1,Gj as dQ,Hj as uQ,Jj as kZ,Kj as TQ,Tj as lQ}from"./chunk-z9xxthp1.js";import{gk as C1}from"./chunk-65j32dtn.js";import{lk as sG,qk as Q9}from"./chunk-beb265c9.js";import{Ck as s,xk as iG}from"./chunk-zypmy8yq.js";import{Dk as pZ,Gk as L}from"./chunk-jx2mgvvt.js";import{Ok as z9}from"./chunk-x9bk5s21.js";import{Pk as xQ}from"./chunk-gqgpwb88.js";import{Zk as Z9}from"./chunk-cxsvzqd4.js";import{$k as rG}from"./chunk-99a4e6zf.js";import{el as m4}from"./chunk-rnp5k8m3.js";function u3($){return typeof $==="function"&&$.prototype!==void 0}function l0($){return typeof $==="string"?[$]:$}function l3($,Z){let J=Z?"attachment":"inline",W=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${W}"; filename*=UTF-8''${encodeURIComponent($)}`}function YK($){return"total"in $&&"partial"in $&&"body"in $}function y9(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function sZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":Y8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function jK($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(YK($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function j8($,Z){if($ instanceof Response)return $;if(!$)return y9();let J=await jK($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return y9()}let{range:G}=Z;if(G){if(z<=0)return sZ(Math.max(z,0));if(!X){if(W instanceof Blob){let F=J8(G,z);if(!F)return sZ(z);W=W.slice(F.start,F.end+1),Y=F.start,j=F.end,X=!0}}}let Q=Boolean(G)&&X,K=Q?206:J.status,B=new Headers;if(B.set("Accept-Ranges","bytes"),B.set("Content-Type",J.type||"application/octet-stream"),B.set("X-Content-Type-Options","nosniff"),Q)B.set("Content-Range",W8(Y,j,z)),B.set("Content-Length",String(j-Y+1));else if(z>=0)B.set("Content-Length",String(z));if(J.name)B.set("Content-Disposition",l3(J.name,J.download));if(J.etag)B.set("ETag",J.etag);if(J.lastModified)B.set("Last-Modified",J.lastModified.toUTCString());for(let[F,D]of Object.entries(J.extraHeaders))B.set(F,D);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:K,headers:B})}return new Response(W,{status:K,headers:B})}class r$ extends Y0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var v9={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function oZ($){if(typeof $==="number"){if(Number.isFinite($)&&$>=0)return Math.floor($);if($===1/0)return 1/0}else{let Z=$.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in v9)))return Math.floor(Number(J[1])*(v9[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var nZ=new WeakMap;function m9($){return nZ.has($)}function h9($){return nZ.get($)?.limit??null}function p9($){let Z=nZ.get($);return Z?Z.read>Z.limit:!1}function zK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function X8($,Z){let J=zK($);if(J!==null&&J>Z)throw new r$(Z)}function i3($,Z,J={}){let W=nZ.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};nZ.set($,Y),GK($,Y)}if(J.checkDeclared!==!1)X8($,Z)}function XK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function z8($,Z){if(Z.stream!==void 0)return Z.stream;let J=XK($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new r$(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function a$($,Z){if(X8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=z8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:G,value:Q}=await W.read();if(G)break;Y.push(Q),j+=Q.byteLength}let z=new Uint8Array(j),X=0;for(let G of Y)z.set(G,X),X+=G.byteLength;return z}function g9($){return $.headers.get("Content-Type")??""}function GK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>z8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>a$($,Z)}),J("arrayBuffer",{value:async()=>{let W=await a$($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await a$($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await a$($,Z)))}),J("blob",{value:async()=>new Blob([await a$($,Z)],{type:g9($)})}),J("formData",{value:async()=>new Response(await a$($,Z),{headers:{"Content-Type":g9($)}}).formData()}),J("clone",{value:()=>{X8($,Z.limit);let W=z8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function c9($){return u3($)}class 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(!c9(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(c9(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=l0($),this}}class l9{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 u9($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(p9($.rawRequest))throw new r$(h9($.rawRequest));throw J}}}class i9{constructor(...$){return new l(...$)}}class s9 extends l{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,W=G8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);return await j8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof Q8)return sZ(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class n9{constructor(...$){return new s9(...$)}}class o9{__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 N0{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 o9($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${d9($)}.`);return QK($,this)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${d9($)}.`);return KK($,this)}file($,Z){return new i9("GET",$,Z)}stream($,Z){return new n9("GET",$,Z)}proxy($,Z={}){return new l9($,Z)}}function d9($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function QK($,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 N0{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 KK($,Z){let J={start:new l("POST",$,"voiceStart"),update:new l("PATCH",$,"voiceUpdate"),end:new l("DELETE",$,"voiceEnd")};return class extends N0{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 O$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function s3($,Z){let J=O$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var FK=/^[A-Za-z0-9_-]+$/,BK=/^:[A-Za-z_][A-Za-z0-9_]*$/,a9=/^[A-Za-z0-9_-]{1,128}$/,VK=/^[A-Za-z0-9_.:-]+$/;class p extends Error{constructor($){super($);this.name="InvalidChannelError"}}function r9($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function t$($){if(typeof $!=="string"||$.length===0)throw new p("A channel pattern must be a non-empty string.");if($.length>255)throw new p(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(BK.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(!FK.test(W))throw new p(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function aZ($,Z={}){let J=t$($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new p(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!a9.test(G))throw new p(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new p(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new p(`The topic built from "${$}" is longer than 255 characters.`);return Y}function K8($){if(t$($).some((J)=>J.startsWith(":")))throw new p(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function t9($){if(typeof $!=="string"||$.length===0||$.length>64||!VK.test($))throw new p(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function e9($,Z){if($===Z)return!0;if($===F0)return Z.startsWith(`${F0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&a9.test(W[j]))}var F0="user";function e$($){let Z=typeof $==="object"&&$!==null?$.id:$;return aZ(`${F0}.:id`,{id:Z})}class t{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class n3 extends t{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return i3(this.req.rawRequest,oZ(Z)),{}}}function OK($){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 DK={"body-limit":n3};class c1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:oZ($.bodyLimit)}get aliases(){return{...DK,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!m9($))i3($,this.defaultBodyLimit,{checkDeclared:!1})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new C,J=this.aliases,W=[];for(let[Y,j]of OK($).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:$W(z)})}}else if(u3(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:$W(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 UK(W.slice(j+1)),z}return Y})()}}function $W($){return $?.runsOnRefusal===!0}async function UK($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class o3{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...l0($)],this}events(...$){return this}}class YW{static __brand="ChannelRouter";channels={};public(){return new o3("public")}private($){return new o3("private",$)}async authorize($,Z,J={},W={}){try{PK(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!jW(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===F0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=aZ(Z,J??{})}catch(G){if(G instanceof p)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new C($,z,"api",Z);return N.exit(()=>a3.exit(()=>N.run(X,async()=>{let G=N.getStore();try{if(Y.middlewares.length>0)await L(c1).runMiddleware(Y.middlewares);if(Z===F0){let Q=await ZW(X);if(!Q)return{ok:!1,code:"denied"};if(j=e$(Q),Y.visibility==="private"&&Y.authorizer){if(await JW(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 JW(Y.authorizer,X,z):await ZW(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(IK(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function LK($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;zW(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 jW($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function ZW($){if(!N.getStore().user&&O$($)===null)return null;try{return await R0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function JW($,Z,J){if(HK($))return new $().authorize(Z,J);return $(Z,J)}function HK($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function IK($){return $?.kind===d1||u1($)||D$($)}var WW=new WeakSet;function PK($){if(WW.has($))return;zW($),WW.add($)}function zW($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!jW(Y))throw new p(`The channel "${W}" is not declared with this.public() or this.private().`);let j=t$(W);if(j[0].startsWith(":"))throw new p(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==F0&&j.length===2&&j[0]===F0)throw new p(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==F0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new p(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===F0?[F0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(TK(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 TK($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class F8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class B8{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class V8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}class XW{static __brand="McpRouter";routes={};scopes;param($){return new F8($.as,$.input,$.bind)}fromTool($,Z={}){return new V8($,Z)}fromApiRoute($,Z,J){return new B8($,Z,J)}}function B0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class O8 extends Y0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class M1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new O8([B0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new O8($,Z)}}var GW=Symbol.for("gemi.HttpResponse");class U${kind;body;status;headers;[GW]=!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 MK(J),new U$("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return U$.json({error:Z},{...J,status:$})}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null}}}function MK($){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.json: a ${$} response has no body.`)}function $Z($){return typeof $==="object"&&$!==null&&$[GW]===!0}function NK($,Z,J={}){return U$.error($,Z,J)}class QW{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return M1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function D8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",l3(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class KW{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 FW($,Z){if($Z($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class BW{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=FW(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 VW{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends N1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends N1{routes=J??{}}}else this.children=class extends N1{routes=Z},this.handler=()=>({})}async run($,Z){let J=FW(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class N1{middlewares=[];featureGates=[];routes={};view($,Z){return new BW($,Z)}file($){return new KW($)}redirect($){return new QW($)}layout($,Z,J){return new VW($,Z,J)}}function _K($){return $}function xK(){return{aliases:{},global:[],bodyLimit:null}}var Y1="redirect";function j1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function ZZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function CK($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(L(s).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function SK($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function r3($,Z){let J=Z||L(E).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=CK($,!W);if(W||!SK(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(Y1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class OW extends t{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let W=await s3(L(E),J);if(!W)throw new L$({redirectTo:r3(J,$)});return Z.setUser(W),{}}}var L8="gemi_same_site",U8="private, no-cache, no-store, max-age=0, must-revalidate";class t3 extends t{run(){let $=N.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(L8))return{};if(O$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(L8,"1"),new DW(`${W.pathname}${W.search}`)}}class DW extends Y0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=AK($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":U8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":U8}},viewData:{status:200,data:{},headers:{"Cache-Control":U8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function AK($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class UW extends t{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 LW={"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 HW extends t{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={...LW,...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={...LW,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var EK="Rate limit exceeded";class i1 extends Y0{result;retryAfter;constructor($,Z=EK){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?H8($):{}};this.payload={api:{status:429,data:{error:{...l1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function H8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class z1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(IW("window",W),IW("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 IW($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}class NW extends t{async run($,Z){let J=fK();if(!J)return{};let W=await J.consume(this.key(),{limit:PW($)??this.config.limit,window:PW(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(H8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new i1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=TW(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${JZ(this.req)}:${this.req.routePath??"*"}`}}function fK(){try{let $=L();return $.bound(z1)?$.make(z1):null}catch{return null}}function JZ($){let Z=MW($.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 PW($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class xW extends t{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new I8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new I8;return{}}}class I8 extends Y0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:_W("csrf","Invalid CSRF token",403)}},view:{}}}class CW{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class SW{all($,Z){return!0}}class P8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new WZ:new e3}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new C,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends t{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof WZ:$ instanceof e3}}function bK($){return new P8($)}async function Z6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await lK($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return uK(z,Z,J,$.url)}async function uK($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:K}=await Y.read();if(Q)break;if(z+K.byteLength>Z){if(!J)throw new $6(W,Z);j.push(K.subarray(0,Z-z)),z=Z;break}j.push(K),z+=K.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function lK($){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 iK={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function H$($){return $.replace(/[&<>"']/g,(Z)=>iK[Z])}var sK={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function T8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return sK[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function M8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function AW($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(T8($.slice(W)));return}if(Y>W)Z.text(T8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(M8($.slice(Y+2,j).trim())),W=j+1}else{let j=nK($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=M8(z.slice(0,G));if(Q){if(Z.open(Q,oK(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function nK($,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 oK($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[M8(W[1])]=T8(W[2]??W[3]??"");return Z}class j0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var wW="http://www.sitemaps.org/schemas/sitemap/0.9",aK="http://www.w3.org/1999/xhtml",x8=`<?xml version="1.0" encoding="UTF-8"?>
2
+ import{Zg as sQ}from"./chunk-n7576zsr.js";import{rh as iQ}from"./chunk-5benn2ys.js";import{Ah as J8,Dh as W8,Eh as Y8,Fh as cZ,Gh as CG,Hh as $Q,Ih as u9,Jh as h,Ph as C,Qh as A8,Rh as WZ,Sh as Q8,Th as e3,Vh as L$,Wh as v,Xh as b4,ji as $6,qi as YZ,sh as tZ,ui as aX,vi as h$,wh as aG,wi as p$,xh as TW,xi as NQ,yh as MW,zh as G8,zi as _Q}from"./chunk-md6wfc1h.js";import{Ci as d1,Di as Y0,Ei as l1,Fi as _W}from"./chunk-p2c7z2nr.js";import{Gi as q3,Hi as YQ,Li as G5,Mi as g4,Ni as N}from"./chunk-yhp70t40.js";import{Qi as lX,Ti as k3}from"./chunk-v4dp93qv.js";import{Xi as P5,_i as UQ}from"./chunk-y6gr3stt.js";import{qj as D$,vj as u1}from"./chunk-pv2mtg8n.js";import{Jj as AX}from"./chunk-ant9ck0r.js";import{Kj as c$,Nj as OQ}from"./chunk-7d26eqv1.js";import{Oj as O1}from"./chunk-qfhcec6q.js";import{Pj as a3,Qj as i0,Rj as x1,Sj as dQ,Tj as uQ,Vj as kZ,Wj as TQ,dk as lQ}from"./chunk-ghbzre7k.js";import{sk as C1}from"./chunk-c6c7p43e.js";import{Ck as Q9,xk as sG}from"./chunk-e440f645.js";import{Jk as iG,Ok as s}from"./chunk-z0jazehw.js";import{Pk as pZ,Sk as L}from"./chunk-xwmy6fby.js";import{_k as z9}from"./chunk-c83e4ghx.js";import{$k as xQ}from"./chunk-z969a4nt.js";import{jl as Z9}from"./chunk-aj2sr77y.js";import{ll as rG}from"./chunk-f9w78tbd.js";import{ql as m4}from"./chunk-038xtqpm.js";function u3($){return typeof $==="function"&&$.prototype!==void 0}function l0($){return typeof $==="string"?[$]:$}function l3($,Z){let J=Z?"attachment":"inline",W=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${W}"; filename*=UTF-8''${encodeURIComponent($)}`}function YK($){return"total"in $&&"partial"in $&&"body"in $}function y9(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function sZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":Y8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function jK($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(YK($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function j8($,Z){if($ instanceof Response)return $;if(!$)return y9();let J=await jK($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return y9()}let{range:G}=Z;if(G){if(z<=0)return sZ(Math.max(z,0));if(!X){if(W instanceof Blob){let F=J8(G,z);if(!F)return sZ(z);W=W.slice(F.start,F.end+1),Y=F.start,j=F.end,X=!0}}}let Q=Boolean(G)&&X,K=Q?206:J.status,B=new Headers;if(B.set("Accept-Ranges","bytes"),B.set("Content-Type",J.type||"application/octet-stream"),B.set("X-Content-Type-Options","nosniff"),Q)B.set("Content-Range",W8(Y,j,z)),B.set("Content-Length",String(j-Y+1));else if(z>=0)B.set("Content-Length",String(z));if(J.name)B.set("Content-Disposition",l3(J.name,J.download));if(J.etag)B.set("ETag",J.etag);if(J.lastModified)B.set("Last-Modified",J.lastModified.toUTCString());for(let[F,D]of Object.entries(J.extraHeaders))B.set(F,D);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:K,headers:B})}return new Response(W,{status:K,headers:B})}class r$ extends Y0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var v9={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function oZ($){if(typeof $==="number"){if(Number.isFinite($)&&$>=0)return Math.floor($);if($===1/0)return 1/0}else{let Z=$.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in v9)))return Math.floor(Number(J[1])*(v9[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var nZ=new WeakMap;function m9($){return nZ.has($)}function h9($){return nZ.get($)?.limit??null}function p9($){let Z=nZ.get($);return Z?Z.read>Z.limit:!1}function zK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function X8($,Z){let J=zK($);if(J!==null&&J>Z)throw new r$(Z)}function i3($,Z,J={}){let W=nZ.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};nZ.set($,Y),GK($,Y)}if(J.checkDeclared!==!1)X8($,Z)}function XK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function z8($,Z){if(Z.stream!==void 0)return Z.stream;let J=XK($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new r$(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function a$($,Z){if(X8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=z8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:G,value:Q}=await W.read();if(G)break;Y.push(Q),j+=Q.byteLength}let z=new Uint8Array(j),X=0;for(let G of Y)z.set(G,X),X+=G.byteLength;return z}function g9($){return $.headers.get("Content-Type")??""}function GK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>z8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>a$($,Z)}),J("arrayBuffer",{value:async()=>{let W=await a$($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await a$($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await a$($,Z)))}),J("blob",{value:async()=>new Blob([await a$($,Z)],{type:g9($)})}),J("formData",{value:async()=>new Response(await a$($,Z),{headers:{"Content-Type":g9($)}}).formData()}),J("clone",{value:()=>{X8($,Z.limit);let W=z8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function c9($){return u3($)}class 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(!c9(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(c9(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=l0($),this}}class l9{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 u9($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(p9($.rawRequest))throw new r$(h9($.rawRequest));throw J}}}class i9{constructor(...$){return new l(...$)}}class s9 extends l{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,W=G8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);return await j8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof Q8)return sZ(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class n9{constructor(...$){return new s9(...$)}}class o9{__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 N0{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 o9($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${d9($)}.`);return QK($,this)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${d9($)}.`);return KK($,this)}file($,Z){return new i9("GET",$,Z)}stream($,Z){return new n9("GET",$,Z)}proxy($,Z={}){return new l9($,Z)}}function d9($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function QK($,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 N0{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 KK($,Z){let J={start:new l("POST",$,"voiceStart"),update:new l("PATCH",$,"voiceUpdate"),end:new l("DELETE",$,"voiceEnd")};return class extends N0{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 O$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function s3($,Z){let J=O$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var FK=/^[A-Za-z0-9_-]+$/,BK=/^:[A-Za-z_][A-Za-z0-9_]*$/,a9=/^[A-Za-z0-9_-]{1,128}$/,VK=/^[A-Za-z0-9_.:-]+$/;class p extends Error{constructor($){super($);this.name="InvalidChannelError"}}function r9($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function t$($){if(typeof $!=="string"||$.length===0)throw new p("A channel pattern must be a non-empty string.");if($.length>255)throw new p(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(BK.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(!FK.test(W))throw new p(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function aZ($,Z={}){let J=t$($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new p(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!a9.test(G))throw new p(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new p(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new p(`The topic built from "${$}" is longer than 255 characters.`);return Y}function K8($){if(t$($).some((J)=>J.startsWith(":")))throw new p(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function t9($){if(typeof $!=="string"||$.length===0||$.length>64||!VK.test($))throw new p(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function e9($,Z){if($===Z)return!0;if($===F0)return Z.startsWith(`${F0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&a9.test(W[j]))}var F0="user";function e$($){let Z=typeof $==="object"&&$!==null?$.id:$;return aZ(`${F0}.:id`,{id:Z})}class t{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class n3 extends t{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return i3(this.req.rawRequest,oZ(Z)),{}}}function OK($){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 DK={"body-limit":n3};class c1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:oZ($.bodyLimit)}get aliases(){return{...DK,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!m9($))i3($,this.defaultBodyLimit,{checkDeclared:!1})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new C,J=this.aliases,W=[];for(let[Y,j]of OK($).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:$W(z)})}}else if(u3(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:$W(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 UK(W.slice(j+1)),z}return Y})()}}function $W($){return $?.runsOnRefusal===!0}async function UK($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class o3{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...l0($)],this}events(...$){return this}}class YW{static __brand="ChannelRouter";channels={};public(){return new o3("public")}private($){return new o3("private",$)}async authorize($,Z,J={},W={}){try{PK(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!jW(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===F0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=aZ(Z,J??{})}catch(G){if(G instanceof p)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new C($,z,"api",Z);return N.exit(()=>a3.exit(()=>N.run(X,async()=>{let G=N.getStore();try{if(Y.middlewares.length>0)await L(c1).runMiddleware(Y.middlewares);if(Z===F0){let Q=await ZW(X);if(!Q)return{ok:!1,code:"denied"};if(j=e$(Q),Y.visibility==="private"&&Y.authorizer){if(await JW(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 JW(Y.authorizer,X,z):await ZW(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(IK(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function LK($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;zW(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 jW($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function ZW($){if(!N.getStore().user&&O$($)===null)return null;try{return await R0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function JW($,Z,J){if(HK($))return new $().authorize(Z,J);return $(Z,J)}function HK($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function IK($){return $?.kind===d1||u1($)||D$($)}var WW=new WeakSet;function PK($){if(WW.has($))return;zW($),WW.add($)}function zW($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!jW(Y))throw new p(`The channel "${W}" is not declared with this.public() or this.private().`);let j=t$(W);if(j[0].startsWith(":"))throw new p(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==F0&&j.length===2&&j[0]===F0)throw new p(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==F0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new p(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===F0?[F0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(TK(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 TK($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class F8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class B8{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class V8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}class XW{static __brand="McpRouter";routes={};scopes;param($){return new F8($.as,$.input,$.bind)}fromTool($,Z={}){return new V8($,Z)}fromApiRoute($,Z,J){return new B8($,Z,J)}}function B0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class O8 extends Y0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class M1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new O8([B0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new O8($,Z)}}var GW=Symbol.for("gemi.HttpResponse");class U${kind;body;status;headers;[GW]=!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 MK(J),new U$("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return U$.json({error:Z},{...J,status:$})}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null}}}function MK($){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.json: a ${$} response has no body.`)}function $Z($){return typeof $==="object"&&$!==null&&$[GW]===!0}function NK($,Z,J={}){return U$.error($,Z,J)}class QW{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return M1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function D8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",l3(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class KW{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 FW($,Z){if($Z($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class BW{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=FW(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 VW{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends N1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends N1{routes=J??{}}}else this.children=class extends N1{routes=Z},this.handler=()=>({})}async run($,Z){let J=FW(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class N1{middlewares=[];featureGates=[];routes={};view($,Z){return new BW($,Z)}file($){return new KW($)}redirect($){return new QW($)}layout($,Z,J){return new VW($,Z,J)}}function _K($){return $}function xK(){return{aliases:{},global:[],bodyLimit:null}}var Y1="redirect";function j1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function ZZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function CK($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(L(s).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function SK($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function r3($,Z){let J=Z||L(E).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=CK($,!W);if(W||!SK(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(Y1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class OW extends t{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let W=await s3(L(E),J);if(!W)throw new L$({redirectTo:r3(J,$)});return Z.setUser(W),{}}}var L8="gemi_same_site",U8="private, no-cache, no-store, max-age=0, must-revalidate";class t3 extends t{run(){let $=N.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(L8))return{};if(O$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(L8,"1"),new DW(`${W.pathname}${W.search}`)}}class DW extends Y0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=AK($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":U8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":U8}},viewData:{status:200,data:{},headers:{"Cache-Control":U8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function AK($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class UW extends t{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 LW={"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 HW extends t{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={...LW,...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={...LW,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var EK="Rate limit exceeded";class i1 extends Y0{result;retryAfter;constructor($,Z=EK){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?H8($):{}};this.payload={api:{status:429,data:{error:{...l1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function H8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class z1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(IW("window",W),IW("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 IW($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}class NW extends t{async run($,Z){let J=fK();if(!J)return{};let W=await J.consume(this.key(),{limit:PW($)??this.config.limit,window:PW(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(H8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new i1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=TW(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${JZ(this.req)}:${this.req.routePath??"*"}`}}function fK(){try{let $=L();return $.bound(z1)?$.make(z1):null}catch{return null}}function JZ($){let Z=MW($.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 PW($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class xW extends t{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new I8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new I8;return{}}}class I8 extends Y0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:_W("csrf","Invalid CSRF token",403)}},view:{}}}class CW{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class SW{all($,Z){return!0}}class P8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new WZ:new e3}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new C,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends t{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof WZ:$ instanceof e3}}function bK($){return new P8($)}async function Z6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await lK($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return uK(z,Z,J,$.url)}async function uK($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:K}=await Y.read();if(Q)break;if(z+K.byteLength>Z){if(!J)throw new $6(W,Z);j.push(K.subarray(0,Z-z)),z=Z;break}j.push(K),z+=K.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function lK($){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 iK={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function H$($){return $.replace(/[&<>"']/g,(Z)=>iK[Z])}var sK={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function T8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return sK[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function M8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function AW($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(T8($.slice(W)));return}if(Y>W)Z.text(T8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(M8($.slice(Y+2,j).trim())),W=j+1}else{let j=nK($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=M8(z.slice(0,G));if(Q){if(Z.open(Q,oK(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function nK($,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 oK($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[M8(W[1])]=T8(W[2]??W[3]??"");return Z}class j0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var wW="http://www.sitemaps.org/schemas/sitemap/0.9",aK="http://www.w3.org/1999/xhtml",x8=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  `,EW=`<urlset xmlns="${wW}" xmlns:xhtml="${aK}">
4
4
  `,fW=`</urlset>
5
5
  `,I$=50000,rZ=52428800,bW=2048,rK=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),tK=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,eK="application/xml; charset=utf-8",RW=new TextEncoder;function C8($,Z){let J;try{J=new URL($)}catch{throw new j0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new j0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>bW)throw new j0(`Sitemap: ${Z} is over ${bW} characters: "${W.slice(0,80)}\u2026".`);return W}function kW($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new j0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!tK.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 $F($){let Z=C8($.loc,"loc"),J=`<url><loc>${H$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${H$(kW($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!rK.has($.changefreq))throw new j0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);J+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let W=$.priority;if(!Number.isFinite(W)||W<0||W>1)throw new j0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let Y=W.hrefLang?.trim();if(!Y)throw new j0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=C8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${H$(Y)}" href="${H$(j)}"/>`}return`${J}</url>
@@ -14,7 +14,7 @@ ${Z}</sitemapindex>
14
14
  `)),Z.onSettle((K)=>{if(X||K.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([K.path,K.variantKey,K.data])}
15
15
  `))});let Q=setTimeout(()=>G(!0),J);Z.allSettled().then(()=>G(!1),()=>G(!1))},cancel(){j(!1)}})}import{Fragment as fM,createContext as QD,createElement as bM,lazy as RM,use as wM,useContext as kM}from"react";function fG($){return{islands:[],render:$,instances:new WeakMap,count:0}}var g3="gemi-slot",bG="data-slot",RG="data-gemi-slot";var KD=Symbol.for("gemi.staticRender"),wG=globalThis[KD]??=QD(null);import{createHash as gG}from"crypto";var t7='var r=document,i=window,a=history;i.__gemi_nav?.d();var L=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:L.signal,...s}),q=i.__gemi_nav={d:()=>L.abort()},v=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},D=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},R=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")v(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>v(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),v(n,s)});for(let m of n.children)l.observe(m)}}},O=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(O)?.content,C=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},y={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,N=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},Y=(t)=>{let e=r.body,n=t.body,s=D(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),R(e,s)},H=async(t,e)=>{let n=++b,s=!e&&y[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||C(d)!=C(r))throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),Y(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)N(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),y[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=y[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(y[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(O)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();R(r,D(r));_(!0);';import{createHash as FD}from"crypto";import{existsSync as qG,readFileSync as BD}from"fs";import{join as J9}from"path";var yG=".script",VD=[".ts",".js"],OD="document-scripts.json",vG="data-gemi-script",DD=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function UD($){if(typeof $!=="string"||!DD.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 LD($,Z){for(let J of VD){let W=J9($,"views",`${Z}${yG}${J}`);if(qG(W))return W}return null}async function kG($){let Z=await Bun.build({entrypoints:[$],target:"browser",format:"iife",minify:!0,throw:!1});if(!Z.success||!Z.outputs[0]){let W=Z.logs.map((Y)=>String(Y)).join(`
16
16
  `);throw Error(`The document script ${$} does not bundle.
17
- ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function HD($){return`'sha256-${FD("sha256").update($).digest("base64")}'`}var e7,$9=new Map;function ID(){if(e7===void 0){let $=J9(Z9(),"dist","server",OD);e7=qG($)?JSON.parse(BD($,"utf8")):null}return e7??null}async function W9($){UD($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=ID()?.[$];if(j!==void 0)return j;let z=$9.get($);if(z)return z}let J=J9(Z9(),"app"),W=LD(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${yG}.ts (or .js).`);if(!Z)return kG(W);let Y=kG(W);return $9.set($,Y),Y.catch(()=>$9.delete($)),Y}async function pM($){return HD(await W9($))}var PD="gemi-islands",oM=`'sha256-${gG("sha256").update(z9).digest("base64")}'`;function Y9($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var j9=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),aM=`'sha256-${gG("sha256").update(t7).digest("base64")}'`,TD='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',MD="gemi-static";function mG($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((V)=>{let O=V.module?J(V.module):void 0;if(!O)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 O.preload)z.add(U);if(V.preloadDynamic)for(let U of O.dynamicPreload??[])z.add(U)}return{s:O.src,e:V.export,l:V.load}});let G=X.some((V)=>V!==null),Q=j?`<script type="module" ${vG}="${j9(j.name)}">${j.source}</script>`:"";if(!G&&!Y)return Y9($,"</head>",Q,!1);let B=(Y?`<meta name="${MD}" content="${j9(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((V)=>`<link rel="modulepreload" href="${j9(V)}"/>`).join("")+Q,F=Y?t7:z9,D=(G?`<script type="application/json" id="${PD}">${_1({i:X})}</script>`:"")+`<script type="module">${W?TD+F:F}</script>`;return Y9(Y9($,"</head>",B,!1),"</body>",D,!0)}function ND($,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 hG($){let Z=`<template ${RG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=ND($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let G=`<${g3} ${bG}="${j}" style="display:contents"></${g3}>`;$=$.split(G).join(`<${g3} style="display:contents">${X}</${g3}>`)}return $}function pG($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function cG($,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 _D=async()=>(await import("./chunk-pm8wjatv.js")).default,X9,m3=async(...$)=>{return X9??=import("react-dom/server.browser").catch((Z)=>{throw X9=void 0,Z}),(await X9).renderToReadableStream(...$)},uG=1e4,lG="no-locale",xD=`
17
+ ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function HD($){return`'sha256-${FD("sha256").update($).digest("base64")}'`}var e7,$9=new Map;function ID(){if(e7===void 0){let $=J9(Z9(),"dist","server",OD);e7=qG($)?JSON.parse(BD($,"utf8")):null}return e7??null}async function W9($){UD($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=ID()?.[$];if(j!==void 0)return j;let z=$9.get($);if(z)return z}let J=J9(Z9(),"app"),W=LD(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${yG}.ts (or .js).`);if(!Z)return kG(W);let Y=kG(W);return $9.set($,Y),Y.catch(()=>$9.delete($)),Y}async function pM($){return HD(await W9($))}var PD="gemi-islands",oM=`'sha256-${gG("sha256").update(z9).digest("base64")}'`;function Y9($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var j9=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),aM=`'sha256-${gG("sha256").update(t7).digest("base64")}'`,TD='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',MD="gemi-static";function mG($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((V)=>{let O=V.module?J(V.module):void 0;if(!O)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 O.preload)z.add(U);if(V.preloadDynamic)for(let U of O.dynamicPreload??[])z.add(U)}return{s:O.src,e:V.export,l:V.load}});let G=X.some((V)=>V!==null),Q=j?`<script type="module" ${vG}="${j9(j.name)}">${j.source}</script>`:"";if(!G&&!Y)return Y9($,"</head>",Q,!1);let B=(Y?`<meta name="${MD}" content="${j9(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((V)=>`<link rel="modulepreload" href="${j9(V)}"/>`).join("")+Q,F=Y?t7:z9,D=(G?`<script type="application/json" id="${PD}">${_1({i:X})}</script>`:"")+`<script type="module">${W?TD+F:F}</script>`;return Y9(Y9($,"</head>",B,!1),"</body>",D,!0)}function ND($,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 hG($){let Z=`<template ${RG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=ND($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let G=`<${g3} ${bG}="${j}" style="display:contents"></${g3}>`;$=$.split(G).join(`<${g3} style="display:contents">${X}</${g3}>`)}return $}function pG($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function cG($,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 _D=async()=>(await import("./chunk-w17p2k8g.js")).default,X9,m3=async(...$)=>{return X9??=import("react-dom/server.browser").catch((Z)=>{throw X9=void 0,Z}),(await X9).renderToReadableStream(...$)},uG=1e4,lG="no-locale",xD=`
18
18
  !function(){try{var d=document.documentElement,c=d.classList;
19
19
  c.remove('light','dark');
20
20
  var e=localStorage.getItem('theme');
@@ -25,7 +25,7 @@ if('system'===e||(!e&&'system'===defaultTheme)){
25
25
  }else if(e){
26
26
  c.add(e||'')
27
27
  }}catch(e){}}()
28
- `;async function CD($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var K9="/assets";function SD($){return $===K9||$.startsWith(`${K9}/`)}function AD($){let Z=$.filter(SD);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${K9}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function ED($){let Z=L(W1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function G9($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function fD($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class h3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];staticRoutes=[];root=null;shellReporter=SG();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;constructor($){let Z=tX();this.partialRendering=$.partialRendering??Z.partialRendering,this.localeRouting=$.localeRouting??Z.localeRouting,this.hooks={onRequestStart:$.onRequestStart??Z.onRequestStart,onRequestEnd:$.onRequestEnd??Z.onRequestEnd,onRequestFail:$.onRequestFail??Z.onRequestFail,onStreamComplete:$.onStreamComplete??Z.onStreamComplete};let J={"/":$.rootRouter,"/auth":N7};this.flatViewRoutes=w4(J),AD(Object.keys(this.flatViewRoutes)),this.routeManifest=q4(J),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,W])=>W.at(-1)!=="FILE")),this.componentTree=v4(J),this.flatComponentTree=o7(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,W])=>W.static).map(([W])=>W);for(let W of this.staticRoutes){let Y=this.flatViewRoutes[W].static?.layout;if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=L(s1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)g4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{h$.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let G=new Set(Z?.preload??[]);for(let Q of W)for(let K of J?.[Q]??[])G.add(K);return[...G].map((Q)=>g1("link",{key:`modulepreload:${Q}`,rel:"modulepreload",href:Q}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,G;if(W.layout){if(G=$.viewImportMap[W.layout],!G)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let Q=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let K=Q9(),B=new AbortController,F=setTimeout(()=>B.abort(),uG),D=(O)=>{if(Bun.env.NODE_ENV!=="production")console.error(O)},V=fG(async(O,U)=>{let H=await m3(O,{signal:B.signal,identifierPrefix:U,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:D});return await H.allReady.catch(()=>{}),await new Response(H).text()});try{let O,U=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(U)O={name:U,source:await W9(U)};let H;if(W.navigation){let x=W.navigation===!0?{}:W.navigation,A=x.version?String(await J(()=>x.version(Z))):"";H={identity:[W.layout??"",$.buildId??"",O?.name??"",A].join("|"),prefetch:x.prefetch==="none"?"none":"intent"}}let T=await m3(g1(wG.Provider,{value:V,children:g1(dG,{children:[...Q,g1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:K,rootLayout:G,key:"root"})]})}),{signal:B.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:D});await T.allReady.catch(()=>{});let I=hG(await new Response(T).text());return new Response(mG(I,V,$.resolveIsland,Bun.env.NODE_ENV!=="production",H,O),{status:200,headers:X})}finally{clearTimeout(F),J(()=>this.completeStream(Z,z.summarize(B.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:K,noStream:B,url:F,user:D,viewData:V,breadcrumbs:O,urlLocaleSegment:U,meta:H,isOgRequest:T,appId:I,features:x,staticView:A}=$,f=G.replace(`/${U}`,""),S={kind:"view",data:{meta:H,pageData:{[f]:V},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:O,router:{urlLocaleSegment:U,pathname:Y,params:X,currentPath:G,searchParams:F.search,is404:!Y?!0:!1,domain:Z.domain?ED(Z):null},appId:I,features:x,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},M=this.root,P=this.routeManifest[Y];return async(k)=>{let{bootstrapModules:m=[],loaders:h1,getStyles:J0,viewImportMap:a,cssManifest:q,ogMap:U0,viewModules:d$,clientEntry:u$,modulePreloadManifest:lZ,assetBase:I1,resolveIsland:l$,buildId:i$}=k,r=u$?[]:m,c3=(W0)=>[W0,`window.loaders=${h1}`,...u$?[`import(${JSON.stringify(u$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(T){let W0=null,n$=null;for(let o$ of P??[])if(typeof U0[o$]==="function")n$=o$,W0=U0[o$];if(!W0)return new Response("Not found",{status:404});let oQ=Object.values(S.data.pageData)[0];try{await m3(g1(W0,oQ[n$]),{onError:()=>{}})}catch(o$){let{fonts:aQ,...rQ}=o$.satoriOptions,tQ=await Promise.all(aQ.map((d3)=>{return CD(d3.name,d3.weight,d3.style).then((WK)=>({...d3,data:WK}))})),q9=new Headers(j);q9.set("Content-Type","image/png");let[eQ,$K]=await Promise.all([_D(),b4("Rendering an OG image")]),ZK=await eQ(o$.jsx,{...rQ,fonts:tQ}),JK=await $K(Buffer.from(ZK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(JK),{headers:q9})}return new Response("data")}if(A&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:A,currentViews:P,data:S.data,serverQueries:Q,headers:j,getStyles:J0,viewImportMap:a,viewModules:d$,resolveIsland:l$,buildId:i$});if(S.data.cssManifest=q,S.data.modulePreloadManifest=lZ??{},I1&&I1!=="/")S.data.assetBase=I1;let Z8=this.modulePreloadLinks({clientEntry:u$,modulePreloadManifest:lZ,views:P??["404"],routeKey:Y??"404"}),s$=await J0(P);S.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let P1=new AbortController,iZ=setTimeout(()=>P1.abort(),uG),T1=Q6(K)||B,b=Bun.env.NODE_ENV!=="production"&&!T1&&Y&&this.shellReporter.shouldObserve(Y)?AG():null,p0=Q9();try{let W0=await m3(g1(dG,{children:[...Z8,...s$,g1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:xD}}),g1(M,{data:S.data,viewImportMap:a,viewModules:d$,serverQueries:Q,dictionarySink:p0,key:"root"})]}),{bootstrapScriptContent:c3(`window.__GEMI_DATA__ = ${_1(S.data)}`),bootstrapModules:r,signal:P1.signal,...T1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(n$){if(Bun.env.NODE_ENV!=="production")console.error(n$)}});if(W0.allReady.catch(()=>{}).finally(()=>clearTimeout(iZ)),T1)await W0.allReady.catch(()=>{});return new Response(v8(W0,Q,{onShell:T1?void 0:()=>Q.markShell(),onChunk:b?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(P1.signal.aborted)),b)this.shellReporter.report(Y,b.measure())})},p0),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(W0){if(clearTimeout(iZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(P1.signal.aborted))),W0;let n$=await m3(g1("div"),{bootstrapScriptContent:c3(`window.error= ${_1(W0.message)}; window.stack_trace=${_1(W0.stack)};window.__GEMI_DATA__ = ${_1(S.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...r]:r});return new Response(v8(n$,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(P1.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(D$(Z))return 404;if(Z?.kind===d1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(u1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof v1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),G=j,Q=null,K=null,B=L(s),F=y3(this.flatViewRoutes,j),D=B.isLocaleAware&&this.localeRouting==="prefix"&&!F?.route.middleware.includes(lG);if(D&&B.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,K=z;if(D&&!Y&&K===null&&!(K===null&&F!==null)){let M=iG(z,B.supportedLocales,B.defaultLocale);if(M){let P=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${M}${P}${W?".json":""}${J.search}`}})}}if(D&&!Y){let M=L(s).detectLocale(new C($,{},"view",G));if(K===null&&M!==B.defaultLocale){let P=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${M}${P}${J.search}`}})}}G=G.replace("//","/");let O=[],U=[],H=null,T={},I=null,x=!1,A=[],f;try{let M=y3(this.flatViewRoutes,G);if(K&&M?.route.middleware.includes(lG))M=null;if(M){if(H=M.routePath,T=M.params,O=M.route.exec,U=M.route.middleware,A=M.route.features,x=U.includes("no-stream"),f=M.route.static,W&&this.partialRendering){let P=$.headers.get(n7),k=_G({flatViewRoutes:this.flatViewRoutes,supportedLocales:L(s).supportedLocales,from:P,origin:J.origin,to:{segments:M.route.segments,params:T,search:J.search}});if(k.startIndex>0)O=O.slice(k.startIndex),I={from:P,carriedViews:k.carriedViews}}}}catch(M){throw M}if(f&&W)return new Response("Not found",{status:404});let S=new C($,T,"view",H);return this.hooks.onRequestStart(S),await N.run(S,async()=>{let M=null,P=N.getStore(),k=pZ.getStore(),m=(q)=>pZ.run(k,()=>N.runWith(P,q));P.serverQueries=new mZ(v3($));let h1=new Set;P.serverQueries.onQueryFail((q)=>{h1.add(q.error);try{m(()=>Promise.resolve(this.hooks.onRequestFail(a,q.error)).catch(()=>{}))}catch{}});let J0=pG(f);if(K){let q=K.replaceAll("/","");V$.setLocale(q,{cookie:J0.locale})}else if(B.isLocaleAware&&!D)P.setLocale(B.defaultLocale);else V$.setLocale(void 0,{cookie:J0.locale});let a=P.req;if(J0.session)g4();try{let q=null;try{await L(c1).runMiddleware(U)}catch(b){if(q=this.viewRefusalStatus(a,b,h1),q===null)throw b}if(q!==null||A.length>0&&!await this.passesFeatureGates(A))H=null,O=[],a.routePath="";let U0=L(s),d$=U0.isEnabled,u$=U0.isLocaleAware,lZ=new C($,a.params),I1={defaultLocale:U0.defaultLocale,timeZone:U0.detectTimeZone(lZ)};if(u$){let b=null;if(K)b=K.replaceAll("/",""),P.setLocale(b);else if(!D)b=P.locale??U0.defaultLocale;else b=U0.detectLocale(lZ),P.setLocale(b);let p0=d$?U0.getPageTranslations(b,a.routePath):{};I1={...I1,supportedLocales:U0.supportedLocales,currentLocale:b,dictionary:{[b]:p0},defaultLocale:U0.defaultLocale,...D?{}:{localeRouting:"off"}}}await sG(I1.currentLocale??"");let l$;try{l$=await Promise.all(O.map((b)=>b(a)))}catch(b){if(q=this.viewRefusalStatus(a,b,h1),q===null)throw b;H=null,O=[],a.routePath="",l$=[]}let{cookies:i$,headers:r}=P;if(q!==null)r.set("Cache-Control","no-store");M={data:l$,cookies:i$,headers:r,user:P.user,prefetchedData:P.serverQueries.snapshotResolved(),currentPathName:H,params:a.params,urlLocaleSegment:Q,meta:P.renderMeta(),appId:L(a7).id,features:await L(s1).forClient()};let{params:c3,user:Z8}=M,s$={},P1={};for(let b of l$??[]){let[p0,W0]=Object.entries(b)?.[0]??[];if(!p0||!W0)continue;P1[`${p0}:${H}`]=W0.breadcrumb,s$[p0]=W0}let iZ=s$.FILE;if(iZ){for(let b of i$)r.append("Set-Cookie",b.toString());try{await this.onRequestEnd(a)}catch(b){h$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}return await D8(iZ,r)}if(W){r.set("Content-Type","application/x-ndjson; charset=utf-8"),r.append("Vary",n7),i$.forEach((p0)=>r.append("Set-Cookie",p0.toString())),await this.hooks.onRequestEnd(a);let b={meta:I&&!P.metadata.touched?null:M.meta,data:{[G]:s$},breadcrumbs:P1,prefetchedData:P.serverQueries.snapshotResolved(),i18n:I1,features:M.features,is404:!H,appId:M.appId,partial:I};return new Response(EG(b,P.serverQueries,void 0,({aborted:p0})=>m(()=>this.completeStream(a,P.serverQueries.summarize(p0)))),{headers:r})}if(r.set("Content-Type","text/html; charset=utf-8"),!x&&!(f&&H))r.append("Vary","User-Agent");let T1=Boolean(f&&H);if(!T1||J0.session)g4();for(let b of i$)r.append("Set-Cookie",b.toString());if(!T1||J0.csrf){let b=Bun.CSRF.generate(process.env.SECRET);r.append("Set-Cookie",`csrf_token=${b}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(a,{mintSession:!T1||J0.session})}catch(b){h$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}if(T1)cG(r,f);return await this.render({req:a,runInRequestScope:m,csrfTokenHMAC:Buffer.from(""),currentPathName:H,headers:r,i18n:I1,params:c3,pathname:J.pathname,serverQueries:P.serverQueries,userAgent:$.headers.get("user-agent"),noStream:x,url:J,user:Z8,viewData:s$,breadcrumbs:P1,urlLocaleSegment:Q,meta:M.meta,appId:M.appId,features:M.features,isOgRequest:Y,staticView:H?f:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===d1){let U0=W?fD(q.payload.viewData??q.payload.api):G9(q.payload.view);for(let d$ of P.cookies)U0.headers.append("Set-Cookie",d$.toString());return U0}if(!h1.has(q))this.hooks.onRequestFail(a,q);if(u1(q))return console.error(q),W?hZ():G9(r7());if(q instanceof v1&&q.status===403)return W?hZ():G9(r7());throw q}},Z)}}function F9(){let $=JSON.stringify({error:l1("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class tG extends N0{routes={"/api-routes":this.get(()=>{let $=L(h4).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=L(h3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var bD=new Set([p1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),RD=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,wD=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function kD($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(bD.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===p1)throw Error(`dispatchAs: credentials may not set the "${p1}" cookie. The access token stays the initiator's.`);if(!RD.test(Y)||!wD.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function qD($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(G){Y(),z.error(G);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function nG($){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 oG($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,G]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,G)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}class h4{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=rX();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=f7({"/":$.rootRouter,"/auth":_7,"/__gemi__/services/i18n":x7,"/__gemi__/services/logs":E7,"/__gemi__/services/image":A7,"/__gemi__/debug":tG})}getRouteHandlerAndParams($){let Z=new URL($.url),J=rG(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 nG(Y.payload.api);else{if(D$(Y))return F9();if(this.onRequestFail(Z,Y),console.error(Y),u1(Y))return hZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=N.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===d1)return nG(j.payload.api);if(D$(j))return F9();if(this.onRequestFail(J.req,j),console.error(j),u1(j))return hZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){h$.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(!Y||!Y[$.method])return new Response(JSON.stringify({error:l1("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await N.run(j,async()=>{let z=N.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,W)};try{let Q=L(s);if(Q.isEnabled){let O=Q.detectLocale(j);z.setLocale(O)}z.setRequest(j),L(c1).applyDefaultBodyLimit($);let K=await this.runRouteMiddleware(W,j);if(K instanceof Response){let O=oG(K,z.headers,z.cookies);return await G(),O}let B=await this.getRouteData(W),F=z.headers,D=z.cookies;if(B instanceof Response){let O=oG(B,F,D);if(this.isOpenEndedBody($,O)){let U=qD(O,()=>this.endRequest(z,j,W));return X=!0,U}return await G(),O}let V=($Z(B)?B:U$.json(B)).toResponse(F,D);return await G(),V}catch(Q){if(!X)try{await G()}catch(K){console.error(K)}throw Q}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let G=Y?.identity;if(G!==void 0&&(typeof G!=="object"||!G?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let Q=new Headers,K=[],B=G?null:$.cookies.get(p1);if(B)K.push(`${p1}=${B}`);if(Y?.credentials)kD(Q,K,Y.credentials,G!==void 0);if(K.length>0)Q.set("Cookie",K.join("; "));let F=G?null:$.headers.get(p1);if(F)Q.set(p1,F);let D=$.headers.get("User-Agent");if(D)Q.set("User-Agent",D);let V;if(W instanceof FormData)V=W;else if(W!==void 0)Q.set("Content-Type","application/json"),V=JSON.stringify(W);let O=new Request(z,{method:Z,headers:Q,body:V,...Y?.signal?{signal:Y.signal}:{}});if(aG(O,JZ($),G?.grant,Y?.progress),$.domain)cZ(O,$.domain);let U=G?{user:G.user}:void 0;return N.exit(()=>a3.exit(()=>this.handleApiRequest(O,U)))}}import{timingSafeEqual as yD}from"crypto";import{isIP as vD}from"net";var u4="",O9="*",gD=60000,mD=1e4,V9=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,p4=16,B9=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,c4="x-forwarded-host";function eG($){return $.startsWith(":")}function d4($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&yD(J,W)}function hD($){if(!$)return null;if($===!0)return{header:c4,clientIpHeader:null,secret:null};return{header:($.hostHeader??c4).toLowerCase(),clientIpHeader:$.clientIpHeader?.toLowerCase()??null,secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function pD($){if(!$||$===!0)return;let{hostHeader:Z,clientIpHeader:J,secret:W}=$;if(Z!==void 0&&(typeof Z!=="string"||!B9.test(Z)))throw Error(`\`route.domains.trustProxy.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(Z)}.`);if(J!==void 0){if(typeof J!=="string"||!B9.test(J))throw Error(`\`route.domains.trustProxy.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(J)}.`);if(!W)throw Error("`route.domains.trustProxy.clientIpHeader` needs `secret`: without proof the proxy sent it, any client that reaches the app directly picks its own address.");if(J.toLowerCase()===(Z??c4).toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `hostHeader`.");if(typeof W.header==="string"&&J.toLowerCase()===W.header.toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `secret.header`.")}if(!W)return;if(typeof W.header!=="string"||!B9.test(W.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${W.header}".`);if(W.header.toLowerCase()===(Z??c4).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof W.value!=="string"||W.value.length<p4)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${p4} characters. A guessable one lets any client name its own host.`)}function U1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function cD($){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 dD($){let Z=U1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>V9.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<p4)throw Error(`\`route.domains.ask.secret\` must be at least ${p4} characters. A guessable one is worse than leaving \`ask\` out.`);pD($.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),eG(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>V9.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class D9{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){dD($),this.root=U1($.root),this.hostTrust=hD($.trustProxy);for(let Z of $.groups??[])if(eG(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??gD,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!d4($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.hostTrust;if(!Z?.clientIpHeader||!Z.secret)return null;if(!d4($.headers.get(Z.secret.header),Z.secret.value))return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0]?.trim();return J&&vD(J)?J:null}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return U1(this.forwardedHost($))??U1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&U1(Y)?cD(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:O9,params:{},custom:!0};return null}async allows($,Z){let J=U1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:u4,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&V9.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=mD)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=U1($);if(Z)this.cache.delete(Z)}}}var uD="/__gemi__/domains/ask";class W1{static token="router.domains";resolver;acceptsCustomDomains;groups=new Map;constructor($,Z){this.groups.set(u4,$);let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new D9(J);let W=(Y)=>({api:Y.api?new h4({...Z.api,...Y.api}):$.api,view:Y.view?new h3({...Z.view,...Y.view}):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(O9,W(J.custom.fallback))}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)$Q($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return cZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==uD)return null;if(!d4(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??u4)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function l4($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var ZQ=600000;function JQ($,Z){return[Y6($,Z),Y6($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new c8){W5($.oauthProviders),this.config={...O1(Y5($),$),emailCode:y8($.emailCode)},this.provider=Z}async oauthProvider($){return await GZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await H5(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=L().bound(W1)?L(W1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?L(W1).resolver?.root:U1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??U1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!f8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=l4(J.expiresAt),j=l4(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=N.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/ZQ),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let Q=Y6($,j),K=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:Q,userId:K,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of JQ($,j))if((await this.userProvider.findSession({token:Q,userAgent:Z}))?.user){z=Q;break}}if(!z)return null;let G=await this.getSession(z,Z);if(G)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(G.expiresAt)));return G}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(f8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/ZQ),W=JQ($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=N.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new C;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new L$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=lW(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:tW(Z);return await this.userProvider.createMagicLinkToken({email:$,token:j6("link",$,J),pin:j6("pin",$,Y)}),{email:$,pin:Y,token:J}}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.userProvider.findMagicLinkTokenByEmail($);if(!j)return eZ("pin",$,null,Z),{status:"invalid"};let z=l4(j.createdAt);if(z+W*60000<=Date.now())return eZ("pin",$,null,Z),{status:"expired"};if(!await Z5(j.id,z,Y,W))return await this.userProvider.claimMagicLinkToken(j.id),{status:"too_many_attempts"};if(!eZ("pin",$,j.pin,Z))return{status:"invalid"};if(J.claim!==!1&&!await this.userProvider.claimMagicLinkToken(j.id))return{status:"invalid"};return{status:"ok",row:j}}async verifyMagicLinkToken($,Z){let J=await this.userProvider.findMagicLinkTokenByEmail($),W=eZ("link",$,J?.token,Z);if(!J||!W)return!1;if(l4(J.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(J.id)}}class R0 extends v{static getFacadeAccessor(){return E}static async user(){let $=await R0.userOrNull();if($)return $;throw new L$({redirectTo:r3(N.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=N.getStore();if($?.user)return $.user;let Z=await s3(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=N.getStore()?.req;return j1(Z?.search.get(Y1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await R0.user();if(!await $(Z))throw new WZ}static async guardSafe($){let Z=await R0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class i4{static ensure($,Z={}){let J=N.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new mZ(v3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=i4.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){i4.ensure($,Z[0])}static noPrefetch(){let $=N.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new mZ(v3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function WQ($,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=lD(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 lD($){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 jQ{static origin($){return YQ($)}static absolute($,...Z){return`${q3()}${B0(String($),Z[0]??{})}`}static relative($,...Z){return B0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=L(W1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=N.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):q3();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return WQ({root:W.root,origin:j},$,B0(String(Z),J[0]??{}))}}class zQ{name="Meta";static description($){N.getStore().metadata.description($)}static title($){N.getStore().metadata.title($)}static openGraph($){N.getStore().metadata.openGraph($)}static htmlAttributes($){N.getStore().metadata.htmlAttributes($)}static canonical($){N.getStore().metadata.canonical($)}static alternates($){N.getStore().metadata.alternates($)}static fonts($){N.getStore().metadata.fonts($)}}var iD={set($,Z,J){N.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(N.getStore().req.cookies.has($))return!1;return N.getStore().setCookie($,Z,J),!0},delete($,Z){N.getStore().deleteCookie($,Z)}};class m1 extends v{static getFacadeAccessor(){return p$}static get client(){return this.getFacadeRoot().client}static get($){return m1.client.get($)}static set($,Z){return m1.client.set($,Z)}static del(...$){return m1.client.del(...$)}static exists($){return m1.client.exists($)}static incr($){return m1.client.incr($)}static expire($,Z){return m1.client.expire($,Z)}static ttl($){return m1.client.ttl($)}}function zx($){return $}function XQ(){return{store:"memory",ttl:null}}class U9{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var sD="500";class L9{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${nD(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",sD]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=L(),Z=$.bound(p$)?$.make(p$).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function nD($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var oD="k:",GQ="tag:",aD="t:";class H9{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class I9 extends H9{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=O1(XQ(),$),this.config.ttl!==null&&this.config.ttl!==void 0)c$(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new KQ(this,Z)}async flush(){await this.store.flush()}async storeKey($){return oD+FQ($)}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=GQ+Z,W=await this.store.get(J);if(W!==null)return W;let Y=QQ();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(GQ+Z,QQ(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:c$(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new U9(this.config.memory);if($==="redis"){let Z=this.options.application;return new L9({...this.config.redis,client:Z?{send:(J,W)=>Z.make(p$).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class KQ extends H9{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){FQ($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${aD}${Z.join(",")}:${$}`}}function FQ($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function QQ(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class BQ extends v{static getFacadeAccessor(){return I9}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class VQ extends v{static getFacadeAccessor(){return z1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class DQ extends v{static getFacadeAccessor(){return OQ}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class LQ extends v{static getFacadeAccessor(){return UQ}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class HQ extends v{static getFacadeAccessor(){return k3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}function kx($){return $}function IQ(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function s4($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function P9($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:rD}=globalThis.Bun;function tD(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var eD=async($)=>{let Z=new rD($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},$U=async($)=>{let Z;try{Z=(await import("./chunk-gng5e7pd.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(()=>{})}},PQ=($)=>tD()?eD($):$U($);var ZU=/^[A-Za-z_][A-Za-z0-9_]*$/;class T9{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!ZU.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??PQ}async createTable(){for(let $ of JU(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 TQ(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
28
+ `;async function CD($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var K9="/assets";function SD($){return $===K9||$.startsWith(`${K9}/`)}function AD($){let Z=$.filter(SD);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${K9}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function ED($){let Z=L(W1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function G9($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function fD($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class h3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];staticRoutes=[];root=null;shellReporter=SG();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;constructor($){let Z=tX();this.partialRendering=$.partialRendering??Z.partialRendering,this.localeRouting=$.localeRouting??Z.localeRouting,this.hooks={onRequestStart:$.onRequestStart??Z.onRequestStart,onRequestEnd:$.onRequestEnd??Z.onRequestEnd,onRequestFail:$.onRequestFail??Z.onRequestFail,onStreamComplete:$.onStreamComplete??Z.onStreamComplete};let J={"/":$.rootRouter,"/auth":N7};this.flatViewRoutes=w4(J),AD(Object.keys(this.flatViewRoutes)),this.routeManifest=q4(J),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,W])=>W.at(-1)!=="FILE")),this.componentTree=v4(J),this.flatComponentTree=o7(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,W])=>W.static).map(([W])=>W);for(let W of this.staticRoutes){let Y=this.flatViewRoutes[W].static?.layout;if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=L(s1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)g4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{h$.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let G=new Set(Z?.preload??[]);for(let Q of W)for(let K of J?.[Q]??[])G.add(K);return[...G].map((Q)=>g1("link",{key:`modulepreload:${Q}`,rel:"modulepreload",href:Q}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,G;if(W.layout){if(G=$.viewImportMap[W.layout],!G)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let Q=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let K=Q9(),B=new AbortController,F=setTimeout(()=>B.abort(),uG),D=(O)=>{if(Bun.env.NODE_ENV!=="production")console.error(O)},V=fG(async(O,U)=>{let H=await m3(O,{signal:B.signal,identifierPrefix:U,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:D});return await H.allReady.catch(()=>{}),await new Response(H).text()});try{let O,U=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(U)O={name:U,source:await W9(U)};let H;if(W.navigation){let x=W.navigation===!0?{}:W.navigation,A=x.version?String(await J(()=>x.version(Z))):"";H={identity:[W.layout??"",$.buildId??"",O?.name??"",A].join("|"),prefetch:x.prefetch==="none"?"none":"intent"}}let T=await m3(g1(wG.Provider,{value:V,children:g1(dG,{children:[...Q,g1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:K,rootLayout:G,key:"root"})]})}),{signal:B.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:D});await T.allReady.catch(()=>{});let I=hG(await new Response(T).text());return new Response(mG(I,V,$.resolveIsland,Bun.env.NODE_ENV!=="production",H,O),{status:200,headers:X})}finally{clearTimeout(F),J(()=>this.completeStream(Z,z.summarize(B.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:K,noStream:B,url:F,user:D,viewData:V,breadcrumbs:O,urlLocaleSegment:U,meta:H,isOgRequest:T,appId:I,features:x,staticView:A}=$,f=G.replace(`/${U}`,""),S={kind:"view",data:{meta:H,pageData:{[f]:V},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:O,router:{urlLocaleSegment:U,pathname:Y,params:X,currentPath:G,searchParams:F.search,is404:!Y?!0:!1,domain:Z.domain?ED(Z):null},appId:I,features:x,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},M=this.root,P=this.routeManifest[Y];return async(k)=>{let{bootstrapModules:m=[],loaders:h1,getStyles:J0,viewImportMap:a,cssManifest:q,ogMap:U0,viewModules:d$,clientEntry:u$,modulePreloadManifest:lZ,assetBase:I1,resolveIsland:l$,buildId:i$}=k,r=u$?[]:m,c3=(W0)=>[W0,`window.loaders=${h1}`,...u$?[`import(${JSON.stringify(u$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(T){let W0=null,n$=null;for(let o$ of P??[])if(typeof U0[o$]==="function")n$=o$,W0=U0[o$];if(!W0)return new Response("Not found",{status:404});let oQ=Object.values(S.data.pageData)[0];try{await m3(g1(W0,oQ[n$]),{onError:()=>{}})}catch(o$){let{fonts:aQ,...rQ}=o$.satoriOptions,tQ=await Promise.all(aQ.map((d3)=>{return CD(d3.name,d3.weight,d3.style).then((WK)=>({...d3,data:WK}))})),q9=new Headers(j);q9.set("Content-Type","image/png");let[eQ,$K]=await Promise.all([_D(),b4("Rendering an OG image")]),ZK=await eQ(o$.jsx,{...rQ,fonts:tQ}),JK=await $K(Buffer.from(ZK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(JK),{headers:q9})}return new Response("data")}if(A&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:A,currentViews:P,data:S.data,serverQueries:Q,headers:j,getStyles:J0,viewImportMap:a,viewModules:d$,resolveIsland:l$,buildId:i$});if(S.data.cssManifest=q,S.data.modulePreloadManifest=lZ??{},I1&&I1!=="/")S.data.assetBase=I1;let Z8=this.modulePreloadLinks({clientEntry:u$,modulePreloadManifest:lZ,views:P??["404"],routeKey:Y??"404"}),s$=await J0(P);S.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let P1=new AbortController,iZ=setTimeout(()=>P1.abort(),uG),T1=Q6(K)||B,b=Bun.env.NODE_ENV!=="production"&&!T1&&Y&&this.shellReporter.shouldObserve(Y)?AG():null,p0=Q9();try{let W0=await m3(g1(dG,{children:[...Z8,...s$,g1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:xD}}),g1(M,{data:S.data,viewImportMap:a,viewModules:d$,serverQueries:Q,dictionarySink:p0,key:"root"})]}),{bootstrapScriptContent:c3(`window.__GEMI_DATA__ = ${_1(S.data)}`),bootstrapModules:r,signal:P1.signal,...T1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(n$){if(Bun.env.NODE_ENV!=="production")console.error(n$)}});if(W0.allReady.catch(()=>{}).finally(()=>clearTimeout(iZ)),T1)await W0.allReady.catch(()=>{});return new Response(v8(W0,Q,{onShell:T1?void 0:()=>Q.markShell(),onChunk:b?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(P1.signal.aborted)),b)this.shellReporter.report(Y,b.measure())})},p0),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(W0){if(clearTimeout(iZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(P1.signal.aborted))),W0;let n$=await m3(g1("div"),{bootstrapScriptContent:c3(`window.error= ${_1(W0.message)}; window.stack_trace=${_1(W0.stack)};window.__GEMI_DATA__ = ${_1(S.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...r]:r});return new Response(v8(n$,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(P1.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(D$(Z))return 404;if(Z?.kind===d1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(u1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof v1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),G=j,Q=null,K=null,B=L(s),F=y3(this.flatViewRoutes,j),D=B.isLocaleAware&&this.localeRouting==="prefix"&&!F?.route.middleware.includes(lG);if(D&&B.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,K=z;if(D&&!Y&&K===null&&!(K===null&&F!==null)){let M=iG(z,B.supportedLocales,B.defaultLocale);if(M){let P=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${M}${P}${W?".json":""}${J.search}`}})}}if(D&&!Y){let M=L(s).detectLocale(new C($,{},"view",G));if(K===null&&M!==B.defaultLocale){let P=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${M}${P}${J.search}`}})}}G=G.replace("//","/");let O=[],U=[],H=null,T={},I=null,x=!1,A=[],f;try{let M=y3(this.flatViewRoutes,G);if(K&&M?.route.middleware.includes(lG))M=null;if(M){if(H=M.routePath,T=M.params,O=M.route.exec,U=M.route.middleware,A=M.route.features,x=U.includes("no-stream"),f=M.route.static,W&&this.partialRendering){let P=$.headers.get(n7),k=_G({flatViewRoutes:this.flatViewRoutes,supportedLocales:L(s).supportedLocales,from:P,origin:J.origin,to:{segments:M.route.segments,params:T,search:J.search}});if(k.startIndex>0)O=O.slice(k.startIndex),I={from:P,carriedViews:k.carriedViews}}}}catch(M){throw M}if(f&&W)return new Response("Not found",{status:404});let S=new C($,T,"view",H);return this.hooks.onRequestStart(S),await N.run(S,async()=>{let M=null,P=N.getStore(),k=pZ.getStore(),m=(q)=>pZ.run(k,()=>N.runWith(P,q));P.serverQueries=new mZ(v3($));let h1=new Set;P.serverQueries.onQueryFail((q)=>{h1.add(q.error);try{m(()=>Promise.resolve(this.hooks.onRequestFail(a,q.error)).catch(()=>{}))}catch{}});let J0=pG(f);if(K){let q=K.replaceAll("/","");V$.setLocale(q,{cookie:J0.locale})}else if(B.isLocaleAware&&!D)P.setLocale(B.defaultLocale);else V$.setLocale(void 0,{cookie:J0.locale});let a=P.req;if(J0.session)g4();try{let q=null;try{await L(c1).runMiddleware(U)}catch(b){if(q=this.viewRefusalStatus(a,b,h1),q===null)throw b}if(q!==null||A.length>0&&!await this.passesFeatureGates(A))H=null,O=[],a.routePath="";let U0=L(s),d$=U0.isEnabled,u$=U0.isLocaleAware,lZ=new C($,a.params),I1={defaultLocale:U0.defaultLocale,timeZone:U0.detectTimeZone(lZ)};if(u$){let b=null;if(K)b=K.replaceAll("/",""),P.setLocale(b);else if(!D)b=P.locale??U0.defaultLocale;else b=U0.detectLocale(lZ),P.setLocale(b);let p0=d$?U0.getPageTranslations(b,a.routePath):{};I1={...I1,supportedLocales:U0.supportedLocales,currentLocale:b,dictionary:{[b]:p0},defaultLocale:U0.defaultLocale,...D?{}:{localeRouting:"off"}}}await sG(I1.currentLocale??"");let l$;try{l$=await Promise.all(O.map((b)=>b(a)))}catch(b){if(q=this.viewRefusalStatus(a,b,h1),q===null)throw b;H=null,O=[],a.routePath="",l$=[]}let{cookies:i$,headers:r}=P;if(q!==null)r.set("Cache-Control","no-store");M={data:l$,cookies:i$,headers:r,user:P.user,prefetchedData:P.serverQueries.snapshotResolved(),currentPathName:H,params:a.params,urlLocaleSegment:Q,meta:P.renderMeta(),appId:L(a7).id,features:await L(s1).forClient()};let{params:c3,user:Z8}=M,s$={},P1={};for(let b of l$??[]){let[p0,W0]=Object.entries(b)?.[0]??[];if(!p0||!W0)continue;P1[`${p0}:${H}`]=W0.breadcrumb,s$[p0]=W0}let iZ=s$.FILE;if(iZ){for(let b of i$)r.append("Set-Cookie",b.toString());try{await this.onRequestEnd(a)}catch(b){h$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}return await D8(iZ,r)}if(W){r.set("Content-Type","application/x-ndjson; charset=utf-8"),r.append("Vary",n7),i$.forEach((p0)=>r.append("Set-Cookie",p0.toString())),await this.hooks.onRequestEnd(a);let b={meta:I&&!P.metadata.touched?null:M.meta,data:{[G]:s$},breadcrumbs:P1,prefetchedData:P.serverQueries.snapshotResolved(),i18n:I1,features:M.features,is404:!H,appId:M.appId,partial:I};return new Response(EG(b,P.serverQueries,void 0,({aborted:p0})=>m(()=>this.completeStream(a,P.serverQueries.summarize(p0)))),{headers:r})}if(r.set("Content-Type","text/html; charset=utf-8"),!x&&!(f&&H))r.append("Vary","User-Agent");let T1=Boolean(f&&H);if(!T1||J0.session)g4();for(let b of i$)r.append("Set-Cookie",b.toString());if(!T1||J0.csrf){let b=Bun.CSRF.generate(process.env.SECRET);r.append("Set-Cookie",`csrf_token=${b}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(a,{mintSession:!T1||J0.session})}catch(b){h$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}if(T1)cG(r,f);return await this.render({req:a,runInRequestScope:m,csrfTokenHMAC:Buffer.from(""),currentPathName:H,headers:r,i18n:I1,params:c3,pathname:J.pathname,serverQueries:P.serverQueries,userAgent:$.headers.get("user-agent"),noStream:x,url:J,user:Z8,viewData:s$,breadcrumbs:P1,urlLocaleSegment:Q,meta:M.meta,appId:M.appId,features:M.features,isOgRequest:Y,staticView:H?f:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===d1){let U0=W?fD(q.payload.viewData??q.payload.api):G9(q.payload.view);for(let d$ of P.cookies)U0.headers.append("Set-Cookie",d$.toString());return U0}if(!h1.has(q))this.hooks.onRequestFail(a,q);if(u1(q))return console.error(q),W?hZ():G9(r7());if(q instanceof v1&&q.status===403)return W?hZ():G9(r7());throw q}},Z)}}function F9(){let $=JSON.stringify({error:l1("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class tG extends N0{routes={"/api-routes":this.get(()=>{let $=L(h4).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=L(h3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var bD=new Set([p1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),RD=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,wD=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function kD($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(bD.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===p1)throw Error(`dispatchAs: credentials may not set the "${p1}" cookie. The access token stays the initiator's.`);if(!RD.test(Y)||!wD.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function qD($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(G){Y(),z.error(G);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function nG($){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 oG($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,G]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,G)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}class h4{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=rX();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=f7({"/":$.rootRouter,"/auth":_7,"/__gemi__/services/i18n":x7,"/__gemi__/services/logs":E7,"/__gemi__/services/image":A7,"/__gemi__/debug":tG})}getRouteHandlerAndParams($){let Z=new URL($.url),J=rG(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 nG(Y.payload.api);else{if(D$(Y))return F9();if(this.onRequestFail(Z,Y),console.error(Y),u1(Y))return hZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=N.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===d1)return nG(j.payload.api);if(D$(j))return F9();if(this.onRequestFail(J.req,j),console.error(j),u1(j))return hZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){h$.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(!Y||!Y[$.method])return new Response(JSON.stringify({error:l1("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await N.run(j,async()=>{let z=N.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,W)};try{let Q=L(s);if(Q.isEnabled){let O=Q.detectLocale(j);z.setLocale(O)}z.setRequest(j),L(c1).applyDefaultBodyLimit($);let K=await this.runRouteMiddleware(W,j);if(K instanceof Response){let O=oG(K,z.headers,z.cookies);return await G(),O}let B=await this.getRouteData(W),F=z.headers,D=z.cookies;if(B instanceof Response){let O=oG(B,F,D);if(this.isOpenEndedBody($,O)){let U=qD(O,()=>this.endRequest(z,j,W));return X=!0,U}return await G(),O}let V=($Z(B)?B:U$.json(B)).toResponse(F,D);return await G(),V}catch(Q){if(!X)try{await G()}catch(K){console.error(K)}throw Q}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let G=Y?.identity;if(G!==void 0&&(typeof G!=="object"||!G?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let Q=new Headers,K=[],B=G?null:$.cookies.get(p1);if(B)K.push(`${p1}=${B}`);if(Y?.credentials)kD(Q,K,Y.credentials,G!==void 0);if(K.length>0)Q.set("Cookie",K.join("; "));let F=G?null:$.headers.get(p1);if(F)Q.set(p1,F);let D=$.headers.get("User-Agent");if(D)Q.set("User-Agent",D);let V;if(W instanceof FormData)V=W;else if(W!==void 0)Q.set("Content-Type","application/json"),V=JSON.stringify(W);let O=new Request(z,{method:Z,headers:Q,body:V,...Y?.signal?{signal:Y.signal}:{}});if(aG(O,JZ($),G?.grant,Y?.progress),$.domain)cZ(O,$.domain);let U=G?{user:G.user}:void 0;return N.exit(()=>a3.exit(()=>this.handleApiRequest(O,U)))}}import{timingSafeEqual as yD}from"crypto";import{isIP as vD}from"net";var u4="",O9="*",gD=60000,mD=1e4,V9=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,p4=16,B9=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,c4="x-forwarded-host";function eG($){return $.startsWith(":")}function d4($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&yD(J,W)}function hD($){if(!$)return null;if($===!0)return{header:c4,clientIpHeader:null,secret:null};return{header:($.hostHeader??c4).toLowerCase(),clientIpHeader:$.clientIpHeader?.toLowerCase()??null,secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function pD($){if(!$||$===!0)return;let{hostHeader:Z,clientIpHeader:J,secret:W}=$;if(Z!==void 0&&(typeof Z!=="string"||!B9.test(Z)))throw Error(`\`route.domains.trustProxy.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(Z)}.`);if(J!==void 0){if(typeof J!=="string"||!B9.test(J))throw Error(`\`route.domains.trustProxy.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(J)}.`);if(!W)throw Error("`route.domains.trustProxy.clientIpHeader` needs `secret`: without proof the proxy sent it, any client that reaches the app directly picks its own address.");if(J.toLowerCase()===(Z??c4).toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `hostHeader`.");if(typeof W.header==="string"&&J.toLowerCase()===W.header.toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `secret.header`.")}if(!W)return;if(typeof W.header!=="string"||!B9.test(W.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${W.header}".`);if(W.header.toLowerCase()===(Z??c4).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof W.value!=="string"||W.value.length<p4)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${p4} characters. A guessable one lets any client name its own host.`)}function U1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function cD($){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 dD($){let Z=U1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>V9.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<p4)throw Error(`\`route.domains.ask.secret\` must be at least ${p4} characters. A guessable one is worse than leaving \`ask\` out.`);pD($.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),eG(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>V9.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class D9{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){dD($),this.root=U1($.root),this.hostTrust=hD($.trustProxy);for(let Z of $.groups??[])if(eG(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??gD,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!d4($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.hostTrust;if(!Z?.clientIpHeader||!Z.secret)return null;if(!d4($.headers.get(Z.secret.header),Z.secret.value))return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0]?.trim();return J&&vD(J)?J:null}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return U1(this.forwardedHost($))??U1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&U1(Y)?cD(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:O9,params:{},custom:!0};return null}async allows($,Z){let J=U1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:u4,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&V9.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=mD)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=U1($);if(Z)this.cache.delete(Z)}}}var uD="/__gemi__/domains/ask";class W1{static token="router.domains";resolver;acceptsCustomDomains;groups=new Map;constructor($,Z){this.groups.set(u4,$);let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new D9(J);let W=(Y)=>({api:Y.api?new h4({...Z.api,...Y.api}):$.api,view:Y.view?new h3({...Z.view,...Y.view}):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(O9,W(J.custom.fallback))}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)$Q($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return cZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==uD)return null;if(!d4(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??u4)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function l4($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var ZQ=600000;function JQ($,Z){return[Y6($,Z),Y6($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new c8){W5($.oauthProviders),this.config={...O1(Y5($),$),emailCode:y8($.emailCode)},this.provider=Z}async oauthProvider($){return await GZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await H5(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=L().bound(W1)?L(W1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?L(W1).resolver?.root:U1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??U1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!f8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=l4(J.expiresAt),j=l4(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=N.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/ZQ),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let Q=Y6($,j),K=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:Q,userId:K,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of JQ($,j))if((await this.userProvider.findSession({token:Q,userAgent:Z}))?.user){z=Q;break}}if(!z)return null;let G=await this.getSession(z,Z);if(G)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(G.expiresAt)));return G}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(f8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/ZQ),W=JQ($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=N.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new C;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new L$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=lW(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:tW(Z);return await this.userProvider.createMagicLinkToken({email:$,token:j6("link",$,J),pin:j6("pin",$,Y)}),{email:$,pin:Y,token:J}}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.userProvider.findMagicLinkTokenByEmail($);if(!j)return eZ("pin",$,null,Z),{status:"invalid"};let z=l4(j.createdAt);if(z+W*60000<=Date.now())return eZ("pin",$,null,Z),{status:"expired"};if(!await Z5(j.id,z,Y,W))return await this.userProvider.claimMagicLinkToken(j.id),{status:"too_many_attempts"};if(!eZ("pin",$,j.pin,Z))return{status:"invalid"};if(J.claim!==!1&&!await this.userProvider.claimMagicLinkToken(j.id))return{status:"invalid"};return{status:"ok",row:j}}async verifyMagicLinkToken($,Z){let J=await this.userProvider.findMagicLinkTokenByEmail($),W=eZ("link",$,J?.token,Z);if(!J||!W)return!1;if(l4(J.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(J.id)}}class R0 extends v{static getFacadeAccessor(){return E}static async user(){let $=await R0.userOrNull();if($)return $;throw new L$({redirectTo:r3(N.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=N.getStore();if($?.user)return $.user;let Z=await s3(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=N.getStore()?.req;return j1(Z?.search.get(Y1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await R0.user();if(!await $(Z))throw new WZ}static async guardSafe($){let Z=await R0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class i4{static ensure($,Z={}){let J=N.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new mZ(v3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=i4.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){i4.ensure($,Z[0])}static noPrefetch(){let $=N.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new mZ(v3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function WQ($,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=lD(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 lD($){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 jQ{static origin($){return YQ($)}static absolute($,...Z){return`${q3()}${B0(String($),Z[0]??{})}`}static relative($,...Z){return B0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=L(W1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=N.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):q3();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return WQ({root:W.root,origin:j},$,B0(String(Z),J[0]??{}))}}class zQ{name="Meta";static description($){N.getStore().metadata.description($)}static title($){N.getStore().metadata.title($)}static openGraph($){N.getStore().metadata.openGraph($)}static htmlAttributes($){N.getStore().metadata.htmlAttributes($)}static canonical($){N.getStore().metadata.canonical($)}static alternates($){N.getStore().metadata.alternates($)}static fonts($){N.getStore().metadata.fonts($)}}var iD={set($,Z,J){N.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(N.getStore().req.cookies.has($))return!1;return N.getStore().setCookie($,Z,J),!0},delete($,Z){N.getStore().deleteCookie($,Z)}};class m1 extends v{static getFacadeAccessor(){return p$}static get client(){return this.getFacadeRoot().client}static get($){return m1.client.get($)}static set($,Z){return m1.client.set($,Z)}static del(...$){return m1.client.del(...$)}static exists($){return m1.client.exists($)}static incr($){return m1.client.incr($)}static expire($,Z){return m1.client.expire($,Z)}static ttl($){return m1.client.ttl($)}}function zx($){return $}function XQ(){return{store:"memory",ttl:null}}class U9{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var sD="500";class L9{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${nD(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",sD]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=L(),Z=$.bound(p$)?$.make(p$).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function nD($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var oD="k:",GQ="tag:",aD="t:";class H9{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class I9 extends H9{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=O1(XQ(),$),this.config.ttl!==null&&this.config.ttl!==void 0)c$(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new KQ(this,Z)}async flush(){await this.store.flush()}async storeKey($){return oD+FQ($)}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=GQ+Z,W=await this.store.get(J);if(W!==null)return W;let Y=QQ();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(GQ+Z,QQ(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:c$(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new U9(this.config.memory);if($==="redis"){let Z=this.options.application;return new L9({...this.config.redis,client:Z?{send:(J,W)=>Z.make(p$).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class KQ extends H9{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){FQ($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${aD}${Z.join(",")}:${$}`}}function FQ($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function QQ(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class BQ extends v{static getFacadeAccessor(){return I9}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class VQ extends v{static getFacadeAccessor(){return z1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class DQ extends v{static getFacadeAccessor(){return OQ}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class LQ extends v{static getFacadeAccessor(){return UQ}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class HQ extends v{static getFacadeAccessor(){return k3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}function kx($){return $}function IQ(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function s4($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function P9($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:rD}=globalThis.Bun;function tD(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var eD=async($)=>{let Z=new rD($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},$U=async($)=>{let Z;try{Z=(await import("./chunk-fwmmy0jn.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(()=>{})}},PQ=($)=>tD()?eD($):$U($);var ZU=/^[A-Za-z_][A-Za-z0-9_]*$/;class T9{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!ZU.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??PQ}async createTable(){for(let $ of JU(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 TQ(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
29
29
  INSERT INTO ${W} (channel, seq) VALUES (${Z}, 1)
30
30
  ON CONFLICT (channel) DO UPDATE SET seq = ${W}.seq + 1
31
31
  RETURNING seq
@@ -117,6 +117,6 @@ data: ${JSON.stringify(Z)}
117
117
  "updated_at" BIGINT NOT NULL,
118
118
  "finished_at" BIGINT,
119
119
  "deadline_at" BIGINT${W}
120
- )`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var yQ=191,vQ=30000;class t4 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class e4 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class k9{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=O1(wQ(),$),this.store=KU(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(dZ);return this.ownFeed??=new dZ,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){hQ("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;hQ("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:c$($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return QU(Z),this.change($,L1,{status:"running",progress:Z})}complete($,Z){return this.change($,L1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,L1,{status:"failed",error:mQ(Z)})}cancel($,Z){return this.change($,L1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new t4($);if(H1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(G)=>{if(Y.signal.aborted)return;await this.progress($,G)}},X;try{let G=await Z(z);X=await this.complete($,G)}catch(G){if(!(G instanceof e4)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,L1,{status:"failed",error:G instanceof e4?mQ(G):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+c$(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new t4($);let z=null;for(;;){if(H1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let G=W-Date.now();if(G<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await gQ(z,Math.min(G,X??1/0,vQ),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new t4($);if(yield W,H1(W.status))return;for await(let Y of J){let j=GU(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,H1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=c$($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||H1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,L1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(H1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,gQ(j,Math.min(z??1/0,vQ))]);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 gQ($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>G(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},G=(Q)=>{X(),W(Q)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>G(!0),()=>G(!0))})}function GU($,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 mQ($){if(typeof $==="string")return{message:$};if($ instanceof e4)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function hQ($,Z){if(typeof Z!=="string"||Z===""||Z.length>yQ)throw TypeError(`A run's ${$} is a string of 1 to ${yQ} characters; got ${JSON.stringify(Z)}.`)}function QU($){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 KU($,Z){if($==="memory")return new E9;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(C1).connection();return new w9(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class pQ extends v{static getFacadeAccessor(){return k9}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class cQ extends v{static getFacadeAccessor(){return s1}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class $8{bound;constructor($){this.bound=$}get name(){return this.bound??x1()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,J=this.connection(Z);return lQ(J.sql,(W)=>dQ(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-1awxdnb6.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=sQ($,iQ(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=i0();if($===void 0)return;return x1()===this.name?$:void 0}connection($=this.name){return uQ($),L(C1).connection($)}}var uZ=new $8;class nQ extends v{static getFacadeAccessor(){return C1}static connection($){return new $8($)}static get sql(){return uZ.sql}static get dialect(){return uZ.dialect}static query($){return uZ.query($)}static execute($){return uZ.execute($)}static transaction($){return uZ.transaction($)}static schema(){return uZ.schema()}static close(){return this.getFacadeRoot().close()}}export{l0 as Od,sZ as Pd,j8 as Qd,r$ as Rd,oZ as Sd,N0 as Td,s3 as Ud,E8 as Vd,f8 as Wd,lW as Xd,i1 as Yd,z1 as Zd,t as _d,NW as $d,JZ as ae,iW as be,sW as ce,R8 as de,w8 as ee,j6 as fe,eZ as ge,LF as he,xI as ie,Y5 as je,F5 as ke,g8 as le,B5 as me,V5 as ne,xF as oe,O5 as pe,m8 as qe,AF as re,EF as se,h8 as te,D5 as ue,U5 as ve,s1 as we,L5 as xe,wF as ye,c8 as ze,L8 as Ae,t3 as Be,M1 as Ce,U$ as De,NK as Ee,D8 as Fe,N1 as Ge,V$ as He,i4 as Ie,jQ as Je,zQ as Ke,iD as Le,m1 as Me,zx as Ne,XQ as Oe,U9 as Pe,L9 as Qe,I9 as Re,KQ as Se,BQ as Te,VQ as Ue,DQ as Ve,LQ as We,HQ as Xe,kx as Ye,IQ as Ze,s4 as _e,P9 as $e,T9 as af,M9 as bf,n4 as cf,dZ as df,fQ as ef,bQ as ff,p as gf,aZ as hf,N4 as if,QP as jf,KP as kf,FP as lf,DP as mf,NX as nf,O7 as of,CX as pf,PP as qf,EX as rf,m0 as sf,b3 as tf,fX as uf,RQ as vf,VC as wf,A9 as xf,L1 as yf,H1 as zf,E9 as Af,w9 as Bf,XU as Cf,t4 as Df,e4 as Ef,k9 as Ff,pQ as Gf,cQ as Hf,$8 as If,nQ as Jf,U7 as Kf,fO as Lf,C7 as Mf,S7 as Nf,fT as Of,nX as Pf,oX as Qf,n3 as Rf,c1 as Sf,hT as Tf,rX as Uf,tX as Vf,a7 as Wf,hZ as Xf,r7 as Yf,pM as Zf,oM as _f,aM as $f,K9 as ag,SD as bg,G9 as cg,fD as dg,h3 as eg,F9 as fg,nG as gg,oG as hg,h4 as ig,W1 as jg,E as kg,R0 as lg,o3 as mg,YW as ng,LK as og,ZW as pg,zW as qg,F8 as rg,B8 as sg,V8 as tg,XW as ug,_K as vg,xK as wg,OW as xg,UW as yg,HW as zg,xW as Ag,CW as Bg,SW as Cg,P8 as Dg,bK as Eg,j0 as Fg,gW as Gg,jZ as Hg,dW as Ig};
120
+ )`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var yQ=191,vQ=30000;class t4 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class e4 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class k9{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=O1(wQ(),$),this.store=KU(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(dZ);return this.ownFeed??=new dZ,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){hQ("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;hQ("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:c$($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return QU(Z),this.change($,L1,{status:"running",progress:Z})}complete($,Z){return this.change($,L1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,L1,{status:"failed",error:mQ(Z)})}cancel($,Z){return this.change($,L1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new t4($);if(H1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(G)=>{if(Y.signal.aborted)return;await this.progress($,G)}},X;try{let G=await Z(z);X=await this.complete($,G)}catch(G){if(!(G instanceof e4)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,L1,{status:"failed",error:G instanceof e4?mQ(G):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+c$(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new t4($);let z=null;for(;;){if(H1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let G=W-Date.now();if(G<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await gQ(z,Math.min(G,X??1/0,vQ),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new t4($);if(yield W,H1(W.status))return;for await(let Y of J){let j=GU(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,H1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=c$($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||H1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,L1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(H1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,gQ(j,Math.min(z??1/0,vQ))]);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 gQ($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>G(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},G=(Q)=>{X(),W(Q)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>G(!0),()=>G(!0))})}function GU($,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 mQ($){if(typeof $==="string")return{message:$};if($ instanceof e4)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function hQ($,Z){if(typeof Z!=="string"||Z===""||Z.length>yQ)throw TypeError(`A run's ${$} is a string of 1 to ${yQ} characters; got ${JSON.stringify(Z)}.`)}function QU($){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 KU($,Z){if($==="memory")return new E9;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(C1).connection();return new w9(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class pQ extends v{static getFacadeAccessor(){return k9}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class cQ extends v{static getFacadeAccessor(){return s1}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class $8{bound;constructor($){this.bound=$}get name(){return this.bound??x1()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,J=this.connection(Z);return lQ(J.sql,(W)=>dQ(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-c0m8pcbd.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=sQ($,iQ(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=i0();if($===void 0)return;return x1()===this.name?$:void 0}connection($=this.name){return uQ($),L(C1).connection($)}}var uZ=new $8;class nQ extends v{static getFacadeAccessor(){return C1}static connection($){return new $8($)}static get sql(){return uZ.sql}static get dialect(){return uZ.dialect}static query($){return uZ.query($)}static execute($){return uZ.execute($)}static transaction($){return uZ.transaction($)}static schema(){return uZ.schema()}static close(){return this.getFacadeRoot().close()}}export{l0 as _d,sZ as $d,j8 as ae,r$ as be,oZ as ce,N0 as de,s3 as ee,E8 as fe,f8 as ge,lW as he,i1 as ie,z1 as je,t as ke,NW as le,JZ as me,iW as ne,sW as oe,R8 as pe,w8 as qe,j6 as re,eZ as se,LF as te,xI as ue,Y5 as ve,F5 as we,g8 as xe,B5 as ye,V5 as ze,xF as Ae,O5 as Be,m8 as Ce,AF as De,EF as Ee,h8 as Fe,D5 as Ge,U5 as He,s1 as Ie,L5 as Je,wF as Ke,c8 as Le,L8 as Me,t3 as Ne,M1 as Oe,U$ as Pe,NK as Qe,D8 as Re,N1 as Se,V$ as Te,i4 as Ue,jQ as Ve,zQ as We,iD as Xe,m1 as Ye,zx as Ze,XQ as _e,U9 as $e,L9 as af,I9 as bf,KQ as cf,BQ as df,VQ as ef,DQ as ff,LQ as gf,HQ as hf,kx as if,IQ as jf,s4 as kf,P9 as lf,T9 as mf,M9 as nf,n4 as of,dZ as pf,fQ as qf,bQ as rf,p as sf,aZ as tf,N4 as uf,QP as vf,KP as wf,FP as xf,DP as yf,NX as zf,O7 as Af,CX as Bf,PP as Cf,EX as Df,m0 as Ef,b3 as Ff,fX as Gf,RQ as Hf,VC as If,A9 as Jf,L1 as Kf,H1 as Lf,E9 as Mf,w9 as Nf,XU as Of,t4 as Pf,e4 as Qf,k9 as Rf,pQ as Sf,cQ as Tf,$8 as Uf,nQ as Vf,U7 as Wf,fO as Xf,C7 as Yf,S7 as Zf,fT as _f,nX as $f,oX as ag,n3 as bg,c1 as cg,hT as dg,rX as eg,tX as fg,a7 as gg,hZ as hg,r7 as ig,pM as jg,oM as kg,aM as lg,K9 as mg,SD as ng,G9 as og,fD as pg,h3 as qg,F9 as rg,nG as sg,oG as tg,h4 as ug,W1 as vg,E as wg,R0 as xg,o3 as yg,YW as zg,LK as Ag,ZW as Bg,zW as Cg,F8 as Dg,B8 as Eg,V8 as Fg,XW as Gg,_K as Hg,xK as Ig,OW as Jg,UW as Kg,HW as Lg,xW as Mg,CW as Ng,SW as Og,P8 as Pg,bK as Qg,j0 as Rg,gW as Sg,jZ as Tg,dW as Ug};
121
121
 
122
- //# debugId=B65CF732B4A69BAD64756E2164756E21
122
+ //# debugId=A0A615885F51D7FA64756E2164756E21