gemi 0.218.0 → 0.220.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 (238) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +2 -2
  3. package/dist/ai/testing/index.js +2 -2
  4. package/dist/ai/testing/index.js.map +1 -1
  5. package/dist/app/index.js +1 -1
  6. package/dist/bun/plugin.js +1 -1
  7. package/dist/bun/preload.js +1 -1
  8. package/dist/{chunk-xyv3y476.js → chunk-0av1gyns.js} +3 -3
  9. package/dist/{chunk-xyv3y476.js.map → chunk-0av1gyns.js.map} +1 -1
  10. package/dist/{chunk-yxtfg4wy.js → chunk-0k2r6bep.js} +2 -2
  11. package/dist/{chunk-yxtfg4wy.js.map → chunk-0k2r6bep.js.map} +1 -1
  12. package/dist/chunk-169e9dg7.js +517 -0
  13. package/dist/chunk-169e9dg7.js.map +25 -0
  14. package/dist/{chunk-xp5mmgfp.js → chunk-2vv04thj.js} +2 -2
  15. package/dist/{chunk-xp5mmgfp.js.map → chunk-2vv04thj.js.map} +1 -1
  16. package/dist/{chunk-gxfyd8wr.js → chunk-2y0nr525.js} +3 -3
  17. package/dist/{chunk-gxfyd8wr.js.map → chunk-2y0nr525.js.map} +1 -1
  18. package/dist/{chunk-aes0ecnp.js → chunk-37209psn.js} +3 -3
  19. package/dist/{chunk-aes0ecnp.js.map → chunk-37209psn.js.map} +1 -1
  20. package/dist/{chunk-yedb5vvg.js → chunk-3dkv4989.js} +2 -2
  21. package/dist/{chunk-5gp49wph.js.map → chunk-3dkv4989.js.map} +1 -1
  22. package/dist/{chunk-5wh3cw2x.js → chunk-3y91vexx.js} +3 -3
  23. package/dist/{chunk-5wh3cw2x.js.map → chunk-3y91vexx.js.map} +1 -1
  24. package/dist/{chunk-4s72m6zx.js → chunk-4v5nwqw6.js} +3 -3
  25. package/dist/{chunk-4s72m6zx.js.map → chunk-4v5nwqw6.js.map} +1 -1
  26. package/dist/{chunk-v0sgcy87.js → chunk-4wh4dfgf.js} +1 -1
  27. package/dist/{chunk-1nw9jhpt.js → chunk-50791bmz.js} +2 -2
  28. package/dist/{chunk-1nw9jhpt.js.map → chunk-50791bmz.js.map} +1 -1
  29. package/dist/{chunk-rp2f9mq1.js → chunk-55btq9c7.js} +2 -2
  30. package/dist/{chunk-rp2f9mq1.js.map → chunk-55btq9c7.js.map} +1 -1
  31. package/dist/{chunk-w3ks9nz7.js → chunk-5h2xj3cx.js} +2 -2
  32. package/dist/{chunk-w3ks9nz7.js.map → chunk-5h2xj3cx.js.map} +1 -1
  33. package/dist/{chunk-at6zjajz.js → chunk-5jvbr0e5.js} +2 -2
  34. package/dist/{chunk-at6zjajz.js.map → chunk-5jvbr0e5.js.map} +1 -1
  35. package/dist/{chunk-hmtn7996.js → chunk-5mrtgr7q.js} +2 -2
  36. package/dist/{chunk-hmtn7996.js.map → chunk-5mrtgr7q.js.map} +1 -1
  37. package/dist/{chunk-9g5qh1ya.js → chunk-6d67a1d4.js} +2 -2
  38. package/dist/{chunk-9g5qh1ya.js.map → chunk-6d67a1d4.js.map} +1 -1
  39. package/dist/{chunk-q0d45r2j.js → chunk-6r7956dh.js} +2 -2
  40. package/dist/{chunk-q0d45r2j.js.map → chunk-6r7956dh.js.map} +1 -1
  41. package/dist/{chunk-ee7xb9qr.js → chunk-6ttbhhnn.js} +1 -1
  42. package/dist/{chunk-w85wrer7.js → chunk-726gd69z.js} +2 -2
  43. package/dist/{chunk-w85wrer7.js.map → chunk-726gd69z.js.map} +1 -1
  44. package/dist/{chunk-dgna0e7g.js → chunk-79wjkaa4.js} +2 -2
  45. package/dist/{chunk-dgna0e7g.js.map → chunk-79wjkaa4.js.map} +1 -1
  46. package/dist/{chunk-gxd1388t.js → chunk-7etvj6w2.js} +2 -2
  47. package/dist/{chunk-gxd1388t.js.map → chunk-7etvj6w2.js.map} +1 -1
  48. package/dist/chunk-7sjzgme6.js +88 -0
  49. package/dist/{chunk-sxxkkx75.js.map → chunk-7sjzgme6.js.map} +3 -10
  50. package/dist/chunk-89egc0h3.js +5 -0
  51. package/dist/{chunk-d6bgh2nr.js.map → chunk-89egc0h3.js.map} +1 -1
  52. package/dist/{chunk-4k3r37be.js → chunk-8a3fqcf0.js} +2 -2
  53. package/dist/{chunk-4k3r37be.js.map → chunk-8a3fqcf0.js.map} +1 -1
  54. package/dist/{chunk-3r7z4kc0.js → chunk-8ddt5fa2.js} +2 -2
  55. package/dist/{chunk-3r7z4kc0.js.map → chunk-8ddt5fa2.js.map} +1 -1
  56. package/dist/chunk-8gnbc9dg.js +8 -0
  57. package/dist/{chunk-xese0rng.js.map → chunk-8gnbc9dg.js.map} +4 -5
  58. package/dist/{chunk-c95ds04p.js → chunk-8nctfg18.js} +2 -2
  59. package/dist/{chunk-c95ds04p.js.map → chunk-8nctfg18.js.map} +1 -1
  60. package/dist/{chunk-17agj0r3.js → chunk-8vpe54ek.js} +2 -2
  61. package/dist/{chunk-17agj0r3.js.map → chunk-8vpe54ek.js.map} +1 -1
  62. package/dist/{chunk-9c8e4nkz.js → chunk-97tj0d7v.js} +2 -2
  63. package/dist/{chunk-9c8e4nkz.js.map → chunk-97tj0d7v.js.map} +1 -1
  64. package/dist/{chunk-7081awrd.js → chunk-9yascc81.js} +2 -2
  65. package/dist/{chunk-7081awrd.js.map → chunk-9yascc81.js.map} +1 -1
  66. package/dist/{chunk-9pvxexh1.js → chunk-adw279ge.js} +2 -2
  67. package/dist/{chunk-9pvxexh1.js.map → chunk-adw279ge.js.map} +1 -1
  68. package/dist/{chunk-ncw3zjxm.js → chunk-anc5v266.js} +2 -2
  69. package/dist/{chunk-ncw3zjxm.js.map → chunk-anc5v266.js.map} +1 -1
  70. package/dist/{chunk-6b7z5h54.js → chunk-ax042w6k.js} +2 -2
  71. package/dist/{chunk-6b7z5h54.js.map → chunk-ax042w6k.js.map} +1 -1
  72. package/dist/{chunk-b1pps9bj.js → chunk-b87wvmsz.js} +2 -2
  73. package/dist/{chunk-b1pps9bj.js.map → chunk-b87wvmsz.js.map} +1 -1
  74. package/dist/{chunk-xn7azkgd.js → chunk-bqm79ar0.js} +3 -3
  75. package/dist/{chunk-xn7azkgd.js.map → chunk-bqm79ar0.js.map} +1 -1
  76. package/dist/{chunk-5gp49wph.js → chunk-cf8bztwq.js} +2 -2
  77. package/dist/{chunk-yedb5vvg.js.map → chunk-cf8bztwq.js.map} +1 -1
  78. package/dist/{chunk-kggwk7hz.js → chunk-dj0nvj66.js} +1 -1
  79. package/dist/{chunk-xf3wke41.js → chunk-e4zxacxd.js} +2 -2
  80. package/dist/{chunk-xf3wke41.js.map → chunk-e4zxacxd.js.map} +1 -1
  81. package/dist/{chunk-b8tmmpcf.js → chunk-fp9yn4k8.js} +2 -2
  82. package/dist/{chunk-b8tmmpcf.js.map → chunk-fp9yn4k8.js.map} +1 -1
  83. package/dist/{chunk-sba3s380.js → chunk-fqhkkpq3.js} +2 -2
  84. package/dist/{chunk-sba3s380.js.map → chunk-fqhkkpq3.js.map} +1 -1
  85. package/dist/{chunk-nhebjh6n.js → chunk-fxa72ppw.js} +1 -1
  86. package/dist/{chunk-w9sw2kn7.js → chunk-gyszenps.js} +3 -3
  87. package/dist/{chunk-w9sw2kn7.js.map → chunk-gyszenps.js.map} +1 -1
  88. package/dist/{chunk-eh3ktv8k.js → chunk-h1wmpa03.js} +2 -2
  89. package/dist/{chunk-eh3ktv8k.js.map → chunk-h1wmpa03.js.map} +1 -1
  90. package/dist/{chunk-5vdkqv17.js → chunk-h9nt7hm6.js} +2 -2
  91. package/dist/{chunk-5vdkqv17.js.map → chunk-h9nt7hm6.js.map} +1 -1
  92. package/dist/{chunk-s7jwsbfd.js → chunk-j9abwrkv.js} +3 -3
  93. package/dist/{chunk-s7jwsbfd.js.map → chunk-j9abwrkv.js.map} +1 -1
  94. package/dist/{chunk-m68cxnbv.js → chunk-jf2dr481.js} +2 -2
  95. package/dist/{chunk-m68cxnbv.js.map → chunk-jf2dr481.js.map} +1 -1
  96. package/dist/{chunk-h6knw9f0.js → chunk-k16phdjv.js} +1 -1
  97. package/dist/{chunk-vewxnk3g.js → chunk-k6af7qek.js} +2 -2
  98. package/dist/{chunk-vewxnk3g.js.map → chunk-k6af7qek.js.map} +1 -1
  99. package/dist/{chunk-bcfwa370.js → chunk-kp7wcpx7.js} +2 -2
  100. package/dist/{chunk-bcfwa370.js.map → chunk-kp7wcpx7.js.map} +1 -1
  101. package/dist/{chunk-d6056zme.js → chunk-mt82209n.js} +2 -2
  102. package/dist/{chunk-d6056zme.js.map → chunk-mt82209n.js.map} +1 -1
  103. package/dist/{chunk-vawqmdh4.js → chunk-ncnygh0s.js} +2 -2
  104. package/dist/{chunk-vawqmdh4.js.map → chunk-ncnygh0s.js.map} +1 -1
  105. package/dist/{chunk-g178aect.js → chunk-nqgeny8m.js} +4 -4
  106. package/dist/{chunk-g178aect.js.map → chunk-nqgeny8m.js.map} +1 -1
  107. package/dist/{chunk-zy6hj5cc.js → chunk-nqqyn3cx.js} +2 -2
  108. package/dist/{chunk-zy6hj5cc.js.map → chunk-nqqyn3cx.js.map} +1 -1
  109. package/dist/{chunk-ppdfwnqw.js → chunk-nzd7z4s6.js} +1 -1
  110. package/dist/{chunk-m0pfdc1n.js → chunk-p4v71qfx.js} +3 -3
  111. package/dist/{chunk-m0pfdc1n.js.map → chunk-p4v71qfx.js.map} +1 -1
  112. package/dist/{chunk-vck02shp.js → chunk-ps5rpy9n.js} +2 -2
  113. package/dist/{chunk-vck02shp.js.map → chunk-ps5rpy9n.js.map} +1 -1
  114. package/dist/{chunk-gt6eq1p2.js → chunk-pxjkxhf9.js} +3 -3
  115. package/dist/{chunk-gt6eq1p2.js.map → chunk-pxjkxhf9.js.map} +1 -1
  116. package/dist/{chunk-r90djdx6.js → chunk-pxjptskr.js} +2 -2
  117. package/dist/{chunk-r90djdx6.js.map → chunk-pxjptskr.js.map} +1 -1
  118. package/dist/{chunk-6ncn8rdn.js → chunk-q5xcjm5z.js} +2 -2
  119. package/dist/{chunk-6ncn8rdn.js.map → chunk-q5xcjm5z.js.map} +1 -1
  120. package/dist/{chunk-ww62b10k.js → chunk-qs2xvc8g.js} +2 -2
  121. package/dist/{chunk-ww62b10k.js.map → chunk-qs2xvc8g.js.map} +1 -1
  122. package/dist/{chunk-sqqh78tf.js → chunk-qy0k2s5f.js} +2 -2
  123. package/dist/{chunk-sqqh78tf.js.map → chunk-qy0k2s5f.js.map} +1 -1
  124. package/dist/{chunk-jzqywxpj.js → chunk-rat2827k.js} +2 -2
  125. package/dist/{chunk-jzqywxpj.js.map → chunk-rat2827k.js.map} +1 -1
  126. package/dist/{chunk-ykshxc5k.js → chunk-s3gn68dy.js} +2 -2
  127. package/dist/{chunk-ykshxc5k.js.map → chunk-s3gn68dy.js.map} +1 -1
  128. package/dist/{chunk-8524ejgk.js → chunk-sfrjkysf.js} +2 -2
  129. package/dist/{chunk-8524ejgk.js.map → chunk-sfrjkysf.js.map} +1 -1
  130. package/dist/{chunk-fq7wkefg.js → chunk-snmyjq03.js} +2 -2
  131. package/dist/{chunk-fq7wkefg.js.map → chunk-snmyjq03.js.map} +1 -1
  132. package/dist/{chunk-cwm5x7rf.js → chunk-swmf6w3z.js} +2 -2
  133. package/dist/{chunk-cwm5x7rf.js.map → chunk-swmf6w3z.js.map} +1 -1
  134. package/dist/{chunk-evgs2tr8.js → chunk-t0ke72e9.js} +2 -2
  135. package/dist/{chunk-evgs2tr8.js.map → chunk-t0ke72e9.js.map} +2 -2
  136. package/dist/{chunk-snt0523y.js → chunk-t586p2g2.js} +2 -2
  137. package/dist/{chunk-snt0523y.js.map → chunk-t586p2g2.js.map} +1 -1
  138. package/dist/{chunk-zyvmbqcx.js → chunk-t8ygf6zj.js} +3 -3
  139. package/dist/{chunk-zyvmbqcx.js.map → chunk-t8ygf6zj.js.map} +1 -1
  140. package/dist/chunk-tac25cnj.js +39 -0
  141. package/dist/chunk-tac25cnj.js.map +20 -0
  142. package/dist/{chunk-7t13vyzg.js → chunk-vcw98sp6.js} +3 -3
  143. package/dist/{chunk-7t13vyzg.js.map → chunk-vcw98sp6.js.map} +1 -1
  144. package/dist/{chunk-tw338bbv.js → chunk-vcy1y0ta.js} +2 -2
  145. package/dist/{chunk-tw338bbv.js.map → chunk-vcy1y0ta.js.map} +1 -1
  146. package/dist/{chunk-fhb00fjx.js → chunk-vmmjq9fn.js} +2 -2
  147. package/dist/{chunk-fhb00fjx.js.map → chunk-vmmjq9fn.js.map} +1 -1
  148. package/dist/{chunk-prc4bcgp.js → chunk-wt4ekzp9.js} +2 -2
  149. package/dist/{chunk-prc4bcgp.js.map → chunk-wt4ekzp9.js.map} +1 -1
  150. package/dist/{chunk-k8nsefzb.js → chunk-wy82t7mz.js} +2 -2
  151. package/dist/{chunk-k8nsefzb.js.map → chunk-wy82t7mz.js.map} +1 -1
  152. package/dist/{chunk-7rmb1v9c.js → chunk-x3pbssy4.js} +2 -2
  153. package/dist/{chunk-7rmb1v9c.js.map → chunk-x3pbssy4.js.map} +1 -1
  154. package/dist/chunk-xjgfmefy.js +19 -0
  155. package/dist/{chunk-4sbrvmz9.js.map → chunk-xjgfmefy.js.map} +3 -3
  156. package/dist/{chunk-qstjm3cb.js → chunk-yj7pbbnm.js} +2 -2
  157. package/dist/{chunk-qstjm3cb.js.map → chunk-yj7pbbnm.js.map} +1 -1
  158. package/dist/{chunk-qa528feb.js → chunk-zmt5kdpb.js} +2 -2
  159. package/dist/{chunk-qa528feb.js.map → chunk-zmt5kdpb.js.map} +1 -1
  160. package/dist/client/index.d.ts +2 -0
  161. package/dist/client/index.d.ts.map +1 -1
  162. package/dist/client/index.js +54 -1
  163. package/dist/client/index.js.map +1 -1
  164. package/dist/client/useWorkflow.d.ts +51 -0
  165. package/dist/client/useWorkflow.d.ts.map +1 -0
  166. package/dist/config/index.js +1 -1
  167. package/dist/console/run.js +2 -2
  168. package/dist/console/run.js.map +1 -1
  169. package/dist/container/index.js +2 -2
  170. package/dist/container/index.js.map +1 -1
  171. package/dist/database/index.js +2 -2
  172. package/dist/database/index.js.map +1 -1
  173. package/dist/email/index.js +2 -2
  174. package/dist/email/index.js.map +1 -1
  175. package/dist/facades/index.js +2 -2
  176. package/dist/facades/index.js.map +1 -1
  177. package/dist/foundation/index.js +2 -2
  178. package/dist/foundation/index.js.map +1 -1
  179. package/dist/http/index.js +2 -2
  180. package/dist/http/index.js.map +1 -1
  181. package/dist/i18n/dictionaryRuntime.js +2 -2
  182. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  183. package/dist/i18n/index.js +2 -2
  184. package/dist/i18n/index.js.map +1 -1
  185. package/dist/kernel/index.js +2 -2
  186. package/dist/kernel/index.js.map +1 -1
  187. package/dist/orm/index.js +2 -2
  188. package/dist/orm/index.js.map +1 -1
  189. package/dist/probe/index.js +2 -2
  190. package/dist/probe/index.js.map +1 -1
  191. package/dist/server/index.js +2 -2
  192. package/dist/server/index.js.map +1 -1
  193. package/dist/services/index.d.ts +4 -2
  194. package/dist/services/index.d.ts.map +1 -1
  195. package/dist/services/index.js +3 -3
  196. package/dist/services/index.js.map +2 -2
  197. package/dist/services/queue/DatabaseQueueDriver.d.ts +8 -1
  198. package/dist/services/queue/DatabaseQueueDriver.d.ts.map +1 -1
  199. package/dist/services/queue/QueueManager.d.ts +2 -0
  200. package/dist/services/queue/QueueManager.d.ts.map +1 -1
  201. package/dist/services/queue/work.js +2 -2
  202. package/dist/services/queue/work.js.map +1 -1
  203. package/dist/services/queue/workflow/DatabaseWorkflowStore.d.ts +21 -0
  204. package/dist/services/queue/workflow/DatabaseWorkflowStore.d.ts.map +1 -1
  205. package/dist/services/queue/workflow/ItemSource.d.ts +68 -0
  206. package/dist/services/queue/workflow/ItemSource.d.ts.map +1 -0
  207. package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts +12 -0
  208. package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts.map +1 -1
  209. package/dist/services/queue/workflow/Step.d.ts +30 -10
  210. package/dist/services/queue/workflow/Step.d.ts.map +1 -1
  211. package/dist/services/queue/workflow/Workflow.d.ts +26 -38
  212. package/dist/services/queue/workflow/Workflow.d.ts.map +1 -1
  213. package/dist/services/queue/workflow/WorkflowRuntime.d.ts +45 -0
  214. package/dist/services/queue/workflow/WorkflowRuntime.d.ts.map +1 -1
  215. package/dist/services/queue/workflow/WorkflowStore.d.ts +25 -17
  216. package/dist/services/queue/workflow/WorkflowStore.d.ts.map +1 -1
  217. package/dist/services/queue/workflow/wire.d.ts +71 -0
  218. package/dist/services/queue/workflow/wire.d.ts.map +1 -0
  219. package/dist/services/queue/workflow/workflowContract.d.ts.map +1 -1
  220. package/dist/stats/route-table.js +1 -1
  221. package/dist/support/index.js +2 -2
  222. package/dist/support/index.js.map +1 -1
  223. package/dist/vitest/index.js +1 -1
  224. package/package.json +1 -1
  225. package/dist/chunk-4sbrvmz9.js +0 -19
  226. package/dist/chunk-d6bgh2nr.js +0 -5
  227. package/dist/chunk-ktee4gy4.js +0 -484
  228. package/dist/chunk-ktee4gy4.js.map +0 -23
  229. package/dist/chunk-sxxkkx75.js +0 -117
  230. package/dist/chunk-xb0evp2m.js +0 -5
  231. package/dist/chunk-xb0evp2m.js.map +0 -12
  232. package/dist/chunk-xese0rng.js +0 -13
  233. /package/dist/{chunk-v0sgcy87.js.map → chunk-4wh4dfgf.js.map} +0 -0
  234. /package/dist/{chunk-ee7xb9qr.js.map → chunk-6ttbhhnn.js.map} +0 -0
  235. /package/dist/{chunk-kggwk7hz.js.map → chunk-dj0nvj66.js.map} +0 -0
  236. /package/dist/{chunk-nhebjh6n.js.map → chunk-fxa72ppw.js.map} +0 -0
  237. /package/dist/{chunk-h6knw9f0.js.map → chunk-k16phdjv.js.map} +0 -0
  238. /package/dist/{chunk-ppdfwnqw.js.map → chunk-nzd7z4s6.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
2
  function p(j){return Object.freeze({name:j})}class N extends Error{key;constructor(j){super(`Request state "${j.name}" is not set. Check that whatever sets it (a middleware, \`context()\`) ran for this request.`);this.key=j;this.name="MissingRequestStateError"}}class P{#j=new Map;get(j){return this.#j.get(j)}require(j){if(!this.#j.has(j))throw new N(j);return this.#j.get(j)}set(j,J){return this.#j.set(j,J),J}has(j){return this.#j.has(j)}delete(j){return this.#j.delete(j)}static carry(j,J){for(let[Q,V]of j.#j)if(!J.#j.has(Q))J.#j.set(Q,V)}}function z(){for(let j of["HOST_NAME","APP_URL"]){let J=process.env[j]?.trim().replace(/\/+$/,"");if(J)return J}return}function d(j){let J=z(),Q=J===void 0?"fallback":J===process.env.HOST_NAME?.trim().replace(/\/+$/,"")?"HOST_NAME":"APP_URL",V=J??j?.trim().replace(/\/+$/,"");if(!V)throw Error("The app's public origin is not configured: set HOST_NAME (or APP_URL), e.g. HOST_NAME=https://example.com.");let Z=URL.canParse(V)?new URL(V).protocol:null;if(Z!=="http:"&&Z!=="https:")throw Error(`The app's public origin from ${Q} (${JSON.stringify(V)}) is not an absolute http(s) URL, e.g. https://example.com.`);return V}import{AsyncLocalStorage as v}from"async_hooks";var R=new Set(["woff2","woff","truetype","opentype","collection","embedded-opentype","svg"]),q={woff2:"woff2",woff:"woff",ttf:"truetype",otf:"opentype",ttc:"collection",eot:"embedded-opentype",svg:"svg"};var y=new Set(["auto","block","swap","fallback","optional"]),w=/^[a-zA-Z0-9.%+\- ]+$/,k=/^[uU]\+[0-9a-fA-F?]{1,6}(-[0-9a-fA-F]{1,6})?(\s*,\s*[uU]\+[0-9a-fA-F?]{1,6}(-[0-9a-fA-F]{1,6})?)*$/;function G(j){throw TypeError(`Meta.fonts: ${j}`)}function h(j){let J=(j.split(/[?#]/)[0]??"").split("/").pop()??"",Q=J.lastIndexOf(".");return Q===-1?null:q[J.slice(Q+1).toLowerCase()]??null}function U(j,J){if(J===void 0||J===null)return null;let Q=String(J).trim();if(!Q||!w.test(Q))G(`${j} ${JSON.stringify(J)} is not a valid font-${j} value`);return Q}function T(j){if(!Array.isArray(j))G("expected an array of fonts");return j.map((J)=>{if(typeof J?.family!=="string"||!J.family.trim())G("every font needs a family");let Q=typeof J.src==="string"?[{url:J.src}]:J.src;if(!Array.isArray(Q)||Q.length===0)G(`font "${J.family}" needs a src`);let V=Q.map(($)=>{if(typeof $?.url!=="string"||!$.url.trim())G(`font "${J.family}" has a source without a url`);if($.format!==void 0&&!R.has($.format))G(`font "${J.family}" has an unknown format ${JSON.stringify($.format)}`);return{url:$.url.trim(),format:$.format??h($.url)}}),Z=J.display??"swap";if(!y.has(Z))G(`display ${JSON.stringify(Z)} is not a valid font-display value`);let X=J.unicodeRange?.trim()||null;if(X&&!k.test(X))G(`unicodeRange ${JSON.stringify(J.unicodeRange)} is not a valid unicode-range`);return{family:J.family.trim(),src:V,weight:U("weight",J.weight),style:U("style",J.style),stretch:U("stretch",J.stretch),display:Z,unicodeRange:X,preload:J.preload===!0}})}class Y{content={title:"Gemi App",description:null,openGraph:null,htmlAttributes:null,canonical:null,alternates:null,fonts:null,robots:null,translate:null,tags:null};touched=!1;setFields=new Set;render(){return{title:this.content.title,description:this.content.description,openGraph:this.content.openGraph,htmlAttributes:this.content.htmlAttributes,canonical:this.content.canonical,alternates:this.content.alternates,fonts:this.content.fonts,robots:this.content.robots,translate:this.content.translate,tags:this.content.tags}}htmlAttributes(j){this.touched=!0;let J=Object.fromEntries(Object.entries(j).filter(([,Q])=>Q!==void 0));this.content.htmlAttributes={...this.content.htmlAttributes,...J}}canonical(j){this.touched=!0,this.content.canonical=j}robots(j){this.touched=!0,this.content.robots=j}translate(j=!0){this.touched=!0,this.translateSet=!0,this.content.translate=j}translateSet=!1;applyTranslateDefault(j){if(!this.translateSet)this.content.translate=j}alternates(j){this.touched=!0,this.content.alternates=j}tags(j){let J=j.map((Q)=>{let V=Q.name!==void 0?"name":"property",Z=Q.name??Q.property;if(typeof Z!=="string"||Z===""||Q.name!==void 0&&Q.property!==void 0)throw TypeError("Meta.tags: each tag needs either a `name` or a `property`.");if(typeof Q.content!=="string")throw TypeError(`Meta.tags: the tag ${Z} has no string \`content\`.`);return{[V]:Z,content:Q.content}});this.touched=!0,this.content.tags=[...this.content.tags??[],...J]}fonts(j){let J=T(j);this.touched=!0,this.content.fonts=[...this.content.fonts??[],...J]}title(j){this.touched=!0,this.setFields.add("title"),this.content.title=j}description(j){this.touched=!0,this.setFields.add("description"),this.content.description=j}get hasAllDefaultFields(){return this.setFields.size===3}applyDefaults(j){if(!this.setFields.has("title")&&j.title!==void 0)this.content.title=j.title;if(!this.setFields.has("description")&&j.description!==void 0)this.content.description=j.description;if(!this.setFields.has("openGraph")&&j.openGraph){let{title:J,description:Q,type:V,...Z}=j.openGraph;this.content.openGraph=this.normalizeOpenGraph({...Z,title:J??this.content.title,description:Q??this.content.description??void 0,type:V??"website"})}}openGraph(j){this.touched=!0,this.setFields.add("openGraph"),this.content.openGraph=this.normalizeOpenGraph(j)}normalizeOpenGraph({title:j,description:J,type:Q,url:V,image:Z,imageAlt:X,imageWidth:$,imageHeight:H,siteName:E,twitterTitle:x,twitterDescription:A,twitterImage:W=Z,twitterImageAlt:O=X,twitterImageWidth:C=$,twitterImageHeight:S=H,twitterCard:I=W?"summary_large_image":"summary"}){let D=(B)=>B&&!B.startsWith("http")?`${z()}${B}`:B;return Object.fromEntries(Object.entries({title:j,description:J,type:Q,url:V,image:D(Z),imageAlt:X,imageWidth:$,imageHeight:H,siteName:E,twitterTitle:x,twitterDescription:A,twitterImage:D(W),twitterImageAlt:O,twitterImageWidth:C,twitterImageHeight:S,twitterCard:I}).filter(([B,F])=>F!==void 0&&F!==null))}}function M(j,J,Q={}){return[`${j}=${J}`,Q.maxAge?`Max-Age=${Q.maxAge}`:"",Q.httpOnly?"HttpOnly":"",Q.secure?"Secure":"",Q.sameSite?`SameSite=${Q.sameSite}`:"SameSite=Strict",Q.path?`Path=${Q.path}`:"Path=/",Q.domain?`Domain=${Q.domain}`:"",Q.expires?`Expires=${Q.expires.toUTCString()}`:"",Q.partitioned?"Partitioned":""].filter((V)=>V!=="").join("; ")}var K=new v;class _{req;cookies=new Set;headers=new Headers;serverQueries=null;user=null;csrfHmac=null;locale=null;metadata=new Y;rangeRequest=null;sessionId=null;featureEvaluations=null;featureContext=null;featureBuckets=null;pendingWork=new Set;ended=!1;constructor(j){this.req=j}waitUntil(j){if(this.ended)return;let J=Promise.resolve(j).then(()=>{},()=>{});this.pendingWork.add(J),J.then(()=>this.pendingWork.delete(J))}hasPendingWork(){return this.pendingWork.size>0}async whenIdle(){while(this.pendingWork.size>0)await Promise.all(Array.from(this.pendingWork))}setLocale(j){this.locale=j}renderMeta(){return this.metadata.render()}setCSRFHmac(j){this.csrfHmac=j}setCookie(j,J,Q={}){this.cookies.add(M(j,J,Q))}deleteCookie(j,J={}){this.cookies.add(M(j,"",{...J,maxAge:-1}))}setHeaders(j,J){this.headers.set(j,J)}setUser(j){this.user=j}setRequest(j){this.req=j}destroy(){this.ended=!0,delete this.cookies,delete this.headers,this.serverQueries=null,this.sessionId=null,this.featureEvaluations=null,this.featureContext=null,this.featureBuckets=null,delete this.user}}var b="session_id";function m(){let j=L.getStore();if(!j)return null;if(j.sessionId)return j.sessionId;let J=j.req?.cookies?.get(b);if(J)j.sessionId=J;return j.sessionId}function s(){let j=L.getStore();if(!j)return null;let J=m();if(J)return J;let Q=Bun.randomUUIDv7();return j.sessionId=Q,j.setCookie(b,Q,{httpOnly:!0,secure:Bun.env.NODE_ENV==="production",sameSite:"Lax",expires:new Date(Date.now()+31536000000)}),Q}class L{static getStore(){return K.getStore()}static setRequest(j){K.getStore().req=j}static run(j,J,Q){let V=new _(j);if(Q){if(V.user=Q.user,Q.state&&j.state)P.carry(Q.state,j.state)}return K.run(V,J)}static runWith(j,J){return K.run(j,J)}static exit(j){return K.exit(j)}}
3
- export{z as Qj,d as Rj,p as Sj,N as Tj,P as Uj,m as Vj,s as Wj,L as Xj};
3
+ export{z as Fj,d as Gj,p as Hj,N as Ij,P as Jj,m as Kj,s as Lj,L as Mj};
4
4
 
5
- //# debugId=022F96299E22E08164756E2164756E21
5
+ //# debugId=9E8860029525A43164756E2164756E21
@@ -9,6 +9,6 @@
9
9
  "import { type MetaFont, type NormalizedFont, normalizeFonts } from \"../client/fonts\";\nimport { configuredAppOrigin } from \"../utils/appOrigin\";\n\nexport type { MetaFont };\n\nexport type OpenGraphParams = {\n title: string;\n description?: string;\n type: string;\n url: string;\n /** Rendered as `og:image` only when set. A path is prefixed with the app origin. */\n image?: string;\n imageAlt?: string;\n imageWidth?: number;\n imageHeight?: number;\n /** `og:site_name`, rendered only when set. */\n siteName?: string;\n /** `twitter:title`, rendered only when set (it does not follow `title`). */\n twitterTitle?: string;\n /** `twitter:description`, rendered only when set (it does not follow `description`). */\n twitterDescription?: string;\n twitterImage?: string;\n /** Defaults to `imageAlt`; `null` leaves `twitter:image:alt` out. */\n twitterImageAlt?: string | null;\n /** Defaults to `imageWidth`; `null` leaves `twitter:image:width` out. */\n twitterImageWidth?: number | null;\n /** Defaults to `imageHeight`; `null` leaves `twitter:image:height` out. */\n twitterImageHeight?: number | null;\n /**\n * The `twitter:card` type. Defaults to `\"summary_large_image\"` when the page\n * has an image (`twitterImage ?? image`), `\"summary\"` otherwise.\n */\n twitterCard?: \"summary\" | \"summary_large_image\";\n};\n/**\n * The app-wide default title and metadata (`route.view.meta`, #1042): used for\n * each field that no handler (or `onNotFound`) set. See `ViewRouteConfig.meta`.\n */\nexport type DefaultViewMeta = {\n title?: string;\n description?: string;\n /**\n * Every field is optional: `title` and `description` default to the page's\n * own, `type` to `\"website\"`. `url` is left out of the page unless given.\n */\n openGraph?: Partial<OpenGraphParams>;\n};\n\n/**\n * Attributes for the document's `<html>` element, handed to the root (or a\n * static view's) layout as its `htmlAttributes` prop.\n */\nexport type HtmlAttributes = {\n /** The document's language, e.g. `\"tr\"`. Defaults to the request's locale. */\n lang?: string;\n /** Text direction. Defaults to the one `lang` is written in. */\n dir?: \"ltr\" | \"rtl\" | \"auto\";\n};\n\n/** One `<link rel=\"alternate\" hreflang>`: the same page in another language. */\nexport type AlternateLink = {\n /** A BCP 47 tag, or `\"x-default\"` for the page to use when none matches. */\n hrefLang: string;\n href: string;\n};\n\n/**\n * A `<link rel=\"alternate\" type>` without `hreflang`: the same page in another\n * format, e.g. `{ type: \"text/markdown\", href: \"/docs/intro.md\" }`.\n */\nexport type TypedAlternateLink = {\n /** The linked document's media type. */\n type: string;\n href: string;\n};\n\n/** What `Meta.alternates` takes: a language alternate, or one in another format. */\nexport type MetaAlternate = AlternateLink | TypedAlternateLink;\n\n/**\n * One `<meta>` that `Meta.tags` adds: `name` (e.g. a site-verification token,\n * `{ name: \"google-site-verification\", content }`) or `property`.\n */\nexport type MetaTag =\n | { name: string; property?: never; content: string }\n | { property: string; name?: never; content: string };\n\nexport class Metadata {\n content: any = {\n title: \"Gemi App\",\n description: null,\n openGraph: null,\n htmlAttributes: null,\n canonical: null,\n alternates: null,\n fonts: null,\n robots: null,\n translate: null,\n tags: null,\n };\n\n /**\n * Whether a handler set anything, as opposed to `content` still being the\n * defaults. A partially rendered response that touched no metadata sends\n * none, so the client keeps what the skipped segments put there.\n */\n touched = false;\n\n /** The fields a handler set, which the app's default (`route.view.meta`) leaves alone. */\n private setFields = new Set<keyof DefaultViewMeta>();\n\n render() {\n return {\n title: this.content.title,\n description: this.content.description,\n openGraph: this.content.openGraph,\n htmlAttributes: this.content.htmlAttributes,\n canonical: this.content.canonical,\n alternates: this.content.alternates,\n fonts: this.content.fonts,\n robots: this.content.robots,\n translate: this.content.translate,\n tags: this.content.tags,\n };\n }\n\n /** Merged into what earlier calls set; `undefined` leaves an attribute alone. */\n htmlAttributes(attributes: HtmlAttributes) {\n this.touched = true;\n const defined = Object.fromEntries(\n Object.entries(attributes).filter(([, value]) => value !== undefined),\n );\n this.content.htmlAttributes = { ...this.content.htmlAttributes, ...defined };\n }\n\n canonical(url: string) {\n this.touched = true;\n this.content.canonical = url;\n }\n\n /** `<meta name=\"robots\">`'s content, e.g. `\"noindex, nofollow\"`; the last call wins. */\n robots(content: string) {\n this.touched = true;\n this.content.robots = content;\n }\n\n /**\n * Whether browsers and Google Search may translate the page (#1087). `true`\n * leaves `<meta name=\"google\" content=\"notranslate\">` out; `false` (or no\n * call) keeps it. The last call wins.\n */\n translate(allow = true) {\n this.touched = true;\n this.translateSet = true;\n this.content.translate = allow;\n }\n\n /** Whether a handler called `translate`, which the views' default (`route.view.translate`) leaves alone. */\n private translateSet = false;\n\n /**\n * The views' default (`route.view.translate`, #1087), for a response whose\n * handlers didn't call `translate`. Not a handler call, so `touched` stays\n * as it was.\n */\n applyTranslateDefault(allow: boolean) {\n if (!this.translateSet) {\n this.content.translate = allow;\n }\n }\n\n alternates(links: MetaAlternate[]) {\n this.touched = true;\n this.content.alternates = links;\n }\n\n /** Added to what earlier calls set, so a layout and its page can both add tags. */\n tags(tags: MetaTag[]) {\n const normalized = tags.map((tag) => {\n const key = tag.name !== undefined ? \"name\" : \"property\";\n const value = tag.name ?? tag.property;\n if (typeof value !== \"string\" || value === \"\" || (tag.name !== undefined && tag.property !== undefined)) {\n throw new TypeError(\"Meta.tags: each tag needs either a `name` or a `property`.\");\n }\n if (typeof tag.content !== \"string\") {\n throw new TypeError(`Meta.tags: the tag ${value} has no string \\`content\\`.`);\n }\n return { [key]: value, content: tag.content } as MetaTag;\n });\n this.touched = true;\n this.content.tags = [...(this.content.tags ?? []), ...normalized];\n }\n\n /** Added to what earlier calls declared, so a layout and its page can both declare fonts. */\n fonts(fonts: MetaFont[]) {\n const normalized: NormalizedFont[] = normalizeFonts(fonts);\n this.touched = true;\n this.content.fonts = [...(this.content.fonts ?? []), ...normalized];\n }\n\n title(title: string) {\n this.touched = true;\n this.setFields.add(\"title\");\n this.content.title = title;\n }\n\n description(description: string) {\n this.touched = true;\n this.setFields.add(\"description\");\n this.content.description = description;\n }\n\n /** Whether every field the app's default could fill was set by a handler. */\n get hasAllDefaultFields() {\n return this.setFields.size === 3;\n }\n\n /**\n * Fills each of `title`, `description` and `openGraph` that no handler set\n * from the app's default (`route.view.meta`, #1042). Field by field: a\n * handler's `Meta.title` keeps its title and still gets the default\n * description. Not a handler call, so `touched` stays as it was.\n *\n * The default's Open Graph fields fall back to the page's title and\n * description and to `type: \"website\"`; `url` is only rendered when given.\n */\n applyDefaults(defaults: DefaultViewMeta) {\n if (!this.setFields.has(\"title\") && defaults.title !== undefined) {\n this.content.title = defaults.title;\n }\n if (!this.setFields.has(\"description\") && defaults.description !== undefined) {\n this.content.description = defaults.description;\n }\n if (!this.setFields.has(\"openGraph\") && defaults.openGraph) {\n const { title, description, type, ...rest } = defaults.openGraph;\n this.content.openGraph = this.normalizeOpenGraph({\n ...rest,\n title: title ?? this.content.title,\n description: description ?? this.content.description ?? undefined,\n type: type ?? \"website\",\n });\n }\n }\n\n openGraph(params: OpenGraphParams) {\n this.touched = true;\n this.setFields.add(\"openGraph\");\n this.content.openGraph = this.normalizeOpenGraph(params);\n }\n\n private normalizeOpenGraph({\n title,\n description,\n type,\n url,\n image,\n imageAlt,\n imageWidth,\n imageHeight,\n siteName,\n twitterTitle,\n twitterDescription,\n twitterImage = image,\n twitterImageAlt = imageAlt,\n twitterImageWidth = imageWidth,\n twitterImageHeight = imageHeight,\n twitterCard = twitterImage ? \"summary_large_image\" : \"summary\",\n }: Omit<OpenGraphParams, \"url\"> & { url?: string }) {\n const absolute = (src: string | undefined) =>\n src && !src.startsWith(\"http\") ? `${configuredAppOrigin()}${src}` : src;\n return Object.fromEntries(\n Object.entries({\n title,\n description,\n type,\n url,\n image: absolute(image),\n imageAlt,\n imageWidth,\n imageHeight,\n siteName,\n twitterTitle,\n twitterDescription,\n twitterImage: absolute(twitterImage),\n twitterImageAlt,\n twitterImageWidth,\n twitterImageHeight,\n twitterCard,\n })\n // `null` (a twitter image field turned off) is left out like `undefined`.\n .filter(([_, value]) => value !== undefined && value !== null),\n );\n }\n}\n"
10
10
  ],
11
11
  "mappings": ";AAkCO,SAAS,CAAW,CAAC,EAA2B,CACrD,OAAO,OAAO,OAAO,CAAE,MAAK,CAAC,EAIxB,MAAM,UAAiC,KAAM,CACtB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,aAQjC,SAAU,MACV,QAAS,IAAI,KAAK,KAAK,IAAI,EAAI,WAAyB,CAC1D,CAAC,EACM,EAGF,MAAM,CAAe,OACnB,SAAQ,EAAG,CAChB,OAAO,EAAe,SAAS,QAG1B,WAAU,CAAC,EAA4B,CAC5C,EAAe,SAAS,EAAE,IAAM,QAO3B,IAAM,CACX,EACA,EACA,EACG,CACH,IAAM,EAAQ,IAAI,EAAM,CAAW,EACnC,GAAI,GAEF,GADA,EAAM,KAAO,EAAQ,KACjB,EAAQ,OAAS,EAAY,MAC/B,EAAa,MAAM,EAAQ,MAAO,EAAY,KAAK,EAGvD,OAAO,EAAe,IAAI,EAAO,CAAE,QAU9B,QAAU,CAAC,EAAc,EAAgB,CAC9C,OAAO,EAAe,IAAI,EAAO,CAAE,QAQ9B,KAAO,CAAC,EAAgB,CAC7B,OAAO,EAAe,KAAK,CAAE,EAEjC",
12
- "debugId": "022F96299E22E08164756E2164756E21",
12
+ "debugId": "9E8860029525A43164756E2164756E21",
13
13
  "names": []
14
14
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Om as P}from"./chunk-yedb5vvg.js";class F{provider="custom";supportsIdempotencyKey=!1;async deliver(j){let x=await this.send(j);return{ok:Boolean(x),id:null}}}class G extends F{apiKey;provider="resend";supportsIdempotencyKey=!0;constructor(j=process.env.RESEND_API_KEY){super();this.apiKey=j}async send(j){return(await this.deliver(j)).ok}async deliver(j){let{Resend:x}=await import("./chunk-w3ks9nz7.js"),z=new x(this.apiKey),{idempotencyKey:A,...N}=j,{data:H,error:B}=await z.emails.send(N,A?{idempotencyKey:A}:void 0);if(B)return console.error(B),{ok:!1,id:null,error:B};if(H)return{ok:!0,id:H.id??null};return{ok:!1,id:null}}}function Z(j){return j}function J(){return{driver:new G,drivers:{},headers:{},filterRecipients:(j)=>j}}function Q(j){for(let x=j;x;x=Object.getPrototypeOf(x)){let z=Object.prototype.hasOwnProperty.call(x,"deliver"),A=Object.prototype.hasOwnProperty.call(x,"send");if(z)return!1;if(A)return!0}return!0}async function M(j,x){if(typeof j.deliver==="function"&&!Q(j))return j.deliver(x);return{ok:Boolean(await j.send(x)),id:null}}class U{static token="mail";driver;drivers;headers;recipientFilter;constructor(j={}){let x=J();this.driver=j.driver??x.driver,this.drivers=j.drivers??x.drivers,this.headers=j.headers??x.headers,this.recipientFilter=j.filterRecipients??x.filterRecipients}driverFor(j){if(j===void 0)return this.driver;let x=Object.hasOwn(this.drivers,j)?this.drivers[j]:void 0;if(!x){let z=Object.keys(this.drivers);throw Error(`No mail driver named "${j}". Register it under \`drivers\` in the mail config${z.length?` (registered: ${z.join(", ")})`:""}.`)}return x}filterRecipients(j){return this.recipientFilter(j)}send(j){return this.driver.send(j)}async deliver(j){return M(this.driver,j)}}
3
- export{F as Wl,G as Xl,Z as Yl,J as Zl,M as _l,U as $l};
2
+ import{Qm as P}from"./chunk-3dkv4989.js";class F{provider="custom";supportsIdempotencyKey=!1;async deliver(j){let x=await this.send(j);return{ok:Boolean(x),id:null}}}class G extends F{apiKey;provider="resend";supportsIdempotencyKey=!0;constructor(j=process.env.RESEND_API_KEY){super();this.apiKey=j}async send(j){return(await this.deliver(j)).ok}async deliver(j){let{Resend:x}=await import("./chunk-5h2xj3cx.js"),z=new x(this.apiKey),{idempotencyKey:A,...N}=j,{data:H,error:B}=await z.emails.send(N,A?{idempotencyKey:A}:void 0);if(B)return console.error(B),{ok:!1,id:null,error:B};if(H)return{ok:!0,id:H.id??null};return{ok:!1,id:null}}}function Z(j){return j}function J(){return{driver:new G,drivers:{},headers:{},filterRecipients:(j)=>j}}function Q(j){for(let x=j;x;x=Object.getPrototypeOf(x)){let z=Object.prototype.hasOwnProperty.call(x,"deliver"),A=Object.prototype.hasOwnProperty.call(x,"send");if(z)return!1;if(A)return!0}return!0}async function M(j,x){if(typeof j.deliver==="function"&&!Q(j))return j.deliver(x);return{ok:Boolean(await j.send(x)),id:null}}class U{static token="mail";driver;drivers;headers;recipientFilter;constructor(j={}){let x=J();this.driver=j.driver??x.driver,this.drivers=j.drivers??x.drivers,this.headers=j.headers??x.headers,this.recipientFilter=j.filterRecipients??x.filterRecipients}driverFor(j){if(j===void 0)return this.driver;let x=Object.hasOwn(this.drivers,j)?this.drivers[j]:void 0;if(!x){let z=Object.keys(this.drivers);throw Error(`No mail driver named "${j}". Register it under \`drivers\` in the mail config${z.length?` (registered: ${z.join(", ")})`:""}.`)}return x}filterRecipients(j){return this.recipientFilter(j)}send(j){return this.driver.send(j)}async deliver(j){return M(this.driver,j)}}
3
+ export{F as Yl,G as Zl,Z as _l,J as $l,M as am,U as bm};
4
4
 
