gemi 0.115.0 → 0.117.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 (348) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/app/index.js +2 -2
  4. package/dist/app/index.js.map +1 -1
  5. package/dist/auth/AuthServiceProvider.d.ts.map +1 -1
  6. package/dist/auth/config.d.ts +27 -0
  7. package/dist/auth/config.d.ts.map +1 -1
  8. package/dist/auth/connections/ConnectionManager.d.ts +133 -0
  9. package/dist/auth/connections/ConnectionManager.d.ts.map +1 -0
  10. package/dist/auth/connections/ConnectionStore.d.ts +146 -0
  11. package/dist/auth/connections/ConnectionStore.d.ts.map +1 -0
  12. package/dist/auth/connections/ConnectionsController.d.ts +23 -0
  13. package/dist/auth/connections/ConnectionsController.d.ts.map +1 -0
  14. package/dist/auth/connections/OAuthConnectionProvider.d.ts +105 -0
  15. package/dist/auth/connections/OAuthConnectionProvider.d.ts.map +1 -0
  16. package/dist/auth/connections/errors.d.ts +32 -0
  17. package/dist/auth/connections/errors.d.ts.map +1 -0
  18. package/dist/auth/oauth/oauthState.d.ts +15 -2
  19. package/dist/auth/oauth/oauthState.d.ts.map +1 -1
  20. package/dist/auth/routes.d.ts +13 -0
  21. package/dist/auth/routes.d.ts.map +1 -1
  22. package/dist/bin/orm/emit.d.ts.map +1 -1
  23. package/dist/bin/orm-generator.js +51 -4
  24. package/dist/bin/orm-generator.js.map +4 -4
  25. package/dist/bun/plugin.js +2 -2
  26. package/dist/bun/plugin.js.map +1 -1
  27. package/dist/bun/preload.js +2 -2
  28. package/dist/bun/preload.js.map +1 -1
  29. package/dist/chunk-00n3gwr8.js +71 -0
  30. package/dist/chunk-00n3gwr8.js.map +13 -0
  31. package/dist/{chunk-t4yh4nf9.js → chunk-076jezzg.js} +3 -3
  32. package/dist/{chunk-t4yh4nf9.js.map → chunk-076jezzg.js.map} +1 -1
  33. package/dist/{chunk-qjhw8nje.js → chunk-077rea02.js} +1 -1
  34. package/dist/{chunk-0av6xvm6.js → chunk-1ckha5dt.js} +3 -3
  35. package/dist/{chunk-0av6xvm6.js.map → chunk-1ckha5dt.js.map} +1 -1
  36. package/dist/{chunk-mschc94q.js → chunk-1zzd39qg.js} +2 -2
  37. package/dist/{chunk-mschc94q.js.map → chunk-1zzd39qg.js.map} +1 -1
  38. package/dist/{chunk-5stgtwqw.js → chunk-2bja99cq.js} +2 -2
  39. package/dist/{chunk-5stgtwqw.js.map → chunk-2bja99cq.js.map} +1 -1
  40. package/dist/chunk-2czfefn2.js +10 -0
  41. package/dist/{chunk-t4t3hqe0.js.map → chunk-2czfefn2.js.map} +5 -4
  42. package/dist/{chunk-aazmrxj9.js → chunk-37pk2cjg.js} +2 -2
  43. package/dist/{chunk-aazmrxj9.js.map → chunk-37pk2cjg.js.map} +1 -1
  44. package/dist/{chunk-qsrcdzan.js → chunk-3w4hk6q2.js} +3 -3
  45. package/dist/{chunk-qsrcdzan.js.map → chunk-3w4hk6q2.js.map} +1 -1
  46. package/dist/chunk-51w202vr.js +5 -0
  47. package/dist/{chunk-whtzggn6.js.map → chunk-51w202vr.js.map} +3 -4
  48. package/dist/{chunk-0z8ejxre.js → chunk-5m8vvtvn.js} +3 -3
  49. package/dist/{chunk-0z8ejxre.js.map → chunk-5m8vvtvn.js.map} +1 -1
  50. package/dist/{chunk-jafm3613.js → chunk-5p4z1fgc.js} +2 -2
  51. package/dist/{chunk-jafm3613.js.map → chunk-5p4z1fgc.js.map} +1 -1
  52. package/dist/{chunk-kejwjerj.js → chunk-5w6kyxsj.js} +2 -2
  53. package/dist/{chunk-kejwjerj.js.map → chunk-5w6kyxsj.js.map} +1 -1
  54. package/dist/{chunk-pyk3gzvc.js → chunk-62jw0vsf.js} +2 -2
  55. package/dist/{chunk-pyk3gzvc.js.map → chunk-62jw0vsf.js.map} +1 -1
  56. package/dist/chunk-63ewmmhc.js +5 -0
  57. package/dist/{chunk-t24p7gc6.js.map → chunk-63ewmmhc.js.map} +1 -1
  58. package/dist/{chunk-p1aqq0ga.js → chunk-6ggmk2eg.js} +3 -3
  59. package/dist/{chunk-p1aqq0ga.js.map → chunk-6ggmk2eg.js.map} +1 -1
  60. package/dist/{chunk-2tzm58j3.js → chunk-6y4nk9f1.js} +2 -2
  61. package/dist/{chunk-2tzm58j3.js.map → chunk-6y4nk9f1.js.map} +1 -1
  62. package/dist/{chunk-1hr4xht1.js → chunk-8gtc3s1y.js} +2 -2
  63. package/dist/{chunk-1hr4xht1.js.map → chunk-8gtc3s1y.js.map} +1 -1
  64. package/dist/{chunk-frerzsxq.js → chunk-a22h5cby.js} +2 -2
  65. package/dist/{chunk-frerzsxq.js.map → chunk-a22h5cby.js.map} +1 -1
  66. package/dist/{chunk-zyt2w03d.js → chunk-a32wfzdq.js} +2 -2
  67. package/dist/{chunk-zyt2w03d.js.map → chunk-a32wfzdq.js.map} +1 -1
  68. package/dist/{chunk-t04f3akb.js → chunk-a77586gv.js} +2 -2
  69. package/dist/{chunk-t04f3akb.js.map → chunk-a77586gv.js.map} +1 -1
  70. package/dist/chunk-a7r39713.js +5 -0
  71. package/dist/chunk-a7r39713.js.map +10 -0
  72. package/dist/{chunk-vxm6yevm.js → chunk-arwmvgrz.js} +2 -2
  73. package/dist/{chunk-vxm6yevm.js.map → chunk-arwmvgrz.js.map} +1 -1
  74. package/dist/{chunk-41da9628.js → chunk-bvqae0px.js} +1 -1
  75. package/dist/{chunk-d9mar37g.js → chunk-c2n6zdyd.js} +2 -2
  76. package/dist/{chunk-d9mar37g.js.map → chunk-c2n6zdyd.js.map} +1 -1
  77. package/dist/{chunk-56jky6vf.js → chunk-cytss9mb.js} +2 -2
  78. package/dist/{chunk-56jky6vf.js.map → chunk-cytss9mb.js.map} +1 -1
  79. package/dist/{chunk-vw8849ys.js → chunk-dcgvq79a.js} +2 -2
  80. package/dist/{chunk-m54s6jpr.js.map → chunk-dcgvq79a.js.map} +1 -1
  81. package/dist/{chunk-6chz1ktz.js → chunk-de4t48j9.js} +3 -3
  82. package/dist/{chunk-6chz1ktz.js.map → chunk-de4t48j9.js.map} +1 -1
  83. package/dist/{chunk-cbqazg9k.js → chunk-dz99g58c.js} +2 -2
  84. package/dist/{chunk-cbqazg9k.js.map → chunk-dz99g58c.js.map} +1 -1
  85. package/dist/{chunk-e573yxpq.js → chunk-e7ezmag9.js} +3 -3
  86. package/dist/{chunk-e573yxpq.js.map → chunk-e7ezmag9.js.map} +1 -1
  87. package/dist/{chunk-yer1r3t3.js → chunk-epvpmakp.js} +2 -2
  88. package/dist/{chunk-yer1r3t3.js.map → chunk-epvpmakp.js.map} +1 -1
  89. package/dist/{chunk-yhrye9cm.js → chunk-f8vcwzgd.js} +2 -2
  90. package/dist/{chunk-yhrye9cm.js.map → chunk-f8vcwzgd.js.map} +1 -1
  91. package/dist/chunk-fa37qzm3.js +5 -0
  92. package/dist/chunk-fa37qzm3.js.map +12 -0
  93. package/dist/{chunk-fxgxf16k.js → chunk-ffgmqwzy.js} +2 -2
  94. package/dist/{chunk-fxgxf16k.js.map → chunk-ffgmqwzy.js.map} +1 -1
  95. package/dist/{chunk-er3wf6ng.js → chunk-fk6nxhxn.js} +2 -2
  96. package/dist/{chunk-er3wf6ng.js.map → chunk-fk6nxhxn.js.map} +1 -1
  97. package/dist/{chunk-3hrj5rwm.js → chunk-fnwbbmnk.js} +2 -2
  98. package/dist/{chunk-3hrj5rwm.js.map → chunk-fnwbbmnk.js.map} +1 -1
  99. package/dist/chunk-g2wncay4.js +9 -0
  100. package/dist/{chunk-hytt9qyj.js.map → chunk-g2wncay4.js.map} +3 -4
  101. package/dist/{chunk-gts5p6mw.js → chunk-ge9xjwgq.js} +4 -4
  102. package/dist/{chunk-gts5p6mw.js.map → chunk-ge9xjwgq.js.map} +1 -1
  103. package/dist/{chunk-tw5kwbx4.js → chunk-gjy2qjcr.js} +2 -2
  104. package/dist/{chunk-tw5kwbx4.js.map → chunk-gjy2qjcr.js.map} +1 -1
  105. package/dist/{chunk-15c2vgaf.js → chunk-gn7kne7r.js} +2 -2
  106. package/dist/{chunk-15c2vgaf.js.map → chunk-gn7kne7r.js.map} +1 -1
  107. package/dist/{chunk-9n1hx3mq.js → chunk-hr61ekcr.js} +3 -3
  108. package/dist/{chunk-9n1hx3mq.js.map → chunk-hr61ekcr.js.map} +1 -1
  109. package/dist/{chunk-m54s6jpr.js → chunk-hvgmqt6z.js} +2 -2
  110. package/dist/{chunk-vw8849ys.js.map → chunk-hvgmqt6z.js.map} +1 -1
  111. package/dist/{chunk-aeh67ynz.js → chunk-hvpn18bb.js} +3 -3
  112. package/dist/{chunk-aeh67ynz.js.map → chunk-hvpn18bb.js.map} +1 -1
  113. package/dist/{chunk-jdhdrr2k.js → chunk-j1453bn1.js} +2 -2
  114. package/dist/{chunk-jdhdrr2k.js.map → chunk-j1453bn1.js.map} +1 -1
  115. package/dist/{chunk-tn2bryy2.js → chunk-jpetnpzn.js} +2 -2
  116. package/dist/{chunk-tn2bryy2.js.map → chunk-jpetnpzn.js.map} +1 -1
  117. package/dist/{chunk-mtbygktb.js → chunk-jqrs16g2.js} +3 -3
  118. package/dist/{chunk-mtbygktb.js.map → chunk-jqrs16g2.js.map} +1 -1
  119. package/dist/{chunk-4mfrgd5m.js → chunk-kk77x2v4.js} +2 -2
  120. package/dist/{chunk-4mfrgd5m.js.map → chunk-kk77x2v4.js.map} +1 -1
  121. package/dist/chunk-kpn7f58a.js +14 -0
  122. package/dist/{chunk-dexdkh3z.js.map → chunk-kpn7f58a.js.map} +11 -6
  123. package/dist/chunk-mhteg4yz.js +57 -0
  124. package/dist/{chunk-d6591xck.js.map → chunk-mhteg4yz.js.map} +16 -12
  125. package/dist/{chunk-n672d4g8.js → chunk-n9jyjp4a.js} +2 -2
  126. package/dist/{chunk-n672d4g8.js.map → chunk-n9jyjp4a.js.map} +1 -1
  127. package/dist/{chunk-vbdty91k.js → chunk-nb2gggba.js} +3 -3
  128. package/dist/{chunk-vbdty91k.js.map → chunk-nb2gggba.js.map} +1 -1
  129. package/dist/chunk-ntxsdchf.js +50 -0
  130. package/dist/chunk-ntxsdchf.js.map +10 -0
  131. package/dist/{chunk-2z1981d0.js → chunk-pepzecrm.js} +2 -2
  132. package/dist/{chunk-2z1981d0.js.map → chunk-pepzecrm.js.map} +1 -1
  133. package/dist/{chunk-785b41h1.js → chunk-pgy3mfxw.js} +3 -3
  134. package/dist/{chunk-785b41h1.js.map → chunk-pgy3mfxw.js.map} +1 -1
  135. package/dist/{chunk-98m15b9x.js → chunk-qhw0hej0.js} +2 -2
  136. package/dist/{chunk-98m15b9x.js.map → chunk-qhw0hej0.js.map} +1 -1
  137. package/dist/{chunk-303mprnv.js → chunk-r3v2cnrj.js} +2 -2
  138. package/dist/{chunk-303mprnv.js.map → chunk-r3v2cnrj.js.map} +1 -1
  139. package/dist/{chunk-ktr3k768.js → chunk-rhmpphhc.js} +3 -3
  140. package/dist/{chunk-ktr3k768.js.map → chunk-rhmpphhc.js.map} +1 -1
  141. package/dist/{chunk-fre6f4nk.js → chunk-s4f56035.js} +2 -2
  142. package/dist/{chunk-fre6f4nk.js.map → chunk-s4f56035.js.map} +1 -1
  143. package/dist/{chunk-sr942vb1.js → chunk-sj4f7x4p.js} +2 -2
  144. package/dist/{chunk-sr942vb1.js.map → chunk-sj4f7x4p.js.map} +1 -1
  145. package/dist/{chunk-wyw6p3fg.js → chunk-sksmnjkn.js} +3 -3
  146. package/dist/{chunk-wyw6p3fg.js.map → chunk-sksmnjkn.js.map} +1 -1
  147. package/dist/{chunk-kqxdsv22.js → chunk-stnd9qht.js} +2 -2
  148. package/dist/{chunk-kqxdsv22.js.map → chunk-stnd9qht.js.map} +1 -1
  149. package/dist/{chunk-1myhm0g3.js → chunk-t65074mw.js} +3 -3
  150. package/dist/{chunk-1myhm0g3.js.map → chunk-t65074mw.js.map} +1 -1
  151. package/dist/chunk-t87w4h84.js +24 -0
  152. package/dist/{chunk-wzrt5mac.js.map → chunk-t87w4h84.js.map} +2 -2
  153. package/dist/{chunk-z10cas5r.js → chunk-thz75w6e.js} +2 -2
  154. package/dist/{chunk-z10cas5r.js.map → chunk-thz75w6e.js.map} +1 -1
  155. package/dist/{chunk-xt9tv99x.js → chunk-v8vnxkvp.js} +2 -2
  156. package/dist/{chunk-xt9tv99x.js.map → chunk-v8vnxkvp.js.map} +1 -1
  157. package/dist/{chunk-x7cpth2f.js → chunk-veq07rp8.js} +1 -1
  158. package/dist/{chunk-agyfv3f8.js → chunk-vj5necm0.js} +1 -1
  159. package/dist/{chunk-mps6ynbh.js → chunk-vtc23xpk.js} +2 -2
  160. package/dist/{chunk-mps6ynbh.js.map → chunk-vtc23xpk.js.map} +1 -1
  161. package/dist/{chunk-jmpw6bqz.js → chunk-w4e480he.js} +2 -2
  162. package/dist/{chunk-jmpw6bqz.js.map → chunk-w4e480he.js.map} +1 -1
  163. package/dist/{chunk-8rv62v14.js → chunk-wgb79ysr.js} +2 -2
  164. package/dist/{chunk-8rv62v14.js.map → chunk-wgb79ysr.js.map} +1 -1
  165. package/dist/{chunk-1vzks22y.js → chunk-wk1tp1f1.js} +2 -2
  166. package/dist/{chunk-1vzks22y.js.map → chunk-wk1tp1f1.js.map} +1 -1
  167. package/dist/{chunk-bra1a1fq.js → chunk-wwdbgshx.js} +2 -2
  168. package/dist/{chunk-bra1a1fq.js.map → chunk-wwdbgshx.js.map} +1 -1
  169. package/dist/{chunk-eqse2m6n.js → chunk-wzzrz612.js} +2 -2
  170. package/dist/{chunk-eqse2m6n.js.map → chunk-wzzrz612.js.map} +1 -1
  171. package/dist/{chunk-hdps9n52.js → chunk-x7qwx07b.js} +3 -3
  172. package/dist/{chunk-hdps9n52.js.map → chunk-x7qwx07b.js.map} +1 -1
  173. package/dist/chunk-x84as3vy.js +5 -0
  174. package/dist/chunk-x84as3vy.js.map +12 -0
  175. package/dist/chunk-y0en07zh.js +302 -0
  176. package/dist/chunk-y0en07zh.js.map +17 -0
  177. package/dist/{chunk-d2gfcf85.js → chunk-yfwrbfnw.js} +2 -2
  178. package/dist/{chunk-d2gfcf85.js.map → chunk-yfwrbfnw.js.map} +1 -1
  179. package/dist/{chunk-mazznq15.js → chunk-yhp6bvhj.js} +3 -3
  180. package/dist/{chunk-mazznq15.js.map → chunk-yhp6bvhj.js.map} +1 -1
  181. package/dist/{chunk-tzm3c7n6.js → chunk-yvtmygrk.js} +4 -4
  182. package/dist/{chunk-tzm3c7n6.js.map → chunk-yvtmygrk.js.map} +1 -1
  183. package/dist/{chunk-mqfzdfnz.js → chunk-zkjs3m5m.js} +2 -2
  184. package/dist/{chunk-mqfzdfnz.js.map → chunk-zkjs3m5m.js.map} +1 -1
  185. package/dist/chunk-zw6843j3.js +5 -0
  186. package/dist/chunk-zw6843j3.js.map +12 -0
  187. package/dist/chunks/{ThemeProvider-BgLyzzOL.js → ThemeProvider-BLI4zpLu.js} +8 -3
  188. package/dist/chunks/ThemeProvider-BLI4zpLu.js.map +1 -0
  189. package/dist/client/ClientRouter.d.ts +3 -5
  190. package/dist/client/ClientRouter.d.ts.map +1 -1
  191. package/dist/client/ClientRouterContext.d.ts.map +1 -1
  192. package/dist/client/Head.d.ts +1 -1
  193. package/dist/client/Head.d.ts.map +1 -1
  194. package/dist/client/ServerDataProvider.d.ts +2 -0
  195. package/dist/client/ServerDataProvider.d.ts.map +1 -1
  196. package/dist/client/createRoot.d.ts +2 -4
  197. package/dist/client/createRoot.d.ts.map +1 -1
  198. package/dist/client/fonts.d.ts +69 -0
  199. package/dist/client/fonts.d.ts.map +1 -0
  200. package/dist/client/htmlAttributes.d.ts +18 -0
  201. package/dist/client/htmlAttributes.d.ts.map +1 -0
  202. package/dist/client/index.d.ts +2 -0
  203. package/dist/client/index.d.ts.map +1 -1
  204. package/dist/client/index.js +153 -6
  205. package/dist/client/index.js.map +1 -1
  206. package/dist/config/index.js +1 -1
  207. package/dist/console/builtins.d.ts +13 -0
  208. package/dist/console/builtins.d.ts.map +1 -0
  209. package/dist/console/run.js +13 -11
  210. package/dist/console/run.js.map +6 -5
  211. package/dist/console/runner.d.ts.map +1 -1
  212. package/dist/console/usage.d.ts +2 -0
  213. package/dist/console/usage.d.ts.map +1 -1
  214. package/dist/container/index.js +2 -2
  215. package/dist/container/index.js.map +1 -1
  216. package/dist/database/index.js +2 -2
  217. package/dist/database/index.js.map +1 -1
  218. package/dist/email/index.js +2 -2
  219. package/dist/email/index.js.map +1 -1
  220. package/dist/facades/Connections.d.ts +36 -0
  221. package/dist/facades/Connections.d.ts.map +1 -0
  222. package/dist/facades/Crypt.d.ts +26 -0
  223. package/dist/facades/Crypt.d.ts.map +1 -0
  224. package/dist/facades/Meta.d.ts +17 -1
  225. package/dist/facades/Meta.d.ts.map +1 -1
  226. package/dist/facades/Storage.d.ts +29 -0
  227. package/dist/facades/Storage.d.ts.map +1 -1
  228. package/dist/facades/index.d.ts +2 -0
  229. package/dist/facades/index.d.ts.map +1 -1
  230. package/dist/facades/index.js +2 -2
  231. package/dist/facades/index.js.map +1 -1
  232. package/dist/foundation/index.js +2 -2
  233. package/dist/foundation/index.js.map +1 -1
  234. package/dist/http/HttpRequest.d.ts +4 -0
  235. package/dist/http/HttpRequest.d.ts.map +1 -1
  236. package/dist/http/Metadata.d.ts +28 -0
  237. package/dist/http/Metadata.d.ts.map +1 -1
  238. package/dist/http/index.d.ts +3 -1
  239. package/dist/http/index.d.ts.map +1 -1
  240. package/dist/http/index.js +2 -2
  241. package/dist/http/index.js.map +1 -1
  242. package/dist/http/requestContext.d.ts +4 -0
  243. package/dist/http/requestContext.d.ts.map +1 -1
  244. package/dist/http/safeFetch/errors.d.ts +10 -0
  245. package/dist/http/safeFetch/errors.d.ts.map +1 -1
  246. package/dist/http/safeFetch/index.d.ts +1 -1
  247. package/dist/http/safeFetch/index.d.ts.map +1 -1
  248. package/dist/http/sitemap/Robots.d.ts +95 -0
  249. package/dist/http/sitemap/Robots.d.ts.map +1 -0
  250. package/dist/http/sitemap/Sitemap.d.ts +145 -0
  251. package/dist/http/sitemap/Sitemap.d.ts.map +1 -0
  252. package/dist/http/sitemap/fetchText.d.ts +16 -0
  253. package/dist/http/sitemap/fetchText.d.ts.map +1 -0
  254. package/dist/http/sitemap/index.d.ts +3 -0
  255. package/dist/http/sitemap/index.d.ts.map +1 -0
  256. package/dist/http/sitemap/xml.d.ts +21 -0
  257. package/dist/http/sitemap/xml.d.ts.map +1 -0
  258. package/dist/i18n/Translator.d.ts.map +1 -1
  259. package/dist/i18n/dictionaryRuntime.js +2 -2
  260. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  261. package/dist/i18n/index.d.ts +1 -0
  262. package/dist/i18n/index.d.ts.map +1 -1
  263. package/dist/i18n/index.js +2 -2
  264. package/dist/i18n/index.js.map +2 -2
  265. package/dist/i18n/resolveLocale.d.ts +18 -0
  266. package/dist/i18n/resolveLocale.d.ts.map +1 -1
  267. package/dist/kernel/index.js +3 -3
  268. package/dist/kernel/index.js.map +3 -3
  269. package/dist/kernel/providers.d.ts +2 -2
  270. package/dist/kernel/providers.d.ts.map +1 -1
  271. package/dist/orm/Model.d.ts.map +1 -1
  272. package/dist/orm/encryption-rotate.d.ts +44 -0
  273. package/dist/orm/encryption-rotate.d.ts.map +1 -0
  274. package/dist/orm/encryption.d.ts +54 -0
  275. package/dist/orm/encryption.d.ts.map +1 -0
  276. package/dist/orm/index.d.ts +2 -0
  277. package/dist/orm/index.d.ts.map +1 -1
  278. package/dist/orm/index.js +3 -3
  279. package/dist/orm/index.js.map +4 -4
  280. package/dist/orm/schema.d.ts +25 -1
  281. package/dist/orm/schema.d.ts.map +1 -1
  282. package/dist/server/index.js +2 -2
  283. package/dist/server/index.js.map +1 -1
  284. package/dist/services/encryption/Encrypter.d.ts +86 -0
  285. package/dist/services/encryption/Encrypter.d.ts.map +1 -0
  286. package/dist/services/encryption/EncryptionServiceProvider.d.ts +13 -0
  287. package/dist/services/encryption/EncryptionServiceProvider.d.ts.map +1 -0
  288. package/dist/services/encryption/config.d.ts +36 -0
  289. package/dist/services/encryption/config.d.ts.map +1 -0
  290. package/dist/services/file-storage/drivers/FileStorageDriver.d.ts +12 -1
  291. package/dist/services/file-storage/drivers/FileStorageDriver.d.ts.map +1 -1
  292. package/dist/services/file-storage/drivers/FileSystemDriver.d.ts +8 -1
  293. package/dist/services/file-storage/drivers/FileSystemDriver.d.ts.map +1 -1
  294. package/dist/services/file-storage/drivers/types.d.ts +17 -0
  295. package/dist/services/file-storage/drivers/types.d.ts.map +1 -1
  296. package/dist/services/file-storage/putFromUrl.d.ts +56 -0
  297. package/dist/services/file-storage/putFromUrl.d.ts.map +1 -0
  298. package/dist/services/file-storage/sniffContentType.d.ts +33 -0
  299. package/dist/services/file-storage/sniffContentType.d.ts.map +1 -0
  300. package/dist/services/index.d.ts +19 -5
  301. package/dist/services/index.d.ts.map +1 -1
  302. package/dist/services/index.js +10 -10
  303. package/dist/services/index.js.map +4 -3
  304. package/dist/services/queue/DatabaseQueueDriver.d.ts +96 -7
  305. package/dist/services/queue/DatabaseQueueDriver.d.ts.map +1 -1
  306. package/dist/services/queue/Job.d.ts +72 -0
  307. package/dist/services/queue/Job.d.ts.map +1 -1
  308. package/dist/services/queue/MemoryQueueDriver.d.ts +22 -2
  309. package/dist/services/queue/MemoryQueueDriver.d.ts.map +1 -1
  310. package/dist/services/queue/QueueDriver.d.ts +74 -1
  311. package/dist/services/queue/QueueDriver.d.ts.map +1 -1
  312. package/dist/services/queue/QueueManager.d.ts +47 -0
  313. package/dist/services/queue/QueueManager.d.ts.map +1 -1
  314. package/dist/services/queue/batch.d.ts +112 -0
  315. package/dist/services/queue/batch.d.ts.map +1 -0
  316. package/dist/services/queue/queueDriverContract.d.ts +5 -0
  317. package/dist/services/queue/queueDriverContract.d.ts.map +1 -1
  318. package/dist/services/queue/work.js +2 -2
  319. package/dist/services/queue/work.js.map +1 -1
  320. package/dist/services/router/ViewRouteDispatcher.d.ts +3 -1
  321. package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
  322. package/dist/services/router/config.d.ts +19 -0
  323. package/dist/services/router/config.d.ts.map +1 -1
  324. package/dist/stats/route-table.js +1 -1
  325. package/dist/support/index.js +2 -2
  326. package/dist/support/index.js.map +1 -1
  327. package/dist/testing/index.js +1 -1
  328. package/dist/vitest/index.js +2 -2
  329. package/dist/vitest/index.js.map +1 -1
  330. package/package.json +1 -1
  331. package/dist/chunk-7g9yh5ae.js +0 -5
  332. package/dist/chunk-7g9yh5ae.js.map +0 -12
  333. package/dist/chunk-7vb4eey2.js +0 -217
  334. package/dist/chunk-7vb4eey2.js.map +0 -16
  335. package/dist/chunk-9b4erdy2.js +0 -5
  336. package/dist/chunk-9b4erdy2.js.map +0 -11
  337. package/dist/chunk-d6591xck.js +0 -46
  338. package/dist/chunk-dexdkh3z.js +0 -14
  339. package/dist/chunk-hytt9qyj.js +0 -54
  340. package/dist/chunk-t24p7gc6.js +0 -5
  341. package/dist/chunk-t4t3hqe0.js +0 -10
  342. package/dist/chunk-whtzggn6.js +0 -5
  343. package/dist/chunk-wzrt5mac.js +0 -24
  344. package/dist/chunks/ThemeProvider-BgLyzzOL.js.map +0 -1
  345. /package/dist/{chunk-qjhw8nje.js.map → chunk-077rea02.js.map} +0 -0
  346. /package/dist/{chunk-41da9628.js.map → chunk-bvqae0px.js.map} +0 -0
  347. /package/dist/{chunk-x7cpth2f.js.map → chunk-veq07rp8.js.map} +0 -0
  348. /package/dist/{chunk-agyfv3f8.js.map → chunk-vj5necm0.js.map} +0 -0