5
- //# debugId=29B0598D76B4838464756E2164756E21
5
+ //# debugId=35B40017364BF62C64756E2164756E21
@@ -9,6 +9,6 @@
9
9
  "import { mailConfigDefaults, type MailConfig } from \"./config\";\nimport { deliverThrough } from \"./deliver\";\nimport type { EmailDriver } from \"./drivers/EmailDriver\";\nimport type { EmailDeliveryResult, SendEmailParams } from \"./drivers/types\";\n\nexport class MailManager {\n static token = \"mail\";\n\n readonly driver: EmailDriver;\n readonly drivers: Record<string, EmailDriver>;\n readonly headers: Record<string, string>;\n\n private readonly recipientFilter: NonNullable<MailConfig[\"filterRecipients\"]>;\n\n constructor(config: MailConfig = {}) {\n const defaults = mailConfigDefaults();\n\n this.driver = config.driver ?? defaults.driver;\n this.drivers = config.drivers ?? defaults.drivers;\n this.headers = config.headers ?? defaults.headers;\n this.recipientFilter = config.filterRecipients ?? defaults.filterRecipients;\n }\n\n /**\n * The driver registered as `name` in `drivers`, or the default `driver`\n * without a name. An unknown name throws rather than falling back, so a typo\n * can't send through the wrong provider.\n */\n driverFor(name?: string): EmailDriver {\n if (name === undefined) return this.driver;\n const driver = Object.hasOwn(this.drivers, name) ? this.drivers[name] : undefined;\n if (!driver) {\n const known = Object.keys(this.drivers);\n throw new Error(\n `No mail driver named \"${name}\". Register it under \\`drivers\\` in the mail config${known.length ? ` (registered: ${known.join(\", \")})` : \"\"}.`,\n );\n }\n return driver;\n }\n\n filterRecipients(emails: string[]): Promise<Array<string>> | Array<string> {\n return this.recipientFilter(emails);\n }\n\n send(params: SendEmailParams) {\n return this.driver.send(params);\n }\n\n /** Like `send`, but reports the outcome and the provider's message id. */\n async deliver(params: SendEmailParams): Promise<EmailDeliveryResult> {\n // A driver that doesn't extend `EmailDriver`, or a subclass that only\n // overrides `send`, is called through `send`.\n return deliverThrough(this.driver, params);\n }\n}\n"
10
10
  ],
11
11
  "mappings": ";yCAEO,MAAe,CAAY,CAKvB,SAAmB,SAMnB,uBAAkC,QASrC,QAAO,CAAC,EAAuD,CACnE,IAAM,EAAK,MAAM,KAAK,KAAK,CAAM,EACjC,MAAO,CAAE,GAAI,QAAQ,CAAE,EAAG,GAAI,IAAK,EAEvC,CCvBO,MAAM,UAAqB,CAAY,CAIxB,OAHF,SAAW,SACX,uBAAyB,GAE3C,WAAW,CAAS,EAAS,QAAQ,IAAI,eAAgB,CACvD,MAAM,EADY,mBAId,KAAI,CAAC,EAAyB,CAClC,OAAQ,MAAM,KAAK,QAAQ,CAAM,GAAG,QAGvB,QAAO,CAAC,EAAuD,CAO5E,IAAQ,UAAW,KAAa,+BAC1B,EAAS,IAAI,EAAO,KAAK,MAAM,GAG7B,oBAAmB,GAAY,GAC/B,OAAM,SAAU,MAAM,EAAO,OAAO,KAC1C,EACA,EAAiB,CAAE,gBAAe,EAAI,MACxC,EAEA,GAAI,EAEF,OADA,QAAQ,MAAM,CAAK,EACZ,CAAE,GAAI,GAAO,GAAI,KAAM,OAAM,EAGtC,GAAI,EACF,MAAO,CAAE,GAAI,GAAM,GAAI,EAAK,IAAM,IAAK,EAGzC,MAAO,CAAE,GAAI,GAAO,GAAI,IAAK,EAEjC,CCvBO,SAAS,CAAgB,CAAC,EAAgC,CAC/D,OAAO,EAGF,SAAS,CAAkB,EAAyB,CACzD,MAAO,CACL,OAAQ,IAAI,EACZ,QAAS,CAAC,EACV,QAAS,CAAC,EACV,iBAAkB,CAAC,IAAW,CAChC,ECjBF,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C",
12
- "debugId": "29B0598D76B4838464756E2164756E21",
12
+ "debugId": "35B40017364BF62C64756E2164756E21",
13
13
  "names": []
14
14
  }