@@ -1,14 +0,0 @@
1
- // @bun
2
- import{Rg as F,Sg as t,Tg as l}from"./chunk-15c2vgaf.js";import{Wg as V}from"./chunk-9b4erdy2.js";import{bi as f0}from"./chunk-t4yh4nf9.js";import{ni as h}from"./chunk-1hr4xht1.js";import{ui as LH}from"./chunk-vw8849ys.js";class A0{static kind="controller";constructor(){}}class u0 extends A0{}function Q0(H){let Q=new Map;if(!H)return Q;for(let X of H.split(";")){let $=X.indexOf("=");if($===-1)continue;let Z=X.slice(0,$).trim();if(!Z)continue;Q.set(Z,X.slice($+1).trim())}return Q}function gH(H){return Q0(H.headers.get("cookie"))}function N(H){if(!/^\d+$/.test(H))return null;let Q=Number(H);return Number.isSafeInteger(Q)?Q:null}function J0(H){if(!H)return null;let Q=H.trim();if(!/^bytes=/i.test(Q))return null;let $=Q.slice(6).split(",").map((U)=>U.trim()).filter((U)=>U!=="");if($.length!==1)return null;let Z=$[0],G=Z.indexOf("-");if(G===-1)return null;let W=Z.slice(0,G),Y=Z.slice(G+1);if(W===""){let U=N(Y);if(U===null)return null;return{kind:"suffix",suffixLength:U}}let T=N(W);if(T===null)return null;if(Y==="")return{kind:"offset",start:T,end:null};let M=N(Y);if(M===null||M<T)return null;return{kind:"offset",start:T,end:M}}function L0(H,Q){if(!Number.isFinite(Q)||Q<=0)return null;let X,$;if(H.kind==="suffix"){if(H.suffixLength<=0)return null;X=Math.max(0,Q-H.suffixLength),$=Q-1}else{if(H.start>=Q)return null;if(X=H.start,$=H.end===null?Q-1:Math.min(H.end,Q-1),$<X)return null}return{start:X,end:$,length:$-X+1}}function kH(H){if(H.kind==="suffix")return`bytes=-${H.suffixLength}`;return H.end===null?`bytes=${H.start}-`:`bytes=${H.start}-${H.end}`}function bH(H){if(!H)return null;let Q=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(H.trim());if(!Q)return null;let X=N(Q[1]),$=N(Q[2]),Z=N(Q[3]);if(X===null||$===null||Z===null||$<X)return null;return{start:X,end:$,total:Z}}function fH(H,Q,X){return`bytes ${H}-${Q}/${X}`}function R0(H){return`bytes */${H}`}class S extends F{errors={};constructor(H){super("Validation error");this.name="ValidationError",this.errors=H,this.payload={api:{status:400,data:{error:{kind:"validation_error",messages:H,status:400}},headers:{"Content-Type":"application/json"}},view:{status:400}}}}function o0(H){let[Q,X]=H.match(/\d+|\D+/g)??[];if(!Q||!X)return 0;let $=Number.parseInt(Q);switch(X){case"B":return $;case"KB":return $*1024;case"MB":return $*1024*1024;case"GB":return $*1024*1024*1024;case"TB":return $*1024*1024*1024*1024;default:return 0}}function n0(H){switch(H){case"image":return"image";case"png":return"image/png";case"jpg":return"image/jpeg";case"jpeg":return"image/jpeg";case"ttf":return"font/ttf";case"excel":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"csv":return"text/csv";case"word":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"pdf":return"application/pdf";case"json":return"application/json";default:return H}}function C0(H){if(typeof H==="string"||Array.isArray(H))return H.length;return}function X0(H){return typeof H==="number"&&!Number.isNaN(H)}var i0=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class P extends Error{name="InvalidValidationRuleError"}function c(H,Q){let X=Q===void 0||Q.trim()===""?Number.NaN:Number(Q);if(Number.isNaN(X))throw new P(`Validation rule "${H}:${Q??""}" needs a number, e.g. "${H}:3"`);return X}function P0(H){let Q=H.indexOf(":"),X=Q===-1?H:H.slice(0,Q),$=Q===-1?void 0:H.slice(Q+1);switch(X){case"required":return(Z)=>{if(Z instanceof Blob)return Z.size>0;if(Z===null||Z===void 0)return!1;if(typeof Z==="string"||Array.isArray(Z))return Z.length>0;return!0};case"string":return(Z)=>typeof Z==="string";case"boolean":return(Z)=>typeof Z==="boolean";case"number":return(Z)=>X0(Z);case"password":return(Z)=>{return typeof Z==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test(Z)};case"min":{let Z=c(X,$);return(G)=>{let W=C0(G);return W!==void 0&&W>=Z}}case"max":{let Z=c(X,$);return(G)=>{let W=C0(G);return W!==void 0&&W<=Z}}case"gte":{let Z=c(X,$);return(G)=>X0(G)&&G>=Z}case"lte":{let Z=c(X,$);return(G)=>X0(G)&&G<=Z}case"email":return(Z)=>{return typeof Z==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Z)};case"file":return(Z)=>{return Z instanceof Blob};case"fileType":{if(!$)throw new P('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let Z=n0($);return(G)=>G instanceof Blob&&G.type.startsWith(Z)}case"fileSize":{let Z=o0($??"");if(Z===0&&!/^0+(B|KB|MB|GB|TB)$/.test($??""))throw new P(`Validation rule "fileSize:${$??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return(G)=>G instanceof Blob&&G.size<=Z}case"array":return(Z)=>Array.isArray(Z);case"object":return(Z)=>typeof Z==="object"&&Z!==null&&!Array.isArray(Z)&&!(Z instanceof Blob);case"in":{let Z=($??"").split(",").filter((G)=>G!=="");if(Z.length===0)throw new P('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return(G)=>typeof G==="string"&&Z.includes(G)}default:throw new P(`Unknown validation rule "${H}". Known rules: ${i0.join(", ")}`)}}function w(H){if(!H.definition)throw Error(`gemi/ai: the recursive schema "${H.name}" was used before its definition returned; \`self\` can be nested into the schema, but not parsed or emitted inside the callback`);return H.definition}var i=new WeakMap;function j0(H){return typeof H==="object"&&H!==null&&i.has(H)}function d(H){let Q=i.get(H);if(!Q)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return Q}function t0(H){let Q={defs:{},cells:new Map},X=H;if(H.node.kind==="ref"){let Z=w(H.node.cell);X={...Z,...H.description?{description:H.description}:{},optional:H.optional,nullable:H.nullable||Z.nullable}}let $=g(X,Q);return Object.keys(Q.defs).length>0?{...$,$defs:Q.defs}:$}function g(H,Q){let X=(H.optional||H.nullable)&&H.node.kind!=="json",$=r0(s0(H.node,Q),X),Z=[H.description,l0(H.node)].filter(Boolean).join(" ");if(Z&&$.$ref!==void 0)$={anyOf:[$]};return Z?{description:Z,...$}:$}function l0(H){let Q=[];if(H.kind==="string"||H.kind==="enum"){let X=H.checks;if(X?.format)Q.push(`Format: ${X.format.name}.`);if(X?.minLength!==void 0)Q.push(`At least ${X.minLength} characters.`);if(X?.maxLength!==void 0)Q.push(`At most ${X.maxLength} characters.`)}else if(H.kind==="number"){let X=H.checks;if(X?.minimum!==void 0)Q.push(`Minimum ${X.minimum}.`);if(X?.exclusiveMinimum!==void 0)Q.push(`Greater than ${X.exclusiveMinimum}.`);if(X?.maximum!==void 0)Q.push(`Maximum ${X.maximum}.`);if(X?.exclusiveMaximum!==void 0)Q.push(`Less than ${X.exclusiveMaximum}.`)}else if(H.kind==="array"){let X=H.checks;if(X?.minItems!==void 0)Q.push(`At least ${X.minItems} items.`);if(X?.maxItems!==void 0)Q.push(`At most ${X.maxItems} items.`)}return Q.join(" ")}function s0(H,Q){switch(H.kind){case"string":return{type:"string"};case"number":return{type:H.checks?.integer?"integer":"number"};case"boolean":return{type:"boolean"};case"literal":return{type:typeof H.value,const:H.value};case"enum":return{type:"string",enum:H.values};case"array":return{type:"array",items:g(H.item,Q)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(H.shape).map(([X,$])=>[X,g($,Q)])),required:Object.keys(H.shape),additionalProperties:!1};case"union":return{anyOf:H.members.map((X)=>g(X,Q))};case"json":return{};case"ref":{let{cell:X}=H,$=Q.cells.get(X.name);if($&&$!==X)throw Error(`gemi/ai: two different recursive schemas are named "${X.name}" in one schema; give each s.recursive(...) its own name`);if(!$)Q.cells.set(X.name,X),Q.defs[X.name]={},Q.defs[X.name]=g(w(X),Q);return{$ref:`#/$defs/${X.name}`}}}}function r0(H,Q){if(!Q)return H;if(H.anyOf)return{...H,anyOf:[...H.anyOf,{type:"null"}]};if(H.enum||H.const!==void 0)return{anyOf:[H,{type:"null"}]};if(typeof H.type==="string")return{...H,type:[H.type,"null"]};return{anyOf:[H,{type:"null"}]}}function a0(H){if(H===null)return"null";if(Array.isArray(H))return"array";return typeof H}function e0(H,Q){if(typeof Q==="number"&&!Number.isFinite(Q))return String(Q);if(H.kind==="literal"||H.kind==="enum"){if(typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean")return JSON.stringify(Q)}return a0(Q)}function O0(H){let Q=H.node,X=(()=>{switch(Q.kind){case"number":return Q.checks?.integer?"integer":"number";case"string":case"boolean":return Q.kind;case"literal":return JSON.stringify(Q.value);case"enum":return`one of ${Q.values.map(($)=>JSON.stringify($)).join(" | ")}`;case"array":return"array";case"object":return"object";case"union":return"one of the variants";case"json":return"a JSON value";case"ref":return O0({...w(Q.cell),optional:!1,nullable:!1})}})();return H.optional||H.nullable?`${X} or null`:X}function HH(H){let Q="";for(let X of H)Q+=typeof X==="number"?`[${X}]`:Q?`.${X}`:X;return Q}function QH(H){let Q=HH(H);return Q?`${Q}: `:""}function Z0(H){return`${QH(H.path)}${H.message}`}function u(H,Q){if(Q===null||Q===void 0)return H.optional||H.nullable?1:0;let X=H.node;switch(X.kind){case"string":return typeof Q==="string"?1:0;case"number":return typeof Q==="number"?1:0;case"boolean":return typeof Q==="boolean"?1:0;case"literal":return Q===X.value?10:0;case"enum":return typeof Q==="string"&&X.values.includes(Q)?10:0;case"array":return Array.isArray(Q)?1:0;case"object":{if(typeof Q!=="object"||Array.isArray(Q))return 0;let $=Q,Z=1;for(let[G,W]of Object.entries(X.shape))Z+=u(W,$[G]);return Z}case"union":return X.members.reduce(($,Z)=>Math.max($,u(Z,Q)),0);case"json":return 1;case"ref":return I0(X.cell,Q,()=>1,()=>u(w(X.cell),Q))}}function I0(H,Q,X,$){if(typeof Q!=="object"||Q===null)return $();if(H.active.has(Q))return X();H.active.add(Q);try{return $()}finally{H.active.delete(Q)}}function j(H,Q,X,$){if(H.optional&&(Q===null||Q===void 0))return{drop:!0,value:void 0};if(H.nullable&&Q===null)return{drop:!1,value:null};return{drop:!1,value:XH(H,Q,X,$)}}function XH(H,Q,X,$){let Z=H.node,G=()=>{let W=Q===void 0?"required":Z.kind==="literal"?"const":Z.kind==="enum"&&typeof Q==="string"?"enum":"type",Y=W==="const"?{allowedValue:Z.value}:W==="enum"?{allowedValues:Z.values}:{};$.push({path:X,code:W,message:`expected ${O0(H)}, got ${e0(Z,Q)}`,params:Y});return};switch(Z.kind){case"string":if(typeof Q!=="string")return G();return V0(Z.checks,Q,X,$),Q;case"number":if(typeof Q!=="number"||!Number.isFinite(Q))return G();if(Z.checks?.integer&&!Number.isInteger(Q))return G();return $H(Z.checks,Q,X,$),Q;case"boolean":return typeof Q==="boolean"?Q:G();case"literal":return Q===Z.value?Q:G();case"enum":if(typeof Q!=="string"||!Z.values.includes(Q))return G();return V0(Z.checks,Q,X,$),Q;case"array":{if(!Array.isArray(Q))return G();let W=Q.map((M,U)=>{let R=j(Z.item,M,[...X,U],$);return R.drop?void 0:R.value}),{minItems:Y,maxItems:T}=Z.checks??{};if(Y!==void 0&&Q.length<Y)$.push({path:X,code:"minItems",message:`expected at least ${Y} items, got ${Q.length}`,params:{limit:Y}});if(T!==void 0&&Q.length>T)$.push({path:X,code:"maxItems",message:`expected at most ${T} items, got ${Q.length}`,params:{limit:T}});return W}case"object":{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return G();let W=Q,Y={};for(let[T,M]of Object.entries(Z.shape)){let U=j(M,W[T],[...X,T],$);if(!U.drop)Y[T]=U.value}if(Z.unknownKeys)for(let T of Object.keys(W)){if(Object.hasOwn(Z.shape,T)||W[T]===void 0)continue;if(Z.unknownKeys==="error"){$.push({path:[...X,T],code:"additionalProperties",message:"unknown key",params:{additionalProperty:T}});continue}b(W[T],[...X,T],$,new Set),Object.defineProperty(Y,T,{value:W[T],enumerable:!0,writable:!0,configurable:!0})}return Y}case"union":{let W;for(let Y of Z.members){let T=[],M=j(Y,Q,X,T);if(T.length===0)return M.drop?void 0:M.value;let U=u(Y,Q);if(!W||U>W.score)W={issues:T,score:U}}$.push({path:X,code:"anyOf",message:`no matching variant; closest: ${W.issues.map(Z0).join("; ")}`,params:{closest:W.issues}});return}case"json":if(Q===void 0)return G();return b(Q,X,$,new Set),Q;case"ref":return I0(Z.cell,Q,()=>{$.push({path:X,code:"type",message:"expected a finite tree, got a circular reference",params:{}});return},()=>j(w(Z.cell),Q,X,$).value)}}function ZH(H){let Q=0;for(let X of H)Q++;return Q}function V0(H,Q,X,$){if(!H)return;let{minLength:Z,maxLength:G,format:W}=H;if(Z!==void 0||G!==void 0){let Y=ZH(Q);if(Z!==void 0&&Y<Z)$.push({path:X,code:"minLength",message:`expected at least ${Z} characters, got ${Y}`,params:{limit:Z}});if(G!==void 0&&Y>G)$.push({path:X,code:"maxLength",message:`expected at most ${G} characters, got ${Y}`,params:{limit:G}})}if(W){let Y=!1;try{Y=W.test(Q)===!0}catch{}if(!Y)$.push({path:X,code:"format",message:`expected a string in format "${W.name}"`,params:{format:W.name}})}}function $H(H,Q,X,$){if(!H)return;let Z=(G,W,Y,T)=>{if(W===void 0||Y(W))return;$.push({path:X,code:G,message:`expected ${T} ${W}, got ${Q}`,params:{limit:W}})};Z("minimum",H.minimum,(G)=>Q>=G,"at least"),Z("exclusiveMinimum",H.exclusiveMinimum,(G)=>Q>G,"more than"),Z("maximum",H.maximum,(G)=>Q<=G,"at most"),Z("exclusiveMaximum",H.exclusiveMaximum,(G)=>Q<G,"less than")}function b(H,Q,X,$,Z=!0){let G=(Y)=>{X.push({path:Q,code:"type",message:`expected a JSON value, got ${Y}`,params:{}})};switch(typeof H){case"undefined":case"string":case"boolean":return;case"number":if(!Number.isFinite(H))G(String(H));return;case"bigint":return G("a bigint");case"function":return G("a function");case"symbol":return G("a symbol")}if(H===null)return;let W=H;if($.has(W))return G("a circular reference");$.add(W);try{let Y=Z?W.toJSON:void 0;if(typeof Y==="function"){let T;try{T=Y.call(W)}catch{return G("a toJSON that threw")}if(T===void 0)return G("a toJSON that returns undefined");return b(T,Q,X,$,!1)}if(Array.isArray(H))H.forEach((T,M)=>b(T,[...Q,M],X,$));else for(let[T,M]of Object.entries(W))b(M,[...Q,T],X,$)}finally{$.delete(W)}}function A(H){return o(H)}function o(H){let Q={toJSONSchema:()=>t0(H),parse(X){let $=[],Z=j(H,X,[],$);if($.length>0)throw Error($.map(Z0).join("; "));return Z.drop?void 0:Z.value},safeParse(X){let $=[],Z=j(H,X,[],$);if($.length>0)return{ok:!1,errors:$.map(Z0)};return{ok:!0,value:Z.drop?void 0:Z.value}},validate(X){let $=[],Z=j(H,X,[],$);if($.length>0)return{ok:!1,issues:$};return{ok:!0,value:Z.drop?void 0:Z.value}},describe:(X)=>o({...H,description:X}),optional:()=>o({...H,optional:!0}),nullable:()=>o({...H,nullable:!0,optional:!1})};return i.set(Q,H),Q}function L(H){return{node:H,optional:!1,nullable:!1}}var _0=["strip","error","passthrough"];class q0 extends Error{problems;constructor(H){super(`gemi/ai: s.fromJSONSchema cannot model this schema:
3
- ${H.map((Q)=>`- ${Q}`).join(`
4
- `)}`);this.name="JSONSchemaError",this.problems=H}}var GH=new Set(["title","$schema","$id","$comment","examples","default","deprecated","readOnly","writeOnly"]),x={string:["minLength","maxLength","format"],number:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],integer:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],boolean:[],object:["properties","required","additionalProperties"],array:["items","minItems","maxItems"]};function m(H){return typeof H==="object"&&H!==null&&!Array.isArray(H)}function n(H,Q,X,$){let Z=(D,K=X)=>{$.push(K?`${K}: ${D}`:D);return},G=(D)=>X?`${X}.${D}`:D;if(!m(H))return Z("expected a schema object");let W=new Set(Q.ignoreKeywords??[]),Y=(D)=>GH.has(D)||D.startsWith("x-")||W.has(D),T=!1,M=H.type;if(Array.isArray(M)){let D=M.filter((K)=>K!=="null");if(D.length!==1)return Z(`type ${JSON.stringify(M)} is not supported; only one type, optionally with "null". Use anyOf for alternatives`,G("type"));T=D.length<M.length,M=D[0]}if(M!==void 0&&(typeof M!=="string"||!(M in x)))return Z(`type ${JSON.stringify(M)} is not supported; expected one of ${Object.keys(x).join(", ")}`,G("type"));let U=new Set(["type","description","enum","const","anyOf",...M?x[M]:[]]),R=!1;for(let D of Object.keys(H)){if(U.has(D)||Y(D))continue;R=!0;let K=Object.entries(x).find(([,z])=>z.includes(D));Z(K&&K[0]!==M?`"${D}" applies to type ${K[0]}, and this schema is ${M?`type ${M}`:"untyped"}`:`"${D}" is not supported by s.fromJSONSchema`,G(D))}if(R)return;if(H.description!==void 0&&typeof H.description!=="string")return Z("expected a string",G("description"));let p=H.description,C=(D)=>({node:D,optional:!1,nullable:T,...p?{description:p}:{}});if(H.anyOf!==void 0){if(M!==void 0||H.enum!==void 0||H.const!==void 0)return Z("anyOf cannot be combined with type, enum or const here",G("anyOf"));if(!Array.isArray(H.anyOf)||H.anyOf.length===0)return Z("expected a non-empty array",G("anyOf"));let D=[],K=!1;if(H.anyOf.forEach((z,B)=>{if(m(z)&&z.type==="null"&&Object.keys(z).length===1){T=!0;return}let J=n(z,Q,G(`anyOf[${B}]`),$);if(J)D.push(J);else K=!0}),K)return;if(D.length===0)return Z("anyOf has only null in it",G("anyOf"));if(D.length===1){let z=D[0];return{...z,nullable:z.nullable||T,...p?{description:p}:{}}}return C({kind:"union",members:D})}if(H.const!==void 0){let D=H.const;if(typeof D!=="string"&&typeof D!=="number"&&typeof D!=="boolean")return Z("only a string, number or boolean const is supported",G("const"));if(M!==void 0&&typeof D!==(M==="integer"?"number":M))return Z(`const ${JSON.stringify(D)} is not of type ${M}`,G("const"));return C({kind:"literal",value:D})}let q;if(M==="string"){if(q=WH(H,Q,G,$),q===null)return}if(H.enum!==void 0){if(!Array.isArray(H.enum)||H.enum.length===0)return Z("expected a non-empty array",G("enum"));let D=H.enum.filter((B)=>B!==null);if(D.length<H.enum.length)T=!0;let K=D.find((B)=>!(typeof B==="string"||typeof B==="number"||typeof B==="boolean")||M!==void 0&&typeof B!==(M==="integer"?"number":M));if(K!==void 0||D.length===0)return Z(M?`every value must be of type ${M}${D.length===0?", and there must be one":`; ${JSON.stringify(K)} is not`}`:"only strings, numbers and booleans are supported",G("enum"));if(D.every((B)=>typeof B==="string"))return C({kind:"enum",values:[...new Set(D)],...q?{checks:q}:{}});let z=[...new Set(D)];if(z.length===1)return C({kind:"literal",value:z[0]});return C({kind:"union",members:z.map((B)=>L({kind:"literal",value:B}))})}switch(M){case void 0:return Z("a schema needs a type, an enum, a const or an anyOf");case"string":return C({kind:"string",...q?{checks:q}:{}});case"number":case"integer":{let D=M==="integer"?{integer:!0}:{},K=!1;for(let z of x.number){let B=H[z];if(B===void 0)continue;if(typeof B!=="number"||!Number.isFinite(B)){Z("expected a number",G(z)),K=!0;continue}D[z]=B}if(K)return;return C({kind:"number",...Object.keys(D).length>0?{checks:D}:{}})}case"boolean":return C({kind:"boolean"});case"array":{if(!m(H.items))return Z('an array needs "items" to be one schema (tuples are not supported)',G("items"));let D={},K=!1;for(let B of["minItems","maxItems"]){let J=H[B];if(J===void 0)continue;if(typeof J!=="number"||!Number.isInteger(J)||J<0){Z("expected a non-negative integer",G(B)),K=!0;continue}D[B]=J}let z=n(H.items,Q,G("items"),$);if(!z||K)return;return C({kind:"array",item:z,...Object.keys(D).length>0?{checks:D}:{}})}case"object":{let D=H.properties??{};if(!m(D))return Z("expected an object",G("properties"));if(H.additionalProperties!==void 0&&H.additionalProperties!==!1)return Z("only false is supported; a record with arbitrary keys has no strict-mode form (use s.json())",G("additionalProperties"));let K=H.required??[];if(!Array.isArray(K)||!K.every((_)=>typeof _==="string"))return Z("expected an array of property names",G("required"));let z=K.filter((_)=>!Object.hasOwn(D,_));if(z.length>0)return Z(`lists properties the schema doesn't have: ${z.join(", ")}`,G("required"));let B={},J=!1;for(let[_,d0]of Object.entries(D)){let H0=n(d0,Q,G(`properties.${_}`),$);if(!H0){J=!0;continue}B[_]=K.includes(_)?H0:{...H0,optional:!0}}if(J)return;let e=Q.unknownKeys;return C({kind:"object",shape:B,...e==="error"||e==="passthrough"?{unknownKeys:e}:{}})}}return}function WH(H,Q,X,$){let Z={},G=!1;for(let W of["minLength","maxLength"]){let Y=H[W];if(Y===void 0)continue;if(typeof Y!=="number"||!Number.isInteger(Y)||Y<0){$.push(`${X(W)}: expected a non-negative integer`),G=!0;continue}Z[W]=Y}if(H.format!==void 0){let W=H.format,Y=typeof W==="string"?Q.formats?.[W]:void 0;if(typeof W!=="string")$.push(`${X("format")}: expected a string`),G=!0;else if(!Y||!Object.hasOwn(Q.formats,W))$.push(`${X("format")}: unknown format ${JSON.stringify(W)}; pass a check for it in the formats option`),G=!0;else Z.format={name:W,test:YH(Y)}}if(G)return null;return Object.keys(Z).length>0?Z:void 0}function YH(H){if(H===!0)return()=>!0;if(H instanceof RegExp)return(Q)=>{return H.lastIndex=0,H.test(Q)};return H}var mH={string:()=>A(L({kind:"string"})),number:()=>A(L({kind:"number"})),boolean:()=>A(L({kind:"boolean"})),literal:(H)=>A(L({kind:"literal",value:H})),enum:(H)=>A(L({kind:"enum",values:H})),object:(H)=>A(L({kind:"object",shape:Object.fromEntries(Object.entries(H).map(([Q,X])=>[Q,d(X)]))})),array:(H)=>A(L({kind:"array",item:d(H)})),union:(H)=>A(L({kind:"union",members:H.map(d)})),json:()=>A(L({kind:"json"})),recursive:MH,fromJSONSchema:(H,Q={})=>{let X=[];if(Q.unknownKeys!==void 0&&!_0.includes(Q.unknownKeys))throw Error(`gemi/ai: s.fromJSONSchema's unknownKeys option must be one of ${_0.map((Z)=>JSON.stringify(Z)).join(", ")}, got ${JSON.stringify(Q.unknownKeys)}`);let $=n(H,Q,"",X);if(!$||X.length>0)throw new q0(X.length>0?X:["unreadable schema"]);return A($)}};function dH(H){let Q=i.get(H);if(Q)return k(Q.node);return y(H.toJSONSchema())}function y(H){if(!(H.$ref!==void 0||H.type!==void 0||H.enum!==void 0||H.const!==void 0||H.anyOf!==void 0||H.properties!==void 0||H.items!==void 0))return!1;for(let X of Object.values(H.properties??{}))if(!y(X))return!1;if(H.items&&!y(H.items))return!1;for(let X of H.anyOf??[])if(!y(X))return!1;for(let X of Object.values(H.$defs??{}))if(!y(X))return!1;return!0}function k(H,Q=new Set){switch(H.kind){case"string":case"number":case"boolean":case"literal":case"enum":return!0;case"object":return Object.values(H.shape).every((X)=>k(X.node,Q));case"array":return k(H.item.node,Q);case"union":return H.members.every((X)=>k(X.node,Q));case"json":return!1;case"ref":if(Q.has(H.cell))return!0;return Q.add(H.cell),k(w(H.cell).node,Q)}}function $0(H,Q,X=new Set){let $=H.node;if($.kind==="union")return $.members.some((Z)=>$0(Z,Q,X));if($.kind!=="ref")return!1;if($.cell===Q)return!0;if(X.has($.cell)||!$.cell.definition)return!1;return X.add($.cell),$0($.cell.definition,Q,X)}var TH=/^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;function MH(H,Q){if(typeof H!=="string"||!TH.test(H))throw Error(`gemi/ai: s.recursive needs a name of letters, digits, "_" and "-" (starting with a letter or "_", at most 64), got ${JSON.stringify(H)}`);let X={name:H,active:new Set},$=()=>L({kind:"ref",cell:X}),Z=d(Q(A($())));if(Z.optional)throw Error(`gemi/ai: the recursive schema "${H}" is optional() as a whole; mark the places that use it optional instead`);if($0(Z,X))throw Error(`gemi/ai: the recursive schema "${H}" refers to itself outside any object or array, so it describes no finite value; nest \`self\` in an s.object(...) field or an s.array(...)`);return X.definition=Z,A($())}function N0(H){if(typeof H!=="string")return null;let[Q]=H.split(";",1),X=Q.trim().toLowerCase();return X===""?null:X}function w0(H){if(H===null)return!1;if(H==="application/json")return!0;let Q=H.indexOf("/");return Q>0&&H.endsWith("+json")&&H.length>Q+1+5}var f=new WeakMap;function nH(H,Q,X,$){f.set(H,{clientAddress:Q,...X?{grant:Object.freeze({...X,scopes:Object.freeze([...X.scopes])})}:{},...$?{progress:$}:{}})}function E0(H){return f.get(H)?.progress}function S0(H){return f.get(H)?.grant}function x0(H){return f.has(H)}function iH(H){return f.get(H)?.clientAddress}var g0=new WeakMap;function lH(H,Q){g0.set(H,Q)}function y0(H){return g0.get(H)??null}var G0=new WeakMap;function sH(H,Q){let X=G0.get(H)??[];if(!X.includes(Q))G0.set(H,[...X,Q])}function rH(H){return G0.get(H)??[]}class E{data;constructor(H){this.data=H}get(H){return this.data[H]}has(H){return this.data[H]!==void 0}toJSON(){return this.data}}function k0(H){return typeof H==="object"&&H!==null&&!(H instanceof Blob)}function DH(H,Q){if(!Q.includes(".")||Object.hasOwn(H,Q))return[{path:[Q],value:H[Q]}];let X=[{path:[],value:H}];for(let $ of Q.split(".")){let Z=[];for(let{path:G,value:W}of X){if($==="*"){if(Array.isArray(W))W.forEach((Y,T)=>Z.push({path:[...G,T],value:Y}));else if(k0(W))for(let[Y,T]of Object.entries(W))Z.push({path:[...G,Y],value:T});continue}if(Array.isArray(W)&&/^\d+$/.test($)){Z.push({path:[...G,Number($)],value:W[Number($)]});continue}Z.push({path:[...G,$],value:k0(W)&&Object.hasOwn(W,$)?W[$]:void 0})}X=Z}return X}function b0(H){return H.join(".")}class UH{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;constructor(H,Q,X,$){if(!H){let T=V.getStore().req;this.params=T.params,this.rawRequest=T.rawRequest,this.kind=T.kind,this.routePath=T.routePath,this.domain=T.domain??null}else this.params=Q,this.rawRequest=H,this.routePath=$,this.kind=X??"api",this.domain=y0(H);this.headers=this.rawRequest.headers;let Z=Q0(this.rawRequest.headers.get("Cookie")),G=new URL(this.rawRequest.url),W=new Map;for(let[T,M]of G.searchParams)if(W.has(T)){let U=W.get(T);if(Array.isArray(U))U.push(M),W.set(T,U);else W.set(T,[U,M])}else W.set(T,M);let Y=Object.fromEntries(W.entries());this.search=new E(Y),this.cookies=Z}locale(){return V.getStore().locale}ctx(){return V.getStore()}isModelOriginated(){return x0(this.rawRequest)}mcpGrant(){return S0(this.rawRequest)??null}reportProgress(H){let Q=E0(this.rawRequest);if(!Q)return!1;return Q(H),!0}get signal(){return this.rawRequest.signal}range(){return J0(this.rawRequest.headers.get("Range"))}refine(H){return{}}async parseBody(){let H=N0(this.rawRequest.headers.get("Content-Type"));if(w0(H))return new E(await this.parseJsonBody());if(H==="application/x-www-form-urlencoded"||H==="multipart/form-data"){let Q;try{Q=await this.rawRequest.formData()}catch($){if($ instanceof F)throw $;throw new F("The request body could not be read as a form.")}let X=new Map;for(let[$,Z]of Q.entries())if(X.has($)){let G=X.get($);if(Array.isArray(G))G.push(Z);else X.set($,[G,Z])}else X.set($,Z);return new E(Object.fromEntries(X.entries()))}return new E({})}async parseJsonBody(){if(!this.rawRequest.body)return{};let H;try{H=await this.rawRequest.text()}catch(X){if(X instanceof F)throw X;throw new F("The request body could not be read.")}if(H.trim()==="")return{};let Q;try{Q=JSON.parse(H)}catch{throw new F("The request body is not valid JSON.")}if(Q===null||typeof Q!=="object")throw new F("The request body must be a JSON object.");return Q}validateInput(H){if(j0(this.schema))return this.validateWithSchema(H);let Q=H.toJSON()??{},X={},$=Object.entries(this.schema).map(([Z,G])=>({key:Z,rules:Object.entries(G).map(([W,Y])=>({rule:W,message:Y,check:typeof Y==="function"?null:this.ruleFor(Z,W)}))}));for(let{key:Z,rules:G}of $)for(let{path:W,value:Y}of DH(Q,Z)){let T=this.checkField(Y,G);if(T.length>0){let M=X[b0(W)]??=[];for(let U of T)if(!M.includes(U))M.push(U)}}if(this.addRefinements(X,Q),Object.keys(X).length>0)throw new S(X);return H}checkField(H,Q){let X=Q.some(({rule:G})=>G==="required"),$=H===void 0||H===null||H==="",Z=[];for(let{rule:G,message:W,check:Y}of Q){let T=W,M=!1;if(typeof W==="function")T=W(H),M=typeof T>"u";else M=Y(H);if(M)continue;if($&&!X)continue;if(G==="required")return[String(T)];if(!Z.includes(String(T)))Z.push(String(T))}return Z}validateWithSchema(H){let Q=this.schema.validate(H.toJSON()),X={};if("issues"in Q)for(let Z of Q.issues){let G=b0(Z.path),W=X[G]??=[];if(!W.includes(Z.message))W.push(Z.message)}let $="value"in Q?new E(Q.value):H;if(this.addRefinements(X,$.toJSON()),Object.keys(X).length>0)throw new S(X);return $}addRefinements(H,Q){for(let[X,$]of Object.entries(this.refine(Q)??{})){let Z=H[X]??[];H[X]=Z.includes($)?Z:[...Z,$]}}ruleFor(H,Q){try{return P0(Q)}catch(X){if(X instanceof P)throw new P(`${this.constructor.name}.schema.${H}: ${X.message}`);throw X}}async input(){return this.validateInput(await this.parseBody())}async safeInput(){let H=await this.parseBody();try{return{isValid:!0,errors:{},input:this.validateInput(H)}}catch(Q){if(!(Q instanceof S))throw Q;return{isValid:!1,errors:Q.errors,input:H}}}}class KH extends F{error;constructor(H="Not authorized"){super(H);this.name="AuthorizationError",this.error=H,this.payload={api:{status:401,data:{error:l("authorization",this.error,401)}},view:{}}}}class W0 extends F{static apiStatus=403;error;constructor(H="Insufficient permissions"){super(H);this.name="InsufficientPermissionsError",this.error=H,this.payload={api:{status:W0.apiStatus,data:{error:l("permission",this.error,W0.apiStatus)}},view:{status:403}}}}class Y0 extends F{total;constructor(H){super("Range not satisfiable");this.total=H;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:t("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":R0(H),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class BH extends F{constructor(H="Not found"){super(H);this.name="NotFoundError",this.payload={api:{status:404,data:{error:t("not_found",H,404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class O extends F{fileName;constructor(H){super("File not found");this.fileName=H;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:t("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class zH extends F{constructor(H={}){super("Authentication error");this.name="AuthenticationError";let Q=H.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:l("authentication","Authentication error",401)}},viewData:{status:200,data:{},headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate"},directive:{kind:"Redirect",path:Q}},view:{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:Q}}}}}class v{static getFacadeAccessor(){throw Error(`Facade [${this.name}] does not implement getFacadeAccessor().`)}static getFacadeRoot(){return f0(this.getFacadeAccessor())}}function s(H){if(typeof H!=="string"||/^[\s/.]*$/.test(H))throw Error(`Refusing to delete by prefix ${JSON.stringify(H)}: it would match the whole store`)}class T0{async*objects(H,Q={}){throw Error(`${this.constructor.name} does not implement objects(). Override it to list objects in this backend.`)}async deletePrefix(H,Q={}){s(H);let X=[];for await(let $ of this.objects(H,Q))X.push($.name);for(let $ of X)Q.signal?.throwIfAborted(),await this.delete({name:$,bucket:Q.bucket});return X.length}async delete(H){throw Error(`${this.constructor.name} does not implement delete(). Override it to remove objects from this backend.`)}async read(H){let Q=typeof H==="string"?{name:H}:H,X=await this.fetch({name:Q.name,bucket:Q.bucket});if(!X.ok)throw new O(Q.name);let $=X.headers.get("Content-Type")??"application/octet-stream",Z=X.headers.get("ETag")??void 0,G=X.headers.get("Last-Modified"),W=G?new Date(G):void 0;if(Q.range){let M=await X.blob();return{body:M,start:0,end:M.size-1,total:M.size,partial:!1,type:$,etag:Z,lastModified:W,name:Q.name}}let Y=Number(X.headers.get("Content-Length")),T=Number.isFinite(Y)?Y:0;return{body:X.body,start:0,end:T-1,total:T,partial:!1,type:$,etag:Z,lastModified:W,name:Q.name}}async size(H){let Q=typeof H==="string"?H:H.name,X=typeof H==="string"?void 0:H.bucket,$=await this.fetch({name:Q,bucket:X});if(!$.ok)throw new O(Q);let Z=Number($.headers.get("Content-Length"));if(Number.isFinite(Z))return await $.body?.cancel(),Z;return(await $.blob()).size}}function v0(H,Q){if(!Q)return H;let X=H.getReader(),$=!1,Z,G=()=>{if($=!0,Z)Q.removeEventListener("abort",Z)};return new ReadableStream({start(W){if(Z=()=>{if($)return;G(),W.error(Q.reason),X.cancel(Q.reason).catch(()=>{})},Q.aborted)Z();else Q.addEventListener("abort",Z,{once:!0})},async pull(W){let Y;try{Y=await X.read()}catch(T){if($)return;G(),W.error(T);return}if($)return;if(Y.done){G(),W.close();return}W.enqueue(Y.value)},cancel(W){return G(),X.cancel(W)}},{highWaterMark:0})}import{readdir as M0,rmdir as FH,stat as AH,unlink as JH}from"fs/promises";import{isAbsolute as h0,relative as r,resolve as a,sep as I}from"path";class D0 extends T0{configured;constructor(H){super();this.configured=H}get folderPath(){return this.configured??`${h()}/storage`}async put(H,{signal:Q}={}){Q?.throwIfAborted();let X,$;if(H instanceof Blob)X=H,$=`${Bun.randomUUIDv7()}.${H.type.split("/")[1].split(";")[0]}`;else X=H.body,$=H.name;let Z=X instanceof Buffer?X:X instanceof Blob||X instanceof File?Buffer.from(await X.arrayBuffer()):"",G=`${this.folderPath}/${$}`;return Q?.throwIfAborted(),await Bun.write(G,Z),$}async fetch(H,{signal:Q}={}){Q?.throwIfAborted();let X=process.env.BUCKET_NAME,$;if(typeof H==="string")$=H;else X=H.bucket??X,$=H.name;if(!$)throw Error("Object name has to be specified");let Z=`${this.folderPath}/${$}`,G=Bun.file(Z),W=v0(Bun.file(Z).stream(),Q),Y=new Date(G.lastModified).toUTCString();return new Response(W,{headers:{"Content-Type":G.type,"Content-Length":String(G.size),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":Y}})}async read(H){let Q=typeof H==="string"?{name:H}:H,{name:X,range:$=null}=Q;if(!X)throw Error("Object name has to be specified");let Z=Bun.file(`${this.folderPath}/${X}`);if(!await Z.exists())throw new O(X);let G=Z.size,W=$?L0($,G):null;if($&&!W)throw new Y0(G);let Y=W?.start??0,T=W?W.end:G-1;return{body:W?Z.slice(Y,T+1):Z,start:Y,end:T,total:G,partial:Boolean(W),type:Z.type||"application/octet-stream",lastModified:new Date(Z.lastModified),name:X}}async size(H){let Q=typeof H==="string"?H:H.name,X=Bun.file(`${this.folderPath}/${Q}`);if(!await X.exists())throw new O(Q);return X.size}async delete(H){let Q=typeof H==="string"?H:H.name;if(!Q)throw Error("Object name has to be specified");let X=a(this.folderPath),$=a(X,Q),Z=r(X,$);if(!Z||Z===".."||Z.startsWith(`..${I}`)||h0(Z))throw Error(`Refusing to delete "${Q}": it is outside the storage folder`);try{await JH($)}catch(G){if(G?.code==="ENOENT")return;throw G}}resolvePrefix(H){let Q=a(this.folderPath),X=H.lastIndexOf("/"),$=X===-1?"":H.slice(0,X),Z=X===-1?H:H.slice(X+1),G=a(Q,$),W=r(Q,G);if(W===".."||W.startsWith(`..${I}`)||h0(W))throw Error(`Refusing to list "${H}": it is outside the storage folder`);let Y=W.split(I).join("/");return{root:Q,dir:G,match:Y?`${Y}/${Z}`:Z}}async*objects(H,{signal:Q}={}){Q?.throwIfAborted();let{root:X,dir:$,match:Z}=this.resolvePrefix(H),G=[],W=async(Y)=>{let T;try{T=await M0(Y,{withFileTypes:!0})}catch(M){if(M?.code==="ENOENT"||M?.code==="ENOTDIR")return;throw M}for(let M of T){let U=`${Y}${I}${M.name}`,R=r(X,U).split(I).join("/");if(M.isDirectory()){if(`${R}/`.startsWith(Z)||Z.startsWith(`${R}/`))await W(U)}else if(M.isFile()&&R.startsWith(Z))G.push(R)}};await W($),G.sort();for(let Y of G){Q?.throwIfAborted();let T;try{T=await AH(`${X}/${Y}`)}catch(M){if(M?.code==="ENOENT")continue;throw M}yield{name:Y,size:T.size,lastModified:T.mtime}}}async deletePrefix(H,Q={}){s(H);let{root:X,match:$}=this.resolvePrefix(H);s($);let Z=await super.deletePrefix(H,Q);if(Z>0)await this.pruneEmptyDirs(X,$);return Z}async pruneEmptyDirs(H,Q){let X=[],$=async(Z)=>{let G;try{G=await M0(Z,{withFileTypes:!0})}catch{return}for(let W of G){if(!W.isDirectory())continue;let Y=`${Z}${I}${W.name}`,T=r(H,Y).split(I).join("/");if(`${T}/`.startsWith(Q)||Q.startsWith(`${T}/`)){if(await $(Y),`${T}/`.startsWith(Q))X.push(Y)}}};await $(H);for(let Z of X)try{await FH(Z)}catch{}}async list(){return await M0(this.folderPath)}}function qQ(H){return H}function p0(){return{driver:new D0}}class U0{static token="filesystem";driver;constructor(H={}){this.driver=H.driver??p0().driver}}import{Buffer as RH}from"buffer";async function c0(H){try{return(await import("sharp")).default}catch(Q){throw Error(`${H} requires the 'sharp' package. Install it with \`bun add sharp\`.`,{cause:Q})}}class CH extends v{static getFacadeAccessor(){return U0}static async put(H,Q={}){return this.getFacadeRoot().driver.put(H,Q)}static async metadata(H){let Q=RH.from(await H.arrayBuffer()),X=await c0("Storage.metadata()");try{return await X(Q).metadata()}catch{return{}}}static async fetch(H,Q={}){return Q.signal?.throwIfAborted(),this.getFacadeRoot().driver.fetch(H,Q)}static async read(H,Q={}){let X=typeof H==="string"?{name:H}:{...H},$="range"in Q?Q.range??null:X.range!==void 0?X.range:V.getStore()?.rangeRequest??null;return this.getFacadeRoot().driver.read({...X,range:$})}static list(H){return this.getFacadeRoot().driver.list(H)}static objects(H,Q={}){return this.getFacadeRoot().driver.objects(H,Q)}static async deletePrefix(H,Q={}){return this.getFacadeRoot().driver.deletePrefix(H,Q)}static async delete(H){return this.getFacadeRoot().driver.delete(H)}}import{mkdir as K0,readdir as PH,access as VH}from"fs/promises";async function B0(H){try{return await VH(H),!0}catch{return!1}}class z0{config;static token="log";writer;isReady=!1;flushTimeout;fileSize=0;writerSize=0;isCreatingFile=!1;bootPromise=null;currentLogFilePath;get logsDirPath(){return`${h()}/storage/logs`}constructor(H){this.config=H}boot(){if(!this.bootPromise)this.bootPromise=this.createStorage().catch((H)=>{console.error("Log storage unavailable, file logging disabled",H)}).then(()=>{this.isReady=!0});return this.bootPromise}async createStorage(){let H=`${h()}/storage`;if(!await B0(H))await K0(H);if(!await B0(this.logsDirPath))await K0(this.logsDirPath);await this.newLogFile()}async newLogFile(){if(!await B0(this.logsDirPath))await K0(this.logsDirPath);if(this.isCreatingFile=!0,this.currentLogFilePath){this.writer.flush(),this.writer.end(),this.writer=null;let X=new File([await Bun.file(this.currentLogFilePath).arrayBuffer()],this.currentLogFilePath.split("/").pop(),{type:"text/plain"});this.config.onLogFileClosed(X),this.fileSize=0,this.writerSize=0}let Q=(await PH(this.logsDirPath)).sort().reverse()[0];if(Q){let X=Bun.file(`${this.logsDirPath}/${Q}`);if(X.size<this.config.maxFileSize)this.currentLogFilePath=`${this.logsDirPath}/${Q}`,this.writer=X.writer(),this.writer.write(await X.text()),this.writer.write(`
5
- `),this.writer.flush(),this.fileSize=X.size}if(!this.writer){let X=`${new Date(Date.now()).toISOString()}.log`.replaceAll(":","-");this.currentLogFilePath=`${this.logsDirPath}/${X}`;let $=Bun.file(`${this.logsDirPath}/${X}`);this.writer=$.writer(),this.fileSize=0,this.writerSize=0}this.isCreatingFile=!1}async log(H,Q,X={}){if(!this.isReady)await this.boot();let $=V.getStore(),Z={};if($)Z={url:$.req.rawRequest.url,method:$.req.rawRequest.method,headers:$.req.rawRequest.headers,body:$.req.rawRequest.body};let G={timestamp:new Date(Date.now()).toISOString(),env:Bun.env.NODE_ENV,level:H,message:Q,metadata:{...Z,...X}},W="";try{W=JSON.stringify(G)}catch(Y){console.log("Error parsing log object",Y)}try{let Y=this.config.onLogCreated(G);if(Y instanceof Promise)Y.catch((T)=>console.error("Error in onLogCreated",T))}catch(Y){console.error("Error in onLogCreated",Y)}if(!this.writer)return;this.writerSize+=W.length,this.fileSize+=W.length;try{this.writer.write(W),this.writer.write(`
6
- `),this.tryFlush()}catch(Y){console.error("Error writing log",Y)}}async tryFlush(){if(this.fileSize>this.config.maxFileSize){if(!this.isCreatingFile)await this.newLogFile()}if(this.writerSize>this.config.maxFileSize/2)await this.writer.flush(),this.writerSize=0,await this.newLogFile();else clearTimeout(this.flushTimeout),this.flushTimeout=setTimeout(async()=>{await this.writer.flush(),this.writerSize=0},100)}}class _H extends v{static getFacadeAccessor(){return z0}static debug(H,Q){this.getFacadeRoot().log("debug",H,Q)}static info(H,Q){this.getFacadeRoot().log("info",H,Q)}static notice(H,Q){this.getFacadeRoot().log("notice",H,Q)}static warning(H,Q){this.getFacadeRoot().log("warning",H,Q)}static error(H,Q){this.getFacadeRoot().log("error",H,Q)}static critical(H,Q){this.getFacadeRoot().log("critical",H,Q)}static alert(H,Q){this.getFacadeRoot().log("alert",H,Q)}static emergency(H,Q){this.getFacadeRoot().log("emergency",H,Q)}}class jH{config;static token="redis";instance=null;constructor(H={}){this.config=H}get client(){return this.instance??=new(OH())(this.config.url,this.config.options)}set client(H){this.instance=H}close(){let H=this.instance;this.instance=null,H?.close()}}function OH(){let H=globalThis.Bun?.RedisClient;if(typeof H!=="function")throw Error("Redis requires Bun's built-in Redis client, which this runtime does not provide. Run the app under Bun, or bind your own client for the 'redis' token.");return H}var F0=new TextEncoder;function m0(H){return`id: ${H.seq}
7
- data: ${JSON.stringify(H.event)}
8
-
9
- `}var IH=5000,qH=`: keepalive
10
-
11
- `;function NH(H,Q=IH){let X=null,$=!1,Z=()=>{if($)return;if(X!==null)clearTimeout(X);X=setTimeout(()=>{if(X=null,$)return;try{H.enqueue(F0.encode(qH))}catch{G();return}Z()},Q)},G=()=>{if($=!0,X!==null)clearTimeout(X);X=null};return Z(),{touch:Z,stop:G}}function wH(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function nQ(H,Q=200){let X=H[Symbol.asyncIterator](),$=-1,Z,G=new ReadableStream({start(W){Z=NH(W)},async pull(W){try{let Y=await X.next();if(Y.done){Z.stop(),W.close();return}$=Y.value.seq,W.enqueue(F0.encode(m0(Y.value))),Z.touch()}catch(Y){let T={type:"error",error:SH(Y)};Z.stop(),W.enqueue(F0.encode(m0({seq:$+1,event:T}))),W.close()}},cancel(W){Z.stop(),X.return?.(W)}});return new Response(G,{status:Q,headers:wH()})}var EH=new Set(["frame_cursor_evicted","live_run_not_found"]);function SH(H){let Q=H&&typeof H==="object"?H.code:void 0;if(H instanceof Error&&typeof Q==="string"&&EH.has(Q))return{code:"unknown",message:H.message,retryable:!1};return console.error("[gemi/ai] agent stream failed",H),{code:"unknown",message:"The run's stream failed.",retryable:!1}}
12
- export{A0 as Xf,u0 as Yf,gH as Zf,N0 as _f,nH as $f,S0 as ag,iH as bg,J0 as cg,L0 as dg,kH as eg,bH as fg,fH as gg,R0 as hg,lH as ig,y0 as jg,sH as kg,rH as lg,S as mg,P as ng,q0 as og,mH as pg,dH as qg,UH as rg,KH as sg,W0 as tg,Y0 as ug,BH as vg,O as wg,zH as xg,v as yg,c0 as zg,s as Ag,T0 as Bg,v0 as Cg,D0 as Dg,qQ as Eg,p0 as Fg,U0 as Gg,CH as Hg,z0 as Ig,_H as Jg,jH as Kg,qH as Lg,NH as Mg,wH as Ng,nQ as Og};
13
-
14
- //# debugId=A82A79578A9AE18164756E2164756E21
@@ -1,54 +0,0 @@
1
- // @bun
2
- class U extends Error{argument;model;operation;constructor(z,G,H,V){super(`gemi ORM does not support '${z}' yet (${G}.${H}). `+V);this.argument=z;this.model=G;this.operation=H;this.name="UnsupportedQueryError"}}class k extends U{constructor(z,G,H,V){super(z,G,H,V);this.name="InvalidArgumentError",this.message=`Invalid '${z}' (${G}.${H}). ${V}`}}class q extends U{constructor(z,G,H,V){super(z,G,H,V);this.name="UnsupportedByDesignError",this.message=`gemi ORM does not implement '${z}' (${G}.${H}), and this is a decision rather than a gap. ${V}`}}class h extends Error{field;model;constructor(z,G,H){super(`'${z}' is not a field on model ${G}. Known fields: ${H.join(", ")}.`);this.field=z;this.model=G;this.name="UnknownFieldError"}}class F extends Error{field;value;constructor(z,G){super(`Could not decode the value ${JSON.stringify(String(G))} from column '${z.column}' as ${z.type}. The column's contents do not match `+"the Prisma schema \u2014 was it written by something other than Prisma or "+"the gemi ORM?");this.field=z;this.value=G;this.name="DecodeError"}}class R extends Error{model;operation;constructor(z,G){super(`No ${z} found (${z}.${G}).`);this.model=z;this.operation=G;this.name="RecordNotFoundError"}}function Hz(z){if(z instanceof R)return!0;return typeof z==="object"&&z!==null&&z.name==="RecordNotFoundError"}class b extends Error{model;operation;fields;constraint;constructor(z,G,H,V,Z){super(`Unique constraint violated on ${z}.${G}`+(H.length>0?` for ${H.join(", ")}`:"")+(V?` (constraint '${V}')`:"")+`. A ${z} with those values already exists.`,Z);this.model=z;this.operation=G;this.fields=H;this.constraint=V;this.name="UniqueConstraintError"}}function Vz(z){if(z instanceof b)return!0;return typeof z==="object"&&z!==null&&z.name==="UniqueConstraintError"}class x extends Error{model;operation;dialect;constructor(z,G,H){super(`${z}.${G} needs RETURNING to report its result, and the '${H}' dialect does not support it. The fallback \u2014 `+"lastInsertRowid plus a re-select \u2014 is not implemented.");this.model=z;this.operation=G;this.dialect=H;this.name="ReturningUnsupportedError"}}class D extends Error{model;operation;reason;constructor(z,G,H="denied"){super(H==="no-user"?`${z}.${G} is governed by a policy and there is no user in scope. If this is a cron tick, a queue worker or a script, say so at the call site: Model.asSystem(() => ...). Policies are never skipped just because a user failed to turn up.`:`${z}.${G} was denied by ${z}'s policy.`);this.model=z;this.operation=G;this.reason=H;this.name="PolicyDeniedError"}}function Wz(z){if(z instanceof D)return!0;return typeof z==="object"&&z!==null&&z.name==="PolicyDeniedError"}class g extends Error{model;operation;fields;constructor(z,G,H){let V=H.map((Z)=>`'${Z}'`).join(", ");super(`${z}.${G} writes ${V}, which ${z}'s policy also `+"scopes on \u2014 so this update can move a row outside the scope that "+`selected it, where the caller can no longer read or repair it.
3
-
4
- Add an onUpdate to that policy. It may reassert the column (data => ({ ...data, ${H[0]}: ctx.user.${H[0]} })), reject `+"the write, or allow it explicitly with (_ctx, data) => data \u2014 all "+"three are fine, and the point is that the policy says which.");this.model=z;this.operation=G;this.fields=H;this.name="ScopeEscapeError"}}class f extends Error{model;registered;queried;carries;constructor(z,G,H,V="queried"){super(V==="narrowing"?`${H} extends ${G}, which owns the model '${z}', and carries policies of its own on top of it. A class that narrows an existing model is a view, and the registry holds one `+`class per name \u2014 so registering ${H} would apply its narrowing to every nested read of ${z}, and leaving ${G} registered would skip ${H}'s policies entirely. Neither is a thing to choose for you.
5
-
6
- Keep the view out of the modules you hand to Kernel.models, and query it directly where you want it:
7
-
8
- ${H}.findMany(\u2026) // narrowed, at the call site
9
-
10
- `+`If it is not a view but the model itself, move the policies onto ${G} \u2014 the class the model's name resolves to \u2014 and `+`${H} inherits them everywhere.
11
- `:V==="queried"?`${H} carries policies but the registry resolves '${z}' to ${G}. Nested relation reads go through the registry, so they would run on ${G} and skip every policy on ${H} \u2014 scoped at the root, unscoped inside an include. `+`Register the class that carries the policy:
12
-
13
- import { register } from "gemi/orm"
14
- export class ${H} extends ${G} { \u2026 }
15
- `+` register("${z}", ${H})
16
- `:`This query goes through ${H}, but the registry resolves '${z}' to ${G}, which carries policies ${H} does not. Nested relation reads would be scoped and this query is `+"not \u2014 the same policy applying to some queries and not others. "+`Query ${G} instead:
17
-
18
- ${G}.findMany(\u2026)
19
-
20
- `+"If skipping policies is intended, say so at the call site \u2014 that "+`is what Model.asSystem() is for, and it is the only way to do it that a reader can see.
21
- `);this.model=z;this.registered=G;this.queried=H;this.carries=V;this.name="UnregisteredPolicyClassError"}}class p extends Error{model;index;reason;found;suggestion;constructor(z,G,H,V,Z,Y,B){let J=`${z}.$policies[${G}]`,K=Z.length>1?`${Z.slice(0,-1).join(", ")} or ${Z[Z.length-1]}`:Z[0]??"";super(H==="not-a-policy"?`${J} is ${V}, which is not a policy. An entry is either a `+"policy object \u2014 { scope, onCreate, \u2026 } \u2014 or a class the ORM "+`constructs with no arguments.
22
-
23
- A policy that only sometimes applies belongs in the array rather than in the entry:
24
-
25
- static $policies = [...(multiTenant ? [tenantScope] : [])]
26
- `:H==="not-constructable"?`${J} is ${V}, and a function entry is instantiated with `+"no arguments \u2014 so an arrow function, a plain function, or a "+`factory that was never called cannot be one.
27
-
28
- If it is a factory, call it:
29
-
30
- static $policies = [softDeletes({ field: "deletedAt" })]
31
- `:H==="constructor-threw"?`${J} is ${V}
32
-
33
- A class entry is constructed with no arguments. If this one needs some, construct it yourself and put the instance in the array:
34
-
35
- static $policies = [new TenantPolicy({ field: "orgId" })]
36
-
37
- If the constructor reaches for something that is not ready yet, note that it runs on the first query through this model, not at boot.
38
- `:H==="hook-not-callable"?`${J} has a ${V}, and every hook is called \u2014 so this `+`would throw on the first query that reached it rather than doing whatever it was meant to do. Give it a function, or leave the key out.
39
- `:`${J} has none of ${K}, so it would never run. The model carries a visible $policies array and nothing in it `+"applies to any query \u2014 which for a scope means the model "+`reads unscoped. ${V}`+(Y?` Is '${Y.key}' meant to be \`${Y.hook}\`?`:"")+`
40
- `,B);this.model=z;this.index=G;this.reason=H;this.found=V;this.suggestion=Y;this.name="InvalidPolicyEntryError"}}class v extends Error{model;candidates;constructor(z,G){let H=G.map((V)=>`'${V}'`).join(", ");super(`Two classes in one module claim the model '${z}' \u2014 ${H} \u2014 and `+`neither extends the other, so there is no way to tell which one nested relation reads should run.
41
-
42
- Say which, and registerModels will leave it alone:
43
-
44
- import { register } from "gemi/orm"
45
- register("${z}", ${G[0]})
46
-
47
- A class that is only a typed view over the same rows belongs in a module you do not hand to registerModels.`);this.model=z;this.candidates=G;this.name="AmbiguousModelRegistrationError"}}class S extends Error{model;operation;required;limit;dialect;constructor(z,G,H,V,Z,Y){super(`${z}.${G} would bind ${H} parameters, and the '${Z}' driver accepts at most ${V} in one statement. ${Y}`+(G==="createMany"?" A createMany over the ceiling is normally split across statements inside one transaction, so reaching this means splitting cannot help: a single row binds more than the driver accepts.":" Splitting is not something this operation can do for you \u2014 one "+"statement has to carry one answer. Narrow the query."));this.model=z;this.operation=G;this.required=H;this.limit=V;this.dialect=Z;this.name="ParameterLimitError"}}class m extends Error{model;operation;field;constructor(z,G,H){super(`${z}.${G} is missing a value for '${H}', which is required and has no default.`);this.model=z;this.operation=G;this.field=H;this.name="MissingRequiredValueError"}}class c extends Error{relation;model;constructor(z,G,H){super(`'${z}' is not a relation on model ${G}. `+(H.length>0?`Known relations: ${H.join(", ")}.`:`${G} declares no relations.`));this.relation=z;this.model=G;this.name="UnknownRelationError"}}class u extends Error{model;limit;constructor(z,G){super(`The include tree nests more than ${G} relations deep (at model ${z}). Deeply nested includes are legal, so this is a guard against a generated or malformed argument tree rather than a limit on `+"modelling \u2014 every level costs at least one query.");this.model=z;this.limit=G;this.name="RelationDepthExceededError"}}class d extends Error{model;relation;target;constructor(z,G,H,V){super(`${z}.${G} points at model '${H}', which nothing has registered. The generated artifact and the registry disagree: re-run \`prisma generate\`, and check that app/models/generated/index.ts is imported. `+(V.length>0?`Registered models: ${V.join(", ")}.`:"Nothing is registered at all."));this.model=z;this.relation=G;this.target=H;this.name="UnregisteredRelationTargetError"}}class s extends Error{model;relation;constructor(z,G,H){super(`Cannot resolve how ${z}.${G} joins: ${H} This means `+"app/models/generated is stale or hand-edited \u2014 re-run "+"`prisma generate`.");this.model=z;this.relation=G;this.name="MalformedRelationError"}}class i extends Error{constructor(z,G){super(`No model is registered under the name '${z}'. `+(G.length>0?`Registered models: ${G.join(", ")}.`:"Nothing is registered \u2014 is app/models/generated/index.ts imported?"));this.name="ModelNotRegisteredError"}}class n extends Error{constructor(z){super(`${z} has no $schema. Model subclasses must extend a generated base class from app/models/generated/models.ts.`);this.name="MissingModelSchemaError"}}class o extends Error{model;operation;constructor(z,G){super(`${z}.${G} was given 'lock' outside a transaction. A row lock lasts until the transaction that took it ends, so outside one it is released as soon as the row is read and protects nothing. Run the read and the writes it guards inside Model.transaction(async () => { ... }).`);this.model=z;this.operation=G;this.name="LockOutsideTransactionError"}}function $z(){return{now:new Date,resolved:{}}}var r={now:new Date(0),resolved:{}};function Bz(z){return(G,H=r)=>{let V=[];for(let Z=0;Z<z.length;Z++)V.push(z[Z](G,H));return V}}var _="\x00";function W(z){return{text:z,binders:[]}}function X(z,G=""){return{text:_+G,binders:[z]}}function Jz(z){return z.text.split(_)}function Xz(z,G){return{text:z.join(_),binders:G}}function $(...z){return N(z,"")}function N(z,G){let H="",V=[];for(let Z=0;Z<z.length;Z++){if(Z>0)H+=G;H+=z[Z].text;for(let Y of z[Z].binders)V.push(Y)}return{text:H,binders:V}}function Fz(z,G,H){let V=z.text.split(_),Z=V.length-1;if(Z!==z.binders.length)throw Error(`Compiled ${Z} parameter placeholders but collected ${z.binders.length} binders.`);if(Z>G.maxBoundParameters)throw new S(H.model,H.operation,Z,G.maxBoundParameters,G.name,G.bindsListAsOneParameter?"That is one parameter per value in the statement.":`That is one parameter per value, and on ${G.name} each element of an 'in' list counts separately.`);let Y=V[0];for(let B=0;B<Z;B++)Y+=G.placeholder(B)+V[B+1];return{text:Y,binders:z.binders}}class Q{name="postgres";supportsInsensitiveMode=!0;bindsListAsOneParameter=!0;supportsReturning=!0;maxBoundParameters=65535;typesParametersFromStatement=!0;quoteIdent(z){if(z.includes("\x00"))throw Error(`Refusing to quote the identifier ${JSON.stringify(z)}: it contains a NUL byte, which is reserved as the parameter marker.`);return`"${z.replace(/"/g,'""')}"`}placeholder(z){return`$${z+1}`}inList(z,G,H,V){return $(W(`${z} ${G?"<> all":"= any"} (`),X((Y,B)=>j(V(Y,B))),W(")"))}static COMPOSITE_IN_TYPES={Int:"int",BigInt:"bigint",String:"text",Boolean:"boolean"};canBindCompositeIn(z){return z.length>0&&z.every((G)=>Q.COMPOSITE_IN_TYPES[G])}compositeIn(z,G,H){let V=z.map((Z,Y)=>$(X((B,J)=>j(H(B,J).map((K)=>K[Y]))),W(`::${Q.COMPOSITE_IN_TYPES[G[Y]]}[]`)));return $(W(`(${z.join(", ")}) in (select * from unnest(`),...V.flatMap((Z,Y)=>Y===0?[Z]:[W(", "),Z]),W("))"))}listFilters=new Set(["equals","has","hasEvery","hasSome","isEmpty"]);listHas(z,G){return $(G,W(` = any(${z})`))}listHasEvery(z,G){return $(W(`${z} @> `),G)}listHasSome(z,G){return $(W(`${z} && `),G)}listIsEmpty(z,G){return $(W(`${z} ${G?"=":"<>"} `),X(()=>j([])))}listPush(z,G){return $(W(`array_cat(${z}, `),G,W(")"))}jsonPathSyntax="array";jsonFilters=new Set(["equals","not","string_contains","string_starts_with","string_ends_with","array_contains","lt","lte","gt","gte"]);jsonComparesAsText=!0;jsonExtract(z,G,H){return $(W(`${z} ${H?"#>>":"#>"} `),X((V,Z)=>j(G(V,Z))))}jsonValueAt(z,G){return $(W("("),this.jsonExtract(z,G,!1),W(")::jsonb"))}jsonHasKeys(z,G,H,V){let Z=()=>G===void 0?W(`(${z})::jsonb`):$(W("("),this.jsonExtract(z,G,!1),W(")::jsonb")),Y=V==="one"?$(X(H),W("::text")):$(X((J,K)=>j(H(J,K)??[])),W("::text[]")),B=V==="one"?"?":V==="some"?"?|":"?&";return $(W("(jsonb_typeof("),Z(),W(") = 'object' and "),Z(),W(` ${B} `),Y,W(")"))}distinctFrom(z,G,H){let V=H.type==="Json"&&!H.isList;return $(W(V?`(${z})::jsonb is distinct from `:`${z} is distinct from `),G)}jsonArrayContains(z,G,H){return $(W("("),this.jsonExtract(z,G,!1),W(") @> "),X((V,Z)=>{let Y=H(V,Z);if(Y===null||Y===void 0)return null;return typeof Y==="string"||typeof Y==="object"?Y:JSON.stringify(Y)}),W("::jsonb"))}like(z,G,H){return $(W(`${z} ${G?"ilike":"like"} `),X(H))}ignoreConflicts(){return W(" on conflict do nothing")}rowLock(z,G){let H=z.onLocked==="skipLocked"?" skip locked":z.onLocked==="noWait"?" nowait":"";return W(` for ${z.mode==="share"?"share":"update"} of ${this.quoteIdent(G)}${H}`)}paginate(z,G){let H=[];if(z)H.push($(W(" limit "),X(z)));if(G)H.push($(W(" offset "),X(G)));return $(...H)}constraintViolation(z){let G=z;if(!G)return null;if(String(G.errno??G.code??"")!=="23505")return null;let V=typeof G.constraint==="string"&&G.constraint!==""?G.constraint:void 0,Z=typeof G.detail==="string"?G.detail:"",Y=/\((.+?)\)=/.exec(Z);return{kind:"unique",columns:Y?(Y[1].match(/"(?:[^"]|"")*"|[^,]+/g)??[]).map((J)=>J.trim()).filter((J)=>J!=="").map((J)=>/^".*"$/s.test(J)?J.slice(1,-1).replace(/""/g,'"'):J):[],constraint:V}}castParameter(z){if(z.isList)return"";return z.type==="Json"?"::text::jsonb":""}encode(z,G){if(z===null||z===void 0)return null;if(G.isList){if(!Array.isArray(z))throw Error(`gemi ORM bug: a non-array reached the parameter binder for the scalar list '${G.column}' (received ${typeof z}). Every path that binds a list is supposed to have checked its operand.`);return j(G.type==="Json"?z.map((H)=>H===null||H===void 0?null:JSON.stringify(H)):z)}return z}encodeUntyped(z){return z}needsDecode(z){return z.isList===!0||z.type==="BigInt"||z.type==="Bytes"}decode(z,G){if(z===null||z===void 0)return null;if(G.isList)return this.decodeList(z,G);return this.decodeScalar(z,G)}decodeList(z,G){let H=Array.isArray(z)?z:typeof z==="string"?l(z,G):ArrayBuffer.isView(z)?Array.from(z):null;if(H===null)throw new F(G,z);return H.map((V)=>V===null||V===void 0?null:this.decodeScalar(V,G))}decodeScalar(z,G){switch(G.type){case"BigInt":if(typeof z==="bigint")return z;try{return BigInt(z)}catch{throw new F(G,z)}case"Json":return z;case"Bytes":return Buffer.isBuffer(z)?new Uint8Array(z.buffer,z.byteOffset,z.byteLength):z;default:return z}}}function j(z){let G="{";for(let H=0;H<z.length;H++){if(H>0)G+=",";G+=t(z[H])}return G+"}"}function t(z){if(z===null||z===void 0)return"NULL";if(z instanceof Date)return`"${z.toISOString()}"`;if(ArrayBuffer.isView(z)){let H="";for(let V of new Uint8Array(z.buffer,z.byteOffset,z.byteLength))H+=V.toString(16).padStart(2,"0");return`"\\\\x${H}"`}return`"${(typeof z==="string"?z:String(z)).replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function l(z,G){if(!z.startsWith("{")||!z.endsWith("}"))throw new F(G,z);if(z==="{}")return[];let H=[],V=1,Z=z.length-1;while(V<=Z){let Y="",B=!1;if(z[V]==='"'){B=!0,V++;while(V<Z&&z[V]!=='"')Y+=z[V]==="\\"?z[++V]:z[V],V++;V++}else while(V<Z&&z[V]!==","){if(z[V]==="{")throw new F(G,z);Y+=z[V],V++}if(H.push(!B&&Y.toUpperCase()==="NULL"?null:Y),V<Z&&z[V]!==",")throw new F(G,z);V++}if(G.type!=="Json")return H;return H.map((Y)=>{if(Y===null)return null;try{return JSON.parse(Y)}catch{throw new F(G,Y)}})}var a={"Prisma.DbNull":"db","Prisma.JsonNull":"json","Prisma.AnyNull":"any"};function T(z){return new class{toString(){return z}}}var Qz=T("Prisma.DbNull"),e=T("Prisma.JsonNull"),Iz=T("Prisma.AnyNull"),_z=e;function E(z){if(typeof z!=="object"||z===null)return null;for(let H in z)return null;if(Object.getOwnPropertyNames(z).length>0)return null;let G;try{G=String(z)}catch{return null}return a[G]??null}var zz=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(\.\d+)?$/;function Gz(z,G){if(z instanceof Date)return z;let H;if(typeof z==="number")H=new Date(z);else if(typeof z==="bigint")H=new Date(Number(z));else if(typeof z==="string")H=new Date(zz.test(z)?`${z.replace(" ","T")}Z`:z);else throw new F(G,z);if(Number.isNaN(H.getTime()))throw new F(G,z);return H}class M{name="sqlite";supportsInsensitiveMode=!1;bindsListAsOneParameter=!1;supportsReturning=!0;maxBoundParameters=32766;typesParametersFromStatement=!1;quoteIdent(z){if(z.includes("\x00"))throw Error(`Refusing to quote the identifier ${JSON.stringify(z)}: it contains a NUL byte, which is reserved as the parameter marker.`);return`"${z.replace(/"/g,'""')}"`}placeholder(z){return"?"}inList(z,G,H,V){let Z=G?"not in":"in",Y=[];for(let B=0;B<H;B++)Y.push(X((J,K)=>V(J,K)[B]));return $(W(`${z} ${Z} (`),N(Y,", "),W(")"))}canBindCompositeIn(){return!1}compositeIn(){throw Error("SQLite cannot bind a composite `in`; `canBindCompositeIn` is the guard.")}listFilters=new Set;listHas(){throw Error(I("has"))}listHasEvery(){throw Error(I("hasEvery"))}listHasSome(){throw Error(I("hasSome"))}listIsEmpty(){throw Error(I("isEmpty"))}listPush(){throw Error(I("push"))}jsonPathSyntax="jsonpath";jsonFilters=new Set(["equals","not","string_contains","string_starts_with","string_ends_with"]);jsonComparesAsText=!1;jsonExtract(z,G,H){return $(W(`json_extract(${z}, `),X(G),W(")"))}jsonValueAt(z,G){return $(W(`(${z} -> `),X(G),W(")"))}jsonHasKeys(z,G,H,V,Z){let Y=(C,O)=>G===void 0?"$":G(C,O),B=(C)=>$(W(`json_type(${z}, `),X((O,A)=>{let L=H(O,A),y=C===void 0?L:L[C];return`${Y(O,A)}.${JSON.stringify(String(y))}`}),W(") is not null")),J=V==="one"?[B(void 0)]:Array.from({length:Z},(C,O)=>B(O)),K=J.length===0?W(V==="some"?"0":"1"):N(J,V==="every"?" and ":" or ");return $(W(`(json_type(${z}, `),X(Y),W(") = 'object' and ("),K,W("))"))}distinctFrom(z,G,H){if(H.type==="Json"&&!H.isList)return $(W(`json(${z}) is not json(`),G,W(")"));return $(W(`${z} is not `),G)}jsonArrayContains(){throw Error("SQLite cannot express array_contains; `jsonFilters` is the guard.")}like(z,G,H){return $(W(`${z} like `),X(H))}ignoreConflicts(){return null}rowLock(z,G){return W("")}paginate(z,G){if(!z&&!G)return W("");if(!G)return $(W(" limit "),X(z));return $(W(" limit "),X(z??(()=>-1)),W(" offset "),X(G))}constraintViolation(z){let G=z?.code;if(G!=="SQLITE_CONSTRAINT_UNIQUE"&&G!=="SQLITE_CONSTRAINT_PRIMARYKEY")return null;let H=String(z.message??""),V=/constraint failed:\s*(.+)$/.exec(H);if(!V)return{kind:"unique",columns:[]};return{kind:"unique",columns:V[1].split(",").map((Y)=>Y.trim()).map((Y)=>{let B=Y.indexOf(".");return B===-1?Y:Y.slice(B+1)}).filter((Y)=>Y!=="")}}castParameter(z){return""}encode(z,G){if(z===null||z===void 0)return null;switch(G.type){case"DateTime":return z instanceof Date?z.getTime():z;case"Boolean":return typeof z==="boolean"?z?1:0:z;case"Json":{let H=E(z);if(H==="db")return null;if(H==="json")return"null";if(H==="any")throw Error("gemi ORM bug: Prisma.AnyNull reached the SQLite encoder. It is a filter operand only, and both the filter and write paths are supposed to have handled it before this point.")}return JSON.stringify(z);default:return z}}encodeUntyped(z){if(z instanceof Date)return z.getTime();if(typeof z==="boolean")return z?1:0;return z}needsDecode(z){switch(z.type){case"DateTime":case"Boolean":case"BigInt":case"Json":return!0;default:return!1}}decode(z,G){if(z===null||z===void 0)return null;switch(G.type){case"DateTime":return Gz(z,G);case"Boolean":if(typeof z==="boolean")return z;return Number(z)!==0;case"BigInt":if(typeof z==="bigint")return z;try{return BigInt(z)}catch{throw new F(G,z)}case"Json":try{return typeof z==="string"?JSON.parse(z):z}catch{throw new F(G,z)}default:return z}}}function I(z){return`SQLite has no array type, so it cannot express '${z}' on a scalar list; \`listFilters\` is the guard.`}class w extends Error{constructor(z){super(`The gemi ORM does not support the '${z}' dialect. Only sqlite `+"and postgres are implemented \u2014 see the supported matrix in "+`docs/orm.md.
48
-
49
- The *connection* is fine: Bun's client speaks ${z}, so raw SQL through DB.query / DB.sql and transactions all work. It is the query compiler that has no ${z} dialect, so every model operation raises this.
50
-
51
- Point DATABASE_URL at Postgres or SQLite to use the ORM, or keep using Prisma's own client for this database.`);this.name="UnsupportedDialectError"}}function Rz(z){return P[z]!==null}function bz(){return Object.keys(P)}var P={sqlite:new M,postgres:new Q,mysql:null,mariadb:null};function Dz(z){let G=P[z];if(G===null)throw new w(z);return G}
52
- export{U as ef,k as ff,q as gf,h as hf,F as if,R as jf,Hz as kf,b as lf,Vz as mf,x as nf,D as of,Wz as pf,g as qf,f as rf,p as sf,v as tf,S as uf,m as vf,c as wf,u as xf,d as yf,s as zf,i as Af,n as Bf,o as Cf,$z as Df,Bz as Ef,W as Ff,X as Gf,Jz as Hf,Xz as If,$ as Jf,N as Kf,Fz as Lf,Q as Mf,Qz as Nf,e as Of,Iz as Pf,_z as Qf,E as Rf,M as Sf,w as Tf,Rz as Uf,bz as Vf,Dz as Wf};
53
-
54
- //# debugId=FA4CAB4B2CC09B0564756E2164756E21
@@ -1,5 +0,0 @@
1
- // @bun
2
- import{Kc as o}from"./chunk-mtbygktb.js";import{Lc as i}from"./chunk-n672d4g8.js";import{_g as t}from"./chunk-cbqazg9k.js";import{Zh as r}from"./chunk-7g9yh5ae.js";class n extends i{register(){this.app.singleton(r,()=>new r(t(o(),this.app.config.get("translation",{}))))}}
3
- export{n as eb};
4
-
5
- //# debugId=C32FA7347CB1EE1064756E2164756E21
@@ -1,10 +0,0 @@
1
- // @bun
2
- import{Sb as oZ,Vb as t,Wb as aZ,dc as XZ}from"./chunk-0z8ejxre.js";import{oc as DZ,qc as e,sc as U3,tc as B3,vc as C3}from"./chunk-ktr3k768.js";import{Ac as N3,Cc as z3,Dc as X3,Ec as D,Fc as Y3,Gc as K3,Ic as H3,xc as W3}from"./chunk-7vb4eey2.js";import{Lc as F}from"./chunk-n672d4g8.js";import{Ae as _Z,Jd as p,Td as J3,Ud as LZ,Ve as yZ,Yd as r,ad as D3,ed as v,ge as TZ,hd as sZ,ie as $Z,ld as A3,me as SZ,ue as l,ye as m,ze as WZ}from"./chunk-d6591xck.js";import{Xe as I3,Ye as AZ}from"./chunk-whtzggn6.js";import{Gg as qZ,Ig as ZZ,Jg as a,Kg as i,pg as b,rg as PZ}from"./chunk-dexdkh3z.js";import{Wg as tZ}from"./chunk-9b4erdy2.js";import{Xg as G3,Zg as k}from"./chunk-tn2bryy2.js";import{_g as _}from"./chunk-cbqazg9k.js";import{eh as P3}from"./chunk-1myhm0g3.js";import{Uh as OZ}from"./chunk-qsrcdzan.js";import{_h as V3,bi as g}from"./chunk-t4yh4nf9.js";var T3="mcp",S3=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class L extends XZ{status;constructor(Z,$){super(Z);this.status=$;this.name="McpToolError"}}class d extends Error{reason;constructor(Z,$){super(Z);this.reason=$;this.name="McpCallRefusedError"}}var j3=/^[A-Za-z0-9_-]{1,64}$/,M3=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,jZ=4000,y=1e5,k3=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i;class f{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;constructor(Z,$,G={}){this.router=Z;this.dispatcher=$;this.files=E3(G.files);for(let[W,z]of Object.entries(Z.routes??{}))this.plans.set(W,this.plan(W,z));this.resolveScopes()}list(Z,$){if(MZ(Z),Z.kind==="local")return this.descriptors($);let G=[];for(let[W,z]of this.plans){if(!z.remote||!this.grants(Z.principal,W))continue;if(kZ(z.remote,$))G.push(z.remote)}return G}descriptors(Z){let $=[];for(let{descriptor:G}of this.plans.values())if(kZ(G,Z))$.push(G);return $}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([Z,{description:$}])=>({name:Z,description:$}))}scopesFor(Z){return[...this.scopeTools].filter(([,{tools:$}])=>$.has(Z)).map(([$])=>$)}async execute(Z,$,G,W,z={}){MZ(Z);let X=this.plans.get($);if(Z.kind==="remote"){if(!X?.remote||!this.grants(Z.principal,$))throw new d(`There is no tool named "${$}".`,"unknown-tool");if(X.descriptor.requiresApproval&&z.approved!==!0)throw new d(`"${$}" needs the user's approval, and this call does not have it.`,"approval-required");W=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${$}".`);let Y=X,K=Z.kind==="remote"?Y.remote:Y.descriptor,U=K.inputSchema.safeParse(G);if(U.ok===!1)throw new L(`Invalid arguments for "${$}": ${U.errors.join(", ")}`);let H=U.value,Q={caller:Z,req:Z.req,tool:K,input:H,ctx:W},V=await this.fillPath(Y,Q),{path:I}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${V}`));if(I!==K.url)throw new L(`"${$}" has nothing at ${V}.`,404);let C={};for(let q of Y.jsonKeys)if(H[q]!==void 0)C[q]=H[q];let P,x="";if(Y.fileFields.length>0)P=await this.formData(Y,C,Q);else if(K.method==="GET")x=c3(C);else if(Y.jsonKeys.length>0)P=C;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(Q)):void 0,w={...j?{credentials:j}:{},...z.signal?{signal:z.signal}:{},...z.progress?{progress:z.progress}:{},...Z.kind==="remote"?{identity:{user:Z.principal.user,grant:{via:Z.principal.via,id:Z.principal.id,scopes:Z.principal.scopes,...Z.principal.clientId?{clientId:Z.principal.clientId}:{}}}}:{}},u;try{let q=x?`${V}?${x}`:V;u=Object.keys(w).length>0?await this.dispatcher.dispatchAs(Z.req,K.method,q,P,w):await this.dispatcher.dispatchAs(Z.req,K.method,q,P)}catch(q){throw console.error(`[gemi/mcp] Dispatching "${$}" failed:`,q),new L(`"${$}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await bZ($,u);return await this.project(Y,Q,u)}plan(Z,$){if(!j3.test(Z))throw Error(`McpRouter: "${Z}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let G=`McpRouter: "${Z}" (${$?.method} ${$?.url})`;if(!($ instanceof Object)||$.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${Z}" is not a route. Declare it with this.fromApiRoute(...).`);let{method:W,url:z,meta:X}=$;if(z.startsWith("/__gemi__"))throw Error(`${G} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[z]?.[W];if(!Y)throw Error(`${G} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...z.matchAll(M3)].map(([,B,A])=>({name:B,modifier:A})),U=X.params??{};for(let B of K)if(!(B.name in U))throw Error(`${G}: the path param "${B.name}" must be bound or declared "input".`);for(let[B,A]of Object.entries(U)){if(!K.some((M)=>M.name===B))throw Error(`${G}: "${B}" in params is not a param of the url.`);if(EZ(A))v3(G,`params.${B}`,A);else RZ(G,`params.${B}`,A)}let H=[],Q;if(X.input){if(Q=X.input.toJSONSchema(),Q.type!=="object"||!Q.properties)throw Error(`${G}: input must be an s.object(...), the fields of the request body.`);H=Object.keys(Q.properties)}let V=Object.entries(X.files??{}).map(([B,A])=>({name:B,binder:A}));for(let B of V)RZ(G,`files.${B.name}`,B.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${G}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${G}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${G}: title must be a non-empty string.`);let I=m3(G,W,X.annotations);if(V.length>0&&W==="GET")throw Error(`${G}: a GET has no body to carry a file.`);let C={},P=(B,A)=>{if(B in C)throw Error(`${G}: "${B}" is the input key of two params or files, and the model can only send one.`);C[B]=A},x=new Map,j=new Map;for(let B of K){let A=U[B.name];if(A==="input"){let M=b.string().describe(`The ":${B.name}" segment of the url.`);P(B.name,B.modifier==="?"||B.modifier==="*"?M.optional():M)}else if(EZ(A)){let M=A.as??B.name;P(M,A.input),j.set(B.name,{key:M,param:A})}else x.set(B.name,A)}let w={};for(let B of V)if(B.binder==="input")P(B.name,b.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),w[B.name]=this.remoteFileSchema();let u=[...Object.keys(C),...V.map((B)=>B.name)];for(let B of new Set(u))if(H.includes(B))throw Error(`${G}: "${B}" is both an input field and a param or file, and the model can only send one.`);let q=Object.freeze({name:Z,description:X.description,method:W,url:z,inputSchema:wZ(X.input,Q,b.object(C)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:I,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...Y.source?{source:Y.source}:{}}),q3=!V.every((B)=>B.binder==="input")?null:V.length===0?q:Object.freeze({...q,inputSchema:wZ(X.input,Q,b.object(u3(C,Object.keys(w))),w)});return{descriptor:q,remote:q3,params:K,paramBinders:x,modelParams:j,fileFields:V,jsonKeys:H,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:Z,fetch:$}=this.files,G={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${Z} bytes decoded.`}};if($)G.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let W={type:"object",description:$?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:G,required:["name","mimeType"],additionalProperties:!1},z=Object.keys(G),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],U={};for(let H of Object.keys(Y))if(!z.includes(H))K.push(`a file has no field "${H}"`);for(let H of z){let Q=Y[H];if(Q===void 0||Q===null){if(H==="name"||H==="mimeType")K.push(`a file needs "${H}"`);continue}if(typeof Q!=="string")K.push(`a file's "${H}" must be a string`);else U[H]=Q}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:U}};return{toJSONSchema:()=>W,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}async fillPath(Z,$){let{input:G,req:W}=$,z=Z.descriptor.url;for(let X of Z.params){let Y=Z.paramBinders.get(X.name),K=Z.modelParams.get(X.name),U;if(Y||K){if(U=K?await this.bind(Z,`the param "${X.name}"`,()=>K.param.bind(G[K.key],W,$),{refusals:!0}):await this.bind(Z,`the param "${X.name}"`,()=>Y(W,$)),U===void 0||U===null||U==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${Z.descriptor.name}" returned ${JSON.stringify(U)}.`),new L(`"${Z.descriptor.name}" failed on the server.`,500)}else U=G[X.name];let H=`:${X.name}${X.modifier}`;if(U===void 0||U===null||U===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new L(`"${X.name}" of "${Z.descriptor.name}" must not be empty.`);z=z.replace(`/${H}`,"");continue}z=z.replace(H,d3(Z.descriptor.name,X,String(U)))}return z}async formData(Z,$,G){let{input:W,ctx:z}=G,X=Z.descriptor.name;if(G.caller.kind==="remote"){let K=new FormData;for(let[U,H]of Object.entries($))zZ(K,U,H);for(let U of Z.fileFields)K.append(U.name,await this.remoteFile(X,U.name,W[U.name]));return K}if(!z)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,U]of Object.entries($))zZ(Y,K,U);for(let K of Z.fileFields){let U=K.binder==="input"?W[K.name]:await this.bind(Z,`the file "${K.name}"`,()=>K.binder(z,G));if(typeof U!=="string"||U==="")throw new L(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await z.attachments.file(U))}return Y}async remoteFile(Z,$,G){let W=(Q)=>new L(`"${$}" of "${Z}" ${Q}`,400),z=G,{maxBytes:X,fetch:Y}=this.files;if(!w3(z.name))throw W("needs a name of 1 to 255 characters, without control characters or slashes.");if(!b3.test(z.mimeType))throw W(`has a mimeType that is not a media type: "${z.mimeType.slice(0,100)}".`);let K=typeof z.data==="string",U=typeof z.url==="string";if(K===U)throw W(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let Q=z.data.replace(/\s+/g,"");if(Math.floor(Q.length*3/4)-f3(Q)>X)throw W(`is larger than the ${X} bytes a file may be.`);if(Q.length%4!==0||!y3.test(Q))throw W("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(Q,"base64")],z.name,{type:z.mimeType})}if(!Y)throw W("cannot be fetched from a URL here. Send its bytes, base64, in data.");let H;try{H=new URL(z.url)}catch{throw W("has a url that is not a URL.")}if(H.protocol!=="https:")throw W("can only be fetched from an https URL.");try{let Q=await yZ(H.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!Q.ok)throw W(`could not be fetched: ${H.host} answered ${Q.status}.`);let V=await Q.arrayBuffer();return new File([V],z.name,{type:z.mimeType})}catch(Q){if(Q instanceof L)throw Q;throw W(`could not be fetched from ${H.host}: ${Q instanceof Error?Q.message:"failed"}.`)}}grants(Z,$){for(let G of Z.scopes??[])if(this.scopeTools.get(G)?.tools.has($))return!0;return!1}resolveScopes(){let Z=this.router.scopes;if(Z===void 0){this.scopeTools.set(T3,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof Z!=="object"||Z===null)throw Error("McpRouter: scopes must be an object of scope names.");let $=new Set([...this.plans.values()].flatMap(({descriptor:G})=>G.tags));for(let[G,W]of Object.entries(Z)){let z=`McpRouter: scope "${G}"`;if(!S3.test(G))throw Error(`${z} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof W?.description!=="string"||W.description==="")throw Error(`${z} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of W.tags??[]){if(!$.has(Y))throw Error(`${z} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:U}]of this.plans)if(U.tags.includes(Y))X.add(K)}for(let Y of W.names??[]){if(!this.plans.has(Y))throw Error(`${z} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${z} reaches no tool. Give it tags or names.`);this.scopeTools.set(G,{description:W.description,tools:X})}}async project(Z,$,G){let{name:W,outputSchema:z}=Z.descriptor;if(G.status<200||G.status>=300)return await bZ(W,G);let X=(V,I)=>{if(I===void 0)console.error(`[gemi/mcp] "${W}" ${V}`);else console.error(`[gemi/mcp] "${W}" ${V}`,I);return new L(`"${W}" failed on the server.`,500)},Y=G.headers.get("Content-Type"),K=await G.text(),U=null;if(K!=="")try{U=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let H=U;if(Z.result)try{H=await Z.result(U,$)}catch(V){throw X("failed in its result projection:",V)}if(z){let V=z.safeParse(H);if(V.ok===!1)throw X(`answered what its output schema refuses: ${V.errors.join(", ")}`);H=V.value}if(H===void 0)return null;let Q=JSON.stringify(H);if(Q!==void 0&&Q.length>y)return`${Q.slice(0,y)}\u2026 [cut at ${y} of ${Q.length} characters]`;return H}async bind(Z,$,G,W={}){try{return await G()}catch(z){if(W.refusals&&z instanceof XZ)throw z;throw console.error(`[gemi/mcp] Binding ${$} of "${Z.descriptor.name}" failed:`,z),new L(`"${Z.descriptor.name}" failed on the server.`,500)}}}function MZ(Z){if(Z?.kind==="local"&&Z.req)return;if(Z?.kind==="remote"&&Z.req&&Z.principal?.user&&typeof Z.principal.id==="string"&&Array.isArray(Z.principal.scopes))return;throw Error('McpRegistry: a caller is { kind: "local", req } or { kind: "remote", req, principal }, with the principal a caller resolver verified.')}function kZ(Z,$){if($?.names&&!$.names.includes(Z.name))return!1;if($?.tags&&!Z.tags.some((G)=>$.tags.includes(G)))return!1;return!0}var R3=10485760;function E3(Z){let $=Z?.maxBytes??R3;if(!Number.isSafeInteger($)||$<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let G=Z?.fetchUrls===!0?{}:typeof Z?.fetchUrls==="object"&&Z.fetchUrls!==null?Z.fetchUrls:null;return{maxBytes:$,fetch:G}}function w3(Z){if(Z.length===0||Z.length>255)return!1;for(let $ of Z){let G=$.codePointAt(0);if(G<32||G===127||$==="/"||$==="\\")return!1}return!0}var b3=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,y3=/^[A-Za-z0-9+/]*={0,2}$/;function f3(Z){return Z.endsWith("==")?2:Z.endsWith("=")?1:0}function RZ(Z,$,G){if(G!=="input"&&typeof G!=="function")throw Error(`${Z}: ${$} must be a function or "input".`)}function EZ(Z){return Z instanceof Object&&Z.__internal_brand==="McpModelParam"}function v3(Z,$,G){if(G.as!==void 0&&(typeof G.as!=="string"||G.as===""))throw Error(`${Z}: ${$}.as must be a non-empty string.`);let W=G.input;if(typeof W?.safeParse!=="function"||typeof W.toJSONSchema!=="function")throw Error(`${Z}: ${$}.input must be a schema, built with s.`);if(typeof G.bind!=="function")throw Error(`${Z}: ${$}.bind must be a function.`)}var g3=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function h3(Z){switch(Z){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function m3(Z,$,G){if(G!==void 0&&(typeof G!=="object"||G===null))throw Error(`${Z}: annotations must be an object of hints.`);let W=h3($);for(let[z,X]of Object.entries(G??{})){if(!g3.has(z))throw Error(`${Z}: "${z}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${Z}: annotations.${z} must be true or false.`);W[z]=X}if(W.readOnlyHint===!0&&(W.destructiveHint||W.idempotentHint))throw Error(`${Z} is read-only${G?.readOnlyHint?"":` (a ${$})`} and also ${W.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(W)}function wZ(Z,$,G,W={}){let z=G.toJSONSchema(),X=Object.fromEntries(Object.entries(W).map(([U,H])=>[U,H.toJSONSchema()])),Y={...$??{},type:"object",properties:{...$?.properties??{},...z.properties,...X},required:[...$?.required??[],...z.required??[],...Object.keys(W)],additionalProperties:!1},K=(U)=>{if(typeof U!=="object"||U===null||Array.isArray(U))return{ok:!1,errors:["expected an object"]};let H=[],Q={};if(Z){let I=Z.safeParse(U);if(I.ok===!1)H.push(...I.errors);else Q={...I.value}}let V=G.safeParse(U);if(V.ok===!1)H.push(...V.errors);else Q={...Q,...V.value};for(let[I,C]of Object.entries(W)){let P=U[I];if(P===void 0){H.push(`"${I}" is required`);continue}let x=C.safeParse(P);if(x.ok===!1)H.push(...x.errors.map((j)=>`${I}: ${j}`));else Q[I]=x.value}return H.length>0?{ok:!1,errors:H}:{ok:!0,value:Q}};return{toJSONSchema:()=>Y,safeParse:K,parse(U){let H=K(U);if(H.ok===!1)throw Error(H.errors.join(", "));return H.value}}}function u3(Z,$){return Object.fromEntries(Object.entries(Z).filter(([G])=>!$.includes(G)))}function d3(Z,$,G){let W=$.modifier==="*"||$.modifier==="+"?G.split("/"):[G];if(W.some((z)=>z==="."||z===".."))throw new L(`"${G}" is not a valid value for "${$.name}" of "${Z}".`);return W.map(encodeURIComponent).join("/")}function zZ(Z,$,G){if(G===void 0||G===null)return;if(Array.isArray(G)){for(let W of G)zZ(Z,$,W);return}Z.append($,typeof G==="object"?JSON.stringify(G):String(G))}function c3(Z){let $=new URLSearchParams,G=(W,z)=>{if(z===void 0||z===null)return;if(Array.isArray(z)){for(let X of z)G(W,X);return}$.append(W,typeof z==="object"?JSON.stringify(z):String(z))};for(let[W,z]of Object.entries(Z))G(W,z);return $.toString()}async function bZ(Z,$){if($.status>=200&&$.status<300){let W=$.headers.get("Content-Type");if(W&&!k3.test(W)){let X=(await $.arrayBuffer()).byteLength;return`"${Z}" answered with ${X} bytes of ${W}, which is not shown.`}let z=await $.text();if(z==="")return null;if(z.length>y)return`${z.slice(0,y)}\u2026 [cut at ${y} of ${z.length} characters]`;try{return JSON.parse(z)}catch{return z}}let G=await $.text();if($.status>=400&&$.status<500){let W=G.length>jZ?`${G.slice(0,jZ)}\u2026`:G;throw new L(`"${Z}" was refused with ${$.status}${W?`: ${W}`:"."}`,$.status)}if($.status<500)console.error(`[gemi/mcp] "${Z}" answered ${$.status}${$.headers.get("Location")?` to ${$.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new L(`"${Z}" failed on the server.`,$.status)}import{createHash as p3,randomBytes as i3,timingSafeEqual as l3}from"crypto";function YZ(Z){let $=Z.headers.get("authorization");if(!$)return null;let G=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec($.trim());return G?G[1]:null}class n3{options;name="api-key";constructor(Z){this.options=Z;if(typeof Z?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test(Z.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof Z.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate(Z){return`${Z}${i3(32).toString("base64url")}`}static hash(Z){return p3("sha256").update(Z).digest("hex")}static hashesMatch(Z,$){let G=Buffer.from(Z),W=Buffer.from($);return G.length===W.length&&l3(G,W)}async resolve(Z){let $=YZ(Z);if(!$?.startsWith(this.options.prefix))return null;let G=await this.options.verify($,Z);if(!G)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!G.user||typeof G.id!=="string"||G.id===""||!Array.isArray(G.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:G.user,via:this.name,id:G.id,scopes:[...G.scopes]}}}}import{createHash as rZ,randomBytes as hZ}from"crypto";async function KZ(Z,$){let G=t3();if(!G)return null;let W=await G.consume(Z,$);return W.allowed?null:Math.max(1,Math.ceil(W.retryAfter/1000))}function t3(){try{let Z=g();return Z.bound(v)?Z.make(v):null}catch{return null}}var HZ=["2026-07-28"],n=["2025-11-25","2025-06-18","2025-03-26"],UZ=[...HZ,...n],QZ="io.modelcontextprotocol/protocolVersion",VZ="io.modelcontextprotocol/clientCapabilities";var BZ="io.modelcontextprotocol/serverInfo",N={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class J extends Error{code;data;status;constructor(Z,$,G,W=200){super($);this.code=Z;this.data=G;this.status=W;this.name="JsonRpcError"}}function T(Z,$){return{jsonrpc:"2.0",id:Z,error:{code:$.code,message:$.message,...$.data!==void 0?{data:$.data}:{}}}}function fZ(Z){if(Array.isArray(Z))throw new J(N.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof Z!=="object"||Z===null||Z.jsonrpc!=="2.0")throw new J(N.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let $=Z,G=$.id,W=typeof G==="string"||typeof G==="number"&&Number.isFinite(G);if(typeof $.method==="string"){if($.params!==void 0&&(typeof $.params!=="object"||$.params===null||Array.isArray($.params)))throw new J(N.InvalidRequest,"params must be an object.",void 0,400);if(G===void 0)return{kind:"notification",message:$};if(!W)throw new J(N.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:$}}if(W&&(("result"in $)||("error"in $)))return{kind:"response",message:$};throw new J(N.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function IZ(Z,$){let G=Z.outputSchema?.toJSONSchema(),W={...Z.annotations,...Z.title&&!$?{title:Z.title}:{}};return{name:Z.name,...Z.title?{title:Z.title}:{},description:Z.description,inputSchema:Z.inputSchema.toJSONSchema(),...G&&($||G.type==="object")?{outputSchema:G}:{},...Object.keys(W).length>0?{annotations:W}:{}}}function O(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function vZ(Z){let $=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec(Z);if(!$)return Z;try{let G=Buffer.from($[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(G)}catch{return null}}import{createHmac as s3,timingSafeEqual as o3}from"crypto";function JZ(Z,$,G){let W=Buffer.from(JSON.stringify(G)).toString("base64url");return`${$}.${W}.${gZ(Z,$,W).toString("base64url")}`}function FZ(Z,$,G,W=Date.now()){if(typeof G!=="string"||G.length>8192)return null;let z=G.split(".");if(z.length!==3||z[0]!==$)return null;let[,X,Y]=z,K=Buffer.from(Y,"base64url"),U=gZ(Z,$,X);if(K.length!==U.length||!o3(K,U))return null;let H;try{H=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof H!=="object"||H===null)return null;if(typeof H.exp!=="number"||H.exp<=W)return null;return H}function gZ(Z,$,G){return s3("sha256",t(Z)).update(`${$}.${G}`).digest()}var NZ="gemi.mcp.request-state.v1",mZ="gemi.mcp.session.v1",a3=86400000,uZ=600000,dZ="gemi_approval",xZ=2000,r3={limit:600,window:60},e3={limit:30,window:60};class c{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;pending=new Map;inflight=new Map;constructor(Z,$){this.registry=Z;if(typeof $.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=G8($.url);let G=$.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");this.resolvers=G,t(NZ),this.context={resource:this.resource,registry:Z},this.allowedOrigins=new Set(($.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.rateLimit=$.rateLimit===!1?!1:$.rateLimit??r3,this.maxBodyBytes=$.maxBodyBytes??Math.ceil(Z.maxFileBytes*1.4)+1048576,this.serverInfo={name:$.server?.name??"gemi",version:$.server?.version??"1.0.0"},this.instructions=$.server?.instructions,this.nonces=$.nonces??new oZ,this.approvalTimeoutMs=$.approvalTimeoutMs??uZ;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle(Z){let $=new URL(Z.url);if($.host!==this.endpoint.host)return null;for(let z of this.resolvers){let X=await z.handle?.(Z,this.context);if(X)return X}if($.pathname!==this.endpoint.pathname)return null;let G=Z.headers.get("origin");if(G!==null&&!this.allowedOrigins.has(G))return S(T(null,new J(N.InvalidRequest,"Origin not allowed.")),403);let W=G?$8(G):{};if(Z.method==="OPTIONS")return new Response(null,{status:204,headers:{...W,"Access-Control-Allow-Methods":"POST","Access-Control-Allow-Headers":"Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name, Last-Event-ID","Access-Control-Max-Age":"600"}});if(Z.method!=="POST")return cZ(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),W);return cZ(await this.post(Z),W)}async post(Z){let $=null;for(let Y of this.resolvers){let K=await Y.resolve(Z,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt(Z)??this.unauthorized(K.description);$={...K.principal,via:Y.name};break}if(!$)return(YZ(Z)!==null?await this.failedAttempt(Z):null)??this.unauthorized();let G=await this.spend($);if(G)return G;let W=Z.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(W))return new Response("Content-Type must be application/json.",{status:415});let z;try{z=JSON.parse(await Z8(Z,this.maxBodyBytes))}catch(Y){if(Y instanceof o)return S(T(null,new J(N.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return S(T(null,new J(N.ParseError,"Parse error.")),400)}let X=new PZ(Z,{},"api",this.endpoint.pathname);return await tZ.run(X,async()=>{try{return await this.dispatch(Z,X,$,z)}catch(Y){if(Y instanceof J){let K=O(z)&&(typeof z.id==="string"||typeof z.id==="number")?z.id:null;return S(T(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),S(T(null,new J(N.InternalError,"Internal error.")),500)}},{user:$.user})}async dispatch(Z,$,G,W){let z=fZ(W),X={kind:"remote",req:$,principal:G};if(z.kind==="response"){let P=this.session(Z,G),x=this.pending.get(String(z.message.id));if(x&&x.session===P.id)this.pending.delete(String(z.message.id)),x.resolve(z.message);return new Response(null,{status:202})}let{message:Y}=z,K=Y.params??{},U=O(K._meta)?K._meta:{};if(typeof U[QZ]==="string"){if(this.checkModernHeaders(Z,Y,U[QZ]),z.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(P,x)=>this.modern({principal:G,caller:X,message:Y,params:K,era:{modern:!0},stream:P,signal:x}),iZ(K),Z.signal)}if(Y.method==="initialize"){if(z.kind!=="request")throw new J(N.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(z.message,K,G)}let H=this.session(Z,G),Q=Z.headers.get("mcp-protocol-version");if(Q!==null&&Q!==H.state.v)throw new J(N.InvalidRequest,`MCP-Protocol-Version ${Q} is not the session's ${H.state.v}.`,void 0,400);if(z.kind==="notification"){if(Y.method==="notifications/cancelled"){let P=K.requestId;this.inflight.get(`${H.id}:${String(P)}`)?.abort()}return new Response(null,{status:202})}let V=`${H.id}:${String(Y.id)}`,I=new AbortController;this.inflight.set(V,I);let C=AbortSignal.any([I.signal,Z.signal]);try{return await this.respond(Y,async(P,x)=>this.legacy({principal:G,caller:X,message:Y,params:K,era:{modern:!1,session:H.state,sessionId:H.id},stream:P,signal:x}),iZ(K)||z8(this.registry,Y,H.state),C,()=>this.inflight.delete(V))}catch(P){throw this.inflight.delete(V),P}}async modern(Z){switch(Z.message.method){case"server/discover":return this.complete({supportedVersions:UZ,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:this.registry.list(Z.caller).map(($)=>IZ($,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool(Z);default:throw new J(N.MethodNotFound,`Method not found: ${Z.message.method}`,void 0,404)}}async legacy(Z){switch(Z.message.method){case"ping":return{};case"tools/list":return{tools:this.registry.list(Z.caller).map(($)=>IZ($,!1))};case"tools/call":return await this.callTool(Z);default:throw new J(N.MethodNotFound,`Method not found: ${Z.message.method}`)}}complete(Z){return{resultType:"complete",...Z,_meta:{[BZ]:this.serverInfo}}}initialize(Z,$,G){let W=$.protocolVersion,z=n.includes(W)?W:n[0],X=O($.capabilities)?$.capabilities:{},Y={v:z,e:pZ(X.elicitation),p:s(G),exp:Date.now()+a3},K=JZ(mZ,"gms1",Y);return S({jsonrpc:"2.0",id:Z.id,result:{protocolVersion:z,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session(Z,$){let G=Z.headers.get("mcp-session-id");if(!G)throw new J(N.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let W=FZ(mZ,"gms1",G);if(!W||W.p!==s($))throw new J(N.InvalidRequest,"Session not found.",void 0,404);return{id:G,state:W}}checkModernHeaders(Z,$,G){if(!HZ.includes(G))throw new J(N.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:UZ,requested:G},400);let W=(Y)=>new J(N.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if(Z.headers.get("mcp-protocol-version")!==G)throw W("MCP-Protocol-Version does not match the protocol version in _meta.");if(Z.headers.get("mcp-method")!==$.method)throw W("Mcp-Method does not match the method.");let z=$.params??{},X=$.method==="tools/call"||$.method==="prompts/get"?z.name:$.method==="resources/read"?z.uri:void 0;if(X!==void 0){let Y=Z.headers.get("mcp-name");if(Y===null||vZ(Y)!==X)throw W("Mcp-Name does not match the request's name.")}}async callTool(Z){let{params:$,caller:G,principal:W}=Z,z=$.name;if(typeof z!=="string")throw new J(N.InvalidParams,"tools/call needs a tool name.");let X=$.arguments??{},Y=this.registry.list(G,{names:[z]})[0];if(!Y)throw new J(N.InvalidParams,`Unknown tool: ${z}`);let K=!1;if(Y.requiresApproval){let I=Y.inputSchema.safeParse(X);if(I.ok===!1)return this.toolResult(Z,{content:[{type:"text",text:`Invalid arguments for "${z}": ${I.errors.join(", ")}`}],isError:!0});let C=await this.approval(Z,Y,X);if(C.kind==="answer")return C.result;K=!0}let U=X8(Z),H;try{H=await this.registry.execute(G,z,X,void 0,{approved:K,signal:Z.signal,...U?{progress:U}:{}})}catch(I){if(I instanceof L)return this.toolResult(Z,{content:[{type:"text",text:I.message}],isError:!0});if(I instanceof d)throw new J(N.InvalidParams,I.reason==="unknown-tool"?`Unknown tool: ${z}`:I.message);return console.error(`[gemi/mcp] "${z}" failed for ${W.via}:${W.id}:`,I),this.toolResult(Z,{content:[{type:"text",text:`"${z}" failed on the server.`}],isError:!0})}let Q=typeof H==="string"?H:JSON.stringify(H??null),V=Y.outputSchema&&(Z.era.modern||O(H))?{structuredContent:H}:{};return this.toolResult(Z,{content:[{type:"text",text:Q}],...V,isError:!1})}toolResult(Z,$){return Z.era.modern?this.complete($):$}async approval(Z,$,G){let W=Y8($,G),z=(H)=>({kind:"answer",result:this.toolResult(Z,{content:[{type:"text",text:H}],isError:!0})});if(Z.era.modern){let H=O(Z.params._meta)?Z.params._meta:{},Q=O(H[VZ])?H[VZ]:{},V=O(Z.params.inputResponses)?Z.params.inputResponses:null,I=Z.params.requestState,C=W8(G);if(V&&I!==void 0){let x=FZ(NZ,"grs1",I);if(!x||x.p!==s(Z.principal)||x.t!==$.name||x.a!==C)throw new J(N.InvalidParams,"requestState is not valid for this call.");if(!await this.spendNonce(x.n,x.exp))throw new J(N.InvalidParams,"requestState has already been used.");return lZ(V[dZ])?{kind:"approved"}:z(`The user did not approve "${$.name}", and it did not run.`)}if(!pZ(Q.elicitation))throw new J(N.MissingRequiredClientCapability,`"${$.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400);let P={p:s(Z.principal),t:$.name,a:C,n:hZ(16).toString("base64url"),exp:Date.now()+uZ};return{kind:"answer",result:{resultType:"input_required",inputRequests:{[dZ]:{method:"elicitation/create",params:{mode:"form",...W}}},requestState:JZ(NZ,"grs1",P),_meta:{[BZ]:this.serverInfo}}}}let X=Z.era;if(!X.session.e||!Z.stream)return z(`"${$.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`);let Y=`gemi-approval-${hZ(12).toString("base64url")}`,K=X.sessionId,U=await new Promise((H)=>{let Q=setTimeout(()=>{this.pending.delete(Y),H(null)},this.approvalTimeoutMs),V=(I)=>{clearTimeout(Q),H(I)};this.pending.set(Y,{session:K,resolve:V}),Z.signal.addEventListener("abort",()=>{this.pending.delete(Y),V(null)}),Z.stream.send({jsonrpc:"2.0",id:Y,method:"elicitation/create",params:X.session.v==="2025-11-25"?{mode:"form",...W}:W})});return U&&!U.error&&lZ(U.result)?{kind:"approved"}:z(`The user did not approve "${$.name}", and it did not run.`)}async spendNonce(Z,$){try{return await this.nonces.consume(Z,$)}catch(G){return console.error("[gemi/mcp] Spending an approval failed:",G),!1}}async respond(Z,$,G,W,z){if(!G)try{let U=await $(null,W);return S({jsonrpc:"2.0",id:Z.id,result:U},200)}finally{z?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,W]),K=new eZ(()=>X.abort());return(async()=>{try{let U=await $(K,Y);K.send({jsonrpc:"2.0",id:Z.id,result:U})}catch(U){if(U instanceof J)K.send(T(Z.id,U));else console.error("[gemi/mcp] The MCP endpoint failed:",U),K.send(T(Z.id,new J(N.InternalError,"Internal error.")))}finally{z?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized(Z){let $=this.resolvers.map((W)=>W.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',G=Z?`${$}, error="invalid_token", error_description="${Z.replace(/["\\]/g,"")}"`:$;return S(T(null,new J(N.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":G})}async failedAttempt(Z){let $=sZ(new PZ(Z,{},"api",this.endpoint.pathname)),G=await KZ(`mcp-auth-failed:${$}`,e3);return G===null?null:nZ(G)}async spend(Z){if(!this.rateLimit)return null;let $=await KZ(`mcp-endpoint:${Z.via}:${Z.id}`,this.rateLimit);return $===null?null:nZ($)}}class eZ{readable;controller;closed=!1;encoder=new TextEncoder;constructor(Z){this.readable=new ReadableStream({start:($)=>{this.controller=$},cancel:()=>{this.closed=!0,Z()}})}send(Z){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
3
- data: ${JSON.stringify(Z)}
4
-
5
- `))}close(){if(this.closed)return;this.closed=!0,this.controller.close()}}class o extends Error{}async function Z8(Z,$){let G=Number(Z.headers.get("content-length"));if(Number.isFinite(G)&&G>$)throw new o;if(!Z.body)return"";let W=Z.body.getReader(),z=[],X=0;for(;;){let{done:Y,value:K}=await W.read();if(Y)break;if(X+=K.byteLength,X>$)throw await W.cancel(),new o;z.push(K)}return Buffer.concat(z).toString("utf8")}function S(Z,$,G={}){return new Response(JSON.stringify(Z),{status:$,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...G}})}function cZ(Z,$){for(let[G,W]of Object.entries($))Z.headers.set(G,W);return Z}function $8(Z){return{"Access-Control-Allow-Origin":Z,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function G8(Z){let $;try{$=new URL(Z)}catch{throw Error(`route.mcp.remote.url: "${Z}" is not a URL.`)}let G=$.hostname==="localhost"||$.hostname==="127.0.0.1"||$.hostname==="[::1]";if($.protocol!=="https:"&&!($.protocol==="http:"&&G))throw Error("route.mcp.remote.url must be https (http only on localhost): tokens travel to it.");if($.search||$.hash||$.username||$.password)throw Error("route.mcp.remote.url must have no query, fragment or credentials.");if($.pathname==="/"||$.pathname.endsWith("/"))throw Error('route.mcp.remote.url needs a path of its own, like "/mcp", without a trailing slash.');return $}function s(Z){return rZ("sha256").update(`${Z.via}\x00${Z.id}\x00${Z.user?.id}`).digest("base64url").slice(0,32)}function W8(Z){return rZ("sha256").update(aZ(Z??{})).digest("base64url")}function pZ(Z){if(!O(Z))return!1;if(Object.keys(Z).length===0)return!0;return"form"in Z}function iZ(Z){let $=O(Z._meta)?Z._meta:{};return typeof $.progressToken==="string"||typeof $.progressToken==="number"}function z8(Z,$,G){if($.method!=="tools/call"||!G.e)return!1;let W=$.params?.name;return typeof W==="string"&&Z.descriptors({names:[W]})[0]?.requiresApproval===!0}function X8(Z){let G=(O(Z.params._meta)?Z.params._meta:{}).progressToken;if(!Z.stream||typeof G!=="string"&&typeof G!=="number")return;let W=-1/0;return(z)=>{if(typeof z?.progress!=="number"||!Number.isFinite(z.progress)||z.progress<=W)return;W=z.progress,Z.stream.send({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:G,progress:z.progress,...typeof z.total==="number"?{total:z.total}:{},...typeof z.message==="string"?{message:z.message.slice(0,1000)}:{}}})}}function Y8(Z,$){let G=JSON.stringify($??{},null,1),W=G.length>xZ?`${G.slice(0,xZ)}\u2026 (${G.length-xZ} more characters not shown)`:G;return{message:`Allow "${Z.title??Z.name}" to run? ${Z.description}
6
-
7
- Arguments: ${W}`,requestedSchema:{type:"object",properties:{approve:{type:"boolean",title:"Approve",description:`Run "${Z.title??Z.name}" with these arguments.`}},required:["approve"]}}}function lZ(Z){return O(Z)&&Z.action==="accept"&&O(Z.content)&&Z.content.approve===!0}function nZ(Z){return S(T(null,new J(N.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String(Z)})}async function K8(Z,$={}){try{if(!await Z.shouldRun.call(Z))return}catch(z){console.error(`Error evaluating shouldRun for cron job ${Z.name}:`,z);return}let G=H8(Z.withoutOverlapping);if(!Z.onOneServer&&G===void 0){await CZ(Z);return}let W;try{if(W=$.locks?.()??U8(),Z.onOneServer){let z=Math.floor(($.now??Date.now())/60000);if(!await W.store.advance(`gemi:cron-tick:${Z.name}`,z))return}}catch(z){console.error(`Could not claim the tick of cron job ${Z.name}; skipped it:`,z);return}if(G===void 0){await CZ(Z);return}try{await W.run(`gemi:cron:${Z.name}`,{ttl:G},(z)=>CZ(Z,z))}catch(z){if(z instanceof G3)console.error(`Cron job ${Z.name} lost its withoutOverlapping lock while running: another tick may have started alongside it.`,z);else console.error(`Could not take the withoutOverlapping lock of cron job ${Z.name}:`,z)}}var Z3=300000;function H8(Z){if(!Z)return;if(Z===!0)return Z3;return Z.expiresAfter??Z3}var $3;function U8(){return $3??=new k(new W3),$3}async function CZ(Z,$){try{await Z.onTick.call(Z)}catch(G){console.error(`Error executing cron job ${Z.name}:`,G)}try{await Z.callback.call(Z,$)}catch(G){console.error(`Error in cron job ${Z.name}:`,G)}try{await Z.onComplete.call(Z)}catch(G){console.error(`Error completing cron job ${Z.name}:`,G)}}class R{static token="scheduler";handles=[];resolved;inFlight=new Map;stopped=!1;locks;constructor(Z){this.resolved=Z.jobs}get jobs(){return[...this.resolved]}useJobs(Z){this.resolved=Z}useLocks(Z){this.locks=Z}start(Z=($)=>$()){if(this.stopped=!1,this.resolved.length===0)return;let $=globalThis.__gemiCronJobs??=new Map,G=new Map;for(let W of this.resolved){let z=new W;if(!z.name){console.error(`Cron job must have a name \u2014 ${W.name||"an anonymous class"} has none, so it is not scheduled. If this is a base class that other jobs extend, move it out of the discovered directory: \`abstract\` does not survive to runtime, so a class under app/cron is indistinguishable from a job.`);continue}if(!z.cron){console.error(`Cron job must have an expression. Job: ${z.name}`);continue}let X=G.get(z.name);if(X!==void 0){console.error(`Two cron jobs claim the name "${z.name}" \u2014 ${X} is scheduled and ${W.name||"an anonymous class"} is not. A name is the scheduler's key, so only one job can hold it. Rename one.`);continue}G.set(z.name,W.name||"an anonymous class"),$.get(z.name)?.stop();let Y=Bun.cron(z.cron,()=>{if(this.stopped)return;let K=this.locks;return this.track(z.name,()=>Z(()=>K8(z,{locks:K})))});$.set(z.name,Y),this.handles.push(Y)}}stop(){this.stopped=!0;for(let Z of this.handles)Z.stop();this.handles=[]}async drain(Z=1/0){this.stop();let $,G=new Promise((W)=>{if(Z!==1/0)$=setTimeout(W,Z)});return await Promise.race([Promise.allSettled([...this.inFlight.values()].map((W)=>W.done)),G]),clearTimeout($),{unfinished:[...this.inFlight.values()].map((W)=>({...W.tick}))}}get running(){return this.inFlight.size}track(Z,$){let G={},W=Promise.resolve().then($).finally(()=>this.inFlight.delete(G));return this.inFlight.set(G,{tick:{name:Z,startedAt:new Date},done:W}),W}}import{isMainThread as Q8}from"worker_threads";var V8=100,B8=(Z)=>Math.min(V8,Math.floor(Z/10));class I8 extends F{register(){this.app.singleton(D,()=>new D(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(k,()=>this.app.make(D).locks)}async boot(){let Z=this.app.config.get("queue",{});if(Z.jobs!==void 0)return;let{jobsDir:$}=_(z3(),Z);this.app.make(D).useJobs(await U3($))}async shutdown(Z){if(!this.app.resolved(D))return;let $=this.app.make(D);if($.running>0)console.log(`[gemi] Shutting down: waiting for ${$.running} running queued job(s).`);let G=Z?.timeoutMs,{unfinished:W}=await $.drain(G===void 0?1/0:Math.max(0,G-B8(G)));if(W.length>0)return console.error("[gemi] Queued jobs still running at shutdown: "+W.map((z)=>`${z.name} (${z.id})`).join(", ")),{abandoned:!0}}}function _9(Z){if(F8(Z),Bun.env.NODE_ENV!=="production")return N8(Z);if(Q3(Z))return;if(!Y3())return;if(!Z.bound(D))return;Z.make(D).start()}function Q3(Z){let $=Z.config.get("queue",{}).driver??"memory";return $==="memory"||$ instanceof X3}function J8(Z){if(Q3(Z))return!0;if(typeof Z.config.get("queue",{}).driver!=="function"||!Z.bound(D))return!1;try{return!Z.make(D).durable}catch{return!1}}function F8(Z){let $=process.env.GEMI_QUEUE_CLAIM;if($===void 0||H3())return;if(process.env.ROOT_DIR===void 0||!Q8)return;if(K3()){if(!J8(Z))return;console.warn('[gemi] GEMI_QUEUE_CLAIM=off is ignored: the memory queue driver keeps jobs in the process that dispatched them, so no worker could run them. This server runs its own jobs. Use a driver other processes can read, such as "database", to hand jobs to `gemi queue:work`.')}else if($.trim().toLowerCase()!=="on")console.warn(`[gemi] GEMI_QUEUE_CLAIM="${$}" is not "off" or "on", so this server claims jobs. Set it to "off" to leave them to \`gemi queue:work\`.`)}function N8(Z){let $=globalThis.__gemiDevQueue;if(!$)return;if(globalThis.__gemiDevQueue=void 0,$.stop(),Z.bound(D))Z.make(D).start()}class x8 extends F{register(){this.app.singleton(p,()=>new p(this.app.config.get("changeFeed",{}),{application:this.app}))}async shutdown(){if(!this.app.resolved(p))return;await this.app.make(p).close()}}class P8 extends F{register(){this.app.singleton(_Z,()=>new _Z(this.app.config.get("auth",{})))}}var C8=100,_8=(Z)=>Math.min(C8,Math.floor(Z/10));class D8 extends F{register(){this.app.singleton(R,()=>new R(_(DZ(),this.app.config.get("schedule",{}))))}async boot(){let Z=this.app.make(R),$=this.app.config.get("schedule",{});if($.jobs===void 0){let{jobsDir:W}=_(DZ(),$);Z.useJobs(await B3(W))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let G=this.app;if(G.bound(k))Z.useLocks(()=>G.make(k));Z.start((W)=>V3.run(G,W))}async shutdown(Z){if(!this.app.resolved(R))return;let $=this.app.make(R);if($.running>0)console.log(`[gemi] Shutting down: waiting for ${$.running} running cron tick(s).`);let G=Z?.timeoutMs,{unfinished:W}=await $.drain(G===void 0?1/0:Math.max(0,G-_8(G)));if(W.length>0)return console.error("[gemi] Cron jobs still running at shutdown: "+W.map((z)=>`${z.name} (started ${z.startedAt.toISOString()})`).join(", ")),{abandoned:!0}}}class h extends J3{modelName;constructor(Z="FeatureFlag"){super();this.modelName=Z}get available(){return I3(this.modelName)}async load(){if(!this.available)throw new LZ(this.modelName);let Z=AZ(this.modelName);return await Z.asSystem(()=>Z.findMany())}async write(Z,$,G){if(!this.available)throw new LZ(this.modelName);let W=AZ(this.modelName),z=this.hasActorColumn(W),X={active:$};if(z)X.updatedBy=G.actor;return await W.asSystem(()=>W.upsert({where:{key:Z},create:{key:Z,...X},update:X})),{actorRecorded:z}}hasActorColumn(Z){let $=Z?.$schema?.fields?.updatedBy;return $!==void 0&&$.type==="String"}}function m9(Z){return Z}function F3(){return{features:void 0,enabled:!0,source:new h,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class A8 extends F{register(){this.app.singleton(r,()=>{let Z=this.app.config.get("features",{}),$=_(F3(),Z);if(Z?.model!==void 0&&Z?.source===void 0)$.source=new h(Z.model);else if(Z?.model!==void 0&&Z.source instanceof h&&Z.source.modelName!==Z.model)a.warning(`app/config/features.ts sets \`model: "${Z.model}"\` and a source reading "${Z.source.modelName}". The source wins; drop \`model\` to silence this.`);return new r($,(G)=>a.warning(G))})}async boot(){let Z=this.app.make(r);if(!Z.config.enabled)return;try{await Z.refresh()}catch($){a.error(`Could not warm the feature flag cache at boot. ${$ instanceof Error?$.message:String($)}`)}}}class L8 extends F{register(){this.app.singleton(OZ,()=>new OZ(this.app.config.get("mail",{})))}}function O8(Z){return`listener:${Z}`}function x3(Z,$){q8(Z);let{maxAttempts:G,backoff:W,worker:z}=$,X=Z.event.name,Y=class extends N3{maxAttempts=G;backoff=W;worker=z;async run(...K){let[U,H]=T8(K),Q=g(E).rehydrate(U,H);await new Z().handle(Q)}onFail(K){console.error(`The listener ${Z.name} threw while handling ${X} off the queue. The queue will retry it up to ${G} times in total; nothing the dispatcher did is waiting on it.`,K)}onDeadletter(K){console.error(`The listener ${Z.name} failed every one of its ${G} attempts at ${X} and has been dead-lettered, so this side effect did not happen and will not be retried.`,K)}};return Object.defineProperty(Y,"name",{value:O8(Z.name),writable:!0}),Y}function q8(Z){if(Object.getOwnPropertyDescriptor(Z,"name")?.writable)return;throw Error(`The listener ${Z.name} sets \`queued = true\` but does not declare \`static name\`, so it would be registered with the queue `+"under its class name \u2014 which a production build renames while the "+`payload that names it does not. Add: static name = "${Z.name}";`)}function T8(Z){return typeof Z[0]==="string"?Z:Z[0]}class E{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor(Z={}){this.config=_(e(),Z),this.useListeners(this.config.listeners)}useListeners(Z){this.config.listeners=Z,this.listeners={},this.events={};let $=new Set;for(let G of Z){if(!G.event){console.error(`Listener ${G.name} does not declare \`static event\`, so there is no event name to register it under and its handle will never run. Add: static event = SomeEvent;`);continue}if($.has(G.name)){console.error(`Two event listeners are named "${G.name}" \u2014 the first is `+"registered and this one is not. A listener's name identifies it across the framework, so only one class can hold it. Rename one.");continue}$.add(G.name);let W=G.event.name,z=new G;this.events[W]??=G.event,(this.listeners[W]??=[]).push({listener:G,job:z.queued?x3(G,z):null})}}get queuedListenerJobs(){return Object.values(this.listeners).flat().flatMap(({job:Z})=>Z?[Z]:[])}get registeredListeners(){return[...this.config.listeners]}dispatch(Z,$){if(this.deferToCommit(Z,$,!1))return;this.runListeners(Z,$)}async dispatchAndWait(Z,$){if(this.deferToCommit(Z,$,!0))return;return this.runListeners(Z,$)}deferToCommit(Z,$,G){let{name:W,afterCommit:z}=Z.constructor;if(!z)return!1;let X=P3(()=>this.runListeners(Z,$));if(X&&G)this.warnNothingIsWaitedFor(W);return X}async runListeners(Z,$){let G=Z.constructor.name,W=this.listeners[G];if(!W?.length){this.warnNothingIsListening(G);return}for(let{listener:z,job:X}of W){if(X){this.enqueue(X,z,G,$);continue}try{await new z().handle(Z)}catch(Y){console.error(`The listener ${z.name} threw while handling ${G}. The `+"listeners after it still ran \u2014 a listener's failure is its own.",Y)}}}rehydrate(Z,$=[]){let G=this.events[Z];if(!G)throw Error(`Cannot rebuild the event "${Z}" that came off the queue: no registered listener binds to an event of that name, so there is no class to construct. A queued listener runs in an application that `+"discovered its own listeners \u2014 check that this process sees the "+`same app/listeners as the one that dispatched, and that the event declares \`static name = "${Z}"\`.`);return new G(...$)}enqueue(Z,$,G,W){if(W===void 0){console.error(`The listener ${$.name} is queued, but ${G} reached the dispatcher without its constructor arguments, so there is nothing for the queue to rebuild it from and the listener was skipped. Dispatch through ${G}.dispatch(...) or ${G}.dispatchAndWait(...), which carry them.`);return}let z=(X)=>console.error(`The listener ${$.name} could not be queued for ${G}, so it did not run and will not be retried. The listeners after it still ran.`,X);try{g(D).push(Z,JSON.stringify([G,W]),{reportFailure:!1}).catch(z)}catch(X){z(X)}}warnNothingIsWaitedFor(Z){if(Bun.env.NODE_ENV==="production")return;if(this.warnedAboutWaiting.has(Z))return;this.warnedAboutWaiting.add(Z),console.warn(`[gemi] ${Z}.dispatchAndWait() was called inside a transaction and ${Z} declares \`static afterCommit = true\`, so it resolved `+"immediately with no listener having run \u2014 they run when the "+"transaction commits. Await the transaction instead, or drop afterCommit if the caller needs the side effects first. Development only.")}warnNothingIsListening(Z){if(Bun.env.NODE_ENV==="production")return;if(this.warnedFor.has(Z))return;this.warnedFor.add(Z),console.warn(`[gemi] ${Z} was dispatched and nothing is listening for it. A listener registers under the name its event declares, so check that app/listeners holds a Listener with \`static event = ${Z}\` and that ${Z} declares \`static name = "${Z}"\`. Development only.`)}}class S8 extends F{register(){this.app.singleton(E,()=>new E(this.app.config.get("events",{})))}async boot(){let Z=this.app.make(E),$=this.app.config.get("events",{});if($.listeners===void 0){let{listenersDir:z}=_(e(),$);Z.useListeners(await C3(z))}let G=Z.queuedListenerJobs;if(G.length===0)return;let W=this.app.make(D);for(let z of G)W.registerJob(z)}}class j8 extends F{register(){this.app.singleton(qZ,()=>new qZ(this.app.config.get("filesystem",{})))}}class M8 extends F{register(){this.app.singleton(TZ,()=>new TZ(this.app.config.get("image",{})))}}class k8 extends F{register(){this.app.instance(SZ,new SZ)}}function T$(Z){return Z}function _3(){return{maxFileSize:10485760,onLogFileClosed:()=>{},onLogCreated:()=>{}}}class R8 extends F{register(){this.app.singleton(ZZ,()=>new ZZ(_(_3(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(ZZ).boot()}}class E8 extends F{register(){this.app.singleton($Z,()=>new $Z(_(D3(),this.app.config.get("middleware",{}))))}boot(){this.app.make($Z).assertGlobalMiddleware()}}function h$(Z){return Z}function L3(){return{driver:new A3,limit:1000,window:60}}class w8 extends F{register(){this.app.singleton(v,()=>new v(_(L3(),this.app.config.get("ratelimiter",{}))))}}function l$(Z){return Z}function O3(){return{url:process.env.REDIS_URL,options:void 0}}class b8 extends F{register(){this.app.singleton(i,()=>new i(_(O3(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(i))return;this.app.make(i).close()}}function GZ(Z,$){let G=Z.get($);if(!G)throw Error(`Missing "${$}" configuration. Route dispatching needs a root router \u2014 declare it in "app/config/route.ts".`);return G}class y8 extends F{register(){this.app.singleton(m,()=>new m(GZ(this.app.config,"route.api"))),this.app.singleton(l,()=>new l(GZ(this.app.config,"route.view"))),this.app.singleton(WZ,()=>new WZ({api:this.app.make(m),view:this.app.make(l)},{api:GZ(this.app.config,"route.api"),view:GZ(this.app.config,"route.view"),domains:this.app.config.get("route.domains")})),this.app.singleton(f,()=>{let Z=this.app.config.get("route.mcp");if(!Z?.router)throw Error('No MCP router is configured. Declare one as `mcp: { router }` in "app/config/route.ts".');return new f(new Z.router,this.app.make(m),{files:Z.remote?.files})}),this.registerMcpHttp()}registerMcpHttp(){this.app.singleton(c,()=>{let Z=this.app.config.get("route.mcp");if(!Z?.remote?.enabled)throw Error("The MCP endpoint is not enabled: set route.mcp.remote.enabled.");return new c(this.app.make(f),Z.remote)})}boot(){if(this.app.make(m),this.app.make(l),this.app.make(WZ),this.app.config.get("route.mcp"))this.app.make(f);let Z=this.app.config.get("route.mcp.remote");if(Z?.enabled===!0)this.app.make(c);else if(Z?.enabled!==void 0&&Z.enabled!==!1)throw Error("route.mcp.remote.enabled must be true or false.")}}
8
- export{T3 as hb,L as ib,d as jb,f as kb,YZ as lb,n3 as mb,KZ as nb,JZ as ob,FZ as pb,c as qb,R as rb,I8 as sb,_9 as tb,x8 as ub,P8 as vb,D8 as wb,h as xb,m9 as yb,F3 as zb,A8 as Ab,L8 as Bb,E as Cb,S8 as Db,j8 as Eb,M8 as Fb,k8 as Gb,T$ as Hb,_3 as Ib,R8 as Jb,E8 as Kb,h$ as Lb,L3 as Mb,w8 as Nb,l$ as Ob,O3 as Pb,b8 as Qb,y8 as Rb};
9
-
10
- //# debugId=B4C295A9D161FC3A64756E2164756E21
@@ -1,5 +0,0 @@
1
- // @bun
2
- import{Af as _,Ef as R,Ff as W,Gf as F,Hf as C,If as G,Jf as Y,Kf as N,Lf as S,Rf as K,ef as O,ff as Z}from"./chunk-hytt9qyj.js";import{si as P}from"./chunk-vw8849ys.js";var E={};P(E,{registeredNames:()=>b,register:()=>T,has:()=>y,get:()=>A,clearRegistry:()=>x});var J=new Map;function T(q,z){J.set(q,z)}function y(q){return J.has(q)}function A(q){let z=J.get(q);if(z===void 0)throw new _(q,[...J.keys()]);return z}function b(){return[...J.keys()]}function x(){J.clear()}var w=/^\s*::\s*(?:text\s*::\s*)?(jsonb|json)\b(?!\s*\[)/i,h=/^\s*as\s+(jsonb|json)\s*\)/i,c=/\bcast\s*\(\s*$/i,f=new Set;function U(q,z){if(!z.typesParametersFromStatement)return{fragment:q,jsonParameters:f};let B=C(q),D=new Set,H;for(let X=0;X<B.length-1;X++){let $=B[X+1],Q=w.exec($);if(Q){H??=[...B],H[X+1]=`::text::${Q[1]}${$.slice(Q[0].length)}`,D.add(X);continue}let V=h.exec($);if(V&&c.test((H??B)[X]))H??=[...B],H[X+1]=` as text)::${V[1]}${$.slice(V[0].length)}`,D.add(X)}if(!H)return{fragment:q,jsonParameters:D};return{fragment:G(H,q.binders),jsonParameters:D}}function M(q,z){if(q===null||q===void 0)return null;let B=K(q);if(B==="db")return null;if(B==="json")return"null";if(B==="any")throw new Z(z,"DB",z,"Prisma.AnyNull is a filter operand \u2014 it asks for a SQL NULL *or* a JSON "+"null \u2014 so it has no single value to bind. Write the one you mean: "+"Prisma.DbNull for the column being NULL, Prisma.JsonNull for the JSON value.");if(typeof q==="string")return q;let D;try{D=JSON.stringify(q)}catch(H){throw new Z(z,"DB",z,`A parameter cast to json could not be serialised: ${H instanceof Error?H.message:String(H)}. `+"Bind text you have serialised yourself if the value is not JSON \u2014 a "+"bigint has no JSON form, and neither does a cycle.")}if(D===void 0)throw new Z(z,"DB",z,`A ${typeof q} was bound to a parameter cast to json, and has no JSON form. Bind the value it stands for.`);return D}var I=new WeakSet;function L(q){return I.add(q),q}function k(q){return typeof q==="object"&&q!==null&&I.has(q)}function t(q,...z){if(!Array.isArray(q)||!("raw"in q))throw new O("sql","DB","sql","'sql' is a tagged template \u2014 write sql`select 1`, not sql(\"select 1\"). "+"To put text that is not a value into a statement, use 'unsafeSql', and read what it says first.");let B=[];for(let D=0;D<q.length;D++)if(B.push(W(q[D])),D<z.length)B.push(j(z[D]));return L(Y(...B))}function r(q,z=", "){if(!Array.isArray(q))throw new Z("join","DB","sql",`Expected an array of fragments or values, got ${typeof q}.`);if(q.length===0)return p;let B=q.map(j);if(k(z)){let D=[];for(let H=0;H<B.length;H++){if(H>0)D.push(z);D.push(B[H])}return L(Y(...D))}return v(z),L(N(B,z))}var g=/^[\s,]*$|^\s*(?:and|or)\s*$/i;function v(q){if(typeof q==="string"&&g.test(q))return;throw new Z("join","DB","sql",typeof q==="string"?`A separator is written into the SQL text, so it may only be glue: whitespace, commas, or 'and' / 'or'. Got ${JSON.stringify(q)}. If that is deliberate, say so with `+"unsafeSql(...) \u2014 and never build one from anything that came from "+"outside the program.":`Expected a separator string or a fragment, got ${q===null?"null":typeof q}.`)}var p=L(Object.freeze({text:"",binders:Object.freeze([])}));function a(q){if(typeof q!=="string")throw new Z("unsafeSql","DB","sql",`Expected a string literal, got ${Array.isArray(q)?"an array":typeof q}. 'unsafeSql' is a plain call, not a tagged template \u2014 a template would `+"interpolate values into the SQL text, which is the one thing it must never do.");return L(W(q))}function e(q,z,B="query"){if(!k(q))throw new Z(B,"DB",B,`Expected a fragment built with 'sql', got ${q===null?"null":typeof q}. A plain string is not accepted here on purpose \u2014 it would be the one `+"path into the SQL text that nobody had to think about.");let D=U(q,z),H=S(D.fragment,z,{model:"DB",operation:B});return{text:H.text,values:R(H.binders)(void 0).map((X,$)=>D.jsonParameters.has($)?M(X,B):X===null||X===void 0?X??null:z.encodeUntyped(X))}}function j(q){if(k(q))return q;return F(()=>q)}
3
- export{T as We,y as Xe,A as Ye,b as Ze,E as _e,t as $e,r as af,p as bf,a as cf,e as df};
4
-
5
- //# debugId=FB86B3DB3224645264756E2164756E21
@@ -1,24 +0,0 @@
1
- // @bun
2
- import{S as D,T as KJ,U as OJ}from"./chunk-jafm3613.js";import{na as B,ra as L,sa as UJ}from"./chunk-frerzsxq.js";import{Ca as e}from"./chunk-4mfrgd5m.js";import"./chunk-5stgtwqw.js";import{Nc as a,qe as QJ,re as A}from"./chunk-d6591xck.js";import"./chunk-whtzggn6.js";import"./chunk-hytt9qyj.js";import{cg as o,dg as n,gg as i}from"./chunk-dexdkh3z.js";import{Tg as WJ}from"./chunk-15c2vgaf.js";import"./chunk-9b4erdy2.js";import"./chunk-tn2bryy2.js";import"./chunk-cbqazg9k.js";import"./chunk-1myhm0g3.js";import"./chunk-kejwjerj.js";import"./chunk-aazmrxj9.js";import"./chunk-7g9yh5ae.js";import"./chunk-t4yh4nf9.js";import"./chunk-1vzks22y.js";import"./chunk-zyt2w03d.js";import{ni as YJ}from"./chunk-1hr4xht1.js";import{oi as N}from"./chunk-d9mar37g.js";import"./chunk-vw8849ys.js";import{join as w,resolve as VJ,sep as zJ}from"path";import{Duplex as qJ}from"stream";import{constants as P,createBrotliCompress as TJ,createGzip as RJ}from"zlib";var bJ=["br","gzip"],kJ=1024,SJ=5,wJ=19,vJ=6;function EJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function yJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[X,...Q]=Z.split(";"),W=X.trim().toLowerCase();if(W==="")continue;let j=1;for(let Y of Q){let K=Y.indexOf("=");if(K===-1)continue;if(Y.slice(0,K).trim().toLowerCase()==="q"){j=EJ(Y.slice(K+1));break}}$.set(W,j)}return $}function b(J,$=bJ){let Z=yJ(J);if(!Z)return null;let X=Z.get("*"),Q=null,W=0;for(let j of $){let Y=Z.get(j)??X??0;if(Y>W)Q=j,W=Y}return Q}function gJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function fJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let X=$.headers.get("Content-Encoding");if(X&&X.trim().toLowerCase()!=="identity")return!1;if(gJ($.headers.get("Cache-Control"),"no-transform"))return!1;let Q=$.headers.get("Content-Length");if(Q!==null&&Number(Q)<kJ)return!1;return!0}function mJ(J){let $=J==="br"?TJ({params:{[P.BROTLI_PARAM_QUALITY]:SJ,[P.BROTLI_PARAM_LGWIN]:wJ},flush:P.BROTLI_OPERATION_FLUSH}):RJ({level:vJ,flush:P.Z_SYNC_FLUSH});return qJ.toWeb($)}function uJ(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((X)=>X.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function c(J,$){if(!fJ(J.method,$))return $;let Z=new Headers($.headers);uJ(Z);let X=b(J.headers.get("Accept-Encoding"));if(!X)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let Q;try{Q=mJ(X)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",X),Z.delete("Content-Length"),new Response($.body.pipeThrough(Q),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as nJ,stat as t}from"fs/promises";import{join as iJ}from"path";import{mkdir as U2,readFile as hJ,stat as K2,writeFile as O2}from"fs/promises";import{dirname as z2,join as cJ}from"path";import{promisify as p}from"util";import{brotliCompress as pJ,constants as C2,gzip as dJ}from"zlib";var lJ=".vite/static-assets.json";var d={br:".br",gzip:".gz"},oJ=["br","gzip"],I2=p(pJ),F2=p(dJ);async function l(J){let $;try{$=await hJ(cJ(J,lJ),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let X={files:{}};for(let[Q,W]of Object.entries(Z)){if(!Array.isArray(W))continue;X.files[Q]=oJ.filter((j)=>W.includes(j))}return X}function k(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function r(J){let $=new Set;async function Z(X,Q){let W;try{W=await nJ(X,{withFileTypes:!0})}catch{return}for(let j of W){if(j.name.startsWith("."))continue;if(Q&&j.name==="assets")continue;let Y=iJ(X,j.name),K=j.isDirectory(),V=j.isFile();if(j.isSymbolicLink())try{let I=await t(Y);K=I.isDirectory(),V=I.isFile()}catch{continue}if(V)$.add(Y);else if(K&&!j.isSymbolicLink())await Z(Y,!1)}}return await Z(J,!0),$}var aJ="public, max-age=31536000, must-revalidate",tJ="public, max-age=31536000, immutable";async function rJ(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let X=b(J.headers.get("Accept-Encoding"),Z);if(!X)return null;let Q=$+d[X];try{let W=await t(Q);return W.isFile()?{encoding:X,path:Q,size:W.size}:null}catch{return null}}async function s(J,$,Z={}){let X=Bun.file($),Q=Z.encodings??[],W={"Content-Type":X.type||"application/octet-stream","Cache-Control":Z.immutable?tJ:aJ,"Accept-Ranges":"bytes"};if(Q.length>0)W.Vary="Accept-Encoding";let j=await rJ(J,$,Q);if(j){let V=Bun.file(j.path);return new Response(V.stream(),{headers:{...W,"Content-Encoding":j.encoding,"Content-Length":String(j.size),ETag:`${k(V.lastModified)}-${j.encoding}`}})}let Y=X.size;W.ETag=k(X.lastModified);let K=o(J.headers.get("Range"));if(K){let V=n(K,Y);if(!V)return a(Y);return new Response(X.slice(V.start,V.end+1).stream(),{status:206,headers:{...W,"Content-Range":i(V.start,V.end,Y),"Content-Length":String(V.length)}})}return new Response(X.stream(),{headers:{...W,"Content-Length":String(Y)}})}import{stat as Z2}from"fs/promises";var _="app/client.tsx";function JJ(J,$=B){let Z=J[_]?.file;if(!Z)return;return{module:L(Z,$),preload:M(J,_,$)}}function M(J,$,Z=B){let X=[],Q=new Set,W=(j)=>{if(Q.has(j))return;Q.add(j);let Y=J[j];if(!Y?.file)return;X.push(L(Y.file,Z));for(let K of Y.imports??[])W(K)};return W($),X}function $J(J,$){let Z=[],X=new Set,Q=new Set,W=(j)=>{if(Q.has(j))return;Q.add(j);let Y=J[j];if(!Y)return;for(let K of Y.imports??[])W(K);for(let K of Y.css??[])if(!X.has(K))X.add(K),Z.push(K)};return W($),Z}function ZJ(J,$=B){let Z=new Map;return(X)=>{if(!Z.has(X)){let Q=`${X}${e}`,W=J[Q]?.file;Z.set(X,W?{src:L(W,$),preload:M(J,Q,$)}:void 0)}return Z.get(X)}}function XJ(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),X=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var r=!1;try{var s=window.sessionStorage,m=JSON.parse(s.getItem(${Z})||"null");var d=m?Date.now()-m.at:NaN;if(navigator.onLine!==!1&&!(d>=0&&d<${$})){s.setItem(${Z},JSON.stringify({url:window.location.href,at:Date.now()}));r=!0}}catch(e){}if(r)window.location.reload();else throw new Error(${X});export {}`}var sJ=new RegExp(`^${QJ}/.+\\.m?js$`);function eJ(J){return sJ.test(J)}function HJ(J){if(eJ(J))return new Response(XJ(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(A(J))return new Response("Not found",{status:404});return}var J2=`<!DOCTYPE html>
3
- <html lang="en">
4
- <head>
5
- <meta charset="UTF-8" />
6
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
- <title>Internal Server Error</title>
8
- <style>
9
- body { font-family: system-ui, sans-serif; margin: 0; min-height: 100vh; display: grid; place-items: center; }
10
- main { text-align: center; padding: 16px; }
11
- h1 { font-size: 1.5rem; margin: 0 0 0.5rem; }
12
- p { margin: 0; opacity: 0.7; }
13
- </style>
14
- </head>
15
- <body>
16
- <main>
17
- <h1>Something went wrong</h1>
18
- <p>Please try again later.</p>
19
- </main>
20
- </body>
21
- </html>`;function S(J,$,Z){if(!Z)console.error(J);else try{Z(J instanceof Error?J:Error(String(J),{cause:J}))}catch(X){console.error(J),console.error(X)}if(N($))return new Response(JSON.stringify({error:WJ("server_error","Internal Server Error",500)}),{status:500,headers:{"Content-Type":"application/json"}});return new Response(J2,{status:500,headers:{"Content-Type":"text/html; charset=utf-8"}})}var $2={kind:"none"};function jJ(J){let $=(J??"").trim().toLowerCase();if($===""||$==="false"||$==="off"||$==="0")return $2;if($==="true")return{kind:"all"};if(/^[1-9]\d*$/.test($))return{kind:"hops",hops:Number($)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify(J)}.`)}function GJ(J,$,Z){if(Z.kind==="all"){if(!J.get("x-forwarded-for")&&$)J.set("x-forwarded-for",$);return}J.delete("x-real-ip");let X=$;if(Z.kind==="hops"){let Q=(J.get("x-forwarded-for")??"").split(",").map((j)=>j.trim()).filter(Boolean),W=Q.length-Z.hops;X=W>=0?Q[W]:Q[0]??$}if(X)J.set("x-forwarded-for",X);else J.delete("x-forwarded-for")}var q=YJ(),X2=w(q,"app"),x=w(q,"dist"),C=w(x,"client");function Q2(J){let $;try{$=decodeURIComponent(J)}catch{return null}let Z=VJ(C,"."+$.replace("/assets/assets","/assets"));return Z.startsWith(C+zJ)?Z:null}async function H2(J){try{return(await Z2(J)).isFile()}catch{return!1}}async function Z3(J,$){let Z=await import(`${x}/client/.vite/manifest.json`),X=await import(`${x}/server/.vite/manifest.json`),Q=await UJ(`${x}/client`);process.env.ROOT_DIR=q,process.env.APP_DIR=X2,process.env.DIST_DIR=x;let W={},j={},Y={},K={},V={},I=(H,G)=>`"${H}": () => import("${G}")`,v=[];for(let H of["404",...J.getFlatComponentTree.call(J)]){let G=X[`app/views/${H}.tsx`];if(!G?.file){console.log(`Server file not found for ${H}`),console.log(G);let z=Object.keys(X),F=`app/views/${H}.tsx`;console.log(`${F} not found in server manifest`),console.log(z)}let U=await import(`${process.env.DIST_DIR}/server/${G?.file}`);W[H]=U.default,j[H]=U.OpenGraph,Y[H]=U;let O=Z[`app/views/${H}.tsx`];if(O?.css&&O?.css.length>0)K[H]=O?.css;if(O)v.push(I(H,L(O?.file,Q))),V[H]=M(Z,`app/views/${H}.tsx`,Q)}let xJ=`{${v.join(",")}}`,E=JJ(Z,Q);if(!E)console.error(`Client manifest has no "${_}" entry \u2014 dist/client is incomplete, so documents will render but never hydrate.`);let LJ=Z["app/client.tsx"]?.css??[],y=(await Promise.all(LJ.map((H)=>Bun.file(`${x}/client/${H}`).text()))).join(`
22
- `),CJ=ZJ(Z,Q),g=new Map,IJ=(H)=>{let G=g.get(H);if(!G)G=Bun.file(`${x}/client/${H}`).text(),g.set(H,G);return G},FJ=async(H,G)=>{let U=new Set;for(let z of G?[G,...H]:H)for(let F of $J(Z,`app/views/${z}.tsx`))U.add(F);let O=await Promise.all([...U].map(async(z)=>({id:z,content:await IJ(z)})));return D(G?O:[{content:y},...O])},PJ=await r(C),f=new Map;for(let[H,G]of Object.entries((await l(C))?.files??{})){let U=VJ(C,H);if(U.startsWith(C+zJ))f.set(U,{immutable:!0,encodings:G})}async function _J(H){let{pathname:G}=new URL(H.url);if(N(G))return await T(H,G);let U=Q2(G);if(A(G)||G.startsWith("/.well-known")||U!==null&&PJ.has(U)){if(!U||!await H2(U))return HJ(G)??await T(H,G);try{return await s(H,U,f.get(U))}catch(z){return J.onException?.(z),new Response("Not found",{status:404})}}return await T(H,G)}async function T(H,G){let U=J.fetch.bind(J);try{let O=await U(H);if(O instanceof Response)return O;else{let z=[];return z.push({content:y}),await O({getStyles:async(R,u)=>{if(!R)return D([]);if(u?.static)return FJ(R,u.layout);for(let AJ of R){let NJ=Z[`app/views/${AJ}.tsx`];for(let h of NJ?.css??[]){let DJ=Bun.file(`${process.env.DIST_DIR}/client/${h}`);z.push({id:h,content:await DJ.text()})}}return D(z)},clientEntry:E,modulePreloadManifest:V,loaders:xJ,viewImportMap:W,viewModules:Y,ogMap:j,cssManifest:K,assetBase:Q,resolveIsland:CJ})}}catch(O){return S(O,G,J.onException)}}let BJ=(process.env.GEMI_COMPRESSION??"auto").toLowerCase()!=="off",MJ=jJ(process.env.GEMI_TRUST_PROXY),m=Bun.serve({maxRequestBodySize:10737418240,fetch:async(H,G)=>{GJ(H.headers,G.requestIP(H)?.address??null,MJ);let U=await $(H,(O)=>J.withGlobalMiddleware(O,_J,(z)=>S(z,new URL(O.url).pathname,J.onException)));return BJ?c(H,U):U},idleTimeout:OJ(),port:process.env.PORT||5173});return KJ({port:m.port,rootDir:q}),m}export{Z3 as httpProd};
23
-
24
- //# debugId=436C7117592AA70664756E2164756E21