@@ -0,0 +1,39 @@
1
+ // @bun
2
+ import{cl as m}from"./chunk-0k2r6bep.js";import{el as H,fl as C,jl as A,ll as E}from"./chunk-0av1gyns.js";import{Nl as g}from"./chunk-zmt5kdpb.js";import{um as k}from"./chunk-6r7956dh.js";import{Qm as l}from"./chunk-3dkv4989.js";class V extends Error{lock;token;constructor(J,Y,Z="its lease ran out or another holder took it"){super(`Lost the lock "${J}" (token ${Y}): ${Z}.`);this.lock=J;this.token=Y;this.name="LockLostError"}}var d=60000,h=100,c=(J)=>new Promise((Y)=>setTimeout(Y,J));class T{store;name;owner;token;ttl;lost;controller=new AbortController;deadline;expiryTimer;renewTimer;done=!1;constructor(J,Y,Z,$,j,W){this.store=J;this.name=Y;this.owner=Z;this.token=$;this.ttl=j;this.lost=this.controller.signal,this.deadline=W+j,this.armExpiry()}get expired(){return this.lost.aborted||performance.now()>=this.deadline}async extend(J=this.ttl){if(this.lost.aborted)return!1;let Y=performance.now();if(!await this.store.extend(this.name,this.owner,this.token,J))return this.markLost(),!1;if(this.done)return!0;return this.deadline=Math.max(this.deadline,Y+J),this.armExpiry(),!0}async isHeld(){if(this.lost.aborted)return!1;let J=await this.store.held(this.name,this.owner,this.token);if(!J)this.markLost();return J}async fence(J){if(this.lost.aborted)throw new V(this.name,this.token);try{return await this.store.fence(this.name,this.owner,this.token,J)}catch(Y){if(Y instanceof V)this.markLost();throw Y}}async release(){if(this.stop(),this.lost.aborted)return!1;return this.store.release(this.name,this.owner,this.token)}startRenewing(){if(this.renewTimer||this.done)return;this.renewTimer=setInterval(()=>{this.extend().catch((J)=>{console.error(`[gemi] Could not renew the lock "${this.name}".`,J)})},Math.max(1,Math.floor(this.ttl/3))),this.renewTimer.unref?.()}markLost(J){if(this.stop(),!this.lost.aborted)this.controller.abort(new V(this.name,this.token,J))}stop(){this.done=!0,clearInterval(this.renewTimer),clearTimeout(this.expiryTimer),this.renewTimer=void 0,this.expiryTimer=void 0}armExpiry(){clearTimeout(this.expiryTimer),this.expiryTimer=setTimeout(()=>this.markLost("its lease ran out before it was renewed"),Math.max(0,this.deadline-performance.now())),this.expiryTimer.unref?.()}}class i{store;static token="locks";constructor(J){this.store=J}async acquire(J,Y={}){let Z=Y.ttl??d;if(!(Z>0))throw Error(`A lock's ttl must be a positive number of milliseconds; got ${Z}.`);let $=Bun.randomUUIDv7(),j=performance.now()+Math.max(0,Y.wait??0);for(;;){let W=performance.now(),z=await this.store.acquire(J,$,Z);if(z!==null){let X=new T(this.store,J,$,z,Z,W);if(Y.renew)X.startRenewing();return X}let G=j-performance.now();if(G<=0)return null;await c(Math.min(h,G))}}async run(J,Y,Z){let $=await this.acquire(J,{...Y,renew:Y.renew??!0});if(!$)return{acquired:!1};let j;try{j=await Z($)}catch(W){throw await $.release().catch(()=>{}),W}if($.expired)throw $.markLost(),$.lost.reason;return await $.release(),{acquired:!0,value:j}}}function VJ(J){return J}function S(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function O(J){let Y=new URLSearchParams;for(let[Z,$]of J)Y.append(Z,String($));return Y.toString()}function R(J){let Y=new Map;if(!J)return Y;let Z;try{Z=new URLSearchParams(J)}catch{return Y}for(let[$,j]of Z){let W=Number(j);if(j!==""&&Number.isSafeInteger(W)&&W>=0)Y.set($,W)}return Y}var{SQL:s}=globalThis.Bun;function t(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var o=async(J)=>{let Y=new s(J,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(Z,$,j)=>Y.listen(Z,$,j),close:()=>Y.close({timeout:1})}},a=async(J)=>{let Y;try{Y=(await import("./chunk-k16phdjv.js")).default}catch($){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:$})}let Z=Y(J,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:($,j,W)=>Z.listen($,j,W),close:()=>Z.end({timeout:1}).catch(()=>{})}},y=(J)=>t()?o(J):a(J);var r=/^[A-Za-z_][A-Za-z0-9_]*$/;class x{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor(J,Y={}){if(J.dialect!=="postgres"&&J.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${J.dialect}.`);let Z=Y.headsTable??"gemi_change_heads",$=Y.entriesTable??"gemi_changes",j=Y.notifyChannel??"gemi_changes";for(let z of[Z,$,j])if(!r.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let W=Y.retain??1000;if(!Number.isInteger(W)||W<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${W}.`);this.headsTable=Z,this.entriesTable=$,this.notifyChannel=j,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name,this.url=J.url,this.retain=W,this.listener=Y.listener??y}async createTable(){for(let J of n(this.headsTable,this.entriesTable))await this.sql.unsafe(J)}joinsTransaction(){return this.transaction()!==void 0}publish(J,Y){let Z=this.transaction();if(!Z){let j=()=>this.sql.begin((z)=>this.append(z,J,Y));if(this.dialect!=="sqlite")return j();let W=this.sqliteTurn.then(j);return this.sqliteTurn=W.catch(()=>{}),W}let $=this.append(Z,J,Y);return E($),$}async append(J,Y,Z){let $=J.unsafe(`"${this.headsTable}"`),j=J.unsafe(`"${this.entriesTable}"`),[W]=await J`
3
+ INSERT INTO ${$} (channel, seq) VALUES (${Y}, 1)
4
+ ON CONFLICT (channel) DO UPDATE SET seq = ${$}.seq + 1
5
+ RETURNING seq
6
+ `,z=Number(W.seq);if(await J`
7
+ INSERT INTO ${j} (channel, seq, data, created_at)
8
+ VALUES (${Y}, ${z}, ${JSON.stringify(Z??null)}, ${Date.now()})
9
+ `,z>this.retain)await J`DELETE FROM ${j} WHERE channel = ${Y} AND seq <= ${z-this.retain}`;if(this.dialect==="postgres")await J`SELECT pg_notify(${this.notifyChannel}, ${`${z} ${Y}`})`;return z}async heads(J){let Y=new Map(J.map((j)=>[j,0]));if(J.length===0)return Y;let Z=this.transaction()??this.sql,$=await Z`
10
+ SELECT channel, seq FROM ${Z.unsafe(`"${this.headsTable}"`)}
11
+ WHERE channel IN ${Z([...J])}
12
+ `;for(let j of $)Y.set(j.channel,Number(j.seq));return Y}async read(J,Y,Z){let $=this.sql,[j]=await $`
13
+ SELECT seq FROM ${$.unsafe(`"${this.headsTable}"`)} WHERE channel = ${J}
14
+ `,W=j?Number(j.seq):0;if(Y>W)return{entries:[],head:W,gap:!0};if(Y===W)return{entries:[],head:W,gap:!1};let z=await $`
15
+ SELECT seq, data FROM ${$.unsafe(`"${this.entriesTable}"`)}
16
+ WHERE channel = ${J} AND seq > ${Y}
17
+ ORDER BY seq
18
+ LIMIT ${Z}
19
+ `;if(z.length===0||Number(z[0].seq)!==Y+1)return{entries:[],head:W,gap:!0};return{entries:z.map((G)=>({seq:Number(G.seq),data:JSON.parse(G.data)})),head:W,gap:!1}}async listen(J,Y){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let Z=await this.listener(this.url);try{await Z.listen(this.notifyChannel,($)=>{let j=$.indexOf(" "),W=Number($.slice(0,j));if(j>0&&Number.isInteger(W))J($.slice(j+1),W)},Y)}catch($){throw await Z.close(),$}return{close:()=>Z.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let J=H();if(J===void 0||C()!==this.connection)return;return J}}function n(J,Y){return[`CREATE TABLE IF NOT EXISTS "${J}" (
20
+ "channel" TEXT NOT NULL PRIMARY KEY,
21
+ "seq" BIGINT NOT NULL
22
+ )`,`CREATE TABLE IF NOT EXISTS "${Y}" (
23
+ "channel" TEXT NOT NULL,
24
+ "seq" BIGINT NOT NULL,
25
+ "data" TEXT NOT NULL,
26
+ "created_at" BIGINT NOT NULL,
27
+ PRIMARY KEY ("channel", "seq")
28
+ )`]}class I{logs=new Map;retain;constructor(J={}){let Y=J.retain??1000;if(!Number.isInteger(Y)||Y<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Y}.`);this.retain=Y}async publish(J,Y){let Z=this.logs.get(J);if(!Z)Z={head:0,entries:[]},this.logs.set(J,Z);let $=++Z.head;if(Z.entries.push({seq:$,data:Y===void 0?null:structuredClone(Y)}),Z.entries.length>this.retain)Z.entries.splice(0,Z.entries.length-this.retain);return $}async heads(J){return new Map(J.map((Y)=>[Y,this.logs.get(Y)?.head??0]))}async read(J,Y,Z){let $=this.logs.get(J),j=$?.head??0;if(Y>j)return{entries:[],head:j,gap:!0};if(!$||Y===j)return{entries:[],head:j,gap:!1};let W=$.entries[0]?.seq??j+1;if(W>Y+1)return{entries:[],head:j,gap:!0};let z=Y+1-W;return{entries:$.entries.slice(z,z+Z),head:j,gap:!1}}}var M=new TextEncoder;function L(J){return`id: ${J.seq}
29
+ data: ${JSON.stringify(J.event)}
30
+
31
+ `}var e=5000,N=`: keepalive
32
+
33
+ `;function JJ(J,Y=e){let Z=null,$=!1,j=()=>{if($)return;if(Z!==null)clearTimeout(Z);Z=setTimeout(()=>{if(Z=null,$)return;try{J.enqueue(M.encode(N))}catch{W();return}j()},Y)},W=()=>{if($=!0,Z!==null)clearTimeout(Z);Z=null};return j(),{touch:j,stop:W}}function _(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function MJ(J,Y=200){let Z=J[Symbol.asyncIterator](),$=-1,j,W=new ReadableStream({start(z){j=JJ(z)},async pull(z){try{let G=await Z.next();if(G.done){j.stop(),z.close();return}$=G.value.seq,z.enqueue(M.encode(L(G.value))),j.touch()}catch(G){let X={type:"error",error:ZJ(G)};j.stop(),z.enqueue(M.encode(L({seq:$+1,event:X}))),z.close()}},cancel(z){j.stop(),Z.return?.(z)}});return new Response(W,{status:Y,headers:_()})}var YJ=new Set(["frame_cursor_evicted","live_run_not_found"]);function ZJ(J){let Y=J&&typeof J==="object"?J.code:void 0;if(J instanceof Error&&typeof Y==="string"&&YJ.has(Y))return{code:"unknown",message:J.message,retryable:!1};return console.error("[gemi/ai] agent stream failed",J),{code:"unknown",message:"The run's stream failed.",retryable:!1}}var w=new TextEncoder;function b(J,Y){return w.encode(`id: ${J}
34
+ data: ${JSON.stringify(Y)}
35
+
36
+ `)}function v(J,Y,Z,$){let j=Y instanceof Request?Y:Y.rawRequest,W=$.cursor??j.headers.get("Last-Event-ID")??new URL(j.url).searchParams.get("cursor"),z;try{z=J.subscribe(Z,{cursor:W,signal:j.signal})}catch(Q){if(!(Q instanceof P))throw Q;return new Response(JSON.stringify({error:"The change feed is at capacity."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":String($.retryAfter??5)}})}let G=null,X=!1,U=!1,B=(Q)=>{if(G)clearInterval(G);if(G=null,z.close(),U)return;U=!0;try{Q.close()}catch{}},p=new ReadableStream({start(Q){G=setInterval(()=>{if(k())return B(Q);try{Q.enqueue(w.encode(N))}catch{B(Q)}},J.config.keepaliveInterval)},async pull(Q){try{if(!X){if(await z.ready(),X=!0,!U)Q.enqueue(b(z.cursor,{type:"ready"}));return}let K=await z.next();if(K.done||U)return B(Q);Q.enqueue(b(z.cursor,K.value))}catch(K){if(!U)console.error("[gemi] A change feed stream failed.",K);B(Q)}},cancel(){if(U=!0,G)clearInterval(G);G=null,z.close()}});return new Response(p,{headers:_()})}var q=255,f=500,$J=30000;class P extends Error{limit;constructor(J){super(`The change feed holds its limit of ${J} subscriptions.`);this.limit=J;this.name="ChangeFeedFullError"}}class jJ{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=f;pollTimer=null;polling=null;constructor(J={},Y={}){this.options=Y;this.config=m(S(),J),this.driver=zJ(this.config.driver,Y.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish(J,Y){F(J);let Z=Y===void 0?null:Y;if(H()!==void 0&&!this.driver.joinsTransaction?.())return A(async()=>{this.wake(J,await this.driver.publish(J,Z))}),null;let $=await this.driver.publish(J,Z);return A(()=>this.wake(J,$)),$}async head(J){return F(J),(await this.driver.heads([J])).get(J)??0}async cursor(J){let Y=D(J);return O(await this.driver.heads(Y))}subscribe(J,Y={}){let Z=D(J);if(this.all.size>=this.config.maxSubscriptions)throw new P(this.config.maxSubscriptions);let $=new u(this,Z,WJ(Y.cursor),this.config,Y.signal);this.all.add($);for(let j of Z){let W=this.followers.get(j);if(!W)this.followers.set(j,W=new Set);W.add($)}return this.startListening(),this.startPolling(),$}stream(J,Y,Z={}){return v(this,J,D(Y),Z)}async close(){if(this.listenState="closed",this.retryTimer)clearTimeout(this.retryTimer);this.retryTimer=null,this.stopPolling();for(let Y of this.all)Y.close();let J=this.listening;this.listening=null,await J?.close(),await this.driver.close?.()}forget(J){if(!this.all.delete(J))return;for(let Y of J.channels){let Z=this.followers.get(Y);if(Z?.delete(J),Z?.size===0)this.followers.delete(Y)}if(this.all.size===0)this.stopPolling()}poll(){return this.polling??=(async()=>{try{let J=[...this.followers.keys()];for(let Y=0;Y<J.length;Y+=500){let Z=await this.driver.heads(J.slice(Y,Y+500));for(let[$,j]of Z)this.wake($,j)}}catch(J){console.error("[gemi] The change feed could not read its channels' heads.",J)}finally{this.polling=null}})(),this.polling}startPolling(){if(this.pollTimer)return;this.pollTimer=setInterval(()=>void this.poll(),this.config.pollInterval),this.pollTimer.unref?.()}stopPolling(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null}wake(J,Y){for(let Z of this.followers.get(J)??[])Z.moved(J,Y)}resync(){this.poll()}startListening(){if(this.listenState!=="off"||!this.driver.listen)return;this.connect()}async connect(){this.listenState="connecting",this.retryTimer=null;try{let J=await this.driver.listen((Y,Z)=>this.wake(Y,Z),()=>this.resync());if(this.listenState!=="connecting"){await J.close();return}this.listening=J,this.listenState="listening",this.backoffMs=f,this.resync()}catch(J){if(this.listenState!=="connecting")return;console.error(`[gemi] The change feed could not listen for other instances' changes; retrying in ${this.backoffMs}ms.`,J),this.listenState="retrying",this.retryTimer=setTimeout(()=>void this.connect(),this.backoffMs),this.retryTimer.unref?.(),this.backoffMs=Math.min(this.backoffMs*2,$J)}}}class u{manager;config;signal;channels;positions=new Map;readTo=new Map;dirty=new Set;pending=[];started=null;wakeUp=null;closed=!1;onAbort=()=>this.close();constructor(J,Y,Z,$,j){this.manager=J;this.config=$;this.signal=j;this.channels=Y;for(let W of Y){let z=Z.get(W);if(z!==void 0)this.positions.set(W,z),this.readTo.set(W,z),this.dirty.add(W)}if(j?.aborted)this.close();else j?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return O(this.positions)}get isClosed(){return this.closed}ready(){return this.started??=(async()=>{let J=this.channels.filter((Z)=>!this.positions.has(Z));if(J.length===0)return;let Y=await this.manager.driver.heads(J);for(let Z of J){let $=Y.get(Z)??0;this.positions.set(Z,$),this.readTo.set(Z,$)}})(),this.started}async next(){await this.ready();for(;;){if(this.closed)return{done:!0,value:void 0};let J=this.pending.shift();if(J)return this.positions.set(J.channel,J.seq),{done:!1,value:J};let Y=this.dirty.values().next().value;if(Y!==void 0){await this.read(Y);continue}await this.idle()}}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}close(){if(this.closed)return;this.closed=!0,this.pending.length=0,this.signal?.removeEventListener("abort",this.onAbort),this.manager.forget(this),this.wake()}moved(J,Y){let Z=this.readTo.get(J);if(Z!==void 0&&Y===Z)return;this.dirty.add(J),this.wake()}async read(J){let Y=this.readTo.get(J)??0;this.dirty.delete(J);let{batchSize:Z}=this.config,{entries:$,head:j,gap:W}=await this.manager.driver.read(J,Y,Z);if(this.closed)return;if(W){this.readTo.set(J,j),this.pending.push({type:"reset",channel:J,seq:j});return}for(let z of $)this.readTo.set(J,z.seq),this.pending.push({type:"change",channel:J,seq:z.seq,data:z.data});if($.length===Z)this.dirty.add(J)}idle(){return new Promise((J)=>{this.wakeUp=J})}wake(){let J=this.wakeUp;this.wakeUp=null,J?.()}}function F(J){if(typeof J!=="string"||J===""||J.length>q)throw Error(`A change feed channel is a string of 1 to ${q} characters; got ${JSON.stringify(J)}.`)}function D(J){let Y=[...new Set(typeof J==="string"?[J]:J)];if(Y.length===0)throw Error("A change feed subscription needs at least one channel.");for(let Z of Y)F(Z);return Y}function WJ(J){if(J===void 0||J===null)return new Map;if(typeof J==="string")return R(J);let Y=J instanceof Map?[...J]:Object.entries(J);return R(O(new Map(Y)))}function zJ(J,Y){if(J==="memory")return new I;if(J==="database"||typeof J==="function"){if(!Y&&(J==="database"||J.length>0))throw Error("The change feed driver needs the application it belongs to, and this ChangeFeedManager was built without one. Pass { application }.");if(J==="database")return new x(Y.make(g));return J(Y)}if(typeof J==="string")throw Error(`Unknown change feed driver "${J}". The changeFeed slice's driver is "memory", "database", a ChangeFeedDriver, or a function returning one.`);return J}var GJ={ms:1,s:1000,m:60000,h:3600000,d:86400000,w:604800000};function vJ(J){if(typeof J==="number"){if(!Number.isFinite(J)||J<0)throw TypeError(`A duration is 0 or more milliseconds; got ${J}.`);return Math.round(J)}let Y=/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w)\s*$/.exec(String(J));if(!Y)throw TypeError(`"${String(J)}" is not a duration. Use milliseconds, or a number and one of ms, s, m, h, d, w ("30s", "7d").`);return Math.round(Number(Y[1])*GJ[Y[2]])}
37
+ export{vJ as Nk,V as Ok,T as Pk,i as Qk,VJ as Rk,S as Sk,O as Tk,R as Uk,x as Vk,I as Wk,L as Xk,JJ as Yk,_ as Zk,MJ as _k,P as $k,jJ as al,u as bl};
38
+
39
+ //# debugId=357E3187D90D9AE464756E2164756E21
@@ -0,0 +1,20 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../services/lock/LockStore.ts", "../services/lock/LockManager.ts", "../services/change-feed/config.ts", "../services/change-feed/cursor.ts", "../services/change-feed/postgresListen.ts", "../services/change-feed/DatabaseChangeFeedDriver.ts", "../services/change-feed/MemoryChangeFeedDriver.ts", "../ai/store/sse.ts", "../services/change-feed/stream.ts", "../services/change-feed/ChangeFeedManager.ts", "../services/queue/workflow/duration.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * Where locks are kept: one record per lock name, with the current holder, a\n * fencing token and a lease.\n *\n * ### The model\n *\n * A lock is held by an **owner** (a random id per acquisition, or a job's id)\n * until its **lease** runs out or the owner releases it. Every successful\n * `acquire` raises the name's **token** by one, so tokens only grow per name and\n * a newer holder always has a larger one than any older holder. A store never\n * forgets a name on release, which is what keeps the token growing; `prune`\n * (on a store that has it) removes names idle for long enough.\n *\n * A lease that runs out is lost, even if nobody has taken the lock since:\n * `extend`, `held` and `fence` all refuse it. That is the rule that makes the\n * token mean something. A holder whose process stalled past its lease cannot\n * renew its way back in after another process may have started the same work.\n *\n * ### Time\n *\n * Durations cross this interface as relative milliseconds, as they do for\n * `QueueDriver`, so a store shared between machines can measure every lease on\n * one clock, its own.\n */\nexport interface LockStore {\n /**\n * Takes `name` for `owner` for `ttlMs`, if nobody holds it or the holder's\n * lease ran out, and resolves to the new fencing token. `null` when it is\n * held. Two concurrent calls, from any processes sharing the store, never\n * both succeed.\n */\n acquire(name: string, owner: string, ttlMs: number): Promise<number | null>;\n\n /**\n * Renews a lease to `ttlMs` from now, and resolves to whether `owner` still\n * held it with `token`. A lease that already ran out is not renewed.\n */\n extend(name: string, owner: string, token: number, ttlMs: number): Promise<boolean>;\n\n /**\n * Ends a hold, and resolves to whether `owner` held it (with `token`, when\n * given) and its lease had not run out. Releasing a lock someone else now\n * holds does nothing.\n */\n release(name: string, owner: string, token?: number): Promise<boolean>;\n\n /** The current holder, or `null` when the lock is free or its lease ran out. */\n holder(name: string): Promise<{ owner: string; token: number } | null>;\n\n /** Whether `owner` still holds `name` with `token`, its lease running. */\n held(name: string, owner: string, token: number): Promise<boolean>;\n\n /**\n * Raises a counter kept under `name` to `value` if it is below it, and\n * resolves to whether it did. For \"once per tick across instances\": every\n * instance advances to the tick's number and only the first one gets `true`.\n * A name used here must not also be used with `acquire`.\n */\n advance(name: string, value: number): Promise<boolean>;\n\n /**\n * Runs `fn` only if `owner` still holds `name` with `token`, and keeps the\n * lock from changing hands until `fn` settles. Rejects with `LockLostError`\n * when the hold is gone. On the database store this is a transaction that\n * locks the lock's row first, so writes `fn` makes through the ORM on the\n * same connection commit only while the hold is current, and a new holder's\n * `acquire` waits for that commit.\n */\n fence<T>(name: string, owner: string, token: number, fn: () => Promise<T>): Promise<T>;\n\n /**\n * Counts one hit against a fixed window kept under `name`: allowed when\n * fewer than `limit` were counted in the current window, which starts at the\n * first hit after the last one ended and lasts `windowMs`. A refused hit is\n * not counted. `resetInMs` is how long until the window ends. A name used\n * here must not also be used with `acquire` or `advance`.\n */\n hit(\n name: string,\n limit: number,\n windowMs: number,\n ): Promise<{ allowed: boolean; resetInMs: number }>;\n\n /** Takes back one counted hit from the current window, if it has one. */\n refund(name: string): Promise<void>;\n}\n\n/** The hold on a lock ended before the work it guarded did. */\nexport class LockLostError extends Error {\n constructor(\n readonly lock: string,\n readonly token: number,\n detail = \"its lease ran out or another holder took it\",\n ) {\n super(`Lost the lock \"${lock}\" (token ${token}): ${detail}.`);\n this.name = \"LockLostError\";\n }\n}\n",
6
+ "import { LockLostError, type LockStore } from \"./LockStore\";\n\nexport type AcquireOptions = {\n /** The lease, in milliseconds. Default one minute. */\n ttl?: number;\n /**\n * How long to keep trying when the lock is held, in milliseconds. Default\n * `0`: one try.\n */\n wait?: number;\n /**\n * Renew the lease every third of `ttl` until the lock is released. Default\n * `true` for `run`, `false` for `acquire`, whose caller may never release.\n */\n renew?: boolean;\n};\n\nexport type LockRunResult<T> = { acquired: true; value: T } | { acquired: false };\n\nconst DEFAULT_TTL = 60_000;\nconst WAIT_STEP = 100;\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * One hold on a lock, from a successful `acquire` until `release` or the end\n * of its lease.\n *\n * `token` is the fencing token: it grows with each new holder of the name, so\n * a write that records it can be refused when an older holder tries to make\n * it late. `fence` does that refusal for writes to the application's own\n * database.\n *\n * `lost` aborts when the hold is known to be gone: a renewal found another\n * holder, or the lease ran out by this process's clock without a successful\n * renewal. The local deadline is measured from just before each request that\n * set the lease, so it always falls before the store's own expiry.\n */\nexport class HeldLock {\n readonly lost: AbortSignal;\n private readonly controller = new AbortController();\n private deadline: number;\n private expiryTimer: ReturnType<typeof setTimeout> | undefined;\n private renewTimer: ReturnType<typeof setInterval> | undefined;\n private done = false;\n\n constructor(\n private readonly store: LockStore,\n readonly name: string,\n readonly owner: string,\n readonly token: number,\n readonly ttl: number,\n requestedAt: number,\n ) {\n this.lost = this.controller.signal;\n this.deadline = requestedAt + ttl;\n this.armExpiry();\n }\n\n /** Whether the lease has run out by this process's clock, or the hold was lost. */\n get expired(): boolean {\n return this.lost.aborted || performance.now() >= this.deadline;\n }\n\n /** Renews the lease. `false`, and `lost` aborted, when the hold was already gone. */\n async extend(ttl = this.ttl): Promise<boolean> {\n if (this.lost.aborted) return false;\n const requestedAt = performance.now();\n const ok = await this.store.extend(this.name, this.owner, this.token, ttl);\n if (!ok) {\n this.markLost();\n return false;\n }\n if (this.done) return true;\n this.deadline = Math.max(this.deadline, requestedAt + ttl);\n this.armExpiry();\n return true;\n }\n\n /** Asks the store whether this hold is still current. */\n async isHeld(): Promise<boolean> {\n if (this.lost.aborted) return false;\n const held = await this.store.held(this.name, this.owner, this.token);\n if (!held) this.markLost();\n return held;\n }\n\n /**\n * Runs `fn` only while this hold is current, and keeps the lock from\n * changing hands until it settles; rejects with `LockLostError` otherwise.\n * On the database store `fn` runs in a transaction on the store's\n * connection, so ORM writes inside it commit only if the hold was current.\n */\n async fence<T>(fn: () => Promise<T>): Promise<T> {\n if (this.lost.aborted) throw new LockLostError(this.name, this.token);\n try {\n return await this.store.fence(this.name, this.owner, this.token, fn);\n } catch (error) {\n if (error instanceof LockLostError) this.markLost();\n throw error;\n }\n }\n\n /** Ends the hold. `false` when it had already been lost. */\n async release(): Promise<boolean> {\n this.stop();\n if (this.lost.aborted) return false;\n return this.store.release(this.name, this.owner, this.token);\n }\n\n /** Renews every third of the lease until `release`. */\n startRenewing() {\n if (this.renewTimer || this.done) return;\n this.renewTimer = setInterval(\n () => {\n this.extend().catch((error) => {\n // Not lost yet: the local deadline still decides, so a store that\n // comes back within the lease keeps the hold.\n console.error(`[gemi] Could not renew the lock \"${this.name}\".`, error);\n });\n },\n Math.max(1, Math.floor(this.ttl / 3)),\n );\n this.renewTimer.unref?.();\n }\n\n /** @internal Marks the hold as gone and stops every timer. */\n markLost(detail?: string) {\n this.stop();\n if (!this.lost.aborted) {\n this.controller.abort(new LockLostError(this.name, this.token, detail));\n }\n }\n\n private stop() {\n this.done = true;\n clearInterval(this.renewTimer);\n clearTimeout(this.expiryTimer);\n this.renewTimer = undefined;\n this.expiryTimer = undefined;\n }\n\n private armExpiry() {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = setTimeout(\n () => this.markLost(\"its lease ran out before it was renewed\"),\n Math.max(0, this.deadline - performance.now()),\n );\n this.expiryTimer.unref?.();\n }\n}\n\n/**\n * Named locks with leases and fencing tokens, over a `LockStore`. The queue\n * builds one over its own storage (`app(QueueManager).locks`), so with the\n * database driver the locks hold across every process sharing the database.\n * The `Lock` facade fronts it.\n */\nexport class LockManager {\n static token = \"locks\";\n\n constructor(readonly store: LockStore) {}\n\n /** Takes the lock, or resolves `null` if it is held (after `wait`, when given). */\n async acquire(name: string, options: AcquireOptions = {}): Promise<HeldLock | null> {\n const ttl = options.ttl ?? DEFAULT_TTL;\n if (!(ttl > 0))\n throw new Error(`A lock's ttl must be a positive number of milliseconds; got ${ttl}.`);\n const owner = Bun.randomUUIDv7();\n const giveUpAt = performance.now() + Math.max(0, options.wait ?? 0);\n for (;;) {\n const requestedAt = performance.now();\n const token = await this.store.acquire(name, owner, ttl);\n if (token !== null) {\n const lock = new HeldLock(this.store, name, owner, token, ttl, requestedAt);\n if (options.renew) lock.startRenewing();\n return lock;\n }\n const left = giveUpAt - performance.now();\n if (left <= 0) return null;\n await sleep(Math.min(WAIT_STEP, left));\n }\n }\n\n /**\n * Runs `fn` while holding the lock, renewing the lease as it runs, and\n * releases it after. `{ acquired: false }` when the lock was held.\n *\n * If the hold is lost while `fn` runs, `lock.lost` aborts, and once `fn`\n * settles this rejects with `LockLostError` instead of resolving: the caller\n * must not treat work done without the lock as done under it.\n */\n async run<T>(\n name: string,\n options: AcquireOptions,\n fn: (lock: HeldLock) => Promise<T> | T,\n ): Promise<LockRunResult<T>> {\n const lock = await this.acquire(name, { ...options, renew: options.renew ?? true });\n if (!lock) return { acquired: false };\n\n let value: T;\n try {\n value = await fn(lock);\n } catch (error) {\n await lock.release().catch(() => {});\n throw error;\n }\n if (lock.expired) {\n lock.markLost();\n throw lock.lost.reason as LockLostError;\n }\n await lock.release();\n return { acquired: true, value };\n }\n}\n",
7
+ "import type { Application } from \"../../foundation/Application\";\nimport type { ChangeFeedDriver } from \"./ChangeFeedDriver\";\n\n// Config key: `changeFeed` (`app/config/changeFeed.ts`).\nexport interface ChangeFeedConfig {\n /**\n * Where the log is kept: `\"memory\"`, `\"database\"`, a `ChangeFeedDriver`, or\n * a function returning one, called once with the application.\n *\n * `\"memory\"` is the default and works for **one process only**: a\n * subscriber on another instance never hears of a publish here. See\n * `MemoryChangeFeedDriver`.\n *\n * `\"database\"` keeps it in the `gemi_change_heads` and `gemi_changes`\n * tables of the default connection, which have to exist, and on Postgres\n * wakes every instance with `LISTEN`/`NOTIFY`. See\n * `DatabaseChangeFeedDriver`.\n */\n driver?: \"memory\" | \"database\" | ChangeFeedDriver | ((application: Application) => ChangeFeedDriver);\n\n /**\n * How often, in milliseconds, a subscription re-reads its channels even\n * when nothing woke it. A safety net for a notification lost between\n * instances, and the only way a driver without `listen` hears of other\n * processes' publishes. Default `30000`.\n */\n pollInterval?: number;\n\n /**\n * How many subscriptions this process holds at once. One more is refused\n * with `ChangeFeedFullError`, which `stream` answers with a `503` and a\n * `Retry-After`. Default `10000`.\n */\n maxSubscriptions?: number;\n\n /** How many entries a subscription reads from the log at a time. Default `100`. */\n batchSize?: number;\n\n /**\n * How often, in milliseconds, `stream` writes a keepalive comment. Bun's\n * idle timeout closes a silent connection after 10 seconds unless\n * `SERVER_IDLE_TIMEOUT` says otherwise. Default `5000`.\n */\n keepaliveInterval?: number;\n}\n\nexport function defineChangeFeedConfig(config: ChangeFeedConfig): ChangeFeedConfig {\n return config;\n}\n\nexport function changeFeedConfigDefaults(): Required<ChangeFeedConfig> {\n return {\n driver: \"memory\",\n pollInterval: 30_000,\n maxSubscriptions: 10_000,\n batchSize: 100,\n keepaliveInterval: 5_000,\n };\n}\n",
8
+ "/**\n * A subscription's position: the last seq it delivered of each channel,\n * written as a query string, `site%3A42=17&site%3A43=4`.\n *\n * One string for every channel of a stream, because it travels as the SSE\n * event `id`, and the browser sends back only the last one as\n * `Last-Event-ID`. Readable in a network panel, and safe in a header.\n */\nexport type ChangeFeedCursor = ReadonlyMap<string, number>;\n\nexport function encodeCursor(positions: ChangeFeedCursor): string {\n const params = new URLSearchParams();\n for (const [channel, seq] of positions) params.append(channel, String(seq));\n return params.toString();\n}\n\n/**\n * The positions a cursor holds. A malformed one, or one whose seq is not a\n * whole number of 0 or more, is left out: a channel without a position starts\n * from its head, which is what a client with no usable cursor should get.\n */\nexport function decodeCursor(cursor: string | null | undefined): Map<string, number> {\n const positions = new Map<string, number>();\n if (!cursor) return positions;\n let params: URLSearchParams;\n try {\n params = new URLSearchParams(cursor);\n } catch {\n return positions;\n }\n for (const [channel, value] of params) {\n const seq = Number(value);\n if (value !== \"\" && Number.isSafeInteger(seq) && seq >= 0) positions.set(channel, seq);\n }\n return positions;\n}\n",
9
+ "import { SQL } from \"bun\";\n\n/**\n * One `LISTEN` connection: what the database change-feed driver needs from a\n * Postgres client.\n *\n * Bun's `SQL` (1.4 and later) and the `postgres` package share this shape:\n * `listen` resolves once the server acknowledged the `LISTEN`, and both\n * reconnect by themselves after the connection drops and call `onListen`\n * again, which is the moment notifications may have been missed. Measured on\n * Bun 1.4.2 and postgres 3.4.9 with `pg_terminate_backend`.\n */\nexport type PostgresListener = {\n listen(\n channel: string,\n onNotify: (payload: string) => void,\n onListen?: () => void,\n ): Promise<unknown>;\n close(): Promise<void>;\n};\n\n/** Opens a dedicated listening client for `url`. */\nexport type PostgresListenerFactory = (url: string) => Promise<PostgresListener>;\n\n/** Whether this Bun's `SQL` can `LISTEN` (Bun 1.4 and later). */\nexport function bunCanListen(): boolean {\n return Bun.semver.satisfies(Bun.version, \">=1.4.0\");\n}\n\n/** A one-connection Bun `SQL` client. Needs Bun 1.4 or later. */\nexport const bunListener: PostgresListenerFactory = async (url) => {\n const client = new SQL(url, { max: 1, idleTimeout: 0, maxLifetime: 0 }) as SQL & {\n listen: PostgresListener[\"listen\"];\n };\n return {\n listen: (channel, onNotify, onListen) => client.listen(channel, onNotify, onListen),\n close: () => client.close({ timeout: 1 }),\n };\n};\n\n/**\n * A one-connection client from the `postgres` package, for Bun 1.3, whose\n * `SQL` cannot `LISTEN`. The package is an optional peer dependency: install\n * it in the app (`bun add postgres`) to use the database driver across\n * instances on Bun 1.3.\n */\nexport const postgresPackageListener: PostgresListenerFactory = async (url) => {\n let postgres: (url: string, options: Record<string, unknown>) => PostgresJsClient;\n try {\n // A variable specifier, so bundlers and type-checkers do not insist on\n // the optional package being installed.\n const specifier = \"postgres\";\n postgres = ((await import(specifier)) as { default: typeof postgres }).default;\n } catch (cause) {\n throw new Error(\n \"The change feed's database driver needs a Postgres client that can LISTEN: \" +\n \"Bun 1.4 or later, or the `postgres` package (bun add postgres).\",\n { cause },\n );\n }\n const client = postgres(url, {\n max: 1,\n idle_timeout: 0,\n max_lifetime: null,\n fetch_types: false,\n onnotice: () => {},\n });\n return {\n listen: (channel, onNotify, onListen) => client.listen(channel, onNotify, onListen),\n close: () => client.end({ timeout: 1 }).catch(() => {}),\n };\n};\n\ntype PostgresJsClient = {\n listen: PostgresListener[\"listen\"];\n end(options: { timeout: number }): Promise<void>;\n};\n\n/** Bun's own client when it can listen, the `postgres` package otherwise. */\nexport const defaultPostgresListener: PostgresListenerFactory = (url) =>\n bunCanListen() ? bunListener(url) : postgresPackageListener(url);\n",
10
+ "import type { SQL, TransactionSQL } from \"bun\";\n\nimport type { DatabaseConnection } from \"../../database/Connection\";\nimport type { Dialect } from \"../../database/dialect\";\nimport { commitDependsOn, currentConnectionName, currentTransaction } from \"../../orm/context\";\nimport type { ChangeFeedDriver, ChangeFeedRead } from \"./ChangeFeedDriver\";\nimport { defaultPostgresListener, type PostgresListenerFactory } from \"./postgresListen\";\n\nexport type DatabaseChangeFeedDriverOptions = {\n /** The heads table: one row per channel. Default `gemi_change_heads`. */\n headsTable?: string;\n /** The entries table: the kept log. Default `gemi_changes`. */\n entriesTable?: string;\n /** Entries kept per channel. Default `1000`. */\n retain?: number;\n /**\n * The Postgres `NOTIFY` channel that wakes other instances. Default\n * `gemi_changes`. Instances share a feed only when they use the same one.\n */\n notifyChannel?: string;\n /**\n * Opens the `LISTEN` connection. Default: Bun's `SQL` on Bun 1.4 and later,\n * the `postgres` package (an optional peer dependency) before that.\n */\n listener?: PostgresListenerFactory;\n};\n\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\ntype Connection = Pick<DatabaseConnection, \"sql\" | \"dialect\"> &\n Partial<Pick<DatabaseConnection, \"name\" | \"url\">>;\n\n/**\n * A change feed kept in two tables of the application's database: a head row\n * per channel holding its latest seq, and the last `retain` entries of each\n * channel. Works on Postgres and SQLite; MySQL is not supported yet.\n *\n * ### Publishing\n *\n * A publish raises the channel's head with an upsert and inserts the entry,\n * in one transaction: the caller's ORM transaction when one is open on this\n * driver's connection (Postgres only, see `transaction`), its own otherwise.\n * The upsert locks the head row until that transaction ends, so publishers to\n * one channel take turns and seqs become visible in order. Publishers to\n * different channels do not wait for each other.\n *\n * ### Across instances\n *\n * On Postgres a publish also runs `pg_notify` in the same transaction, which\n * Postgres delivers only on commit, and only if it commits. `listen` holds\n * one `LISTEN` connection per process; a reconnect after a drop calls\n * `onResync`, because notifications sent meanwhile are gone. On SQLite there\n * is nobody else to tell: one process owns the file.\n */\nexport class DatabaseChangeFeedDriver implements ChangeFeedDriver {\n readonly headsTable: string;\n readonly entriesTable: string;\n readonly notifyChannel: string;\n private readonly sql: SQL;\n private readonly dialect: Dialect;\n private readonly connection: string | undefined;\n private readonly url: string | undefined;\n private readonly retain: number;\n private readonly listener: PostgresListenerFactory;\n private sqliteTurn: Promise<unknown> = Promise.resolve();\n\n constructor(connection: Connection, options: DatabaseChangeFeedDriverOptions = {}) {\n if (connection.dialect !== \"postgres\" && connection.dialect !== \"sqlite\") {\n throw new Error(\n `The change feed's database driver supports Postgres and SQLite, not ${connection.dialect}.`,\n );\n }\n const headsTable = options.headsTable ?? \"gemi_change_heads\";\n const entriesTable = options.entriesTable ?? \"gemi_changes\";\n const notifyChannel = options.notifyChannel ?? \"gemi_changes\";\n for (const name of [headsTable, entriesTable, notifyChannel]) {\n if (!IDENTIFIER.test(name)) {\n throw new Error(\n `\"${name}\" is not a plain identifier. Use letters, digits and underscores.`,\n );\n }\n }\n const retain = options.retain ?? 1000;\n if (!Number.isInteger(retain) || retain < 1) {\n throw new Error(`The change feed's retain must be a whole number, 1 or more; got ${retain}.`);\n }\n this.headsTable = headsTable;\n this.entriesTable = entriesTable;\n this.notifyChannel = notifyChannel;\n this.sql = connection.sql;\n this.dialect = connection.dialect;\n this.connection = connection.name;\n this.url = connection.url;\n this.retain = retain;\n this.listener = options.listener ?? defaultPostgresListener;\n }\n\n /**\n * Creates both tables if they do not exist, the same DDL Prisma generates\n * for the models in the docs. For tests and apps that do not manage their\n * schema with Prisma.\n */\n async createTable(): Promise<void> {\n for (const statement of createTableStatements(this.headsTable, this.entriesTable)) {\n await this.sql.unsafe(statement);\n }\n }\n\n joinsTransaction(): boolean {\n return this.transaction() !== undefined;\n }\n\n publish(channel: string, data: unknown): Promise<number> {\n // Read at the call, never kept: Bun's handle stays callable after its\n // transaction ended and then runs on the pool, outside any transaction.\n const tx = this.transaction();\n if (!tx) {\n const publish = () => this.sql.begin((own) => this.append(own, channel, data));\n if (this.dialect !== \"sqlite\") return publish();\n // Bun gives SQLite one connection, and a second `begin` while one is\n // open fails (\"cannot start a transaction within a transaction\"), so\n // this process's publishes take turns.\n const turn = this.sqliteTurn.then(publish);\n this.sqliteTurn = turn.catch(() => {});\n return turn;\n }\n const written = this.append(tx, channel, data);\n // A failed statement aborts a Postgres transaction, and a COMMIT after\n // that is quietly a rollback. Tying the commit to the write makes the\n // failure the caller's error even when the caller did not await.\n commitDependsOn(written);\n return written;\n }\n\n private async append(q: SQL, channel: string, data: unknown): Promise<number> {\n const heads = q.unsafe(`\"${this.headsTable}\"`);\n const entries = q.unsafe(`\"${this.entriesTable}\"`);\n const [row] = await q`\n INSERT INTO ${heads} (channel, seq) VALUES (${channel}, 1)\n ON CONFLICT (channel) DO UPDATE SET seq = ${heads}.seq + 1\n RETURNING seq\n `;\n const seq = Number(row.seq);\n await q`\n INSERT INTO ${entries} (channel, seq, data, created_at)\n VALUES (${channel}, ${seq}, ${JSON.stringify(data ?? null)}, ${Date.now()})\n `;\n if (seq > this.retain) {\n await q`DELETE FROM ${entries} WHERE channel = ${channel} AND seq <= ${seq - this.retain}`;\n }\n if (this.dialect === \"postgres\") {\n await q`SELECT pg_notify(${this.notifyChannel}, ${`${seq} ${channel}`})`;\n }\n return seq;\n }\n\n async heads(channels: readonly string[]): Promise<Map<string, number>> {\n const heads = new Map(channels.map((channel) => [channel, 0]));\n if (channels.length === 0) return heads;\n // Inside an ORM transaction on this connection, read on it: the caller\n // already holds one pooled connection, and waiting for a second one while\n // holding it can exhaust the pool (#1249). It also sees the transaction's\n // own publishes.\n const q = this.transaction() ?? this.sql;\n const rows: { channel: string; seq: number | string }[] = await q`\n SELECT channel, seq FROM ${q.unsafe(`\"${this.headsTable}\"`)}\n WHERE channel IN ${q([...channels])}\n `;\n for (const row of rows) heads.set(row.channel, Number(row.seq));\n return heads;\n }\n\n async read(channel: string, after: number, limit: number): Promise<ChangeFeedRead> {\n const q = this.sql;\n const [found] = await q`\n SELECT seq FROM ${q.unsafe(`\"${this.headsTable}\"`)} WHERE channel = ${channel}\n `;\n const head = found ? Number(found.seq) : 0;\n if (after > head) return { entries: [], head, gap: true };\n if (after === head) return { entries: [], head, gap: false };\n const rows: { seq: number | string; data: string }[] = await q`\n SELECT seq, data FROM ${q.unsafe(`\"${this.entriesTable}\"`)}\n WHERE channel = ${channel} AND seq > ${after}\n ORDER BY seq\n LIMIT ${limit}\n `;\n if (rows.length === 0 || Number(rows[0]!.seq) !== after + 1) {\n return { entries: [], head, gap: true };\n }\n return {\n entries: rows.map((row) => ({ seq: Number(row.seq), data: JSON.parse(row.data) })),\n head,\n gap: false,\n };\n }\n\n async listen(\n onChange: (channel: string, seq: number) => void,\n onResync: () => void,\n ): Promise<{ close(): Promise<void> }> {\n // One process owns a SQLite file, and the manager wakes its own\n // subscribers after each publish.\n if (this.dialect !== \"postgres\") return { close: async () => {} };\n if (!this.url) {\n throw new Error(\n \"The change feed's database driver needs the connection's url to LISTEN. \" +\n \"Build it from a DatabaseManager connection, which has one.\",\n );\n }\n const client = await this.listener(this.url);\n try {\n await client.listen(\n this.notifyChannel,\n (payload) => {\n const space = payload.indexOf(\" \");\n const seq = Number(payload.slice(0, space));\n if (space > 0 && Number.isInteger(seq)) onChange(payload.slice(space + 1), seq);\n },\n onResync,\n );\n } catch (error) {\n await client.close();\n throw error;\n }\n return { close: () => client.close() };\n }\n\n /**\n * The ORM transaction a publish should be written on, and `heads` read on:\n * one open on this driver's own connection, matched by name as the queue's\n * database driver matches it. Never on SQLite, where Bun has one connection and a read on\n * the pool runs inside the open transaction: a subscriber would deliver an\n * entry that may still roll back, and whose seq would then be reused. There\n * the manager publishes after the commit instead.\n */\n private transaction(): TransactionSQL | undefined {\n if (this.dialect === \"sqlite\" || this.connection === undefined) return undefined;\n const tx = currentTransaction();\n if (tx === undefined || currentConnectionName() !== this.connection) return undefined;\n return tx;\n }\n}\n\n/** The DDL for both tables, Postgres and SQLite alike. */\nexport function createTableStatements(heads: string, entries: string): string[] {\n return [\n `CREATE TABLE IF NOT EXISTS \"${heads}\" (\n \"channel\" TEXT NOT NULL PRIMARY KEY,\n \"seq\" BIGINT NOT NULL\n)`,\n `CREATE TABLE IF NOT EXISTS \"${entries}\" (\n \"channel\" TEXT NOT NULL,\n \"seq\" BIGINT NOT NULL,\n \"data\" TEXT NOT NULL,\n \"created_at\" BIGINT NOT NULL,\n PRIMARY KEY (\"channel\", \"seq\")\n)`,\n ];\n}\n",
11
+ "import type { ChangeFeedDriver, ChangeFeedEntry, ChangeFeedRead } from \"./ChangeFeedDriver\";\n\nexport type MemoryChangeFeedDriverOptions = {\n /** Entries kept per channel. Default `1000`. */\n retain?: number;\n};\n\n/**\n * The default driver: each channel's log in this process's memory.\n *\n * **One process only.** Another instance publishes to its own memory, and a\n * subscriber here never hears of it. A restart forgets every channel, and a\n * client resuming with a cursor from before it gets a `reset`, which is the\n * right answer: what it showed must be read again. Use the database driver\n * once there is more than one instance.\n *\n * It has no `listen`: the manager wakes this process's subscribers itself\n * after each publish, and there is nobody else to hear.\n */\nexport class MemoryChangeFeedDriver implements ChangeFeedDriver {\n private readonly logs = new Map<string, { head: number; entries: ChangeFeedEntry[] }>();\n private readonly retain: number;\n\n constructor(options: MemoryChangeFeedDriverOptions = {}) {\n const retain = options.retain ?? 1000;\n if (!Number.isInteger(retain) || retain < 1) {\n throw new Error(`The change feed's retain must be a whole number, 1 or more; got ${retain}.`);\n }\n this.retain = retain;\n }\n\n async publish(channel: string, data: unknown): Promise<number> {\n let log = this.logs.get(channel);\n if (!log) {\n log = { head: 0, entries: [] };\n this.logs.set(channel, log);\n }\n const seq = ++log.head;\n // A structured clone, so a caller mutating its object afterwards does not\n // change what subscribers read, as it could not with the database driver.\n log.entries.push({ seq, data: data === undefined ? null : structuredClone(data) });\n if (log.entries.length > this.retain) log.entries.splice(0, log.entries.length - this.retain);\n return seq;\n }\n\n async heads(channels: readonly string[]): Promise<Map<string, number>> {\n return new Map(channels.map((channel) => [channel, this.logs.get(channel)?.head ?? 0]));\n }\n\n async read(channel: string, after: number, limit: number): Promise<ChangeFeedRead> {\n const log = this.logs.get(channel);\n const head = log?.head ?? 0;\n if (after > head) return { entries: [], head, gap: true };\n if (!log || after === head) return { entries: [], head, gap: false };\n const first = log.entries[0]?.seq ?? head + 1;\n if (first > after + 1) return { entries: [], head, gap: true };\n const start = after + 1 - first;\n return { entries: log.entries.slice(start, start + limit), head, gap: false };\n }\n}\n",
12
+ "import type { AgentError, AgentStreamFrame } from \"../types\";\n\nconst encoder = new TextEncoder();\n\n/**\n * One frame, one SSE event.\n *\n * `id:` carries the frame's `seq`, which is what makes the browser's own\n * `Last-Event-ID` the right cursor on reconnect — the transport asks the\n * question the run already knows how to answer, and the client never has to\n * track a position of its own.\n */\nexport function encodeFrame(frame: AgentStreamFrame): string {\n return `id: ${frame.seq}\\ndata: ${JSON.stringify(frame.event)}\\n\\n`;\n}\n\n/**\n * How long a connection may sit idle before a comment line goes out.\n *\n * The nearest ceiling is not a proxy but our own server: Bun's `idleTimeout`\n * counts socket silence, a streaming body included, and gemi runs at its\n * 10-second default unless `SERVER_IDLE_TIMEOUT` says otherwise. A comment\n * line every 25 seconds was measured to lose the connection at 12; every 5\n * keeps it open, with room for a write that lands late. Azure App Service's\n * front end, at about 230 seconds, is the far ceiling, and 5 clears it by the\n * same margin. A thousand quiet streams cost two hundred thirteen-byte writes\n * a second, which is nothing. Both encoders read this one value, so the two\n * cannot drift apart.\n */\nexport const SSE_KEEPALIVE_INTERVAL_MS = 5_000;\n\n/**\n * The comment line itself. A line starting with `:` is a comment under the SSE\n * spec: every parser on our side skips it, and so does the browser's own\n * `EventSource`.\n */\nexport const SSE_KEEPALIVE = \": keepalive\\n\\n\";\n\n/**\n * Writes a keepalive whenever the stream has been silent for the interval.\n *\n * Armed on creation because the silence before the first frame is real\n * silence too — a model thinking is the common case. `touch()` after every\n * frame is what makes it measure silence rather than elapsed time; `stop()`\n * on close or cancel is what keeps a finished stream from holding a timer.\n *\n * The write is guarded because a cancel can land between the timer firing and\n * the enqueue, and a closed controller throws. There is nothing to do about\n * that except stop. `arm` checks `stopped` too, so a `touch()` that arrives\n * after `stop()` cannot hand a finished stream a timer for one more interval.\n */\nexport function sseKeepalive(\n controller: ReadableStreamDefaultController<Uint8Array>,\n intervalMs = SSE_KEEPALIVE_INTERVAL_MS,\n): { touch(): void; stop(): void } {\n let timer: ReturnType<typeof setTimeout> | null = null;\n let stopped = false;\n\n const arm = () => {\n if (stopped) return;\n if (timer !== null) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = null;\n if (stopped) return;\n try {\n controller.enqueue(encoder.encode(SSE_KEEPALIVE));\n } catch {\n stop();\n return;\n }\n arm();\n }, intervalMs);\n };\n\n const stop = () => {\n stopped = true;\n if (timer !== null) clearTimeout(timer);\n timer = null;\n };\n\n arm();\n return { touch: arm, stop };\n}\n\nexport function sseHeaders(): Record<string, string> {\n return {\n \"Content-Type\": \"text/event-stream\",\n // `no-transform` as well as `no-store`: a proxy that gzips or rechunks the\n // body is a proxy that buffers it, and a buffered token stream arrives all\n // at once, which is the same as not streaming at all.\n \"Cache-Control\": \"no-store, no-transform\",\n Connection: \"keep-alive\",\n // nginx's own name for the same thing.\n \"X-Accel-Buffering\": \"no\",\n };\n}\n\n/**\n * Encodes an async iterable of frames as an SSE response.\n *\n * Pulls one frame per `pull` rather than looping inside `start`: a `start` that\n * awaits the whole run does not resolve until the run is over, and the stream\n * is not readable until it does — which would turn every streamed answer into a\n * single delivery at the end.\n */\nexport function sseResponse(frames: AsyncIterable<AgentStreamFrame>, status = 200): Response {\n const iterator = frames[Symbol.asyncIterator]();\n let lastSeq = -1;\n let keepalive!: ReturnType<typeof sseKeepalive>;\n\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n keepalive = sseKeepalive(controller);\n },\n async pull(controller) {\n try {\n const next = await iterator.next();\n if (next.done) {\n keepalive.stop();\n controller.close();\n return;\n }\n lastSeq = next.value.seq;\n controller.enqueue(encoder.encode(encodeFrame(next.value)));\n keepalive.touch();\n } catch (err) {\n // Past the headers there is no status left to fail with, so the reason\n // goes out as the last event. Closing silently would be\n // indistinguishable from a run that finished, which is the one thing a\n // reattaching client must not be told by mistake.\n const event = { type: \"error\", error: toAgentError(err) } as const;\n keepalive.stop();\n controller.enqueue(encoder.encode(encodeFrame({ seq: lastSeq + 1, event })));\n controller.close();\n }\n },\n cancel(reason) {\n // The client went away. Let the generator unwind so its `finally` runs\n // and it stops waiting on frames nobody will read.\n keepalive.stop();\n void iterator.return?.(reason);\n },\n });\n\n return new Response(body, { status, headers: sseHeaders() });\n}\n\n// `unknown` rather than a new code: `AgentErrorCode` is the wire contract and\n// belongs to the model's failures, not to the transport's.\n//\n// Only the two failures the live-run buffer raises keep their message: gemi\n// wrote them, and they name the cursor, which is what a client can act on.\n// Anything else is a store or a bug talking (a Redis error carries its host),\n// so the client gets a fixed sentence and the log gets the rest (#446).\nconst TRANSPORT_CODES = new Set([\"frame_cursor_evicted\", \"live_run_not_found\"]);\n\nfunction toAgentError(err: unknown): AgentError {\n const code = err && typeof err === \"object\" ? (err as { code?: unknown }).code : undefined;\n if (err instanceof Error && typeof code === \"string\" && TRANSPORT_CODES.has(code)) {\n return { code: \"unknown\", message: err.message, retryable: false };\n }\n console.error(\"[gemi/ai] agent stream failed\", err);\n return { code: \"unknown\", message: \"The run's stream failed.\", retryable: false };\n}\n",
13
+ "import { SSE_KEEPALIVE, sseHeaders } from \"../../ai/store/sse\";\nimport { isShuttingDown } from \"../../server/shutdown\";\nimport type { ChangeFeedMessage, ChangeFeedResponse } from \"./wire\";\nimport { ChangeFeedFullError, type ChangeFeedManager, type ChangeFeedSubscription } from \"./ChangeFeedManager\";\n\nexport type StreamOptions = {\n /**\n * Where to resume. Default: the request's `Last-Event-ID` header, then its\n * `cursor` search parameter, then the channels' heads.\n */\n cursor?: string | null;\n /** How long a client waits before retrying a `503`, in seconds. Default `5`. */\n retryAfter?: number;\n};\n\nconst encoder = new TextEncoder();\n\nfunction frame(id: string, message: ChangeFeedMessage): Uint8Array {\n return encoder.encode(`id: ${id}\\ndata: ${JSON.stringify(message)}\\n\\n`);\n}\n\nexport type { ChangeFeedMessage, ChangeFeedResponse };\n\nexport function changeFeedStream<T>(\n manager: ChangeFeedManager,\n request: { rawRequest: Request } | Request,\n channels: string[],\n options: StreamOptions,\n): ChangeFeedResponse<T> {\n const raw = request instanceof Request ? request : request.rawRequest;\n const cursor =\n options.cursor ??\n raw.headers.get(\"Last-Event-ID\") ??\n new URL(raw.url).searchParams.get(\"cursor\");\n\n let subscription: ChangeFeedSubscription;\n try {\n subscription = manager.subscribe(channels, { cursor, signal: raw.signal });\n } catch (error) {\n if (!(error instanceof ChangeFeedFullError)) throw error;\n return new Response(JSON.stringify({ error: \"The change feed is at capacity.\" }), {\n status: 503,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Retry-After\": String(options.retryAfter ?? 5),\n },\n });\n }\n\n let keepalive: ReturnType<typeof setInterval> | null = null;\n let sentReady = false;\n let closed = false;\n const end = (controller: ReadableStreamDefaultController<Uint8Array>) => {\n if (keepalive) clearInterval(keepalive);\n keepalive = null;\n subscription.close();\n if (closed) return;\n closed = true;\n try {\n controller.close();\n } catch {\n // Cancelled by the client already.\n }\n };\n\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n keepalive = setInterval(() => {\n // A stream never ends by itself, so a server draining its requests\n // ends it: the client reconnects, to an instance that is staying.\n if (isShuttingDown()) return end(controller);\n try {\n controller.enqueue(encoder.encode(SSE_KEEPALIVE));\n } catch {\n end(controller);\n }\n }, manager.config.keepaliveInterval);\n },\n async pull(controller) {\n try {\n if (!sentReady) {\n await subscription.ready();\n sentReady = true;\n if (!closed) controller.enqueue(frame(subscription.cursor, { type: \"ready\" }));\n return;\n }\n const next = await subscription.next();\n if (next.done || closed) return end(controller);\n controller.enqueue(frame(subscription.cursor, next.value));\n } catch (error) {\n // Past the headers there is no status to fail with. Closing lets the\n // client reconnect from the last id it saw, which is still right.\n if (!closed) console.error(\"[gemi] A change feed stream failed.\", error);\n end(controller);\n }\n },\n cancel() {\n closed = true;\n if (keepalive) clearInterval(keepalive);\n keepalive = null;\n subscription.close();\n },\n });\n\n return new Response(body, { headers: sseHeaders() }) as ChangeFeedResponse<T>;\n}\n",
14
+ "import { DatabaseManager } from \"../../database/DatabaseManager\";\nimport type { Application } from \"../../foundation/Application\";\nimport { afterCommit, currentTransaction } from \"../../orm/context\";\nimport { withDefaults } from \"../../support/withDefaults\";\nimport type { ChangeFeedDriver, ChangeFeedEvent } from \"./ChangeFeedDriver\";\nimport { changeFeedConfigDefaults, type ChangeFeedConfig } from \"./config\";\nimport { decodeCursor, encodeCursor } from \"./cursor\";\nimport { DatabaseChangeFeedDriver } from \"./DatabaseChangeFeedDriver\";\nimport { MemoryChangeFeedDriver } from \"./MemoryChangeFeedDriver\";\nimport { changeFeedStream, type ChangeFeedResponse, type StreamOptions } from \"./stream\";\n\n/** The longest channel name, in characters. */\nexport const MAX_CHANNEL_LENGTH = 255;\n\nconst MIN_BACKOFF_MS = 500;\nconst MAX_BACKOFF_MS = 30_000;\n\n/** This process already holds `maxSubscriptions` subscriptions. */\nexport class ChangeFeedFullError extends Error {\n constructor(readonly limit: number) {\n super(`The change feed holds its limit of ${limit} subscriptions.`);\n this.name = \"ChangeFeedFullError\";\n }\n}\n\nexport type SubscribeOptions = {\n /**\n * Where to resume: a cursor string (an SSE event's `id`, or `cursor()`) or\n * a map of channel to seq. A channel without a position starts at its head,\n * so it delivers only what is published from now on.\n */\n cursor?: string | ReadonlyMap<string, number> | Record<string, number> | null;\n /** Ends the subscription when it aborts. */\n signal?: AbortSignal;\n};\n\n/**\n * Change feeds: publish \"channel K changed\", and follow channels from a\n * cursor, in this process or any other sharing the driver's store.\n *\n * ```ts\n * await ChangeFeed.publish(`site:${site.id}`, { pages: [\"/about\"] });\n *\n * for await (const event of ChangeFeed.subscribe([`site:${site.id}`], { signal })) {\n * // { type: \"change\", channel, seq, data } or { type: \"reset\", channel, seq }\n * }\n * ```\n *\n * The driver's log is the truth, and notifications only wake subscribers to\n * read it. A subscription keeps no queue of its own, only which of its\n * channels may have moved; it reads the log when its consumer asks for the\n * next event. So a slow consumer costs nothing while it is behind, and one\n * that fell further behind than the log keeps gets a `reset`.\n */\nexport class ChangeFeedManager {\n static token = \"changeFeed\";\n\n readonly driver: ChangeFeedDriver;\n readonly config: Required<ChangeFeedConfig>;\n private readonly followers = new Map<string, Set<ChangeFeedSubscription>>();\n private readonly all = new Set<ChangeFeedSubscription>();\n private listenState: \"off\" | \"connecting\" | \"listening\" | \"retrying\" | \"closed\" = \"off\";\n private listening: { close(): Promise<void> } | null = null;\n private retryTimer: ReturnType<typeof setTimeout> | null = null;\n private backoffMs = MIN_BACKOFF_MS;\n private pollTimer: ReturnType<typeof setInterval> | null = null;\n private polling: Promise<void> | null = null;\n\n constructor(\n config: ChangeFeedConfig = {},\n private readonly options: { application?: Application } = {},\n ) {\n this.config = withDefaults(changeFeedConfigDefaults(), config);\n this.driver = resolveDriver(this.config.driver, options.application);\n }\n\n /** How many subscriptions this process holds. */\n get subscriptions(): number {\n return this.all.size;\n }\n\n /** Whether this process is listening for other processes' publishes. */\n get isListening(): boolean {\n return this.listenState === \"listening\";\n }\n\n /**\n * Appends `data` (JSON, or nothing) to `channel` and wakes its subscribers,\n * here and on every instance sharing the store. Resolves to the new seq.\n *\n * Inside an ORM transaction nobody is woken before the commit, and nothing\n * is published if it rolls back. The database driver on Postgres writes on\n * the transaction itself; every other driver publishes after the commit,\n * and then this resolves to `null`, since the seq does not exist yet.\n */\n async publish(channel: string, data?: unknown): Promise<number | null> {\n assertChannel(channel);\n const payload = data === undefined ? null : data;\n if (currentTransaction() !== undefined && !this.driver.joinsTransaction?.()) {\n void afterCommit(async () => {\n this.wake(channel, await this.driver.publish(channel, payload));\n });\n return null;\n }\n const seq = await this.driver.publish(channel, payload);\n void afterCommit(() => this.wake(channel, seq));\n return seq;\n }\n\n /** The latest seq of `channel`, `0` before its first publish. */\n async head(channel: string): Promise<number> {\n assertChannel(channel);\n return (await this.driver.heads([channel])).get(channel) ?? 0;\n }\n\n /**\n * A cursor at the channels' heads, for a view to hand its client so the\n * client's subscription resumes from what the view showed rather than\n * from whenever it connected.\n */\n async cursor(channels: string | readonly string[]): Promise<string> {\n const list = channelList(channels);\n return encodeCursor(await this.driver.heads(list));\n }\n\n /**\n * Follows `channels` from `options.cursor`. Iterate it with `for await`;\n * breaking out, `close()`, or `options.signal` ends it. Throws\n * `ChangeFeedFullError` when this process holds `maxSubscriptions` already.\n */\n subscribe(channels: string | readonly string[], options: SubscribeOptions = {}) {\n const list = channelList(channels);\n if (this.all.size >= this.config.maxSubscriptions) {\n throw new ChangeFeedFullError(this.config.maxSubscriptions);\n }\n const subscription = new ChangeFeedSubscription(\n this,\n list,\n toPositions(options.cursor),\n this.config,\n options.signal,\n );\n this.all.add(subscription);\n for (const channel of list) {\n let set = this.followers.get(channel);\n if (!set) this.followers.set(channel, (set = new Set()));\n set.add(subscription);\n }\n this.startListening();\n this.startPolling();\n return subscription;\n }\n\n /**\n * An SSE response following `channels`, for a route handler that has\n * already decided the caller may read them:\n *\n * ```ts\n * \"/sites/:siteId/changes\": this.get(async (req: HttpRequest) => {\n * const site = await Site.findUniqueOrThrow({ where: { publicId: req.params.siteId } });\n * return ChangeFeed.stream(req, `site:${site.id}`);\n * }),\n * ```\n *\n * It resumes from the request's `Last-Event-ID`, ends when the client goes\n * away or the server starts shutting down, and answers `503` with a\n * `Retry-After` when this process holds `maxSubscriptions` already.\n */\n stream<T = unknown>(\n request: { rawRequest: Request } | Request,\n channels: string | readonly string[],\n options: StreamOptions = {},\n ): ChangeFeedResponse<T> {\n return changeFeedStream<T>(this, request, channelList(channels), options);\n }\n\n /** Ends every subscription and stops listening. For shutdown and tests. */\n async close(): Promise<void> {\n this.listenState = \"closed\";\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.retryTimer = null;\n this.stopPolling();\n for (const subscription of this.all) subscription.close();\n const listening = this.listening;\n this.listening = null;\n await listening?.close();\n await this.driver.close?.();\n }\n\n /** @internal */\n forget(subscription: ChangeFeedSubscription) {\n if (!this.all.delete(subscription)) return;\n for (const channel of subscription.channels) {\n const set = this.followers.get(channel);\n set?.delete(subscription);\n if (set?.size === 0) this.followers.delete(channel);\n }\n if (this.all.size === 0) this.stopPolling();\n }\n\n /**\n * Reads the heads of every channel this process follows, in one query per\n * 500 channels, and wakes the subscribers that are behind. Runs every\n * `pollInterval` while there are subscriptions, and at once whenever\n * notifications may have been missed. Cheaper than each subscription\n * re-reading its own log: one query per process, whatever the number of\n * subscribers.\n */\n poll(): Promise<void> {\n this.polling ??= (async () => {\n try {\n const channels = [...this.followers.keys()];\n for (let i = 0; i < channels.length; i += 500) {\n const heads = await this.driver.heads(channels.slice(i, i + 500));\n for (const [channel, seq] of heads) this.wake(channel, seq);\n }\n } catch (error) {\n console.error(\"[gemi] The change feed could not read its channels' heads.\", error);\n } finally {\n this.polling = null;\n }\n })();\n return this.polling;\n }\n\n private startPolling() {\n if (this.pollTimer) return;\n this.pollTimer = setInterval(() => void this.poll(), this.config.pollInterval);\n this.pollTimer.unref?.();\n }\n\n private stopPolling() {\n if (this.pollTimer) clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n\n /** Tells this process's subscribers of `channel` that it reached `seq`. */\n private wake(channel: string, seq: number) {\n for (const subscription of this.followers.get(channel) ?? []) subscription.moved(channel, seq);\n }\n\n private resync() {\n void this.poll();\n }\n\n private startListening() {\n if (this.listenState !== \"off\" || !this.driver.listen) return;\n void this.connect();\n }\n\n private async connect() {\n this.listenState = \"connecting\";\n this.retryTimer = null;\n try {\n const listening = await this.driver.listen!(\n (channel, seq) => this.wake(channel, seq),\n () => this.resync(),\n );\n if (this.listenState !== \"connecting\") {\n await listening.close();\n return;\n }\n this.listening = listening;\n this.listenState = \"listening\";\n this.backoffMs = MIN_BACKOFF_MS;\n // Whatever was published before the LISTEN took hold was not heard.\n this.resync();\n } catch (error) {\n if (this.listenState !== \"connecting\") return;\n console.error(\n `[gemi] The change feed could not listen for other instances' changes; retrying in ${this.backoffMs}ms.`,\n error,\n );\n this.listenState = \"retrying\";\n this.retryTimer = setTimeout(() => void this.connect(), this.backoffMs);\n this.retryTimer.unref?.();\n this.backoffMs = Math.min(this.backoffMs * 2, MAX_BACKOFF_MS);\n }\n }\n}\n\n/**\n * One subscriber's view of its channels: where it is in each, which may have\n * moved, and the few events read from the log but not yet taken.\n */\nexport class ChangeFeedSubscription implements AsyncIterableIterator<ChangeFeedEvent> {\n readonly channels: readonly string[];\n /** What was delivered: the cursor. */\n private readonly positions = new Map<string, number>();\n /** What was read from the log, delivered or still in `pending`. */\n private readonly readTo = new Map<string, number>();\n private readonly dirty = new Set<string>();\n private readonly pending: ChangeFeedEvent[] = [];\n private started: Promise<void> | null = null;\n private wakeUp: (() => void) | null = null;\n private closed = false;\n private readonly onAbort = () => this.close();\n\n constructor(\n private readonly manager: ChangeFeedManager,\n channels: readonly string[],\n positions: Map<string, number>,\n private readonly config: Required<ChangeFeedConfig>,\n private readonly signal?: AbortSignal,\n ) {\n this.channels = channels;\n for (const channel of channels) {\n const seq = positions.get(channel);\n if (seq !== undefined) {\n this.positions.set(channel, seq);\n this.readTo.set(channel, seq);\n this.dirty.add(channel);\n }\n }\n if (signal?.aborted) this.close();\n else signal?.addEventListener(\"abort\", this.onAbort, { once: true });\n }\n\n /** Where the subscription is, as a cursor string. Complete once `ready()` resolved. */\n get cursor(): string {\n return encodeCursor(this.positions);\n }\n\n get isClosed(): boolean {\n return this.closed;\n }\n\n /**\n * Resolves once every channel has a position: the cursor's, or the head\n * when it had none. Called by the first `next()`; call it yourself to\n * read `cursor` before the first event.\n */\n ready(): Promise<void> {\n this.started ??= (async () => {\n const missing = this.channels.filter((channel) => !this.positions.has(channel));\n if (missing.length === 0) return;\n const heads = await this.manager.driver.heads(missing);\n // A publish heard while the heads were read marked its channel dirty,\n // and the read that follows finds it in the log, or finds nothing.\n for (const channel of missing) {\n const head = heads.get(channel) ?? 0;\n this.positions.set(channel, head);\n this.readTo.set(channel, head);\n }\n })();\n return this.started;\n }\n\n async next(): Promise<IteratorResult<ChangeFeedEvent>> {\n await this.ready();\n for (;;) {\n if (this.closed) return { done: true, value: undefined };\n const event = this.pending.shift();\n if (event) {\n this.positions.set(event.channel, event.seq);\n return { done: false, value: event };\n }\n const channel = this.dirty.values().next().value;\n if (channel !== undefined) {\n await this.read(channel);\n continue;\n }\n await this.idle();\n }\n }\n\n async return(): Promise<IteratorResult<ChangeFeedEvent>> {\n this.close();\n return { done: true, value: undefined };\n }\n\n [Symbol.asyncIterator]() {\n return this;\n }\n\n /** Ends the subscription. A pending `next()` resolves `done`. */\n close() {\n if (this.closed) return;\n this.closed = true;\n this.pending.length = 0;\n this.signal?.removeEventListener(\"abort\", this.onAbort);\n this.manager.forget(this);\n this.wake();\n }\n\n /**\n * @internal `channel` reached `seq`. Before `ready()` set a position the\n * channel is marked anyway, and read from its head once it has one.\n */\n moved(channel: string, seq: number) {\n const position = this.readTo.get(channel);\n if (position !== undefined && seq === position) return;\n this.dirty.add(channel);\n this.wake();\n }\n\n private async read(channel: string) {\n const after = this.readTo.get(channel) ?? 0;\n this.dirty.delete(channel);\n const { batchSize } = this.config;\n const { entries, head, gap } = await this.manager.driver.read(channel, after, batchSize);\n if (this.closed) return;\n if (gap) {\n this.readTo.set(channel, head);\n this.pending.push({ type: \"reset\", channel, seq: head });\n return;\n }\n for (const entry of entries) {\n this.readTo.set(channel, entry.seq);\n this.pending.push({ type: \"change\", channel, seq: entry.seq, data: entry.data });\n }\n if (entries.length === batchSize) this.dirty.add(channel);\n }\n\n private idle(): Promise<void> {\n return new Promise((resolve) => {\n this.wakeUp = resolve;\n });\n }\n\n private wake() {\n const wakeUp = this.wakeUp;\n this.wakeUp = null;\n wakeUp?.();\n }\n}\n\nfunction assertChannel(channel: string) {\n if (typeof channel !== \"string\" || channel === \"\" || channel.length > MAX_CHANNEL_LENGTH) {\n throw new Error(\n `A change feed channel is a string of 1 to ${MAX_CHANNEL_LENGTH} characters; got ${JSON.stringify(channel)}.`,\n );\n }\n}\n\nfunction channelList(channels: string | readonly string[]): string[] {\n const list = [...new Set(typeof channels === \"string\" ? [channels] : channels)];\n if (list.length === 0) throw new Error(\"A change feed subscription needs at least one channel.\");\n for (const channel of list) assertChannel(channel);\n return list;\n}\n\nfunction toPositions(cursor: SubscribeOptions[\"cursor\"]): Map<string, number> {\n if (cursor === undefined || cursor === null) return new Map();\n if (typeof cursor === \"string\") return decodeCursor(cursor);\n const entries = cursor instanceof Map ? [...cursor] : Object.entries(cursor);\n return decodeCursor(encodeCursor(new Map(entries as [string, number][])));\n}\n\nfunction resolveDriver(\n driver: Required<ChangeFeedConfig>[\"driver\"],\n application: Application | undefined,\n): ChangeFeedDriver {\n if (driver === \"memory\") return new MemoryChangeFeedDriver();\n if (driver === \"database\" || typeof driver === \"function\") {\n if (!application && (driver === \"database\" || driver.length > 0)) {\n throw new Error(\n \"The change feed driver needs the application it belongs to, and this \" +\n \"ChangeFeedManager was built without one. Pass { application }.\",\n );\n }\n if (driver === \"database\") {\n return new DatabaseChangeFeedDriver(application!.make(DatabaseManager));\n }\n return driver(application!);\n }\n if (typeof driver === \"string\") {\n throw new Error(\n `Unknown change feed driver \"${driver}\". The changeFeed slice's driver is ` +\n `\"memory\", \"database\", a ChangeFeedDriver, or a function returning one.`,\n );\n }\n return driver;\n}\n",
15
+ "/**\n * A length of time: milliseconds as a number, or a number and a unit, such as\n * `\"500ms\"`, `\"30s\"`, `\"5m\"`, `\"2h\"`, `\"7d\"` or `\"1w\"`.\n */\nexport type Duration = number | `${number}${\"ms\" | \"s\" | \"m\" | \"h\" | \"d\" | \"w\"}`;\n\nconst UNITS: Record<string, number> = {\n ms: 1,\n s: 1000,\n m: 60_000,\n h: 60 * 60_000,\n d: 24 * 60 * 60_000,\n w: 7 * 24 * 60 * 60_000,\n};\n\n/** A `Duration` in milliseconds. Throws for anything else, on the caller's stack. */\nexport function toMilliseconds(duration: Duration): number {\n if (typeof duration === \"number\") {\n if (!Number.isFinite(duration) || duration < 0) {\n throw new TypeError(`A duration is 0 or more milliseconds; got ${duration}.`);\n }\n return Math.round(duration);\n }\n const match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d|w)\\s*$/.exec(String(duration));\n if (!match) {\n throw new TypeError(\n `\"${String(duration)}\" is not a duration. Use milliseconds, or a number and ` +\n `one of ms, s, m, h, d, w (\"30s\", \"7d\").`,\n );\n }\n return Math.round(Number(match[1]) * UNITS[match[2]!]!);\n}\n"
16
+ ],
17
+ "mappings": ";6PAwFO,AAAM,IAAsB,DAAM,LAE5B,KACA,MAFX,WAAW,CACA,EACA,EACT,EAAS,8CACT,CACA,MAAM,kBAAkB,aAAgB,OAAW,IAAS,EAJnD,YACA,aAIT,KAAK,KAAO,gBAEhB,CC9EA,IAAM,EAAc,MACd,EAAY,IAEZ,EAAQ,CAAC,IAAe,IAAI,QAAQ,CAAC,IAAY,WAAW,EAAS,CAAE,CAAC,EAgBvE,MAAM,CAAS,CASD,MACR,KACA,MACA,MACA,IAZF,KACQ,WAAa,IAAI,gBAC1B,SACA,YACA,WACA,KAAO,GAEf,WAAW,CACQ,EACR,EACA,EACA,EACA,EACT,EACA,CANiB,aACR,YACA,aACA,aACA,WAGT,KAAK,KAAO,KAAK,WAAW,OAC5B,KAAK,SAAW,EAAc,EAC9B,KAAK,UAAU,KAIb,QAAO,EAAY,CACrB,OAAO,KAAK,KAAK,SAAW,YAAY,IAAI,GAAK,KAAK,cAIlD,OAAM,CAAC,EAAM,KAAK,IAAuB,CAC7C,GAAI,KAAK,KAAK,QAAS,MAAO,GAC9B,IAAM,EAAc,YAAY,IAAI,EAEpC,GAAI,CADO,MAAM,KAAK,MA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gB,IAAW,YAAc,EAAO,OAAS,GAC5D,MAAU,MACR,qIAEF,EAEF,GAAI,IAAW,WACb,OAAO,IAAI,EAAyB,EAAa,KAAK,CAAe,CAAC,EAExE,OAAO,EAAO,CAAY,EAE5B,GAAI,OAAO,IAAW,SACpB,MAAU,MACR,+BAA+B,6GAEjC,EAEF,OAAO,ECldT,IAAM,GAAgC,CACpC,GAAI,EACJ,EAAG,KACH,EAAG,MACH,EAAG,QACH,EAAG,SACH,EAAG,SACL,EAGO,SAAS,EAAc,CAAC,EAA4B,CACzD,GAAI,OAAO,IAAa,SAAU,CAChC,GAAI,CAAC,OAAO,SAAS,CAAQ,GAAK,EAAW,EAC3C,MAAU,UAAU,6CAA6C,IAAW,EAE9E,OAAO,KAAK,MAAM,CAAQ,EAE5B,IAAM,EAAQ,2CAA2C,KAAK,OAAO,CAAQ,CAAC,EAC9E,GAAI,CAAC,EACH,MAAU,UACR,IAAI,OAAO,CAAQ,iGAErB,EAEF,OAAO,KAAK,MAAM,OAAO,EAAM,EAAE,EAAI,GAAM,EAAM,GAAK",
18
+ "debugId": "357E3187D90D9AE464756E2164756E21",
19
+ "names": []
20
+ }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{cm as x}from"./chunk-qstjm3cb.js";function B(j){return j}function C(){return{supportedLocales:[],defaultLocale:"en-US",prefetch:{},components:{},detectLocale:()=>null,onLocaleChange:(j)=>{console.log(`Locale changed to ${j}`)},timeZone:x,detectTimeZone:()=>null}}
3
- export{B as Ne,C as Oe};
2
+ import{em as x}from"./chunk-yj7pbbnm.js";function B(j){return j}function C(){return{supportedLocales:[],defaultLocale:"en-US",prefetch:{},components:{},detectLocale:()=>null,onLocaleChange:(j)=>{console.log(`Locale changed to ${j}`)},timeZone:x,detectTimeZone:()=>null}}
3
+ export{B as Qe,C as Re};
4
4
 
5
- //# debugId=CEBC4D323EDB324D64756E2164756E21
5
+ //# debugId=09FDEDE5303AF52E64756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "import { DEFAULT_TIME_ZONE } from \"./formatter\";\nimport type { Dictionary } from \"./Dictionary\";\nimport type { HttpRequest } from \"../http/HttpRequest\";\n\n// Config key: `translation`. Derived from `I18nServiceProvider`.\nexport interface TranslationConfig {\n supportedLocales?: string[];\n defaultLocale?: string;\n /**\n * @deprecated Only for `Dictionary.create` dictionaries. A `defineDictionary`\n * dictionary needs no entry here — the component that reads it pulls it in,\n * and the bundler ships only the active locale.\n */\n prefetch?: Record<string, Array<Dictionary<any>>>;\n /** @deprecated Only for `Dictionary.create` dictionaries. See `prefetch`. */\n components?: Record<string, Dictionary<any>>;\n\n // Returning `null` falls back to gemi's own locale detection.\n detectLocale?: (req: HttpRequest) => string | null;\n onLocaleChange?: (locale: string) => Promise<void> | void;\n\n /**\n * The IANA time zone dates are formatted in by `useFormatter`,\n * `useDictionary(...).format` and `Lang.formatter()`. Defaults to `UTC`.\n *\n * One zone for server and browser alike, so a server-rendered date and its\n * hydrated copy print the same text. Override per call with\n * `format.date(value, { timeZone })`.\n */\n timeZone?: string;\n /**\n * Resolve the zone for one request, e.g. from a cookie or the signed-in\n * user's profile. Returning `null` (or a zone `Intl` does not know) falls back\n * to `timeZone`. Runs on the server; the result ships with the page.\n */\n detectTimeZone?: (req: HttpRequest) => string | null;\n}\n\nexport function defineTranslationConfig(\n config: TranslationConfig,\n): TranslationConfig {\n return config;\n}\n\nexport function translationConfigDefaults(): Required<TranslationConfig> {\n return {\n supportedLocales: [],\n defaultLocale: \"en-US\",\n prefetch: {},\n components: {},\n detectLocale: () => null,\n onLocaleChange: (locale) => {\n console.log(`Locale changed to ${locale}`);\n },\n timeZone: DEFAULT_TIME_ZONE,\n detectTimeZone: () => null,\n };\n}\n"
6
6
  ],
7
7
  "mappings": ";yCAsCO,SAAS,CAAuB,CACrC,EACmB,CACnB,OAAO,EAGF,SAAS,CAAyB,EAAgC,CACvE,MAAO,CACL,iBAAkB,CAAC,EACnB,cAAe,QACf,SAAU,CAAC,EACX,WAAY,CAAC,EACb,aAAc,IAAM,KACpB,eAAgB,CAAC,IAAW,CAC1B,QAAQ,IAAI,qBAAqB,GAAQ,GAE3C,SAAU,EACV,eAAgB,IAAM,IACxB",
8
- "debugId": "CEBC4D323EDB324D64756E2164756E21",
8
+ "debugId": "09FDEDE5303AF52E64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$ as c,Z as P,aa as f,ba as l}from"./chunk-7rmb1v9c.js";import{Ba as u,Ca as m}from"./chunk-nhebjh6n.js";import"./chunk-v2fd69at.js";import"./chunk-hke4hzfm.js";import"./chunk-0cckwd91.js";import"./chunk-5vdkqv17.js";import"./chunk-ba1h9pm6.js";import"./chunk-4k3r37be.js";import{Pj as S}from"./chunk-eh3ktv8k.js";import{om as T}from"./chunk-cwm5x7rf.js";import{Im as y}from"./chunk-rp2f9mq1.js";import"./chunk-yedb5vvg.js";import{join as YJ}from"path";import{createServer as AJ}from"vite";import{join as R,sep as o}from"path";import{existsSync as a,statSync as s}from"fs";import{IncomingMessage as t,ServerResponse as r}from"http";import{Socket as e}from"net";function i(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
2
+ import{$ as c,Z as P,aa as f,ba as l}from"./chunk-x3pbssy4.js";import{Ba as u,Ca as m}from"./chunk-fxa72ppw.js";import"./chunk-v2fd69at.js";import"./chunk-hke4hzfm.js";import"./chunk-0cckwd91.js";import"./chunk-h9nt7hm6.js";import"./chunk-ba1h9pm6.js";import"./chunk-8a3fqcf0.js";import{Ej as S}from"./chunk-h1wmpa03.js";import{qm as T}from"./chunk-swmf6w3z.js";import{Km as y}from"./chunk-55btq9c7.js";import"./chunk-3dkv4989.js";import{join as YJ}from"path";import{createServer as AJ}from"vite";import{join as R,sep as o}from"path";import{existsSync as a,statSync as s}from"fs";import{IncomingMessage as t,ServerResponse as r}from"http";import{Socket as e}from"net";function i(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
3
3
  `).split(`
4
4
  `).map((W)=>W.trim()).filter((W)=>W.length>0).join(`
5
5
  `).trim()}function N(J){return`
@@ -55,4 +55,4 @@ window.$RefreshSig$ = () => (type) => type;
55
55
  window.__vite_plugin_react_preamble_installed__ = true;
56
56
  `;function zJ(J){let{pathname:W}=new URL(J.url),Z=($)=>new Response($,{headers:{"Content-Type":"application/javascript"}});if(W===k)return Z(ZJ);if(W.startsWith("/render-error.js"))return Z("window.render_error = true");if(W.startsWith("/refresh.js"))return Z($J);return null}function GJ(J,W){let Z=J.config?.publicDir;if(!Z||W==="/assets"||W.startsWith("/assets/"))return!1;let $;try{$=decodeURIComponent(W)}catch{return!1}if($.split("/").some((Q)=>Q.startsWith(".")))return!1;let z=R(Z,$);if(!z.startsWith(Z+o))return!1;try{return s(z).isFile()}catch{return!1}}function E(J,W,Z){let $=R(process.cwd(),"app");return async(z)=>{let{pathname:Q}=new URL(z.url),L=(G)=>{if(console.error(G),Z.ssrFixStacktrace?.(G),x(G),y(Q))return new Response(JSON.stringify({error:S("server_error",G?.message??String(G),500)}),{status:500,headers:{"Content-Type":"application/json"}});return globalThis.__gemiErrorPageServed=!0,new Response(N(I(G)),{status:500,headers:{"Content-Type":"text/html"}})},X=async(G)=>{let O=zJ(G);if(O)return O;try{let Y=J.fetch.bind(J),A=(GJ(Z,Q)&&!(await J.staticFiles(G)).publicFiles?null:await JJ(Z,G))??await Y(G);if(A instanceof Response)return A;let V={},_={},C={},d=(U,j)=>`"${U}": () => import("${j}")`,D=[],n=J.getRequiredViews.call(J);for(let U of["404",...J.getFlatComponentTree.call(J)]){if(Bun.env.NODE_ENV==="test")break;let j=`${process.env.APP_DIR}`,b=n[U];if(b&&!a(`${j}/views/${U}.tsx`))throw f(U,b);let B=await M(Z).import(`${j}/views/${U}.tsx`);V[U]=B.default,_[U]=B?.OpenGraph,C[U]=B,D.push(d(U,`/app/views/${U}.tsx`))}let p=`{${D.join(",")}}`;return await A({getStyles:async(U,j)=>await P($,Z,U,j?.layout),resolveIsland:(U)=>({src:`/${U}${T}`,preload:[]}),buildId:"dev",bootstrapModules:[k],viewImportMap:V,viewModules:C,ogMap:_,loaders:p,cssManifest:{}})}catch(Y){return L(Y)}};return await W(z,(G)=>J.withGlobalMiddleware(G,X,L))}}function QJ(J){try{return Bun.listen({hostname:"0.0.0.0",port:J,socket:{data(){}}}).stop(!0),!0}catch(W){return W?.code!=="EADDRINUSE"}}function g(J,W=QJ){let Z=24678+(J-5173);if(Z>65471)Z=24678;for(let $=Z;$<Z+64;$++)if(W($))return $;throw Error(`Could not find a free port for Vite's HMR websocket: tried ${Z}-${Z+64-1}. Set one explicitly in gemi.config.ts as \`vite: { server: { ws: { port } } }\`.`)}import{createServer as XJ}from"http";var KJ=new Set(["vite-hmr","vite-ping"]);async function q(J){let W=XJ((Z,$)=>{$.writeHead(426,{"Content-Type":"text/plain"}),$.end("Upgrade Required")});return await new Promise((Z,$)=>{W.once("error",$),W.listen(J,"127.0.0.1",()=>{W.off("error",$),Z()})}),W}function w(J){if(!J||typeof J!=="object")return null;let Z=J.server?.address?.();if(Z&&typeof Z==="object"&&"port"in Z)return Number(Z.port)||null;return null}function h(J){if(J.headers.get("upgrade")?.toLowerCase()!=="websocket")return!1;return KJ.has(J.headers.get("sec-websocket-protocol")??"")}var LJ=(J)=>typeof J==="string"?J:new Uint8Array(J);async function v(J,W,Z){let $=new URL(J.url),z=J.headers.get("sec-websocket-protocol")??"vite-hmr",Q={host:J.headers.get("host")??$.host},L=J.headers.get("origin");if(L)Q.origin=L;let X=new WebSocket(`ws://127.0.0.1:${Z}${$.pathname}${$.search}`,{protocols:[z],headers:Q});X.binaryType="arraybuffer";let G={upstream:X,early:[]};if(X.onmessage=(K)=>{let A=LJ(K.data);if(G.browser)G.browser.send(A);else G.early.push(A)},X.onclose=(K)=>{G.browser?.close(UJ(K.code),K.reason)},X.onerror=()=>{},!await new Promise((K)=>{X.addEventListener("open",()=>K(!0),{once:!0}),X.addEventListener("close",()=>K(!1),{once:!0})}))return new Response("Vite refused the HMR websocket",{status:403});if(!W.upgrade(J,{headers:{"Sec-WebSocket-Protocol":z},data:G}))return X.close(),new Response("WebSocket upgrade failed",{status:400});return}function UJ(J){if(J===1000||J>=1001&&J<=1003||J>=1007&&J<=1014)return J;if(J>=3000&&J<=4999)return J;return 1000}var F={open(J){let W=J.data;for(let Z of W.early)J.send(Z);if(W.early=[],W.browser=J,W.upstream.readyState!==WebSocket.OPEN)J.close(1000)},message(J,W){if(J.data.upstream.readyState===WebSocket.OPEN)J.data.upstream.send(W)},close(J){let{upstream:W}=J.data;if(W.readyState<=WebSocket.OPEN)W.close()}};function OJ(J,W){let Z=W.websocket,$=(z)=>z.data?.gemiSocket===!0;return{...W.socketOptions(),maxPayloadLength:16777216,closeOnBackpressureLimit:!1,open:(z)=>$(z)?Z.open?.(z):J.open?.(z),message:(z,Q)=>$(z)?Z.message(z,Q):J.message(z,Q),close:(z,Q,L)=>$(z)?Z.close?.(z,Q,L):J.close?.(z,Q,L)}}var H=process.cwd(),jJ=YJ(H,"app");if(!globalThis.__gemiErrorHooked)globalThis.__gemiErrorHooked=!0,process.on("unhandledRejection",(J)=>{console.error(J),x(J)}),process.on("uncaughtException",(J)=>{console.error(J),x(J)});async function vJ(J,W){let Z=Number(process.env.PORT)||5173,$=l(),z=Boolean(globalThis.__gemiVite),Q=J.devAllowedHosts.call(J);if(Q===!0&&!z)console.warn("gemi dev: `route.domains.devHosts` is `true`, so the dev server answers any Host. A web page you visit can then read the app's source through DNS rebinding. List the hosts you need instead.");let L=globalThis.__gemiVite??=await AJ({configFile:!1,plugins:[m()],server:{middlewareMode:!0,port:Z,ws:{server:await q(g(Z))},allowedHosts:Q,watch:{ignored:(K)=>{let A=K.split(/[/\\]/).pop()??"";return A===".env"||A.startsWith(".env.")}}},appType:"custom",resolve:{dedupe:["react","react-dom"]},optimizeDeps:{include:["react","react-dom","react-dom/client"]},ssr:{external:[...u]}});process.env.ROOT_DIR=H,process.env.APP_DIR=jJ;let X=E(J,W,L),G=w(L.config?.server?.ws),O=J.sockets(),Y=Bun.serve({port:Z,idleTimeout:$,fetch:(K,A)=>{if(G!==null&&h(K))return v(K,A,G);if(J.applyTrustedClientIp(K),O?.matches(K))return O.upgrade(K,A);return X(K)},websocket:O?OJ(F,O):F});if(await O?.start(Y),z)M(L).clearCache();if(z)if(globalThis.__gemiErrorActive&&globalThis.__gemiErrorPageServed)globalThis.__gemiErrorActive=!1,globalThis.__gemiErrorPageServed=!1,L.ws.send({type:"full-reload"});else globalThis.__gemiErrorActive=!1,L.ws.send({type:"custom",event:"http-reload"});else c({port:Y.port,rootDir:H});return Y}export{I as viteErrorPayload,vJ as httpDev};
57
57
 
58
- //# debugId=FAF08D82D2BE927364756E2164756E21
58
+ //# debugId=731F8EC7E5C859DE64756E2164756E21
@@ -9,6 +9,6 @@
9
9
  "import { createServer, type Server as NodeServer } from \"node:http\";\n\nimport type { Server, ServerWebSocket, WebSocketHandler } from \"bun\";\n\n// Vite's HMR websocket, carried on the dev server's own port.\n//\n// In middleware mode Vite has no HTTP server of its own, so by default it\n// stands up a second one for the websocket, on a second port (see\n// `hmrPort.ts`), and tells the browser to connect to `<page host>:<that port>`.\n// A reverse proxy or tunnel (ngrok, a container port mapping, a phone on the\n// LAN through https) only carries the port the page came from, so HMR could\n// not connect there, and the client logged connection failures forever.\n//\n// Vite can attach its websocket to a server it is handed (`server.ws.server`)\n// instead, and then tells the browser to connect to the page's own origin. That\n// server has to be a Node `http.Server`; the dev server is `Bun.serve`. So:\n//\n// - the Node server Vite is handed listens on loopback only, on the port\n// `resolveHmrPort` picked, and answers nothing but websocket upgrades;\n// - `Bun.serve` accepts the browser's upgrade on the page's origin and relays\n// frames both ways to that loopback server.\n//\n// The relay forwards the browser's `Host` and `Origin` and the request's query\n// (the `token`), so Vite still runs its own host and token checks against what\n// the browser actually sent.\n\n/** The subprotocols Vite's client opens its sockets with. */\nconst VITE_PROTOCOLS = new Set([\"vite-hmr\", \"vite-ping\"]);\n\n/**\n * Start the loopback Node server Vite attaches its HMR websocket to.\n * Everything but an upgrade gets `426 Upgrade Required`, as Vite's own\n * websocket server answers.\n */\nexport async function listenHmrServer(port: number): Promise<NodeServer> {\n const server = createServer((_req, res) => {\n res.writeHead(426, { \"Content-Type\": \"text/plain\" });\n res.end(\"Upgrade Required\");\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, \"127.0.0.1\", () => {\n server.off(\"error\", reject);\n resolve();\n });\n });\n return server;\n}\n\n/**\n * The loopback port to relay to, read from the config Vite actually resolved,\n * so an app that set its own `server.ws` in `gemi.config.ts` is relayed to\n * where Vite really is, or not relayed at all. `null` when Vite was not given\n * a server (its websocket is then on a port of its own, and the client goes\n * there directly) or when HMR is off.\n */\nexport function hmrRelayPort(wsConfig: unknown): number | null {\n if (!wsConfig || typeof wsConfig !== \"object\") return null;\n const server = (wsConfig as { server?: { address?: () => unknown } }).server;\n const address = server?.address?.();\n if (address && typeof address === \"object\" && \"port\" in address) {\n return Number((address as { port: number }).port) || null;\n }\n return null;\n}\n\n/** Whether a request is the Vite client opening its HMR (or ping) socket. */\nexport function isHmrUpgrade(req: Request): boolean {\n if (req.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\") return false;\n return VITE_PROTOCOLS.has(req.headers.get(\"sec-websocket-protocol\") ?? \"\");\n}\n\nexport type HmrRelayData = {\n /** The socket to Vite, already open when the browser's is accepted. */\n upstream: WebSocket;\n /** Frames Vite sent before the browser's socket opened (its `connected`). */\n early: (string | Uint8Array)[];\n browser?: ServerWebSocket<HmrRelayData>;\n};\n\ntype Frame = string | Uint8Array;\n\nconst frameOf = (data: unknown): Frame =>\n typeof data === \"string\" ? data : new Uint8Array(data as ArrayBuffer);\n\n/**\n * Open the socket to Vite first, and accept the browser's upgrade only once\n * Vite has accepted it. Returns `undefined` once Bun has taken the request\n * over, or a refusal.\n *\n * The order matters. Vite refuses a socket whose host is not in\n * `allowedHosts`, or a cross-origin one without its token. Had the browser's\n * socket been accepted first and closed when Vite refused, the client would\n * read that as \"server connection lost\", ping (which Vite always answers),\n * and reload the page, forever. Refused before it opens, the client logs one\n * \"failed to connect to websocket\" and the page keeps working.\n */\nexport async function upgradeHmr(\n req: Request,\n server: Server<HmrRelayData>,\n port: number,\n): Promise<Response | undefined> {\n const url = new URL(req.url);\n const protocol = req.headers.get(\"sec-websocket-protocol\") ?? \"vite-hmr\";\n // `Host` is what Vite's `allowedHosts` check reads; the URL's host is the\n // same value `Bun.serve` derived it from.\n const headers: Record<string, string> = {\n host: req.headers.get(\"host\") ?? url.host,\n };\n const origin = req.headers.get(\"origin\");\n if (origin) headers.origin = origin;\n\n const upstream = new WebSocket(\n `ws://127.0.0.1:${port}${url.pathname}${url.search}`,\n {\n protocols: [protocol],\n headers,\n } as any,\n );\n upstream.binaryType = \"arraybuffer\";\n const data: HmrRelayData = { upstream, early: [] };\n\n upstream.onmessage = (event) => {\n const frame = frameOf(event.data);\n if (data.browser) data.browser.send(frame);\n else data.early.push(frame);\n };\n upstream.onclose = (event) => {\n data.browser?.close(sendableCloseCode(event.code), event.reason);\n };\n upstream.onerror = () => {\n // A `close` follows; it ends the browser's socket if there is one.\n };\n\n const opened = await new Promise<boolean>((resolve) => {\n upstream.addEventListener(\"open\", () => resolve(true), { once: true });\n upstream.addEventListener(\"close\", () => resolve(false), { once: true });\n });\n if (!opened) {\n return new Response(\"Vite refused the HMR websocket\", { status: 403 });\n }\n\n const upgraded = server.upgrade(req, {\n // The browser fails a connection whose response does not echo the\n // subprotocol it asked for.\n headers: { \"Sec-WebSocket-Protocol\": protocol },\n data,\n });\n if (!upgraded) {\n upstream.close();\n return new Response(\"WebSocket upgrade failed\", { status: 400 });\n }\n return undefined;\n}\n\n// A close code that may be sent in a close frame. 1005, 1006 and 1015 are\n// reported locally and never sent.\nfunction sendableCloseCode(code: number): number {\n if (\n code === 1000 ||\n (code >= 1001 && code <= 1003) ||\n (code >= 1007 && code <= 1014)\n ) {\n return code;\n }\n if (code >= 3000 && code <= 4999) return code;\n return 1000;\n}\n\n/** `Bun.serve`'s `websocket` option: relays frames to and from Vite. */\nexport const hmrRelayHandler: WebSocketHandler<HmrRelayData> = {\n open(ws: ServerWebSocket<HmrRelayData>) {\n const data = ws.data;\n for (const frame of data.early) ws.send(frame);\n data.early = [];\n data.browser = ws;\n // Vite may have hung up while the upgrade was in flight.\n if (data.upstream.readyState !== WebSocket.OPEN) ws.close(1000);\n },\n message(ws: ServerWebSocket<HmrRelayData>, message) {\n if (ws.data.upstream.readyState === WebSocket.OPEN) {\n ws.data.upstream.send(message);\n }\n },\n close(ws: ServerWebSocket<HmrRelayData>) {\n const { upstream } = ws.data;\n if (upstream.readyState <= WebSocket.OPEN) upstream.close();\n },\n};\n"
10
10
  ],
11
11
  "mappings": ";ifAAA,SAAS,QAET,iBAAS,QCDT,SAAS,GAAM,OACf,eAAS,QAAY,KAErB,oBAAS,oBAAiB,aAC1B,iBAAS,YCLT,SAAS,CAAmB,CAAC,EAAM,CACjC,OACE,EAEG,QAAQ,kBAAmB,EAAE,EAE7B,QAAQ,cAAe,EAAE,EAEzB,QAAQ,WAAY;AAAA,CAAI,EAExB,MAAM;AAAA,CAAI,EACV,IAAI,CAAC,IAAS,EAAK,KAAK,CAAC,EACzB,OAAO,CAAC,IAAS,EAAK,OAAS,CAAC,EAChC,KAAK;AAAA,CAAI,EACT,KAAK,EAIL,SAAS,CAAe,CAAC,EAAU,CACxC,MAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QA0BD,EAAoB,SAAS;AAAA,oBACjB,KAAK,UAAU,EAAK,OAAO,oBAAoB,CAAG,EAAG,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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B,CAAG,EACxB,GAAS,QAAQ,CAAG,EACtB,OAAO,EAAQ,QAAQ,EAAK,CAAM,EAEpC,OAAO,EAAS,CAAG,GAErB,UAAW,EAAU,GAAqB,EAAiB,CAAO,EAAI,CACxE,CAAC,EAgCD,GA/BA,MAAM,GAAS,MAAM,CAAM,EA+BvB,EACF,EAAU,CAAI,EAAE,WAAW,EAQ7B,GAAI,EAMF,GAAI,WAAW,mBAAqB,WAAW,sBAC7C,WAAW,kBAAoB,GAC/B,WAAW,sBAAwB,GACnC,EAAK,GAAG,KAAK,CAAE,KAAM,aAAc,CAAC,EAEpC,gBAAW,kBAAoB,GAC/B,EAAK,GAAG,KAAK,CAAE,KAAM,SAAU,MAAO,aAAc,CAAC,EAIvD,OAAmB,CAAE,KAAM,EAAO,KAAM,SAAQ,CAAC,EAGnD,OAAO",
12
- "debugId": "FAF08D82D2BE927364756E2164756E21",
12
+ "debugId": "731F8EC7E5C859DE64756E2164756E21",
13
13
  "names": []
14
14
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Lm as a}from"./chunk-yedb5vvg.js";var i=a((f)=>{function u(t){let r={};if(t=t.replace(/^\?/,""),t)for(let n of t.split("&")){let[e,s=null]=n.split("=");if(e=decodeURIComponent(e),s)s=decodeURIComponent(s);if(!(e in r))r[e]=s;else if(Array.isArray(r[e]))r[e].push(s);else r[e]=[r[e],s]}return r}f.parseQueryString=u});var U=a((d)=>{var y=i(),c=(t)=>{if(typeof t==="string")return c(new URL(t));let{hostname:r,pathname:n,port:e,protocol:s,search:o}=t,p;if(o)p=y.parseQueryString(o);return{hostname:r,port:e?parseInt(e):void 0,protocol:s,path:n,query:p}};d.parseUrl=c});
2
+ import{Nm as a}from"./chunk-3dkv4989.js";var i=a((f)=>{function u(t){let r={};if(t=t.replace(/^\?/,""),t)for(let n of t.split("&")){let[e,s=null]=n.split("=");if(e=decodeURIComponent(e),s)s=decodeURIComponent(s);if(!(e in r))r[e]=s;else if(Array.isArray(r[e]))r[e].push(s);else r[e]=[r[e],s]}return r}f.parseQueryString=u});var U=a((d)=>{var y=i(),c=(t)=>{if(typeof t==="string")return c(new URL(t));let{hostname:r,pathname:n,port:e,protocol:s,search:o}=t,p;if(o)p=y.parseQueryString(o);return{hostname:r,port:e?parseInt(e):void 0,protocol:s,path:n,query:p}};d.parseUrl=c});
3
3
  export{U};
4
4
 
5
- //# debugId=7444BAECD1A15B5364756E2164756E21
5
+ //# debugId=05359E243FFC06B164756E2164756E21
@@ -6,6 +6,6 @@
6
6
  "'use strict';\n\nvar querystringParser = require('@smithy/querystring-parser');\n\nconst parseUrl = (url) => {\n if (typeof url === \"string\") {\n return parseUrl(new URL(url));\n }\n const { hostname, pathname, port, protocol, search } = url;\n let query;\n if (search) {\n query = querystringParser.parseQueryString(search);\n }\n return {\n hostname,\n port: port ? parseInt(port) : undefined,\n protocol,\n path: pathname,\n query,\n };\n};\n\nexports.parseUrl = parseUrl;\n"
7
7
  ],
8
8
  "mappings": ";uDAEA,SAAS,CAAgB,CAAC,EAAa,CACnC,IAAM,EAAQ,CAAC,EAEf,GADA,EAAc,EAAY,QAAQ,MAAO,EAAE,EACvC,EACA,QAAW,KAAQ,EAAY,MAAM,GAAG,EAAG,CACvC,IAAK,EAAK,EAAQ,MAAQ,EAAK,MAAM,GAAG,EAExC,GADA,EAAM,mBAAmB,CAAG,EACxB,EACA,EAAQ,mBAAmB,CAAK,EAEpC,GAAI,EAAE,KAAO,GACT,EAAM,GAAO,EAEZ,QAAI,MAAM,QAAQ,EAAM,EAAI,EAC7B,EAAM,GAAK,KAAK,CAAK,EAGrB,OAAM,GAAO,CAAC,EAAM,GAAM,CAAK,EAI3C,OAAO,EAGH,mBAAmB,kBCxB3B,IAAI,MAEE,EAAW,CAAC,IAAQ,CACtB,GAAI,OAAO,IAAQ,SACf,OAAO,EAAS,IAAI,IAAI,CAAG,CAAC,EAEhC,IAAQ,WAAU,WAAU,OAAM,WAAU,UAAW,EACnD,EACJ,GAAI,EACA,EAAQ,EAAkB,iBAAiB,CAAM,EAErD,MAAO,CACH,WACA,KAAM,EAAO,SAAS,CAAI,EAAI,OAC9B,WACA,KAAM,EACN,OACJ,GAGI,WAAW",
9
- "debugId": "7444BAECD1A15B5364756E2164756E21",
9
+ "debugId": "05359E243FFC06B164756E2164756E21",
10
10
  "names": []
11
11
  }