gemi 0.116.0 → 0.118.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 (355) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/app/index.js +2 -2
  4. package/dist/app/index.js.map +1 -1
  5. package/dist/auth/AuthServiceProvider.d.ts.map +1 -1
  6. package/dist/auth/config.d.ts +27 -0
  7. package/dist/auth/config.d.ts.map +1 -1
  8. package/dist/auth/connections/ConnectionManager.d.ts +133 -0
  9. package/dist/auth/connections/ConnectionManager.d.ts.map +1 -0
  10. package/dist/auth/connections/ConnectionStore.d.ts +146 -0
  11. package/dist/auth/connections/ConnectionStore.d.ts.map +1 -0
  12. package/dist/auth/connections/ConnectionsController.d.ts +23 -0
  13. package/dist/auth/connections/ConnectionsController.d.ts.map +1 -0
  14. package/dist/auth/connections/OAuthConnectionProvider.d.ts +105 -0
  15. package/dist/auth/connections/OAuthConnectionProvider.d.ts.map +1 -0
  16. package/dist/auth/connections/errors.d.ts +32 -0
  17. package/dist/auth/connections/errors.d.ts.map +1 -0
  18. package/dist/auth/oauth/oauthState.d.ts +15 -2
  19. package/dist/auth/oauth/oauthState.d.ts.map +1 -1
  20. package/dist/auth/routes.d.ts +13 -0
  21. package/dist/auth/routes.d.ts.map +1 -1
  22. package/dist/bin/orm/emit.d.ts.map +1 -1
  23. package/dist/bin/orm-generator.js +51 -4
  24. package/dist/bin/orm-generator.js.map +4 -4
  25. package/dist/bun/plugin.js +2 -2
  26. package/dist/bun/plugin.js.map +1 -1
  27. package/dist/bun/preload.js +2 -2
  28. package/dist/bun/preload.js.map +1 -1
  29. package/dist/{chunk-2tzm58j3.js → chunk-01ehxca0.js} +2 -2
  30. package/dist/{chunk-2tzm58j3.js.map → chunk-01ehxca0.js.map} +1 -1
  31. package/dist/chunk-0gtyects.js +10 -0
  32. package/dist/{chunk-yf1njzd5.js.map → chunk-0gtyects.js.map} +6 -5
  33. package/dist/{chunk-15c2vgaf.js → chunk-1m3hvy3q.js} +2 -2
  34. package/dist/{chunk-15c2vgaf.js.map → chunk-1m3hvy3q.js.map} +1 -1
  35. package/dist/{chunk-6cx8ncd4.js → chunk-1z1rj2zq.js} +3 -3
  36. package/dist/{chunk-6cx8ncd4.js.map → chunk-1z1rj2zq.js.map} +1 -1
  37. package/dist/{chunk-5stgtwqw.js → chunk-2bja99cq.js} +2 -2
  38. package/dist/{chunk-5stgtwqw.js.map → chunk-2bja99cq.js.map} +1 -1
  39. package/dist/{chunk-n672d4g8.js → chunk-30xxc6r7.js} +2 -2
  40. package/dist/{chunk-n672d4g8.js.map → chunk-30xxc6r7.js.map} +1 -1
  41. package/dist/{chunk-qjhw8nje.js → chunk-33s2xqv1.js} +1 -1
  42. package/dist/{chunk-4088szy9.js → chunk-39kyz4k6.js} +3 -3
  43. package/dist/{chunk-4088szy9.js.map → chunk-39kyz4k6.js.map} +1 -1
  44. package/dist/chunk-3nf95j9e.js +5 -0
  45. package/dist/{chunk-1q9kd20m.js.map → chunk-3nf95j9e.js.map} +1 -1
  46. package/dist/chunk-3zxfd7pn.js +14 -0
  47. package/dist/{chunk-pn8v6fj2.js.map → chunk-3zxfd7pn.js.map} +11 -6
  48. package/dist/{chunk-pyk3gzvc.js → chunk-453rmkpm.js} +2 -2
  49. package/dist/{chunk-pyk3gzvc.js.map → chunk-453rmkpm.js.map} +1 -1
  50. package/dist/chunk-47h12eme.js +57 -0
  51. package/dist/{chunk-ms9k0rx6.js.map → chunk-47h12eme.js.map} +15 -11
  52. package/dist/chunk-490sbcma.js +5 -0
  53. package/dist/chunk-490sbcma.js.map +12 -0
  54. package/dist/{chunk-kqxdsv22.js → chunk-4c1kdd8p.js} +2 -2
  55. package/dist/{chunk-kqxdsv22.js.map → chunk-4c1kdd8p.js.map} +1 -1
  56. package/dist/{chunk-jdhdrr2k.js → chunk-5cgq9c43.js} +2 -2
  57. package/dist/{chunk-jdhdrr2k.js.map → chunk-5cgq9c43.js.map} +1 -1
  58. package/dist/{chunk-9n1hx3mq.js → chunk-5dbpgyrx.js} +3 -3
  59. package/dist/{chunk-9n1hx3mq.js.map → chunk-5dbpgyrx.js.map} +1 -1
  60. package/dist/{chunk-eqse2m6n.js → chunk-5ses4tcz.js} +2 -2
  61. package/dist/{chunk-eqse2m6n.js.map → chunk-5ses4tcz.js.map} +1 -1
  62. package/dist/{chunk-2z1981d0.js → chunk-675kzd7z.js} +2 -2
  63. package/dist/{chunk-2z1981d0.js.map → chunk-675kzd7z.js.map} +1 -1
  64. package/dist/{chunk-p1aqq0ga.js → chunk-6ggmk2eg.js} +3 -3
  65. package/dist/{chunk-p1aqq0ga.js.map → chunk-6ggmk2eg.js.map} +1 -1
  66. package/dist/{chunk-mazznq15.js → chunk-76p0rf4d.js} +3 -3
  67. package/dist/{chunk-mazznq15.js.map → chunk-76p0rf4d.js.map} +1 -1
  68. package/dist/{chunk-41da9628.js → chunk-8t6dwwz6.js} +1 -1
  69. package/dist/{chunk-zyt2w03d.js → chunk-8wcpxm41.js} +2 -2
  70. package/dist/{chunk-zyt2w03d.js.map → chunk-8wcpxm41.js.map} +1 -1
  71. package/dist/chunk-9pkj7sk6.js +50 -0
  72. package/dist/chunk-9pkj7sk6.js.map +10 -0
  73. package/dist/{chunk-jmpw6bqz.js → chunk-a1qt8aky.js} +2 -2
  74. package/dist/{chunk-jmpw6bqz.js.map → chunk-a1qt8aky.js.map} +1 -1
  75. package/dist/{chunk-frerzsxq.js → chunk-a22h5cby.js} +2 -2
  76. package/dist/{chunk-frerzsxq.js.map → chunk-a22h5cby.js.map} +1 -1
  77. package/dist/{chunk-e573yxpq.js → chunk-aedkrck1.js} +3 -3
  78. package/dist/{chunk-e573yxpq.js.map → chunk-aedkrck1.js.map} +1 -1
  79. package/dist/{chunk-vxm6yevm.js → chunk-aqpaw4jq.js} +2 -2
  80. package/dist/{chunk-vxm6yevm.js.map → chunk-aqpaw4jq.js.map} +1 -1
  81. package/dist/{chunk-aeh67ynz.js → chunk-bgwtdbfw.js} +3 -3
  82. package/dist/{chunk-aeh67ynz.js.map → chunk-bgwtdbfw.js.map} +1 -1
  83. package/dist/{chunk-tw5kwbx4.js → chunk-bz8xssrc.js} +2 -2
  84. package/dist/{chunk-tw5kwbx4.js.map → chunk-bz8xssrc.js.map} +1 -1
  85. package/dist/{chunk-tzm3c7n6.js → chunk-cte6ysqd.js} +4 -4
  86. package/dist/{chunk-tzm3c7n6.js.map → chunk-cte6ysqd.js.map} +1 -1
  87. package/dist/{chunk-qsrcdzan.js → chunk-cvfg88cx.js} +3 -3
  88. package/dist/{chunk-qsrcdzan.js.map → chunk-cvfg88cx.js.map} +1 -1
  89. package/dist/{chunk-1vzks22y.js → chunk-d806cy7p.js} +2 -2
  90. package/dist/{chunk-1vzks22y.js.map → chunk-d806cy7p.js.map} +1 -1
  91. package/dist/{chunk-6chz1ktz.js → chunk-de4t48j9.js} +3 -3
  92. package/dist/{chunk-6chz1ktz.js.map → chunk-de4t48j9.js.map} +1 -1
  93. package/dist/{chunk-mqfzdfnz.js → chunk-dwpn6fze.js} +2 -2
  94. package/dist/{chunk-mqfzdfnz.js.map → chunk-dwpn6fze.js.map} +1 -1
  95. package/dist/{chunk-vbdty91k.js → chunk-ebret82e.js} +3 -3
  96. package/dist/{chunk-vbdty91k.js.map → chunk-ebret82e.js.map} +1 -1
  97. package/dist/chunk-eke2frrm.js +9 -0
  98. package/dist/{chunk-hytt9qyj.js.map → chunk-eke2frrm.js.map} +3 -4
  99. package/dist/{chunk-yer1r3t3.js → chunk-epvpmakp.js} +2 -2
  100. package/dist/{chunk-yer1r3t3.js.map → chunk-epvpmakp.js.map} +1 -1
  101. package/dist/{chunk-fxgxf16k.js → chunk-fsj5k511.js} +2 -2
  102. package/dist/{chunk-fxgxf16k.js.map → chunk-fsj5k511.js.map} +1 -1
  103. package/dist/{chunk-t4yh4nf9.js → chunk-g5ppst76.js} +3 -3
  104. package/dist/{chunk-t4yh4nf9.js.map → chunk-g5ppst76.js.map} +1 -1
  105. package/dist/{chunk-aazmrxj9.js → chunk-g9hhdcax.js} +2 -2
  106. package/dist/{chunk-aazmrxj9.js.map → chunk-g9hhdcax.js.map} +1 -1
  107. package/dist/{chunk-cbqazg9k.js → chunk-gqfqnv3f.js} +2 -2
  108. package/dist/{chunk-cbqazg9k.js.map → chunk-gqfqnv3f.js.map} +1 -1
  109. package/dist/chunk-hkf2k2eq.js +5 -0
  110. package/dist/{chunk-whtzggn6.js.map → chunk-hkf2k2eq.js.map} +3 -4
  111. package/dist/{chunk-vw8849ys.js → chunk-hm9cjxy2.js} +2 -2
  112. package/dist/{chunk-m54s6jpr.js.map → chunk-hm9cjxy2.js.map} +1 -1
  113. package/dist/{chunk-kejwjerj.js → chunk-hr1r3g0d.js} +2 -2
  114. package/dist/{chunk-kejwjerj.js.map → chunk-hr1r3g0d.js.map} +1 -1
  115. package/dist/{chunk-3hrj5rwm.js → chunk-hzepfrzy.js} +2 -2
  116. package/dist/{chunk-3hrj5rwm.js.map → chunk-hzepfrzy.js.map} +1 -1
  117. package/dist/{chunk-785b41h1.js → chunk-j5858bz7.js} +3 -3
  118. package/dist/{chunk-785b41h1.js.map → chunk-j5858bz7.js.map} +1 -1
  119. package/dist/{chunk-d9mar37g.js → chunk-jf6qqzat.js} +2 -2
  120. package/dist/{chunk-d9mar37g.js.map → chunk-jf6qqzat.js.map} +1 -1
  121. package/dist/{chunk-1hr4xht1.js → chunk-jg79n382.js} +2 -2
  122. package/dist/{chunk-1hr4xht1.js.map → chunk-jg79n382.js.map} +1 -1
  123. package/dist/chunk-k31qfe7a.js +71 -0
  124. package/dist/chunk-k31qfe7a.js.map +13 -0
  125. package/dist/{chunk-4mfrgd5m.js → chunk-kk77x2v4.js} +2 -2
  126. package/dist/{chunk-4mfrgd5m.js.map → chunk-kk77x2v4.js.map} +1 -1
  127. package/dist/{chunk-1myhm0g3.js → chunk-kkte8nze.js} +3 -3
  128. package/dist/{chunk-1myhm0g3.js.map → chunk-kkte8nze.js.map} +1 -1
  129. package/dist/{chunk-hdps9n52.js → chunk-m4kmetpb.js} +3 -3
  130. package/dist/{chunk-hdps9n52.js.map → chunk-m4kmetpb.js.map} +1 -1
  131. package/dist/{chunk-gts5p6mw.js → chunk-n4sdm0jn.js} +4 -4
  132. package/dist/{chunk-gts5p6mw.js.map → chunk-n4sdm0jn.js.map} +1 -1
  133. package/dist/chunk-nang3847.js +416 -0
  134. package/dist/chunk-nang3847.js.map +24 -0
  135. package/dist/{chunk-agyfv3f8.js → chunk-nrezmscd.js} +1 -1
  136. package/dist/{chunk-xt9tv99x.js → chunk-p83erprx.js} +2 -2
  137. package/dist/{chunk-xt9tv99x.js.map → chunk-p83erprx.js.map} +1 -1
  138. package/dist/{chunk-sr942vb1.js → chunk-pkr5dsbk.js} +2 -2
  139. package/dist/{chunk-sr942vb1.js.map → chunk-pkr5dsbk.js.map} +1 -1
  140. package/dist/{chunk-yhrye9cm.js → chunk-pqc16rrx.js} +2 -2
  141. package/dist/{chunk-yhrye9cm.js.map → chunk-pqc16rrx.js.map} +1 -1
  142. package/dist/{chunk-m54s6jpr.js → chunk-pvz90a49.js} +2 -2
  143. package/dist/{chunk-vw8849ys.js.map → chunk-pvz90a49.js.map} +1 -1
  144. package/dist/{chunk-fre6f4nk.js → chunk-q290tgza.js} +2 -2
  145. package/dist/{chunk-fre6f4nk.js.map → chunk-q290tgza.js.map} +1 -1
  146. package/dist/{chunk-8rv62v14.js → chunk-qf4bmee9.js} +2 -2
  147. package/dist/{chunk-8rv62v14.js.map → chunk-qf4bmee9.js.map} +1 -1
  148. package/dist/chunk-qkxnvpaj.js +5 -0
  149. package/dist/chunk-qkxnvpaj.js.map +10 -0
  150. package/dist/chunk-r1favzz4.js +19 -0
  151. package/dist/{chunk-ktr3k768.js.map → chunk-r1favzz4.js.map} +5 -4
  152. package/dist/{chunk-303mprnv.js → chunk-r3v2cnrj.js} +2 -2
  153. package/dist/{chunk-303mprnv.js.map → chunk-r3v2cnrj.js.map} +1 -1
  154. package/dist/{chunk-x7cpth2f.js → chunk-razjfecn.js} +1 -1
  155. package/dist/{chunk-t04f3akb.js → chunk-scc0j5k9.js} +2 -2
  156. package/dist/{chunk-t04f3akb.js.map → chunk-scc0j5k9.js.map} +1 -1
  157. package/dist/{chunk-56jky6vf.js → chunk-sce5jes2.js} +2 -2
  158. package/dist/{chunk-56jky6vf.js.map → chunk-sce5jes2.js.map} +1 -1
  159. package/dist/chunk-sd02ktf2.js +24 -0
  160. package/dist/{chunk-79xg42e7.js.map → chunk-sd02ktf2.js.map} +2 -2
  161. package/dist/{chunk-mschc94q.js → chunk-sn04cyw0.js} +2 -2
  162. package/dist/{chunk-mschc94q.js.map → chunk-sn04cyw0.js.map} +1 -1
  163. package/dist/{chunk-bra1a1fq.js → chunk-tfdmvxza.js} +2 -2
  164. package/dist/{chunk-bra1a1fq.js.map → chunk-tfdmvxza.js.map} +1 -1
  165. package/dist/{chunk-z10cas5r.js → chunk-thz75w6e.js} +2 -2
  166. package/dist/{chunk-z10cas5r.js.map → chunk-thz75w6e.js.map} +1 -1
  167. package/dist/{chunk-v1tfdgy1.js → chunk-tzdenj0n.js} +3 -3
  168. package/dist/{chunk-v1tfdgy1.js.map → chunk-tzdenj0n.js.map} +1 -1
  169. package/dist/{chunk-98m15b9x.js → chunk-x6v2zex2.js} +2 -2
  170. package/dist/{chunk-98m15b9x.js.map → chunk-x6v2zex2.js.map} +1 -1
  171. package/dist/{chunk-d2gfcf85.js → chunk-xfw8zyvn.js} +2 -2
  172. package/dist/{chunk-d2gfcf85.js.map → chunk-xfw8zyvn.js.map} +1 -1
  173. package/dist/{chunk-wyw6p3fg.js → chunk-xtzn0qfh.js} +3 -3
  174. package/dist/{chunk-wyw6p3fg.js.map → chunk-xtzn0qfh.js.map} +1 -1
  175. package/dist/{chunk-tn2bryy2.js → chunk-xx3zvc3g.js} +2 -2
  176. package/dist/{chunk-tn2bryy2.js.map → chunk-xx3zvc3g.js.map} +1 -1
  177. package/dist/{chunk-er3wf6ng.js → chunk-xzn2nmny.js} +2 -2
  178. package/dist/{chunk-er3wf6ng.js.map → chunk-xzn2nmny.js.map} +1 -1
  179. package/dist/{chunk-p91b8zcn.js → chunk-xzyy896s.js} +2 -2
  180. package/dist/{chunk-p91b8zcn.js.map → chunk-xzyy896s.js.map} +1 -1
  181. package/dist/chunk-y09r0wsw.js +5 -0
  182. package/dist/chunk-y09r0wsw.js.map +12 -0
  183. package/dist/{chunk-6d8rvr1v.js → chunk-ygf0z7kk.js} +2 -2
  184. package/dist/{chunk-6d8rvr1v.js.map → chunk-ygf0z7kk.js.map} +1 -1
  185. package/dist/chunk-z759yah5.js +5 -0
  186. package/dist/chunk-z759yah5.js.map +12 -0
  187. package/dist/client/Head.d.ts.map +1 -1
  188. package/dist/client/fonts.d.ts +69 -0
  189. package/dist/client/fonts.d.ts.map +1 -0
  190. package/dist/client/index.d.ts +1 -0
  191. package/dist/client/index.d.ts.map +1 -1
  192. package/dist/client/index.js +75 -1
  193. package/dist/client/index.js.map +1 -1
  194. package/dist/config/index.js +1 -1
  195. package/dist/console/builtins.d.ts +13 -0
  196. package/dist/console/builtins.d.ts.map +1 -0
  197. package/dist/console/run.js +13 -11
  198. package/dist/console/run.js.map +6 -5
  199. package/dist/console/runner.d.ts.map +1 -1
  200. package/dist/console/usage.d.ts +2 -0
  201. package/dist/console/usage.d.ts.map +1 -1
  202. package/dist/container/index.js +2 -2
  203. package/dist/container/index.js.map +1 -1
  204. package/dist/database/index.js +2 -2
  205. package/dist/database/index.js.map +1 -1
  206. package/dist/email/index.js +2 -2
  207. package/dist/email/index.js.map +1 -1
  208. package/dist/facades/Connections.d.ts +36 -0
  209. package/dist/facades/Connections.d.ts.map +1 -0
  210. package/dist/facades/Crypt.d.ts +26 -0
  211. package/dist/facades/Crypt.d.ts.map +1 -0
  212. package/dist/facades/Meta.d.ts +7 -1
  213. package/dist/facades/Meta.d.ts.map +1 -1
  214. package/dist/facades/Storage.d.ts +29 -0
  215. package/dist/facades/Storage.d.ts.map +1 -1
  216. package/dist/facades/index.d.ts +2 -0
  217. package/dist/facades/index.d.ts.map +1 -1
  218. package/dist/facades/index.js +2 -2
  219. package/dist/facades/index.js.map +1 -1
  220. package/dist/foundation/index.js +2 -2
  221. package/dist/foundation/index.js.map +1 -1
  222. package/dist/http/HttpRequest.d.ts +1 -0
  223. package/dist/http/HttpRequest.d.ts.map +1 -1
  224. package/dist/http/Metadata.d.ts +5 -0
  225. package/dist/http/Metadata.d.ts.map +1 -1
  226. package/dist/http/index.d.ts +3 -1
  227. package/dist/http/index.d.ts.map +1 -1
  228. package/dist/http/index.js +2 -2
  229. package/dist/http/index.js.map +1 -1
  230. package/dist/http/requestContext.d.ts +1 -0
  231. package/dist/http/requestContext.d.ts.map +1 -1
  232. package/dist/http/safeFetch/errors.d.ts +10 -0
  233. package/dist/http/safeFetch/errors.d.ts.map +1 -1
  234. package/dist/http/safeFetch/index.d.ts +1 -1
  235. package/dist/http/safeFetch/index.d.ts.map +1 -1
  236. package/dist/http/sitemap/Robots.d.ts +95 -0
  237. package/dist/http/sitemap/Robots.d.ts.map +1 -0
  238. package/dist/http/sitemap/Sitemap.d.ts +145 -0
  239. package/dist/http/sitemap/Sitemap.d.ts.map +1 -0
  240. package/dist/http/sitemap/fetchText.d.ts +16 -0
  241. package/dist/http/sitemap/fetchText.d.ts.map +1 -0
  242. package/dist/http/sitemap/index.d.ts +3 -0
  243. package/dist/http/sitemap/index.d.ts.map +1 -0
  244. package/dist/http/sitemap/xml.d.ts +21 -0
  245. package/dist/http/sitemap/xml.d.ts.map +1 -0
  246. package/dist/i18n/Translator.d.ts.map +1 -1
  247. package/dist/i18n/dictionaryRuntime.js +2 -2
  248. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  249. package/dist/i18n/index.d.ts +1 -1
  250. package/dist/i18n/index.d.ts.map +1 -1
  251. package/dist/i18n/index.js +2 -2
  252. package/dist/i18n/index.js.map +2 -2
  253. package/dist/i18n/resolveLocale.d.ts +18 -0
  254. package/dist/i18n/resolveLocale.d.ts.map +1 -1
  255. package/dist/kernel/index.js +3 -3
  256. package/dist/kernel/index.js.map +3 -3
  257. package/dist/kernel/providers.d.ts +2 -2
  258. package/dist/kernel/providers.d.ts.map +1 -1
  259. package/dist/orm/Model.d.ts.map +1 -1
  260. package/dist/orm/encryption-rotate.d.ts +44 -0
  261. package/dist/orm/encryption-rotate.d.ts.map +1 -0
  262. package/dist/orm/encryption.d.ts +54 -0
  263. package/dist/orm/encryption.d.ts.map +1 -0
  264. package/dist/orm/index.d.ts +2 -0
  265. package/dist/orm/index.d.ts.map +1 -1
  266. package/dist/orm/index.js +3 -3
  267. package/dist/orm/index.js.map +4 -4
  268. package/dist/orm/schema.d.ts +25 -1
  269. package/dist/orm/schema.d.ts.map +1 -1
  270. package/dist/server/index.js +2 -2
  271. package/dist/server/index.js.map +1 -1
  272. package/dist/services/discovery.d.ts +8 -0
  273. package/dist/services/discovery.d.ts.map +1 -1
  274. package/dist/services/encryption/Encrypter.d.ts +86 -0
  275. package/dist/services/encryption/Encrypter.d.ts.map +1 -0
  276. package/dist/services/encryption/EncryptionServiceProvider.d.ts +13 -0
  277. package/dist/services/encryption/EncryptionServiceProvider.d.ts.map +1 -0
  278. package/dist/services/encryption/config.d.ts +36 -0
  279. package/dist/services/encryption/config.d.ts.map +1 -0
  280. package/dist/services/file-storage/drivers/FileStorageDriver.d.ts +12 -1
  281. package/dist/services/file-storage/drivers/FileStorageDriver.d.ts.map +1 -1
  282. package/dist/services/file-storage/drivers/FileSystemDriver.d.ts +8 -1
  283. package/dist/services/file-storage/drivers/FileSystemDriver.d.ts.map +1 -1
  284. package/dist/services/file-storage/drivers/types.d.ts +17 -0
  285. package/dist/services/file-storage/drivers/types.d.ts.map +1 -1
  286. package/dist/services/file-storage/putFromUrl.d.ts +56 -0
  287. package/dist/services/file-storage/putFromUrl.d.ts.map +1 -0
  288. package/dist/services/file-storage/sniffContentType.d.ts +33 -0
  289. package/dist/services/file-storage/sniffContentType.d.ts.map +1 -0
  290. package/dist/services/index.d.ts +26 -5
  291. package/dist/services/index.d.ts.map +1 -1
  292. package/dist/services/index.js +10 -10
  293. package/dist/services/index.js.map +4 -3
  294. package/dist/services/queue/DatabaseQueueDriver.d.ts +117 -7
  295. package/dist/services/queue/DatabaseQueueDriver.d.ts.map +1 -1
  296. package/dist/services/queue/Job.d.ts +75 -0
  297. package/dist/services/queue/Job.d.ts.map +1 -1
  298. package/dist/services/queue/MemoryQueueDriver.d.ts +32 -2
  299. package/dist/services/queue/MemoryQueueDriver.d.ts.map +1 -1
  300. package/dist/services/queue/QueueDriver.d.ts +83 -1
  301. package/dist/services/queue/QueueDriver.d.ts.map +1 -1
  302. package/dist/services/queue/QueueManager.d.ts +80 -7
  303. package/dist/services/queue/QueueManager.d.ts.map +1 -1
  304. package/dist/services/queue/QueueServiceProvider.d.ts.map +1 -1
  305. package/dist/services/queue/backoff.d.ts +6 -0
  306. package/dist/services/queue/backoff.d.ts.map +1 -0
  307. package/dist/services/queue/batch.d.ts +112 -0
  308. package/dist/services/queue/batch.d.ts.map +1 -0
  309. package/dist/services/queue/config.d.ts +9 -0
  310. package/dist/services/queue/config.d.ts.map +1 -1
  311. package/dist/services/queue/queueDriverContract.d.ts +5 -0
  312. package/dist/services/queue/queueDriverContract.d.ts.map +1 -1
  313. package/dist/services/queue/work.js +2 -2
  314. package/dist/services/queue/work.js.map +1 -1
  315. package/dist/services/queue/workflow/DatabaseWorkflowStore.d.ts +89 -0
  316. package/dist/services/queue/workflow/DatabaseWorkflowStore.d.ts.map +1 -0
  317. package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts +43 -0
  318. package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts.map +1 -0
  319. package/dist/services/queue/workflow/Step.d.ts +202 -0
  320. package/dist/services/queue/workflow/Step.d.ts.map +1 -0
  321. package/dist/services/queue/workflow/Workflow.d.ts +124 -0
  322. package/dist/services/queue/workflow/Workflow.d.ts.map +1 -0
  323. package/dist/services/queue/workflow/WorkflowRuntime.d.ts +60 -0
  324. package/dist/services/queue/workflow/WorkflowRuntime.d.ts.map +1 -0
  325. package/dist/services/queue/workflow/WorkflowStore.d.ts +184 -0
  326. package/dist/services/queue/workflow/WorkflowStore.d.ts.map +1 -0
  327. package/dist/services/queue/workflow/duration.d.ts +8 -0
  328. package/dist/services/queue/workflow/duration.d.ts.map +1 -0
  329. package/dist/services/queue/workflow/workflowContract.d.ts +30 -0
  330. package/dist/services/queue/workflow/workflowContract.d.ts.map +1 -0
  331. package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
  332. package/dist/stats/route-table.js +1 -1
  333. package/dist/support/index.js +2 -2
  334. package/dist/support/index.js.map +1 -1
  335. package/dist/vitest/index.js +2 -2
  336. package/dist/vitest/index.js.map +1 -1
  337. package/package.json +1 -1
  338. package/dist/chunk-1q9kd20m.js +0 -5
  339. package/dist/chunk-49nyyjfe.js +0 -5
  340. package/dist/chunk-49nyyjfe.js.map +0 -11
  341. package/dist/chunk-79xg42e7.js +0 -24
  342. package/dist/chunk-7vb4eey2.js +0 -217
  343. package/dist/chunk-7vb4eey2.js.map +0 -16
  344. package/dist/chunk-hytt9qyj.js +0 -54
  345. package/dist/chunk-jmg2zsaf.js +0 -5
  346. package/dist/chunk-jmg2zsaf.js.map +0 -12
  347. package/dist/chunk-ktr3k768.js +0 -19
  348. package/dist/chunk-ms9k0rx6.js +0 -46
  349. package/dist/chunk-pn8v6fj2.js +0 -14
  350. package/dist/chunk-whtzggn6.js +0 -5
  351. package/dist/chunk-yf1njzd5.js +0 -10
  352. /package/dist/{chunk-qjhw8nje.js.map → chunk-33s2xqv1.js.map} +0 -0
  353. /package/dist/{chunk-41da9628.js.map → chunk-8t6dwwz6.js.map} +0 -0
  354. /package/dist/{chunk-agyfv3f8.js.map → chunk-nrezmscd.js.map} +0 -0
  355. /package/dist/{chunk-x7cpth2f.js.map → chunk-razjfecn.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
2
  function v(j){return j==="/api"||j.startsWith("/api/")}function z(j){return v(j)?j.slice(4):j}
3
- export{v as oi,z as pi};
3
+ export{v as cj,z as dj};
4
4
 
5
- //# debugId=63BC684A43BB685D64756E2164756E21
5
+ //# debugId=6E0CC7F698BDC2A164756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "/**\n * The prefix every api route is served under. The browser adds it when it\n * fetches (`/api${path}`) and the server strips it before matching, so an api\n * router's own paths never carry it.\n */\nexport const API_PREFIX = \"/api\";\n\n/**\n * Whether a request pathname is an api request: `/api` itself or anything\n * under `/api/`. A bare `startsWith(\"/api\")` also claims `/apidocs`,\n * `/api-keys` and `/apiary`, so a view route there would never render — the\n * api dispatcher would answer its 404 JSON instead.\n */\nexport function isApiPath(pathname: string): boolean {\n return pathname === API_PREFIX || pathname.startsWith(`${API_PREFIX}/`);\n}\n\n/**\n * The api router path a request pathname addresses: `/api/users/1` is\n * `/users/1`, `/api/` is `/` and `/api` is `\"\"`. Only the leading prefix is\n * stripped — `replace(\"/api\", \"\")` would also strip an `/api` inside the path\n * of a request that did not start with one (`/files/api` becoming `/files`).\n * A pathname outside `/api` comes back unchanged, so the dispatcher can still\n * be handed a request by its route path directly.\n */\nexport function apiPath(pathname: string): string {\n return isApiPath(pathname) ? pathname.slice(API_PREFIX.length) : pathname;\n}\n"
6
6
  ],
7
7
  "mappings": ";AAaO,SAAS,CAAS,CAAC,EAA2B,CACnD,OAAO,IATiB,QASU,EAAS,WAAW,OAAgB,EAWjE,SAAS,CAAO,CAAC,EAA0B,CAChD,OAAO,EAAU,CAAQ,EAAI,EAAS,MAAM,CAAiB,EAAI",
8
- "debugId": "63BC684A43BB685D64756E2164756E21",
8
+ "debugId": "6E0CC7F698BDC2A164756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -2,6 +2,6 @@
2
2
  import{existsSync as $,readdirSync as B}from"fs";import{join as Y,relative as G}from"path";function J(K,Q=[]){let U=[],X=(H)=>{let z=G(K,H).split("\\").join("/");return Q.some((q)=>z===q||z.startsWith(`${q}/`))},V=(H)=>{for(let z of B(H,{withFileTypes:!0}).sort((q,Z)=>q.name<Z.name?-1:q.name>Z.name?1:0)){let q=Y(H,z.name);if(X(q))continue;if(z.isDirectory()){if(z.name.startsWith(".")||z.name==="node_modules")continue;if($(Y(q,"package.json")))continue;V(q);continue}if(!z.name.endsWith(".ts")&&!z.name.endsWith(".tsx"))continue;if(z.name.endsWith(".d.ts"))continue;if(/\.(test|test-d|spec|bench)\.tsx?$/.test(z.name))continue;U.push(q)}};if(!$(K))return U;return V(K),U}class A extends Error{constructor(K,Q){super(K,Q);this.name="DiscoveryError"}}async function W(K,Q,U=[],X){let V=new Set;for(let H of J(K,U)){let z;try{z=await import(H)}catch(q){throw new A(`${H} could not be imported, so the classes in it could not be discovered:
3
3
  ${q.message}
4
4
  List the classes explicitly in the config slice for this directory to skip the walk.`,{cause:q})}for(let q of Object.values(z)){if(typeof q==="function"&&q!==Q&&Object.prototype.isPrototypeOf.call(Q,q)){V.add(q);continue}X?.(q,H)}}return[...V]}function F(){return Y(process.cwd(),process.env.GEMI_PROJECT_DIR??"")}
5
- export{J as ki,A as li,W as mi,F as ni};
5
+ export{J as _i,A as $i,W as aj,F as bj};
6
6
 
7
- //# debugId=E9A6106617E15F1E64756E2164756E21
7
+ //# debugId=E81261D2205887CF64756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "import { existsSync, readdirSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\n\n/**\n * Finding the classes an application declared and never imported — the walk\n * #322 and #323 both end at.\n *\n * ### Why it has to run the files\n *\n * A job that is written and not listed does not fail; it disappears.\n * `QueueManager.run` looks a dispatched name up in the map its config built and\n * drops what is not there, so the dispatch is simply lost. A cron drifts worse:\n * nothing is waiting on a tick, so a job that never fires reports nothing to\n * anyone. What both come down to is that `app/config/queue.ts` naming every\n * `Job` subclass is the *only* thing putting those classes in the module graph —\n * the list and the directory are two spellings of one set, kept in step by hand.\n *\n * The way out of that is to read the directory, and there is no static read that\n * will do: the class does not exist until its module has run. So **every file\n * walked here is imported**, and a file that *does something* when imported does\n * it here — at boot, in production, on every start. `gemi check models` makes\n * the same trade for the same reason and pays it once per CI run; a caller of\n * this pays it once per process.\n *\n * ### What that asks of a caller\n *\n * **Point it at a directory of class declarations, not at `app/`.** The skip\n * rules on `sourceFiles` drop what certainly is not one — tests, benchmarks,\n * `.d.ts`, vendored packages — and nothing else. Widening the guesses is how a\n * discovery pass ends up quietly covering less than the directory holds, which\n * is the same silence in a new place.\n *\n * **Let a broken file stop the boot.** `discoverClasses` rethrows an import\n * failure naming the file rather than dropping it and carrying on, for the same\n * reason: four classes found out of five looks exactly like five out of five.\n *\n * **Leave a way out.** Discovery is what should happen when an app said\n * nothing. An app that lists its classes explicitly must not reach this file at\n * all — that is the escape hatch for a directory holding something this cannot\n * import, and it is the sentence an error from here should point at.\n *\n * ### One more thing worth knowing\n *\n * This imports by absolute path, while the application imports the same files\n * through the `@/app/*` alias. Bun keys its module registry by the *resolved*\n * path, so those two specifiers land on one module: a job already reached from\n * a controller is not evaluated a second time here, and the class object is the\n * same one. `gemi build` leaves that true in production — `packages: \"external\"`\n * keeps the app's own code out of `dist/server/server.mjs` and resolves it from\n * source at runtime, exactly as `gemi dev` does.\n *\n * Nothing here depends on that holding, and deliberately: `QueueManager` and the\n * `Scheduler`'s cross-reload registry are both keyed by name rather than by\n * class identity, so a build that did inline the app's modules would produce a\n * duplicate class object and still register the right job. Worth knowing before\n * writing a registry keyed the other way.\n */\n\n/**\n * The files under `dir` that could declare a class.\n *\n * Everything underneath it, because apps do group classes into folders, minus\n * what cannot be one. Each of these is going to be *imported*, so the exclusions\n * are about what is certainly not source rather than about what is probably not:\n *\n * - **Declaration files.** `.d.ts` has no runtime module behind it.\n * - **Tests, type tests and benchmarks**, by the suffix a runner already\n * recognises.\n * - **Dot-directories and `node_modules`.**\n * - **Any directory holding a `package.json`.** That is a package that happens\n * to live here — a vendored client, a generated SDK — not this app's source,\n * and importing its entry point runs somebody else's module graph. The\n * template has two under `app/models`.\n *\n * `ignore` is the escape hatch for the rest: a path prefix, relative to `dir`,\n * naming a file or a directory of adjacent code that runs something on import.\n * Nothing is ignored by default.\n *\n * The order is the same on every run over the same tree, which matters because\n * the caller is going to import in it: entries are sorted per directory before\n * recursing, and `readdirSync` order is the filesystem's rather than\n * alphabetical — a tree written `A.ts` then `B.ts` reads back `B.ts` first on\n * the machines this was tested on. Sorting per directory rather than sorting the\n * finished list is deliberate: for a tree holding both `a.ts` and `a/b.ts`, this\n * emits `a/b.ts` first, because the directory sorts before the file.\n *\n * A directory that does not exist yields an empty list rather than throwing.\n * \"The app has no jobs yet\" is an ordinary state and not this function's to\n * complain about — but it is indistinguishable from \"the app's source did not\n * ship\", so a caller that boots on the answer owes the reader a word about which\n * one it got.\n */\nexport function sourceFiles(dir: string, ignore: string[] = []): string[] {\n const out: string[] = [];\n\n const ignored = (path: string) => {\n const rel = relative(dir, path).split(\"\\\\\").join(\"/\");\n return ignore.some(\n (pattern) => rel === pattern || rel.startsWith(`${pattern}/`),\n );\n };\n\n const walk = (current: string) => {\n for (const entry of readdirSync(current, { withFileTypes: true }).sort(\n (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),\n )) {\n const path = join(current, entry.name);\n if (ignored(path)) continue;\n\n if (entry.isDirectory()) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\")\n continue;\n if (existsSync(join(path, \"package.json\"))) continue;\n walk(path);\n continue;\n }\n\n if (!entry.name.endsWith(\".ts\") && !entry.name.endsWith(\".tsx\")) continue;\n if (entry.name.endsWith(\".d.ts\")) continue;\n if (/\\.(test|test-d|spec|bench)\\.tsx?$/.test(entry.name)) continue;\n\n out.push(path);\n }\n };\n\n if (!existsSync(dir)) return out;\n\n walk(dir);\n return out;\n}\n\n/**\n * A class, as much of one as this file can name. `abstract` so that a base an\n * app never instantiates directly is a legal argument.\n */\ntype ClassLike = abstract new (...args: never[]) => unknown;\n\n/**\n * A file that would not import, reported with the file that would not import.\n *\n * Separate from a bare rethrow because the stack of a failed dynamic import\n * names the module that failed to *resolve*, several frames deep, and says\n * nothing about the walk that asked for it — so the reader learns that some\n * `?raw` specifier is unresolvable without learning that discovery is what\n * imported it, or that listing the classes explicitly is how they get their boot\n * back.\n */\nexport class DiscoveryError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"DiscoveryError\";\n }\n}\n\n/**\n * Every exported class under `dir` whose prototype chain reaches `base`.\n *\n * `base` is a parameter rather than an import so that this file names no\n * service and stays cheap to depend on — `bin/check-models.ts` uses the walker\n * above and is bundled into `dist/bin/gemi.js`, which is not somewhere gemi's\n * service layer should end up. It is also what lets a test hand in a base class\n * of its own instead of standing up a project that can resolve `gemi/services`.\n *\n * `base` itself is never returned. A directory whose files import their base\n * from a sibling — the shape an app reaches for when several jobs share a gate —\n * re-exports it as often as not, and a framework that scheduled the abstract\n * base along with its subclasses would be running a job nobody wrote.\n *\n * A class is returned once no matter how many exports name it. A barrel in the\n * directory re-exporting everything beside it is the ordinary case, and it makes\n * every class reachable twice.\n *\n * The order is the walk's, and within a file the module namespace's, which the\n * language sorts by name. So the answer is the same on every run — worth having\n * where the caller is a scheduler and the alternative is a boot order that\n * depends on the filesystem.\n *\n * `onSkipped` is handed every export that did *not* match, with the file it came\n * from. Discovery's characteristic failure is a thing the author wrote and this\n * walk cannot see, and by the time an export has been discarded here the\n * information about why is gone — the caller is left holding \"four classes\"\n * where the directory holds five. A caller that can recognise its own\n * near-misses, as `discoverCommands` recognises a builder chain that was never\n * finished, uses this to say so by name instead.\n *\n * @throws DiscoveryError if a walked file cannot be imported. Not a skip: a file\n * that will not load is a class the caller was going to be told about and now is\n * not, which is the failure discovery exists to remove.\n */\nexport async function discoverClasses<T extends ClassLike>(\n dir: string,\n base: T,\n ignore: string[] = [],\n onSkipped?: (value: unknown, file: string) => void,\n): Promise<T[]> {\n const found = new Set<T>();\n\n for (const path of sourceFiles(dir, ignore)) {\n let module: Record<string, unknown>;\n\n try {\n module = (await import(path)) as Record<string, unknown>;\n } catch (error) {\n throw new DiscoveryError(\n `${path} could not be imported, so the classes in it could not be ` +\n `discovered:\\n ${(error as Error).message}\\n` +\n `List the classes explicitly in the config slice for this directory ` +\n `to skip the walk.`,\n { cause: error },\n );\n }\n\n for (const value of Object.values(module)) {\n if (\n typeof value === \"function\" &&\n value !== base &&\n Object.prototype.isPrototypeOf.call(base, value)\n ) {\n found.add(value as unknown as T);\n continue;\n }\n\n onSkipped?.(value, path);\n }\n }\n\n return [...found];\n}\n\n/**\n * The directory an app's `app/` sits in, as the running process can know it.\n *\n * `ROOT_DIR` is the obvious answer and is not available: `Server.start` awaits\n * `waitForBoot()` — every provider's `register` and `boot` — and only then\n * imports the http layer that sets it. Anything resolving paths during boot is\n * earlier than the variable it would want.\n *\n * What it can use is the same rule `httpProd` computes `ROOT_DIR` with a moment\n * later, which is why that file now calls this instead of repeating it. `gemi\n * dev` and `gemi start` both spawn the server with no `cwd`, so the process\n * inherits the CLI's, and the CLI takes `process.cwd()` for the project root\n * itself — `bun/preload.ts` reads `gemi.config` from it on the same assumption.\n *\n * `httpDev` computes a bare `process.cwd()`, so it and `httpProd` already\n * disagree whenever `GEMI_PROJECT_DIR` is set. Nothing in this repo sets it and\n * `gemi start` ignores it when locating the built entry point, so the two rules\n * are the same rule for every configuration that runs today; the divergence is\n * older than this function and wants its own fix.\n */\nexport function projectRoot(): string {\n return join(process.cwd(), process.env.GEMI_PROJECT_DIR ?? \"\");\n}\n"
6
6
  ],
7
7
  "mappings": ";AAAA,qBAAS,iBAAY,WACrB,eAAS,cAAM,aA2FR,SAAS,CAAW,CAAC,EAAa,EAAmB,CAAC,EAAa,CACxE,IAAM,EAAgB,CAAC,EAEjB,EAAU,CAAC,IAAiB,CAChC,IAAM,EAAM,EAAS,EAAK,CAAI,EAAE,MAAM,IAAI,EAAE,KAAK,GAAG,EACpD,OAAO,EAAO,KACZ,CAAC,IAAY,I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K,EAC/C,CACA,EAAM,IAAI,CAAqB,EAC/B,SAGF,IAAY,EAAO,CAAI,GAI3B,MAAO,CAAC,GAAG,CAAK,EAuBX,SAAS,CAAW,EAAW,CACpC,OAAO,EAAK,QAAQ,IAAI,EAAG,QAAQ,IAAI,kBAAoB,EAAE",
8
- "debugId": "E9A6106617E15F1E64756E2164756E21",
8
+ "debugId": "E81261D2205887CF64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -0,0 +1,71 @@
1
+ // @bun
2
+ import{eh as R}from"./chunk-y09r0wsw.js";import{Mh as L}from"./chunk-xx3zvc3g.js";import{ri as T}from"./chunk-hr1r3g0d.js";import{Ri as D}from"./chunk-g5ppst76.js";class X{rows=new Map;async find(j,B){for(let G of this.rows.values())if(G.userId===j&&G.provider===B)return{...G};return null}async list(j){return[...this.rows.values()].filter((B)=>B.userId===j).map((B)=>({...B}))}async save(j,B,G){let K=await this.find(j,B),J=new Date,Q={id:K?.id??Bun.randomUUIDv7(),userId:j,provider:B,...P(G),needsReconnect:!1,revision:(K?.revision??0)+1,createdAt:K?.createdAt??J,updatedAt:J};return this.rows.set(Q.id,Q),{...Q}}async updateTokens(j,B,G){let K=this.rows.get(j);if(!K||K.revision!==B)return null;let J={...K,...P(G),needsReconnect:!1,revision:B+1,updatedAt:new Date};return this.rows.set(j,J),{...J}}async markNeedsReconnect(j){let B=this.rows.get(j);if(B)this.rows.set(j,{...B,needsReconnect:!0,updatedAt:new Date})}async delete(j){this.rows.delete(j)}}class F{encrypter;table;sql;dialect;constructor(j,B,G={}){this.encrypter=B;let K=G.table??"gemi_oauth_connections";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K))throw Error(`The connections table name "${K}" is not a plain identifier.`);this.table=K,this.sql=j.sql,this.dialect=j.dialect}async createTable(){for(let j of A(this.dialect,this.table))await this.sql.unsafe(j)}async find(j,B){let G=this.sql,K=await G`
3
+ SELECT * FROM ${this.name(G)} WHERE user_id = ${j} AND provider = ${B}
4
+ `;return K[0]?this.decode(K[0]):null}async list(j){let B=this.sql;return(await B`
5
+ SELECT * FROM ${this.name(B)} WHERE user_id = ${j} ORDER BY provider
6
+ `).map((K)=>this.decode(K))}async save(j,B,G){let K=this.sql,J=this.encode(G),Q=Date.now(),V=async()=>x(await K`
7
+ UPDATE ${this.name(K)}
8
+ SET provider_account_id = ${J.providerAccountId}, scopes = ${J.scopes},
9
+ access_token = ${J.accessToken}, refresh_token = ${J.refreshToken},
10
+ token_type = ${J.tokenType}, expires_at = ${J.expiresAt},
11
+ needs_reconnect = 0, revision = revision + 1, updated_at = ${Q}
12
+ WHERE user_id = ${j} AND provider = ${B}
13
+ `);if(await V()===0)try{await K`
14
+ INSERT INTO ${this.name(K)} (id, user_id, provider, provider_account_id, scopes,
15
+ access_token, refresh_token, token_type, expires_at, needs_reconnect, revision,
16
+ created_at, updated_at)
17
+ VALUES (${Bun.randomUUIDv7()}, ${j}, ${B}, ${J.providerAccountId},
18
+ ${J.scopes}, ${J.accessToken}, ${J.refreshToken}, ${J.tokenType},
19
+ ${J.expiresAt}, 0, 1, ${Q}, ${Q})
20
+ `}catch(W){if(await V()===0)throw W}let Z=await this.find(j,B);if(!Z)throw Error("The OAuth connection vanished while it was being saved.");return Z}async updateTokens(j,B,G){let K=this.sql,J=this.encode(G),Q=await K`
21
+ UPDATE ${this.name(K)}
22
+ SET provider_account_id = COALESCE(${J.providerAccountId}, provider_account_id),
23
+ scopes = ${J.scopes}, access_token = ${J.accessToken},
24
+ refresh_token = ${J.refreshToken}, token_type = ${J.tokenType},
25
+ expires_at = ${J.expiresAt}, needs_reconnect = 0, revision = revision + 1,
26
+ updated_at = ${Date.now()}
27
+ WHERE id = ${j} AND revision = ${B}
28
+ `;if(x(Q)===0)return null;let V=await K`SELECT * FROM ${this.name(K)} WHERE id = ${j}`;return V[0]?this.decode(V[0]):null}async markNeedsReconnect(j){let B=this.sql;await B`UPDATE ${this.name(B)} SET needs_reconnect = 1, updated_at = ${Date.now()} WHERE id = ${j}`}async delete(j){let B=this.sql;await B`DELETE FROM ${this.name(B)} WHERE id = ${j}`}async rotateEncryption(j={}){let B=this.sql,G=this.encrypter(),K=await B`
29
+ SELECT id, access_token, refresh_token, revision FROM ${this.name(B)} ORDER BY id
30
+ `,J=0;for(let Q of K){let V=(W)=>typeof W==="string"&&G.needsReencryption(W);if(!V(Q.access_token)&&!V(Q.refresh_token))continue;if(J+=1,j.dryRun)continue;let Z=(W)=>W===null?null:G.encrypt(G.decrypt(W));await B`
31
+ UPDATE ${this.name(B)}
32
+ SET access_token = ${Z(Q.access_token)}, refresh_token = ${Z(Q.refresh_token)},
33
+ revision = revision + 1
34
+ WHERE id = ${Q.id} AND revision = ${Number(Q.revision)}
35
+ `}return{scanned:K.length,rotated:J}}encode(j){let B=this.encrypter();return{providerAccountId:j.providerAccountId,scopes:j.scopes.join(" "),accessToken:B.encrypt(j.accessToken),refreshToken:j.refreshToken===null?null:B.encrypt(j.refreshToken),tokenType:j.tokenType,expiresAt:j.expiresAt===null?null:j.expiresAt.getTime()}}decode(j){let B=this.encrypter();return{id:String(j.id),userId:String(j.user_id),provider:String(j.provider),providerAccountId:j.provider_account_id===null?null:String(j.provider_account_id),scopes:String(j.scopes??"").split(" ").filter(Boolean),accessToken:B.decrypt(String(j.access_token)),refreshToken:j.refresh_token===null?null:B.decrypt(String(j.refresh_token)),tokenType:j.token_type===null?null:String(j.token_type),expiresAt:j.expires_at===null?null:new Date(Number(j.expires_at)),needsReconnect:Number(j.needs_reconnect)===1,revision:Number(j.revision),createdAt:new Date(Number(j.created_at)),updatedAt:new Date(Number(j.updated_at))}}get mysql(){return this.dialect==="mysql"||this.dialect==="mariadb"}name(j){return j.unsafe(this.mysql?`\`${this.table}\``:`"${this.table}"`)}}function P(j){return{providerAccountId:j.providerAccountId,scopes:[...j.scopes],accessToken:j.accessToken,refreshToken:j.refreshToken,tokenType:j.tokenType,expiresAt:j.expiresAt}}function x(j){let B=j;return Math.max(Number(B.count??0),Number(B.affectedRows??0))}function A(j,B){if(j==="mysql"||j==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${B}\` (
36
+ \`id\` VARCHAR(191) NOT NULL,
37
+ \`user_id\` VARCHAR(191) NOT NULL,
38
+ \`provider\` VARCHAR(191) NOT NULL,
39
+ \`provider_account_id\` VARCHAR(191) NULL,
40
+ \`scopes\` TEXT NOT NULL,
41
+ \`access_token\` TEXT NOT NULL,
42
+ \`refresh_token\` TEXT NULL,
43
+ \`token_type\` VARCHAR(191) NULL,
44
+ \`expires_at\` BIGINT NULL,
45
+ \`needs_reconnect\` INTEGER NOT NULL DEFAULT 0,
46
+ \`revision\` BIGINT NOT NULL DEFAULT 0,
47
+ \`created_at\` BIGINT NOT NULL,
48
+ \`updated_at\` BIGINT NOT NULL,
49
+
50
+ UNIQUE INDEX \`${B}_user_id_provider_key\`(\`user_id\`, \`provider\`),
51
+ PRIMARY KEY (\`id\`)
52
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let G=j==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',K=j==="sqlite"?"":`,
53
+
54
+ CONSTRAINT "${B}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${B}" (
55
+ ${G}
56
+ "user_id" TEXT NOT NULL,
57
+ "provider" TEXT NOT NULL,
58
+ "provider_account_id" TEXT,
59
+ "scopes" TEXT NOT NULL,
60
+ "access_token" TEXT NOT NULL,
61
+ "refresh_token" TEXT,
62
+ "token_type" TEXT,
63
+ "expires_at" BIGINT,
64
+ "needs_reconnect" INTEGER NOT NULL DEFAULT 0,
65
+ "revision" BIGINT NOT NULL DEFAULT 0,
66
+ "created_at" BIGINT NOT NULL,
67
+ "updated_at" BIGINT NOT NULL${K}
68
+ )`,`CREATE UNIQUE INDEX IF NOT EXISTS "${B}_user_id_provider_key" ON "${B}"("user_id", "provider")`]}class Y extends Error{code;status;providerError;constructor(j,B,G={}){super(B,G.cause!==void 0?{cause:G.cause}:void 0);this.code=j;this.name="OAuthConnectionError",this.status=G.status,this.providerError=G.providerError}}class _ extends Y{provider;constructor(j,B={}){super("reconnect_required",`The ${j} connection needs to be reconnected: its tokens were refused and could not be refreshed.`,B);this.provider=j;this.name="OAuthReconnectRequiredError"}}class O{config;constructor(j){for(let B of["authorizeUrl","tokenUrl"])H(B,j[B]);if(j.revokeUrl!==void 0)H("revokeUrl",j.revokeUrl);if(j.apiBaseUrl===void 0||j.apiBaseUrl===null||j.apiBaseUrl==="")throw Error(`OAuthConnectionProvider: apiBaseUrl is required. Set it to the provider's API origin (e.g. apiBaseUrl: "https://api.figma.com"); connection.fetch only sends the token there.`);H("apiBaseUrl",j.apiBaseUrl),this.config={scopeSeparator:" ",clientAuth:"body",pkce:!0,authorizationParams:{},refreshLeewaySeconds:60,...j}}authorizationUrl(j){let B=new URL(this.config.authorizeUrl),G={...this.config.authorizationParams,response_type:"code",client_id:this.config.clientId,redirect_uri:j.redirectUri,scope:this.config.scopes.join(this.config.scopeSeparator),state:j.state};if(this.config.pkce)G.code_challenge=j.codeChallenge,G.code_challenge_method="S256";for(let[K,J]of Object.entries(G))B.searchParams.set(K,J);return B.toString()}exchangeCode(j){let B=new URLSearchParams({grant_type:"authorization_code",code:j.code,redirect_uri:j.redirectUri});if(this.config.pkce)B.set("code_verifier",j.codeVerifier);return this.tokenRequest(B,{scopes:this.config.scopes,refreshToken:null,phase:"exchange"})}refresh(j,B){let G=new URLSearchParams({grant_type:"refresh_token",refresh_token:j});return this.tokenRequest(G,{scopes:B,refreshToken:j,phase:"refresh"})}async revoke(j,B){if(!this.config.revokeUrl)throw new Y("revoke_unsupported","This provider has no revokeUrl configured. Use disconnect() to forget the tokens locally.");let G=new URLSearchParams({token:j,token_type_hint:B}),K;try{K=await fetch(this.config.revokeUrl,this.post(G))}catch(J){throw new Y("revoke_failed","The revocation request failed.",{cause:J})}if(!K.ok)throw new Y("revoke_failed",`The provider refused the revocation (HTTP ${K.status}).`,{status:K.status})}post(j){let B={"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"};if(this.config.clientAuth==="basic"){let G=`${encodeURIComponent(this.config.clientId)}:${encodeURIComponent(this.config.clientSecret)}`;B.Authorization=`Basic ${Buffer.from(G).toString("base64")}`}else j.set("client_id",this.config.clientId),j.set("client_secret",this.config.clientSecret);return{method:"POST",headers:B,body:j.toString(),redirect:"error"}}async tokenRequest(j,B){let G=B.phase==="exchange"?"exchange_failed":"refresh_failed",K;try{K=await fetch(this.config.tokenUrl,this.post(j))}catch(W){throw new Y(G,"The token request failed.",{cause:W})}let J=await K.json().catch(()=>({}));if(!K.ok||typeof J.access_token!=="string"||J.access_token===""){let W=typeof J.error==="string"&&/^[a-z0-9_]{1,64}$/.test(J.error)?J.error:void 0;throw new Y(G,`The token endpoint refused the ${B.phase==="exchange"?"code":"refresh token"} (HTTP ${K.status}${W?`, ${W}`:""}).`,{status:K.status,providerError:W})}let Q=Number(J.expires_in),V=typeof J.scope==="string"?J.scope:void 0,Z=J.user_id??J.account_id;return{accessToken:J.access_token,refreshToken:typeof J.refresh_token==="string"&&J.refresh_token!==""?J.refresh_token:B.refreshToken,tokenType:typeof J.token_type==="string"?J.token_type:null,expiresAt:Number.isFinite(Q)&&Q>0?new Date(Date.now()+Q*1000):null,scopes:V!==void 0?V.split(/[\s,]+/).filter(Boolean):B.scopes,providerAccountId:typeof Z==="string"||typeof Z==="number"?String(Z):null}}}function H(j,B){let G;try{G=new URL(String(B))}catch{G=void 0}if(!G||G.protocol!=="https:"&&!(G.protocol==="http:"&&U(G.hostname)))throw Error(`OAuthConnectionProvider: ${j} must be an https URL (http only for localhost), got ${JSON.stringify(B)}.`)}function U(j){return j==="localhost"||j==="127.0.0.1"||j==="[::1]"||j==="::1"}class E{options;static token="auth.connections";resolvedStore;refreshing=new Map;fakes;fakeStore;fakeRequests=[];constructor(j){this.options=j}get providers(){return this.options.providers}get store(){if(this.fakeStore)return this.fakeStore;if(!this.resolvedStore){let j=this.options.store;this.resolvedStore=typeof j==="function"?j():j??new F(D(T).connection(),()=>R())}return this.resolvedStore}provider(j){let B=this.options.providers[j];if(!B){let G=Object.keys(this.options.providers);throw new Y("unknown_provider",`No OAuth connection provider "${j}" in auth.connections`+(G.length>0?` (configured: ${G.join(", ")}).`:" (none are configured)."))}return B}async for(j,B){this.provider(B);let G=await this.store.find(z(j),B);return G?new N(this,G):null}async list(j){return(await this.store.list(z(j))).filter((G)=>(G.provider in this.options.providers)).map((G)=>new N(this,G))}async save(j,B,G){let K=this.provider(B),J=await this.store.save(z(j),B,{refreshToken:null,tokenType:null,expiresAt:null,providerAccountId:null,scopes:K.config.scopes,...G});return new N(this,J)}fake(j={}){return this.fakes=new Map(Object.entries(j)),this.fakeStore=new X,this.fakeRequests.length=0,this}restore(){this.fakes=void 0,this.fakeStore=void 0,this.fakeRequests.length=0}get faked(){return this.fakes!==void 0}async send(j,B){if(!this.fakes)return fetch(B);this.fakeRequests.push(B.clone());let G=this.fakes.get(j);if(!G)throw Error(`Connections.fake() has no handler for "${j}". Pass one: Connections.fake({ ${j}: (req) => ... }).`);return G(B)}refresh(j){let B=this.refreshing.get(j.id);if(B)return B;let G=this.withLock(j.id,()=>this.refreshOnce(j)).finally(()=>this.refreshing.delete(j.id));return this.refreshing.set(j.id,G),G}async refreshOnce(j){let B=await this.store.find(j.userId,j.provider);if(!B||B.id!==j.id)throw new _(j.provider);if(B.revision!==j.revision&&!B.needsReconnect)return B;if(B.needsReconnect)throw new _(j.provider);let G=this.provider(B.provider);if(this.faked||B.refreshToken===null){if(this.faked)return B;throw await this.store.markNeedsReconnect(B.id),new _(B.provider)}let K;try{K=await G.refresh(B.refreshToken,B.scopes)}catch(V){if(V instanceof Y&&V.status!==void 0&&V.status>=400&&V.status<500)throw await this.store.markNeedsReconnect(B.id),new _(B.provider,{cause:V,status:V.status,providerError:V.providerError});throw V}let J=await this.store.updateTokens(B.id,B.revision,K);if(J)return J;let Q=await this.store.find(B.userId,B.provider);if(!Q)throw new _(B.provider);return Q}async withLock(j,B){let G=D();if(this.faked||!G.bound(L))return B();let K=await G.make(L).run(`gemi:oauth-connection:${j}`,{ttl:30000,wait:20000},()=>B());if(!K.acquired)throw new Y("refresh_failed","Timed out waiting for another refresh of this connection to finish.");return K.value}}class N{manager;record;constructor(j,B){this.manager=j;this.record=B}get provider(){return this.record.provider}get userId(){return this.record.userId}get providerAccountId(){return this.record.providerAccountId}get scopes(){return this.record.scopes}get expiresAt(){return this.record.expiresAt}get needsReconnect(){return this.record.needsReconnect}get connectedAt(){return this.record.createdAt}hasScopes(...j){return j.every((B)=>this.record.scopes.includes(B))}async fetch(j,B={}){let G=this.resolveUrl(j),K=await this.current(),J=await this.send(G,B,K.accessToken);if(J.response.status!==401||!J.authorized||B.body instanceof ReadableStream)return J.response;await J.response.body?.cancel().catch(()=>{});let Q=await this.refreshFrom(K);return(await this.send(G,B,Q.accessToken)).response}async accessToken(){return(await this.current()).accessToken}async refresh(){await this.refreshFrom(this.record)}async revoke(){if(!this.manager.faked){let j=this.manager.provider(this.record.provider);if(this.record.refreshToken!==null)await j.revoke(this.record.refreshToken,"refresh_token");else await j.revoke(this.record.accessToken,"access_token")}await this.manager.store.delete(this.record.id)}async disconnect(){await this.manager.store.delete(this.record.id)}toJSON(){return{provider:this.provider,providerAccountId:this.providerAccountId,scopes:[...this.scopes],expiresAt:this.expiresAt,needsReconnect:this.needsReconnect,connectedAt:this.connectedAt}}[Symbol.for("nodejs.util.inspect.custom")](){return{ProviderConnection:this.toJSON()}}async current(){if(this.record.needsReconnect)throw new _(this.record.provider);let j=this.manager.provider(this.record.provider).config.refreshLeewaySeconds*1000,B=this.record.expiresAt?.getTime();if(B!==void 0&&B-Date.now()<=j)return this.refreshFrom(this.record);return this.record}async refreshFrom(j){try{this.record=await this.manager.refresh(j)}catch(B){if(B instanceof _)this.record={...this.record,needsReconnect:!0};throw B}return this.record}resolveUrl(j){let B=this.manager.provider(this.record.provider).config.apiBaseUrl,G;try{G=new URL(String(j),B)}catch{throw new Y("forbidden_url",`connection.fetch was given ${JSON.stringify(String(j))}, which is not a URL.`)}if(G.origin!==new URL(B).origin)throw new Y("forbidden_url",`connection.fetch only sends the ${this.record.provider} token to ${new URL(B).origin} (apiBaseUrl), not to ${G.origin}.`);if(G.protocol!=="https:"&&!(G.protocol==="http:"&&U(G.hostname)))throw new Y("forbidden_url",`connection.fetch only sends a token over https, not to ${G.origin}.`);return G}async send(j,B,G){let K=j,J=(B.method??"GET").toUpperCase(),Q=B.body,V=!0;if(B.redirect==="manual"||B.redirect==="error")return{response:await this.manager.send(this.record.provider,this.request(K,B,J,Q,G)),authorized:V};for(let Z=0;;Z++){let W=this.request(K,{...B,redirect:"manual"},J,Q,V?G:null),$=await this.manager.send(this.record.provider,W),M=$.headers.get("location");if(!C.has($.status)||M===null||Z>=5)return{response:$,authorized:V};await $.body?.cancel().catch(()=>{});let S=new URL(M,K);if(S.origin!==K.origin)V=!1;if($.status===303||($.status===301||$.status===302)&&J==="POST")J="GET",Q=void 0;K=S}}request(j,B,G,K,J){let Q=new Headers(B.headers);if(J===null)Q.delete("authorization");else Q.set("Authorization",`Bearer ${J}`);return new Request(j,{...B,method:G,body:K,headers:Q})}}var C=new Set([301,302,303,307,308]);function z(j){let B=typeof j==="object"&&j!==null?j.id:j;if(B===void 0||B===null||B==="")throw TypeError("An OAuth connection belongs to a user: pass the user (or its id).");return String(B)}
69
+ export{X as Pg,F as Qg,Y as Rg,_ as Sg,O as Tg,E as Ug,N as Vg};
70
+
71
+ //# debugId=7D5DD820045F8F3E64756E2164756E21
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../auth/connections/ConnectionStore.ts", "../auth/connections/errors.ts", "../auth/connections/OAuthConnectionProvider.ts", "../auth/connections/ConnectionManager.ts"],
4
+ "sourcesContent": [
5
+ "import type { SQL } from \"bun\";\n\nimport type { DatabaseConnection } from \"../../database/Connection\";\nimport type { Dialect } from \"../../database/dialect\";\nimport type { Encrypter } from \"../../services/encryption/Encrypter\";\nimport type { OAuthTokenSet } from \"./OAuthConnectionProvider\";\n\n/** One stored connection, tokens decrypted. Lives only inside the framework. */\nexport interface ConnectionRecord {\n id: string;\n userId: string;\n provider: string;\n providerAccountId: string | null;\n scopes: string[];\n accessToken: string;\n refreshToken: string | null;\n tokenType: string | null;\n expiresAt: Date | null;\n needsReconnect: boolean;\n /** Bumped on every token change: the compare-and-swap that serialises refreshes. */\n revision: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** Where connections are kept. `DatabaseConnectionStore` in an app, `MemoryConnectionStore` in tests. */\nexport interface ConnectionStore {\n find(userId: string, provider: string): Promise<ConnectionRecord | null>;\n list(userId: string): Promise<ConnectionRecord[]>;\n /** Stores a fresh grant, replacing any connection the user had to this provider. */\n save(userId: string, provider: string, tokens: OAuthTokenSet): Promise<ConnectionRecord>;\n /**\n * Replaces the tokens of the connection at `revision`, or resolves `null`\n * when it has moved on (another request refreshed it first) or is gone.\n */\n updateTokens(id: string, revision: number, tokens: OAuthTokenSet): Promise<ConnectionRecord | null>;\n markNeedsReconnect(id: string): Promise<void>;\n delete(id: string): Promise<void>;\n}\n\nexport class MemoryConnectionStore implements ConnectionStore {\n private readonly rows = new Map<string, ConnectionRecord>();\n\n async find(userId: string, provider: string) {\n for (const row of this.rows.values()) {\n if (row.userId === userId && row.provider === provider) return { ...row };\n }\n return null;\n }\n\n async list(userId: string) {\n return [...this.rows.values()].filter((row) => row.userId === userId).map((row) => ({ ...row }));\n }\n\n async save(userId: string, provider: string, tokens: OAuthTokenSet) {\n const existing = await this.find(userId, provider);\n const now = new Date();\n const row: ConnectionRecord = {\n id: existing?.id ?? Bun.randomUUIDv7(),\n userId,\n provider,\n ...fromTokens(tokens),\n needsReconnect: false,\n revision: (existing?.revision ?? 0) + 1,\n createdAt: existing?.createdAt ?? now,\n updatedAt: now,\n };\n this.rows.set(row.id, row);\n return { ...row };\n }\n\n async updateTokens(id: string, revision: number, tokens: OAuthTokenSet) {\n const row = this.rows.get(id);\n if (!row || row.revision !== revision) return null;\n const next = { ...row, ...fromTokens(tokens), needsReconnect: false, revision: revision + 1, updatedAt: new Date() };\n this.rows.set(id, next);\n return { ...next };\n }\n\n async markNeedsReconnect(id: string) {\n const row = this.rows.get(id);\n if (row) this.rows.set(id, { ...row, needsReconnect: true, updatedAt: new Date() });\n }\n\n async delete(id: string) {\n this.rows.delete(id);\n }\n}\n\nexport interface DatabaseConnectionStoreOptions {\n /** Default `gemi_oauth_connections`. A plain identifier: it is spliced into every statement. */\n table?: string;\n}\n\n/**\n * Connections in a table of the app's database, tokens encrypted with the\n * app's `Encrypter` (the keys in `app/config/encryption.ts`). Raw SQL, like\n * the queue's and the locks' tables, for SQLite, Postgres and MySQL 8 /\n * MariaDB: the table is not an ORM model, so no ORM read can return a token.\n */\nexport class DatabaseConnectionStore implements ConnectionStore {\n readonly table: string;\n private readonly sql: SQL;\n private readonly dialect: Dialect;\n\n constructor(\n connection: Pick<DatabaseConnection, \"sql\" | \"dialect\">,\n private readonly encrypter: () => Encrypter,\n options: DatabaseConnectionStoreOptions = {},\n ) {\n const table = options.table ?? \"gemi_oauth_connections\";\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {\n throw new Error(`The connections table name \"${table}\" is not a plain identifier.`);\n }\n this.table = table;\n this.sql = connection.sql;\n this.dialect = connection.dialect;\n }\n\n /** Creates the table if it does not exist: the DDL Prisma makes for the model in the docs. */\n async createTable(): Promise<void> {\n for (const statement of createConnectionTableStatements(this.dialect, this.table)) {\n await this.sql.unsafe(statement);\n }\n }\n\n async find(userId: string, provider: string) {\n const q = this.sql;\n const rows = (await q`\n SELECT * FROM ${this.name(q)} WHERE user_id = ${userId} AND provider = ${provider}\n `) as RawRow[];\n return rows[0] ? this.decode(rows[0]) : null;\n }\n\n async list(userId: string) {\n const q = this.sql;\n const rows = (await q`\n SELECT * FROM ${this.name(q)} WHERE user_id = ${userId} ORDER BY provider\n `) as RawRow[];\n return rows.map((row) => this.decode(row));\n }\n\n async save(userId: string, provider: string, tokens: OAuthTokenSet) {\n const q = this.sql;\n const values = this.encode(tokens);\n const now = Date.now();\n\n const update = async () =>\n affected(\n await q`\n UPDATE ${this.name(q)}\n SET provider_account_id = ${values.providerAccountId}, scopes = ${values.scopes},\n access_token = ${values.accessToken}, refresh_token = ${values.refreshToken},\n token_type = ${values.tokenType}, expires_at = ${values.expiresAt},\n needs_reconnect = 0, revision = revision + 1, updated_at = ${now}\n WHERE user_id = ${userId} AND provider = ${provider}\n `,\n );\n\n if ((await update()) === 0) {\n try {\n await q`\n INSERT INTO ${this.name(q)} (id, user_id, provider, provider_account_id, scopes,\n access_token, refresh_token, token_type, expires_at, needs_reconnect, revision,\n created_at, updated_at)\n VALUES (${Bun.randomUUIDv7()}, ${userId}, ${provider}, ${values.providerAccountId},\n ${values.scopes}, ${values.accessToken}, ${values.refreshToken}, ${values.tokenType},\n ${values.expiresAt}, 0, 1, ${now}, ${now})\n `;\n } catch (error) {\n // A concurrent callback for the same user and provider inserted first.\n if ((await update()) === 0) throw error;\n }\n }\n\n const saved = await this.find(userId, provider);\n if (!saved) throw new Error(\"The OAuth connection vanished while it was being saved.\");\n return saved;\n }\n\n async updateTokens(id: string, revision: number, tokens: OAuthTokenSet) {\n const q = this.sql;\n const values = this.encode(tokens);\n const result = await q`\n UPDATE ${this.name(q)}\n SET provider_account_id = COALESCE(${values.providerAccountId}, provider_account_id),\n scopes = ${values.scopes}, access_token = ${values.accessToken},\n refresh_token = ${values.refreshToken}, token_type = ${values.tokenType},\n expires_at = ${values.expiresAt}, needs_reconnect = 0, revision = revision + 1,\n updated_at = ${Date.now()}\n WHERE id = ${id} AND revision = ${revision}\n `;\n if (affected(result) === 0) return null;\n const rows = (await q`SELECT * FROM ${this.name(q)} WHERE id = ${id}`) as RawRow[];\n return rows[0] ? this.decode(rows[0]) : null;\n }\n\n async markNeedsReconnect(id: string) {\n const q = this.sql;\n await q`UPDATE ${this.name(q)} SET needs_reconnect = 1, updated_at = ${Date.now()} WHERE id = ${id}`;\n }\n\n async delete(id: string) {\n const q = this.sql;\n await q`DELETE FROM ${this.name(q)} WHERE id = ${id}`;\n }\n\n /**\n * Re-encrypts every token still under an older key. Run by\n * `gemi run encryption:rotate`; a token refreshed in the meantime is\n * already current and is skipped by the revision check.\n */\n async rotateEncryption(options: { dryRun?: boolean } = {}): Promise<{ scanned: number; rotated: number }> {\n const q = this.sql;\n const encrypter = this.encrypter();\n const rows = (await q`\n SELECT id, access_token, refresh_token, revision FROM ${this.name(q)} ORDER BY id\n `) as RawRow[];\n let rotated = 0;\n for (const row of rows) {\n const stale = (value: string | null) => typeof value === \"string\" && encrypter.needsReencryption(value);\n if (!stale(row.access_token) && !stale(row.refresh_token)) continue;\n rotated += 1;\n if (options.dryRun) continue;\n const reseal = (value: string | null) => (value === null ? null : encrypter.encrypt(encrypter.decrypt(value)));\n await q`\n UPDATE ${this.name(q)}\n SET access_token = ${reseal(row.access_token)}, refresh_token = ${reseal(row.refresh_token)},\n revision = revision + 1\n WHERE id = ${row.id} AND revision = ${Number(row.revision)}\n `;\n }\n return { scanned: rows.length, rotated };\n }\n\n private encode(tokens: OAuthTokenSet) {\n const encrypter = this.encrypter();\n return {\n providerAccountId: tokens.providerAccountId,\n scopes: tokens.scopes.join(\" \"),\n accessToken: encrypter.encrypt(tokens.accessToken),\n refreshToken: tokens.refreshToken === null ? null : encrypter.encrypt(tokens.refreshToken),\n tokenType: tokens.tokenType,\n expiresAt: tokens.expiresAt === null ? null : tokens.expiresAt.getTime(),\n };\n }\n\n private decode(row: RawRow): ConnectionRecord {\n const encrypter = this.encrypter();\n return {\n id: String(row.id),\n userId: String(row.user_id),\n provider: String(row.provider),\n providerAccountId: row.provider_account_id === null ? null : String(row.provider_account_id),\n scopes: String(row.scopes ?? \"\").split(\" \").filter(Boolean),\n accessToken: encrypter.decrypt(String(row.access_token)),\n refreshToken: row.refresh_token === null ? null : encrypter.decrypt(String(row.refresh_token)),\n tokenType: row.token_type === null ? null : String(row.token_type),\n expiresAt: row.expires_at === null ? null : new Date(Number(row.expires_at)),\n needsReconnect: Number(row.needs_reconnect) === 1,\n revision: Number(row.revision),\n createdAt: new Date(Number(row.created_at)),\n updatedAt: new Date(Number(row.updated_at)),\n };\n }\n\n private get mysql() {\n return this.dialect === \"mysql\" || this.dialect === \"mariadb\";\n }\n\n private name(q: SQL) {\n return q.unsafe(this.mysql ? `\\`${this.table}\\`` : `\"${this.table}\"`);\n }\n}\n\ninterface RawRow {\n id: unknown;\n user_id: unknown;\n provider: unknown;\n provider_account_id: unknown;\n scopes: unknown;\n access_token: string;\n refresh_token: string | null;\n token_type: unknown;\n expires_at: unknown;\n needs_reconnect: unknown;\n revision: unknown;\n created_at: unknown;\n updated_at: unknown;\n}\n\nfunction fromTokens(tokens: OAuthTokenSet) {\n return {\n providerAccountId: tokens.providerAccountId,\n scopes: [...tokens.scopes],\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n tokenType: tokens.tokenType,\n expiresAt: tokens.expiresAt,\n };\n}\n\nfunction affected(result: unknown): number {\n const counts = result as { count?: number | null; affectedRows?: number | null };\n return Math.max(Number(counts.count ?? 0), Number(counts.affectedRows ?? 0));\n}\n\n/** The connections table, as Prisma generates it for the model in the docs, with `IF NOT EXISTS`. */\nexport function createConnectionTableStatements(dialect: Dialect, table: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${table}\\` (\n \\`id\\` VARCHAR(191) NOT NULL,\n \\`user_id\\` VARCHAR(191) NOT NULL,\n \\`provider\\` VARCHAR(191) NOT NULL,\n \\`provider_account_id\\` VARCHAR(191) NULL,\n \\`scopes\\` TEXT NOT NULL,\n \\`access_token\\` TEXT NOT NULL,\n \\`refresh_token\\` TEXT NULL,\n \\`token_type\\` VARCHAR(191) NULL,\n \\`expires_at\\` BIGINT NULL,\n \\`needs_reconnect\\` INTEGER NOT NULL DEFAULT 0,\n \\`revision\\` BIGINT NOT NULL DEFAULT 0,\n \\`created_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n\n UNIQUE INDEX \\`${table}_user_id_provider_key\\`(\\`user_id\\`, \\`provider\\`),\n PRIMARY KEY (\\`id\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n const key = dialect === \"sqlite\" ? `\"id\" TEXT NOT NULL PRIMARY KEY,` : `\"id\" TEXT NOT NULL,`;\n const constraint =\n dialect === \"sqlite\" ? \"\" : `,\\n\\n CONSTRAINT \"${table}_pkey\" PRIMARY KEY (\"id\")`;\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\n ${key}\n \"user_id\" TEXT NOT NULL,\n \"provider\" TEXT NOT NULL,\n \"provider_account_id\" TEXT,\n \"scopes\" TEXT NOT NULL,\n \"access_token\" TEXT NOT NULL,\n \"refresh_token\" TEXT,\n \"token_type\" TEXT,\n \"expires_at\" BIGINT,\n \"needs_reconnect\" INTEGER NOT NULL DEFAULT 0,\n \"revision\" BIGINT NOT NULL DEFAULT 0,\n \"created_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL${constraint}\n)`,\n `CREATE UNIQUE INDEX IF NOT EXISTS \"${table}_user_id_provider_key\" ON \"${table}\"(\"user_id\", \"provider\")`,\n ];\n}\n",
6
+ "/**\n * Why an OAuth connection operation failed. Never carries a token or a token\n * endpoint's body; `providerError` is the provider's RFC 6749 error code at\n * most (`invalid_grant`).\n */\nexport type OAuthConnectionErrorCode =\n | \"unknown_provider\"\n | \"exchange_failed\"\n | \"refresh_failed\"\n | \"reconnect_required\"\n | \"revoke_failed\"\n | \"revoke_unsupported\"\n | \"forbidden_url\";\n\nexport class OAuthConnectionError extends Error {\n readonly status?: number;\n readonly providerError?: string;\n\n constructor(\n readonly code: OAuthConnectionErrorCode,\n message: string,\n options: { cause?: unknown; status?: number; providerError?: string } = {},\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = \"OAuthConnectionError\";\n this.status = options.status;\n this.providerError = options.providerError;\n }\n}\n\n/**\n * The connection's tokens no longer work and refreshing them failed, so the\n * user has to connect the account again (send them to\n * `/auth/connections/<provider>`). The connection is marked, so every later\n * call fails the same way without asking the provider again, until it is\n * reconnected.\n */\nexport class OAuthReconnectRequiredError extends OAuthConnectionError {\n constructor(\n readonly provider: string,\n options: { cause?: unknown; status?: number; providerError?: string } = {},\n ) {\n super(\n \"reconnect_required\",\n `The ${provider} connection needs to be reconnected: its tokens were refused and could not be refreshed.`,\n options,\n );\n this.name = \"OAuthReconnectRequiredError\";\n }\n}\n",
7
+ "import { OAuthConnectionError } from \"./errors\";\n\nexport interface OAuthConnectionProviderConfig {\n /** The provider's authorization endpoint: `https://www.figma.com/oauth`. */\n authorizeUrl: string;\n /** The token endpoint, for the code exchange and refreshes. */\n tokenUrl: string;\n /**\n * The RFC 7009 revocation endpoint. Without one, `revoke()` is refused and\n * `disconnect()` (which forgets the tokens locally) is the way to remove a\n * connection.\n */\n revokeUrl?: string;\n clientId: string;\n clientSecret: string;\n /** The scopes to request. */\n scopes: string[];\n /** How `scopes` are joined on the authorization URL. Default `\" \"` (RFC 6749). */\n scopeSeparator?: string;\n /**\n * How the client authenticates to the token and revocation endpoints:\n * `\"body\"` sends `client_id` and `client_secret` as form fields (what most\n * providers document), `\"basic\"` sends them as HTTP Basic credentials.\n * Default `\"body\"`.\n */\n clientAuth?: \"body\" | \"basic\";\n /** Send a PKCE challenge (S256). Default `true`; turn off only for a provider that rejects it. */\n pkce?: boolean;\n /**\n * Extra query parameters for the authorization URL, such as\n * `{ access_type: \"offline\", prompt: \"consent\" }` for Google. They cannot\n * replace `state`, the PKCE challenge, `redirect_uri`, `client_id` or `scope`.\n */\n authorizationParams?: Record<string, string>;\n /**\n * The callback URL registered with the provider. Default\n * `${HOST_NAME}/auth/connections/<name>/callback` (the request's origin when\n * `HOST_NAME` is unset).\n */\n redirectUri?: string;\n /**\n * Where the provider's API lives: `https://api.figma.com`. Required:\n * `connection.fetch` takes paths relative to it and **refuses any other\n * origin**, so the user's token only ever goes to the provider's API host,\n * even for a URL that came from user input.\n */\n apiBaseUrl: string;\n /** Refresh this many seconds before the access token expires. Default 60. */\n refreshLeewaySeconds?: number;\n}\n\n/** What a token endpoint answered, normalised. */\nexport interface OAuthTokenSet {\n accessToken: string;\n refreshToken: string | null;\n tokenType: string | null;\n /** Absent when the provider did not say (`expires_in` missing). */\n expiresAt: Date | null;\n /** The scopes granted, when the provider says; otherwise the ones requested. */\n scopes: string[];\n /** The provider's id for the account, when the token response carries one (Figma's `user_id`). */\n providerAccountId: string | null;\n}\n\n/**\n * A provider an app can connect a user's account to, to call its API on the\n * user's behalf — as opposed to `OAuthProvider`, which signs the user in.\n * Configured under `auth.connections`:\n *\n * ```ts\n * connections: {\n * figma: new OAuthConnectionProvider({\n * authorizeUrl: \"https://www.figma.com/oauth\",\n * tokenUrl: \"https://api.figma.com/v1/oauth/token\",\n * clientId: process.env.FIGMA_CLIENT_ID!,\n * clientSecret: process.env.FIGMA_CLIENT_SECRET!,\n * scopes: [\"file_content:read\"],\n * apiBaseUrl: \"https://api.figma.com\",\n * }),\n * }\n * ```\n */\nexport class OAuthConnectionProvider {\n readonly config: Required<\n Omit<OAuthConnectionProviderConfig, \"revokeUrl\" | \"redirectUri\">\n > &\n Pick<OAuthConnectionProviderConfig, \"revokeUrl\" | \"redirectUri\">;\n\n constructor(config: OAuthConnectionProviderConfig) {\n for (const key of [\"authorizeUrl\", \"tokenUrl\"] as const) {\n assertHttpUrl(key, config[key]);\n }\n if (config.revokeUrl !== undefined) assertHttpUrl(\"revokeUrl\", config.revokeUrl);\n // Required (not just recommended): it is what keeps `connection.fetch`\n // from sending the user's token anywhere but the provider's API host. A\n // missing one (`process.env.X` unset, or plain JS) fails the boot, when\n // the auth config is loaded, rather than the first `fetch`.\n if (config.apiBaseUrl === undefined || config.apiBaseUrl === null || config.apiBaseUrl === \"\") {\n throw new Error(\n \"OAuthConnectionProvider: apiBaseUrl is required. Set it to the provider's API origin \" +\n '(e.g. apiBaseUrl: \"https://api.figma.com\"); connection.fetch only sends the token there.',\n );\n }\n assertHttpUrl(\"apiBaseUrl\", config.apiBaseUrl);\n this.config = {\n scopeSeparator: \" \",\n clientAuth: \"body\",\n pkce: true,\n authorizationParams: {},\n refreshLeewaySeconds: 60,\n ...config,\n };\n }\n\n /** The URL to send the browser to. */\n authorizationUrl(args: { state: string; codeChallenge: string; redirectUri: string }): string {\n const url = new URL(this.config.authorizeUrl);\n const params: Record<string, string> = {\n ...this.config.authorizationParams,\n response_type: \"code\",\n client_id: this.config.clientId,\n redirect_uri: args.redirectUri,\n scope: this.config.scopes.join(this.config.scopeSeparator),\n state: args.state,\n };\n if (this.config.pkce) {\n params.code_challenge = args.codeChallenge;\n params.code_challenge_method = \"S256\";\n }\n for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);\n return url.toString();\n }\n\n /** Exchanges an authorization code for tokens. */\n exchangeCode(args: { code: string; codeVerifier: string; redirectUri: string }): Promise<OAuthTokenSet> {\n const body = new URLSearchParams({\n grant_type: \"authorization_code\",\n code: args.code,\n redirect_uri: args.redirectUri,\n });\n if (this.config.pkce) body.set(\"code_verifier\", args.codeVerifier);\n return this.tokenRequest(body, { scopes: this.config.scopes, refreshToken: null, phase: \"exchange\" });\n }\n\n /**\n * Spends `refreshToken` for a new access token. A provider that does not\n * rotate refresh tokens answers without one, and the old one is kept.\n */\n refresh(refreshToken: string, scopes: string[]): Promise<OAuthTokenSet> {\n const body = new URLSearchParams({ grant_type: \"refresh_token\", refresh_token: refreshToken });\n return this.tokenRequest(body, { scopes, refreshToken, phase: \"refresh\" });\n }\n\n /** Revokes `token` at the provider (RFC 7009). */\n async revoke(token: string, hint: \"refresh_token\" | \"access_token\"): Promise<void> {\n if (!this.config.revokeUrl) {\n throw new OAuthConnectionError(\n \"revoke_unsupported\",\n \"This provider has no revokeUrl configured. Use disconnect() to forget the tokens locally.\",\n );\n }\n const body = new URLSearchParams({ token, token_type_hint: hint });\n let response: Response;\n try {\n response = await fetch(this.config.revokeUrl, this.post(body));\n } catch (cause) {\n throw new OAuthConnectionError(\"revoke_failed\", \"The revocation request failed.\", { cause });\n }\n // RFC 7009: 200 whether or not the token was still valid.\n if (!response.ok) {\n throw new OAuthConnectionError(\n \"revoke_failed\",\n `The provider refused the revocation (HTTP ${response.status}).`,\n { status: response.status },\n );\n }\n }\n\n private post(body: URLSearchParams): RequestInit {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n // GitHub answers form-encoded unless asked for JSON.\n Accept: \"application/json\",\n };\n if (this.config.clientAuth === \"basic\") {\n const credentials = `${encodeURIComponent(this.config.clientId)}:${encodeURIComponent(this.config.clientSecret)}`;\n headers.Authorization = `Basic ${Buffer.from(credentials).toString(\"base64\")}`;\n } else {\n body.set(\"client_id\", this.config.clientId);\n body.set(\"client_secret\", this.config.clientSecret);\n }\n return { method: \"POST\", headers, body: body.toString(), redirect: \"error\" };\n }\n\n private async tokenRequest(\n body: URLSearchParams,\n previous: { scopes: string[]; refreshToken: string | null; phase: \"exchange\" | \"refresh\" },\n ): Promise<OAuthTokenSet> {\n const failure = previous.phase === \"exchange\" ? \"exchange_failed\" : \"refresh_failed\";\n let response: Response;\n try {\n response = await fetch(this.config.tokenUrl, this.post(body));\n } catch (cause) {\n throw new OAuthConnectionError(failure, \"The token request failed.\", { cause });\n }\n\n const payload = (await response.json().catch(() => ({}))) as Record<string, unknown>;\n if (!response.ok || typeof payload.access_token !== \"string\" || payload.access_token === \"\") {\n // Only the provider's error code, never the body: it can echo the grant.\n const code = typeof payload.error === \"string\" && /^[a-z0-9_]{1,64}$/.test(payload.error) ? payload.error : undefined;\n throw new OAuthConnectionError(\n failure,\n `The token endpoint refused the ${previous.phase === \"exchange\" ? \"code\" : \"refresh token\"} ` +\n `(HTTP ${response.status}${code ? `, ${code}` : \"\"}).`,\n { status: response.status, providerError: code },\n );\n }\n\n const expiresIn = Number(payload.expires_in);\n const scope = typeof payload.scope === \"string\" ? payload.scope : undefined;\n const accountId = payload.user_id ?? payload.account_id;\n return {\n accessToken: payload.access_token,\n refreshToken:\n typeof payload.refresh_token === \"string\" && payload.refresh_token !== \"\"\n ? payload.refresh_token\n : previous.refreshToken,\n tokenType: typeof payload.token_type === \"string\" ? payload.token_type : null,\n expiresAt: Number.isFinite(expiresIn) && expiresIn > 0 ? new Date(Date.now() + expiresIn * 1000) : null,\n scopes: scope !== undefined ? scope.split(/[\\s,]+/).filter(Boolean) : previous.scopes,\n providerAccountId:\n typeof accountId === \"string\" || typeof accountId === \"number\" ? String(accountId) : null,\n };\n }\n}\n\nfunction assertHttpUrl(key: string, value: unknown): void {\n let url: URL | undefined;\n try {\n url = new URL(String(value));\n } catch {\n url = undefined;\n }\n if (!url || (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && isLoopback(url.hostname)))) {\n throw new Error(\n `OAuthConnectionProvider: ${key} must be an https URL (http only for localhost), got ${JSON.stringify(value)}.`,\n );\n }\n}\n\nexport function isLoopback(hostname: string): boolean {\n return hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\" || hostname === \"::1\";\n}\n",
8
+ "import { DatabaseManager } from \"../../database/DatabaseManager\";\nimport { app } from \"../../foundation/app\";\nimport { currentEncrypter } from \"../../orm/encryption\";\nimport { LockManager } from \"../../services/lock/LockManager\";\nimport {\n type ConnectionRecord,\n type ConnectionStore,\n DatabaseConnectionStore,\n MemoryConnectionStore,\n} from \"./ConnectionStore\";\nimport { OAuthConnectionError, OAuthReconnectRequiredError } from \"./errors\";\nimport { type OAuthConnectionProvider, type OAuthTokenSet, isLoopback } from \"./OAuthConnectionProvider\";\n\n/** A user, as far as a connection is concerned: anything with an `id`. */\nexport type ConnectionOwner = { id: string | number } | string | number;\n\n/** What `Connections.fake` answers an API request with. */\nexport type FakeConnectionHandler = (request: Request) => Response | Promise<Response>;\n\nexport interface ConnectionManagerOptions {\n providers: Record<string, OAuthConnectionProvider>;\n /** Default: a `DatabaseConnectionStore` on the default database connection. */\n store?: ConnectionStore | (() => ConnectionStore);\n}\n\n/**\n * The OAuth connections a user has made, and the one place their tokens are\n * read, refreshed and spent. Reached through the `Connections` facade.\n */\nexport class ConnectionManager {\n static token = \"auth.connections\";\n\n private resolvedStore: ConnectionStore | undefined;\n private readonly refreshing = new Map<string, Promise<ConnectionRecord>>();\n private fakes: Map<string, FakeConnectionHandler> | undefined;\n private fakeStore: MemoryConnectionStore | undefined;\n readonly fakeRequests: Request[] = [];\n\n constructor(private readonly options: ConnectionManagerOptions) {}\n\n get providers(): Record<string, OAuthConnectionProvider> {\n return this.options.providers;\n }\n\n /** The store connections are kept in. */\n get store(): ConnectionStore {\n if (this.fakeStore) return this.fakeStore;\n if (!this.resolvedStore) {\n const configured = this.options.store;\n this.resolvedStore =\n typeof configured === \"function\"\n ? configured()\n : (configured ??\n new DatabaseConnectionStore(app(DatabaseManager).connection(), () => currentEncrypter()));\n }\n return this.resolvedStore;\n }\n\n provider(name: string): OAuthConnectionProvider {\n const provider = this.options.providers[name];\n if (!provider) {\n const known = Object.keys(this.options.providers);\n throw new OAuthConnectionError(\n \"unknown_provider\",\n `No OAuth connection provider \"${name}\" in auth.connections` +\n (known.length > 0 ? ` (configured: ${known.join(\", \")}).` : \" (none are configured).\"),\n );\n }\n return provider;\n }\n\n /** The user's connection to `provider`, or `null` when they have not connected it. */\n async for(user: ConnectionOwner, provider: string): Promise<ProviderConnection | null> {\n this.provider(provider);\n const record = await this.store.find(ownerId(user), provider);\n return record ? new ProviderConnection(this, record) : null;\n }\n\n /** Every connection the user has. */\n async list(user: ConnectionOwner): Promise<ProviderConnection[]> {\n const records = await this.store.list(ownerId(user));\n return records\n .filter((record) => record.provider in this.options.providers)\n .map((record) => new ProviderConnection(this, record));\n }\n\n /**\n * Stores tokens for the user, replacing any earlier connection to the same\n * provider. The connect callback calls this; call it yourself for tokens\n * obtained some other way.\n */\n async save(\n user: ConnectionOwner,\n provider: string,\n tokens: Partial<OAuthTokenSet> & { accessToken: string },\n ): Promise<ProviderConnection> {\n const config = this.provider(provider);\n const record = await this.store.save(ownerId(user), provider, {\n refreshToken: null,\n tokenType: null,\n expiresAt: null,\n providerAccountId: null,\n scopes: config.config.scopes,\n ...tokens,\n });\n return new ProviderConnection(this, record);\n }\n\n // --- testing ---------------------------------------------------------------\n\n /**\n * Fakes every provider's API: connections live in memory, `fetch` answers\n * through `handlers[provider]` (recorded in `fakeRequests`), and nothing\n * reaches a token or revocation endpoint. Returns `this` so a test can\n * `save` a connection to start from.\n */\n fake(handlers: Record<string, FakeConnectionHandler> = {}): this {\n this.fakes = new Map(Object.entries(handlers));\n this.fakeStore = new MemoryConnectionStore();\n this.fakeRequests.length = 0;\n return this;\n }\n\n /** Undoes `fake`. */\n restore(): void {\n this.fakes = undefined;\n this.fakeStore = undefined;\n this.fakeRequests.length = 0;\n }\n\n get faked(): boolean {\n return this.fakes !== undefined;\n }\n\n // --- internals, for ProviderConnection ---------------------------------------\n\n /** @internal */\n async send(provider: string, request: Request): Promise<Response> {\n if (!this.fakes) return fetch(request);\n this.fakeRequests.push(request.clone());\n const handler = this.fakes.get(provider);\n if (!handler) {\n throw new Error(`Connections.fake() has no handler for \"${provider}\". Pass one: Connections.fake({ ${provider}: (req) => ... }).`);\n }\n return handler(request);\n }\n\n /**\n * A record whose access token is not the one at `staleRevision`: refreshed\n * by this call, or by whoever refreshed it first. Serialised per connection\n * in this process (concurrent callers share one refresh) and, through the\n * app's lock store, across processes — a rotating refresh token must be\n * spent exactly once.\n *\n * @internal\n */\n refresh(record: ConnectionRecord): Promise<ConnectionRecord> {\n const inFlight = this.refreshing.get(record.id);\n if (inFlight) return inFlight;\n const task = this.withLock(record.id, () => this.refreshOnce(record)).finally(() =>\n this.refreshing.delete(record.id),\n );\n this.refreshing.set(record.id, task);\n return task;\n }\n\n private async refreshOnce(seen: ConnectionRecord): Promise<ConnectionRecord> {\n // Re-read under the lock: another process may have refreshed already.\n const current = await this.store.find(seen.userId, seen.provider);\n if (!current || current.id !== seen.id) {\n throw new OAuthReconnectRequiredError(seen.provider);\n }\n if (current.revision !== seen.revision && !current.needsReconnect) return current;\n if (current.needsReconnect) throw new OAuthReconnectRequiredError(seen.provider);\n\n const provider = this.provider(current.provider);\n if (this.faked || current.refreshToken === null) {\n if (this.faked) return current;\n await this.store.markNeedsReconnect(current.id);\n throw new OAuthReconnectRequiredError(current.provider);\n }\n\n let tokens: OAuthTokenSet;\n try {\n tokens = await provider.refresh(current.refreshToken, current.scopes);\n } catch (error) {\n // A refusal from the token endpoint is final: the grant is gone. A\n // network error or a 5xx is not, and leaves the connection alone.\n if (error instanceof OAuthConnectionError && error.status !== undefined && error.status >= 400 && error.status < 500) {\n await this.store.markNeedsReconnect(current.id);\n throw new OAuthReconnectRequiredError(current.provider, {\n cause: error,\n status: error.status,\n providerError: error.providerError,\n });\n }\n throw error;\n }\n\n const updated = await this.store.updateTokens(current.id, current.revision, tokens);\n if (updated) return updated;\n // Someone else wrote first (only possible without a shared lock store).\n const winner = await this.store.find(current.userId, current.provider);\n if (!winner) throw new OAuthReconnectRequiredError(current.provider);\n return winner;\n }\n\n private async withLock<T>(id: string, fn: () => Promise<T>): Promise<T> {\n const application = app();\n if (this.faked || !application.bound(LockManager)) return fn();\n const result = await application\n .make(LockManager)\n .run(`gemi:oauth-connection:${id}`, { ttl: 30_000, wait: 20_000 }, () => fn());\n if (!result.acquired) {\n throw new OAuthConnectionError(\n \"refresh_failed\",\n \"Timed out waiting for another refresh of this connection to finish.\",\n );\n }\n return result.value as T;\n }\n}\n\n/**\n * One user's connection to one provider. Never exposes a token as a property,\n * and serialises (`toJSON`, `console.log`) without them.\n */\nexport class ProviderConnection {\n constructor(\n private readonly manager: ConnectionManager,\n private record: ConnectionRecord,\n ) {}\n\n get provider(): string {\n return this.record.provider;\n }\n get userId(): string {\n return this.record.userId;\n }\n get providerAccountId(): string | null {\n return this.record.providerAccountId;\n }\n /** The scopes the provider granted. */\n get scopes(): readonly string[] {\n return this.record.scopes;\n }\n get expiresAt(): Date | null {\n return this.record.expiresAt;\n }\n /** A refresh was refused: the user has to connect again. */\n get needsReconnect(): boolean {\n return this.record.needsReconnect;\n }\n get connectedAt(): Date {\n return this.record.createdAt;\n }\n\n /** Whether every one of `scopes` was granted. */\n hasScopes(...scopes: string[]): boolean {\n return scopes.every((scope) => this.record.scopes.includes(scope));\n }\n\n /**\n * `fetch`, as the user: adds `Authorization: Bearer <token>`, refreshes the\n * token first when it is about to expire, and after a 401 refreshes and\n * retries once. A refresh the provider refuses marks the connection and\n * throws `OAuthReconnectRequiredError`.\n *\n * A path is resolved against the provider's `apiBaseUrl`, and a URL on any\n * other origin is refused (`OAuthConnectionError`,\n * `forbidden_url`), so the token only ever goes to the provider. Redirects\n * are followed by hand: the token is dropped on one that leaves the origin.\n * A streamed request body cannot be sent twice, so a 401 for one is\n * returned rather than retried.\n */\n async fetch(input: string | URL, init: RequestInit = {}): Promise<Response> {\n const url = this.resolveUrl(input);\n const record = await this.current();\n const first = await this.send(url, init, record.accessToken);\n // Retry only a 401 for the token itself, not one from where a redirect\n // led after the token was dropped.\n if (first.response.status !== 401 || !first.authorized || init.body instanceof ReadableStream) {\n return first.response;\n }\n\n await first.response.body?.cancel().catch(() => {});\n const refreshed = await this.refreshFrom(record);\n return (await this.send(url, init, refreshed.accessToken)).response;\n }\n\n /**\n * A valid access token, refreshed first if it is about to expire — for an\n * SDK that wants the token itself. Prefer `fetch`, which also retries a 401.\n */\n async accessToken(): Promise<string> {\n return (await this.current()).accessToken;\n }\n\n /** Refreshes now, whatever the expiry says. */\n async refresh(): Promise<void> {\n await this.refreshFrom(this.record);\n }\n\n /**\n * Revokes the grant at the provider (the refresh token when there is one,\n * which ends the whole grant, else the access token) and deletes the\n * connection. If the provider refuses, nothing is deleted and\n * `OAuthConnectionError` (`revoke_failed`) is thrown — call `disconnect()`\n * to forget the tokens anyway. A provider without a `revokeUrl` throws\n * `revoke_unsupported`; use `disconnect()`.\n */\n async revoke(): Promise<void> {\n if (!this.manager.faked) {\n const provider = this.manager.provider(this.record.provider);\n if (this.record.refreshToken !== null) {\n await provider.revoke(this.record.refreshToken, \"refresh_token\");\n } else {\n await provider.revoke(this.record.accessToken, \"access_token\");\n }\n }\n await this.manager.store.delete(this.record.id);\n }\n\n /** Forgets the tokens locally without telling the provider. */\n async disconnect(): Promise<void> {\n await this.manager.store.delete(this.record.id);\n }\n\n toJSON() {\n return {\n provider: this.provider,\n providerAccountId: this.providerAccountId,\n scopes: [...this.scopes],\n expiresAt: this.expiresAt,\n needsReconnect: this.needsReconnect,\n connectedAt: this.connectedAt,\n };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return { ProviderConnection: this.toJSON() };\n }\n\n private async current(): Promise<ConnectionRecord> {\n if (this.record.needsReconnect) throw new OAuthReconnectRequiredError(this.record.provider);\n const leeway = this.manager.provider(this.record.provider).config.refreshLeewaySeconds * 1000;\n const expiresAt = this.record.expiresAt?.getTime();\n if (expiresAt !== undefined && expiresAt - Date.now() <= leeway) {\n return this.refreshFrom(this.record);\n }\n return this.record;\n }\n\n private async refreshFrom(record: ConnectionRecord): Promise<ConnectionRecord> {\n try {\n this.record = await this.manager.refresh(record);\n } catch (error) {\n if (error instanceof OAuthReconnectRequiredError) {\n this.record = { ...this.record, needsReconnect: true };\n }\n throw error;\n }\n return this.record;\n }\n\n private resolveUrl(input: string | URL): URL {\n const base = this.manager.provider(this.record.provider).config.apiBaseUrl;\n let url: URL;\n try {\n url = new URL(String(input), base);\n } catch {\n throw new OAuthConnectionError(\n \"forbidden_url\",\n `connection.fetch was given ${JSON.stringify(String(input))}, which is not a URL.`,\n );\n }\n if (url.origin !== new URL(base).origin) {\n throw new OAuthConnectionError(\n \"forbidden_url\",\n `connection.fetch only sends the ${this.record.provider} token to ${new URL(base).origin} ` +\n `(apiBaseUrl), not to ${url.origin}.`,\n );\n }\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && isLoopback(url.hostname))) {\n throw new OAuthConnectionError(\n \"forbidden_url\",\n `connection.fetch only sends a token over https, not to ${url.origin}.`,\n );\n }\n return url;\n }\n\n private async send(url: URL, init: RequestInit, token: string): Promise<{ response: Response; authorized: boolean }> {\n let target = url;\n let method = (init.method ?? \"GET\").toUpperCase();\n let body = init.body;\n let authorized = true;\n\n // Followed by hand (unless the caller asked for \"manual\" or \"error\"), so\n // the token never follows a redirect to another origin.\n if (init.redirect === \"manual\" || init.redirect === \"error\") {\n const response = await this.manager.send(this.record.provider, this.request(target, init, method, body, token));\n return { response, authorized };\n }\n\n for (let hop = 0; ; hop++) {\n const request = this.request(target, { ...init, redirect: \"manual\" }, method, body, authorized ? token : null);\n const response = await this.manager.send(this.record.provider, request);\n const location = response.headers.get(\"location\");\n if (!REDIRECTS.has(response.status) || location === null || hop >= 5) return { response, authorized };\n\n await response.body?.cancel().catch(() => {});\n const next = new URL(location, target);\n if (next.origin !== target.origin) authorized = false;\n if (response.status === 303 || ((response.status === 301 || response.status === 302) && method === \"POST\")) {\n method = \"GET\";\n body = undefined;\n }\n target = next;\n }\n }\n\n private request(url: URL, init: RequestInit, method: string, body: RequestInit[\"body\"], token: string | null): Request {\n const headers = new Headers(init.headers);\n if (token === null) headers.delete(\"authorization\");\n else headers.set(\"Authorization\", `Bearer ${token}`);\n return new Request(url, { ...init, method, body, headers });\n }\n}\n\nconst REDIRECTS = new Set([301, 302, 303, 307, 308]);\n\nfunction ownerId(user: ConnectionOwner): string {\n const id = typeof user === \"object\" && user !== null ? user.id : user;\n if (id === undefined || id === null || id === \"\") {\n throw new TypeError(\"An OAuth connection belongs to a user: pass the user (or its id).\");\n }\n return String(id);\n}\n"
9
+ ],
10
+ "mappings": ";sLAwCO,AAAM,LAAiD,LAC3C,KAAO,IAAI,SAEtB,KAAI,CAAC,EAAgB,EAAkB,CAC3C,QAAW,KAAO,KAAK,KAAK,OAAO,EACjC,GAAI,EAAI,SAAW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,IAAM,EAAY,IAAI,IAAI,CAAC,IAAK,IAAK,IAAK,IAAK,GAAG,CAAC,EAEnD,SAAS,CAAO,CAAC,EAA+B,CAC9C,IAAM,EAAK,OAAO,IAAS,UAAY,IAAS,KAAO,EAAK,GAAK,EACjE,GAAI,IAAO,QAAa,IAAO,MAAQ,IAAO,GAC5C,MAAU,UAAU,mEAAmE,EAEzF,OAAO,OAAO,CAAE",
11
+ "debugId": "7D5DD820045F8F3E64756E2164756E21",
12
+ "names": []
13
+ }
@@ -29,6 +29,6 @@ export { h } from ${JSON.stringify("virtual:gemi-island-runtime")};
29
29
  import { hydrateRoot } from "react-dom/client";
30
30
  export ${k}
31
31
  `;
32
- export{q as Aa,w as Ba,x as Ca,y as Da,z as Ea};
32
+ export{q as Ba,w as Ca,x as Da,y as Ea,z as Fa};
33
33
 
34
- //# debugId=1E8F29F86166A83964756E2164756E21
34
+ //# debugId=0683BB0431957F3764756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "/**\n * The browser side of islands, shared by the Vite plugin (which builds it), the\n * servers (which point the loader at it) and the tests.\n *\n * No imports: the Vite plugin is built on its own and the servers load it at\n * boot, so this file stays plain strings.\n */\n\n/**\n * The module that hydrates islands: React, `react-dom/client` and the small\n * `h(marker, Component)` below. A virtual module of gemi's Vite plugin that\n * every island entry imports, so the islands on a page share one copy of\n * React, in one chunk.\n */\nexport const ISLAND_RUNTIME_ID = \"virtual:gemi-island-runtime\";\n\n/** What `resolveId` turns `ISLAND_RUNTIME_ID` into (Vite's virtual-module convention). */\nexport const RESOLVED_ISLAND_RUNTIME_ID = `\\0${ISLAND_RUNTIME_ID}`;\n\n/**\n * The query that turns a module into its island entry: `Counter.tsx?gemi-island`\n * is a module of the plugin's that re-exports `Counter.tsx` as `m` next to the\n * runtime's `h`. It is what a static page imports for an island, and so it\n * is what the client manifest lists, keyed `app/…/Counter.tsx?gemi-island`,\n * with React and `react-dom/client` among its imports.\n */\nexport const ISLAND_ENTRY_QUERY = \"?gemi-island\";\n\n/** The island entry module for `file` (an absolute path or a root-relative URL). */\nexport function islandEntrySource(file: string) {\n return `import * as m from ${JSON.stringify(file)};\nexport { m };\nexport { h } from ${JSON.stringify(ISLAND_RUNTIME_ID)};\n`;\n}\n\n/**\n * `h(marker, Component)`: hydrates one `<gemi-island>` marker with the island's\n * component and the props the server serialised into `data-props`.\n *\n * The island's static children were rendered on the server into a\n * `<gemi-slot>` (the first one that belongs to this marker, not to an island\n * nested in it). They are handed back to the component as that same element\n * with the server's HTML, so hydration matches and React leaves them alone.\n *\n * `data-uid` is the `identifierPrefix` the server rendered the island with, so\n * `useId` agrees on both sides and two islands never share an id.\n *\n * Written as a function body with `createElement` and `hydrateRoot` free, so a\n * test can run it against real React without a bundler.\n */\nexport const ISLAND_HYDRATE_SOURCE = `function h(marker, Component) {\n if (typeof Component !== \"function\" && (typeof Component !== \"object\" || Component === null)) {\n throw new Error(\"gemi: island module has no component export for \" + marker.outerHTML.slice(0, 80));\n }\n const json = marker.getAttribute(\"data-props\");\n const props = json ? JSON.parse(json) : {};\n let slot = null;\n for (const candidate of marker.querySelectorAll(\"gemi-slot\")) {\n if (candidate.closest(\"gemi-island\") === marker) {\n slot = candidate;\n break;\n }\n }\n const children = slot\n ? [createElement(\"gemi-slot\", {\n style: { display: \"contents\" },\n suppressHydrationWarning: true,\n dangerouslySetInnerHTML: { __html: slot.innerHTML },\n })]\n : [];\n return hydrateRoot(marker, createElement(Component, props, ...children), {\n identifierPrefix: marker.getAttribute(\"data-uid\") || undefined,\n });\n}`;\n\n/** The runtime module's source, as the plugin serves and builds it. */\nexport const ISLAND_RUNTIME_SOURCE = `import { createElement } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nexport ${ISLAND_HYDRATE_SOURCE}\n`;\n"
6
6
  ],
7
7
  "mappings": ";AAcO,IAAM,EAAoB,8BAGpB,EAA6B,kCAS7B,EAAqB,eAG3B,SAAS,CAAiB,CAAC,EAAc,CAC9C,MAAO,sBAAsB,KAAK,UAAU,CAAI;AAAA;AAAA,oBAE9B,KAAK,UAlBQ,6BAkBmB;AAAA,EAmB7C,IAAM,EAAwB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GA0BxB,EAAwB;AAAA;AAAA,SAE5B;",
8
- "debugId": "1E8F29F86166A83964756E2164756E21",
8
+ "debugId": "0683BB0431957F3764756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{Ch as W,sh as X,zh as K}from"./chunk-kejwjerj.js";import{AsyncLocalStorage as S}from"async_hooks";var z=new S;function g(){return z.getStore()?.tx}function U(){return z.getStore()?.connection??K}function O(j,q){let v=z.getStore();if(U()===j)return q();return y(j),z.run({...v,depth:v?.depth??0,connection:j===K?void 0:j},q)}function y(j){let q=z.getStore();if(q?.tx===void 0)return;let v=q.connection??K;if(v===j)return;throw new W(v,j)}function L(j){let q=z.getStore();if(q?.tx===void 0||q.afterCommit===void 0)return!1;return q.afterCommit.push(j),!0}function h(j){if(L(j))return Promise.resolve();let q=(v)=>{console.error("An after-commit callback threw. No transaction was open, so it ran immediately.",v)};try{return Promise.resolve(j()).catch(q)}catch(v){return q(v),Promise.resolve()}}function k(j){let q=z.getStore();if(q?.tx===void 0||q.commitDependsOn===void 0)return!1;return q.commitDependsOn.push(j),!0}class F extends Error{constructor(j){super(`A statement this transaction depended on failed after being issued on it, so the transaction rolled back instead of committing: ${j instanceof Error?j.message:String(j)}`,{cause:j});this.name="TransactionDependencyError"}}async function R(j,q){if(j.length===q)return;let B=(await Promise.allSettled(j.slice(q))).find((G)=>G.status==="rejected");if(B)throw new F(B.reason)}function N(){let j=z.getStore();return j?.tx===void 0?null:j.depth}function T(){return z.getStore()?.system===!0}function x(j){let q=z.getStore();return z.run({...q,depth:q?.depth??0,system:!0},j)}function p(j){return z.getStore()?.trashed?.get(j)}function f(j,q,v){let B=z.getStore(),G=new Map(B?.trashed);return G.set(j,q),z.run({...B,depth:B?.depth??0,trashed:G},v)}function C(){return z.getStore()?.actor}function l(j,q){let v=z.getStore();return z.run({...v,depth:v?.depth??0,system:!1,actor:{user:j??null}},q)}function _(j){if(Bun.env.NODE_ENV!=="development")return null;if(j===!1)return null;if(j===void 0)return X;if(!Number.isFinite(j)||j<=0)return X;return j}function A(j){let q=_(j);if(q===null)return()=>{};let v=Error("transaction opened here"),B=setTimeout(()=>{let G=v.stack?.split(`
2
+ import{fi as X,mi as K,pi as W}from"./chunk-hr1r3g0d.js";import{AsyncLocalStorage as S}from"async_hooks";var z=new S;function g(){return z.getStore()?.tx}function U(){return z.getStore()?.connection??K}function O(j,q){let v=z.getStore();if(U()===j)return q();return y(j),z.run({...v,depth:v?.depth??0,connection:j===K?void 0:j},q)}function y(j){let q=z.getStore();if(q?.tx===void 0)return;let v=q.connection??K;if(v===j)return;throw new W(v,j)}function L(j){let q=z.getStore();if(q?.tx===void 0||q.afterCommit===void 0)return!1;return q.afterCommit.push(j),!0}function h(j){if(L(j))return Promise.resolve();let q=(v)=>{console.error("An after-commit callback threw. No transaction was open, so it ran immediately.",v)};try{return Promise.resolve(j()).catch(q)}catch(v){return q(v),Promise.resolve()}}function k(j){let q=z.getStore();if(q?.tx===void 0||q.commitDependsOn===void 0)return!1;return q.commitDependsOn.push(j),!0}class F extends Error{constructor(j){super(`A statement this transaction depended on failed after being issued on it, so the transaction rolled back instead of committing: ${j instanceof Error?j.message:String(j)}`,{cause:j});this.name="TransactionDependencyError"}}async function R(j,q){if(j.length===q)return;let B=(await Promise.allSettled(j.slice(q))).find((G)=>G.status==="rejected");if(B)throw new F(B.reason)}function N(){let j=z.getStore();return j?.tx===void 0?null:j.depth}function T(){return z.getStore()?.system===!0}function x(j){let q=z.getStore();return z.run({...q,depth:q?.depth??0,system:!0},j)}function p(j){return z.getStore()?.trashed?.get(j)}function f(j,q,v){let B=z.getStore(),G=new Map(B?.trashed);return G.set(j,q),z.run({...B,depth:B?.depth??0,trashed:G},v)}function C(){return z.getStore()?.actor}function l(j,q){let v=z.getStore();return z.run({...v,depth:v?.depth??0,system:!1,actor:{user:j??null}},q)}function _(j){if(Bun.env.NODE_ENV!=="development")return null;if(j===!1)return null;if(j===void 0)return X;if(!Number.isFinite(j)||j<=0)return X;return j}function A(j){let q=_(j);if(q===null)return()=>{};let v=Error("transaction opened here"),B=setTimeout(()=>{let G=v.stack?.split(`
3
3
  `).slice(1).join(`
4
4
  `)??"";console.warn(`[gemi] A database transaction has not settled after ${q}ms. It `+"reserves a pooled connection until it does \u2014 check for network or "+`filesystem I/O inside the callback, and move it outside the transaction if you find any.
5
5
  ${G}
6
6
  (development only; set database.slowTransactionThreshold to change the threshold, or false to switch this off)`)},q);return B.unref?.(),()=>clearTimeout(B)}async function D(j,q){if(j.length===0)return;await z.run({...q,tx:void 0,afterCommit:void 0,commitDependsOn:void 0,depth:q?.depth??0},async()=>{for(let v of j)try{await v()}catch(B){console.error("An after-commit callback threw. The transaction it was waiting on had already committed and stays committed, and the callbacks after it still ran.",B)}})}function u(j,q,v){let B=z.getStore(),G=v?.connection??K;if(y(G),B?.tx){let J=B.afterCommit,Q=J?.length??0,P=B.commitDependsOn,M=P?.length??0;return B.tx.savepoint((V)=>{let H=V;return z.run({...B,tx:H,depth:B.depth+1},async()=>{let I=await q(H);if(P)await R(P,M);return I})}).catch((V)=>{if(J)J.length=Q;if(P)P.length=M;throw V})}let Y=A(v?.slowTransactionThreshold),Z=[],$=[];try{return j.begin((J)=>z.run({...B,tx:J,depth:0,connection:G===K?void 0:G,afterCommit:Z,commitDependsOn:$},async()=>{let Q=await q(J);return await R($,0),Q})).finally(Y).then(async(J)=>{return await D(Z,B),J})}catch(J){throw Y(),J}}
7
- export{z as $g,g as ah,U as bh,O as ch,y as dh,L as eh,h as fh,k as gh,F as hh,N as ih,T as jh,x as kh,p as lh,f as mh,C as nh,l as oh,u as ph};
7
+ export{z as Oh,g as Ph,U as Qh,O as Rh,y as Sh,L as Th,h as Uh,k as Vh,F as Wh,N as Xh,T as Yh,x as Zh,p as _h,f as $h,C as ai,l as bi,u as ci};
8
8
 
9
- //# debugId=4C5B7052CD785D8164756E2164756E21
9
+ //# debugId=F7275DB827209D4D64756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "import type { SQL, TransactionSQL } from \"bun\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { SLOW_TRANSACTION_THRESHOLD } from \"../database/config\";\nimport {\n CrossConnectionTransactionError,\n DEFAULT_CONNECTION,\n} from \"../database/Connection\";\n\n/**\n * The ambient transaction: the ORM's own `AsyncLocalStorage`, holding nothing\n * but the open handle and how deep the nesting is.\n *\n * One store per scope with one owner, which is the pattern the framework\n * already follows — `kernel/context.ts` holds the Application,\n * `http/requestContext.ts` the request and its user. The reasoning for\n * not folding this into the kernel's is written up beside it, and the short\n * version is that a transaction scope has to *nest inside* an Application scope\n * without replacing it, and `foundation/app.ts` must keep reading exactly one\n * shape out of the kernel store or resolving a service becomes a transaction\n * concern.\n *\n * What makes an ALS the right home rather than a field somewhere: two concurrent\n * requests each in their own transaction must never see each other's handle.\n * Anything reachable from the Application — which is one object shared by every\n * in-flight request — fails that by construction, and fails it as silently\n * written data, not as an error. \"two concurrent transactions never see each\n * other's handle\" in `context.test.ts` is the test that would catch it.\n */\nexport interface OrmScope {\n /**\n * Bun's transaction handle. Every ORM statement in scope runs on it, which\n * means they all run on one reserved connection — so nothing here may issue\n * two statements concurrently. `Model.$exec` already runs its nested writes\n * and its relation reads sequentially, for exactly this reason.\n */\n tx?: TransactionSQL;\n /** 0 for the outermost transaction, 1+ for each savepoint inside it. */\n depth: number;\n /**\n * Which named connection this subtree's queries run on, and — when `tx` is\n * set — which connection the open transaction belongs to.\n *\n * Ambient rather than an argument threaded through `$exec`, for the same\n * reason the handle above is: a relation read resolves its target through the\n * registry and calls that class's `$exec`, so an argument would have to be\n * carried by every intermediate that has no interest in it, and the one that\n * forgot would silently read a nested `include` off the *other* pool. There\n * is no error that shape produces; there are just rows from the wrong place.\n *\n * `undefined` means the default connection. Kept as absent-rather-than-\n * `\"default\"` so that entering a scope on the default connection is\n * indistinguishable from not entering one, which is what makes the\n * cross-connection check below cost a comparison of two `undefined`s on every\n * application that never declares a second connection.\n */\n connection?: string;\n /**\n * Whether policies are suspended for this scope. Set only by\n * `Model.asSystem`, and never by anything ambient — the whole point is that\n * unscoped access is a decision visible at the call site, not the accidental\n * result of a missing user.\n */\n system?: boolean;\n /**\n * The user policies should scope to, when there is no request to read one\n * from. Set only by `Model.asUser`.\n *\n * A sentinel wrapper rather than the bare value, so that \"a scope was entered\n * with `null`\" stays distinguishable from \"no scope was entered\" — the two\n * mean different things under deny-by-default.\n */\n actor?: { user: unknown };\n /**\n * Work that must not happen unless this transaction commits — an event whose\n * `static afterCommit` is set, today, and nothing else.\n *\n * **Created by the outermost `withTransaction` and never by a savepoint.** A\n * savepoint's scope is a spread of its parent's (`{ ...current, tx: nested }`),\n * so the array arrives here already shared by reference with the transaction\n * that opened it — which is the behaviour wanted rather than a leak. A\n * dispatch made inside a savepoint that commits, in a transaction that then\n * rolls back, must not run: rolling back the outermost transaction discards\n * the list whole, savepoint entries included, because nothing ever drains it.\n *\n * The inverse — a savepoint that rolls back under a transaction that commits\n * — is the case sharing gets wrong on its own, and `withTransaction`'s\n * savepoint branch is where it is put right.\n *\n * Absent, rather than an empty array, on every scope that is not a\n * transaction: `runAsSystem`, `runAsUser` and `runOnConnection` spread\n * whatever they are given, so \"there is a list here\" and \"there is an open\n * transaction here\" have to stay the same question. `deferUntilCommit`\n * answers `false` when either half is missing and the caller runs the work\n * now, which is what keeps a hand-built scope carrying a `tx` — the shape\n * tests write — from swallowing a dispatch into a list nothing drains.\n */\n afterCommit?: AfterCommitCallback[];\n /**\n * Statements written on `tx` that the commit must wait for and must not\n * outlive — today, a job row the database queue driver wrote on the\n * transaction (#563), and nothing else. See `commitDependsOn`.\n *\n * Created and shared exactly as `afterCommit` is, and truncated with it\n * when a savepoint rolls back.\n */\n commitDependsOn?: Promise<unknown>[];\n /**\n * Models whose soft-delete scope (`static $softDeletes`) is lifted or\n * inverted for this async subtree, by name — set only by\n * `Model.withTrashed(fn)` / `Model.onlyTrashed(fn)`.\n *\n * Keyed by model name rather than class because a nested relation read\n * resolves its target through the registry by name, and the block has to\n * reach those reads too. A fresh map per block, never mutated, so an inner\n * block cannot leak its entry back into the enclosing one.\n */\n trashed?: ReadonlyMap<string, TrashedMode>;\n}\n\n/**\n * How a soft-deleted model's trashed rows are treated: `\"with\"` includes them,\n * `\"only\"` reads nothing else. Absent means the default — they are hidden.\n */\nexport type TrashedMode = \"with\" | \"only\";\n\n/**\n * Work deferred to a transaction's commit.\n *\n * Awaited when it is drained, and its rejection is caught there: a callback is\n * a side effect that the transaction is not waiting on and cannot be told\n * about, so the only thing left to do with a failure is report it.\n *\n * Not exported: a caller passes a lambda and never names this, and an export\n * nothing outside this file uses is what `orm/architecture.test.ts` is pointed\n * at. The declaration emit carries it along regardless, so `OrmScope` stays\n * readable from a `.d.ts`.\n */\ntype AfterCommitCallback = () => void | Promise<void>;\n\n/**\n * One ambient scope for the ORM, not one per feature.\n *\n * Transactions (iteration 5) and system access (iteration 6) are both\n * \"something is true for this async subtree and every query in it\", so they\n * share a store rather than minting a second `AsyncLocalStorage` each. The\n * inventory note in `kernel/context.ts` sets the bar for adding one; two\n * booleans-worth of ORM state does not clear it.\n */\nexport const ormContext = new AsyncLocalStorage<OrmScope>();\n\n/**\n * The open transaction, or `undefined` outside one. This is what `Model.$exec`\n * consults to decide which connection a statement runs on.\n *\n * Exported as the escape hatch for code that genuinely needs the handle — a raw\n * query that must join the surrounding transaction, say. **Do not store what it\n * returns.** Bun's handle stays callable after its `begin` resolves: queries on\n * it then run on the pooled connection, outside any transaction, and succeed.\n * Verified against both dialects, and it is the reason `Model.transaction`'s\n * callback takes no argument.\n */\nexport function currentTransaction(): TransactionSQL | undefined {\n return ormContext.getStore()?.tx;\n}\n\n/**\n * The connection every query in this scope runs on unless it names another.\n *\n * `\"default\"` outside any scope, so callers get a name rather than a\n * `string | undefined` to normalise themselves — the store keeps it absent,\n * which is not the same distinction and is nobody else's business.\n */\nexport function currentConnectionName(): string {\n return ormContext.getStore()?.connection ?? DEFAULT_CONNECTION;\n}\n\n/**\n * Run `fn` with `name` as the ambient connection.\n *\n * Merged into the current scope rather than replacing it, exactly as\n * `runAsSystem` and `runAsUser` are: naming a connection must not drop an open\n * transaction handle or re-enable policies underneath it.\n *\n * Deliberately absent from `orm/index.ts`, so it is not part of what an\n * application can reach — `Model.on(name)` and `DB.connection(name)` are the\n * two doors, and both funnel through here so that a nested relation read,\n * which resolves its own class out of the registry and calls its `$exec`,\n * inherits the connection without anything having to pass it along.\n */\nexport function runOnConnection<T>(\n name: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = ormContext.getStore();\n if (currentConnectionName() === name) return fn();\n\n // ENTERING A CONNECTION IS WHERE THE CROSS-CONNECTION CHECK BELONGS, not at\n // each door — and it has to be *here*, before the scope is entered, because\n // entering it is what makes the check impossible afterwards.\n //\n // The scope carries `tx` and `connection` together, so overwriting the name\n // while an open handle stays in place produces a store that says \"a\n // transaction on analytics\" while holding the *default* connection's handle.\n // Every check downstream then agrees with itself and the statement runs on\n // the wrong connection's transaction. `Model.save` found this: it routes to\n // the row's own connection, so it is the one caller that switches connections\n // with a transaction already open.\n assertConnectionUsable(name);\n\n return ormContext.run(\n {\n ...current,\n depth: current?.depth ?? 0,\n connection: name === DEFAULT_CONNECTION ? undefined : name,\n },\n fn,\n );\n}\n\n/**\n * Refuse a statement that names one connection while a transaction is open on\n * another.\n *\n * The check `withTransaction`'s single-connection note asked for, and the\n * reasoning for refusing rather than routing is on\n * `CrossConnectionTransactionError`. Both doors call it — `Model.$exec` for\n * every model operation, `DB` for a raw fragment — because either one alone\n * leaves the other free to straddle the two connections, and a raw `DB.execute`\n * escaping a transaction is the more damaging of the two.\n *\n * Only ever fires on a query that *names* a connection: an unqualified one\n * resolves to the ambient name, which is the transaction's own.\n */\nexport function assertConnectionUsable(name: string): void {\n const store = ormContext.getStore();\n if (store?.tx === undefined) return;\n\n const open = store.connection ?? DEFAULT_CONNECTION;\n if (open === name) return;\n\n throw new CrossConnectionTransactionError(open, name);\n}\n\n/**\n * Hold `callback` until the open transaction commits, and say whether that\n * happened.\n *\n * `false` means there was nothing to wait for — no transaction is open, or the\n * scope was entered by hand rather than by `withTransaction` — and the caller\n * must run the work itself, now. That return value is the whole contract: a\n * caller that ignores it turns \"no transaction here\" into a side effect queued\n * on a list nothing will ever drain, which is a dispatch that silently never\n * happens.\n *\n * `true` means the callback is on the outermost scope's list and will run after\n * `begin` resolves, outside the transaction, whatever the caller does next. It\n * will not run at all if the transaction rolls back, or if a savepoint it was\n * registered inside rolls back — both of which are the point.\n *\n * Nothing here is ordered against anything but the other deferred callbacks:\n * they run in registration order, one at a time, after the commit round-trip.\n */\nexport function deferUntilCommit(callback: AfterCommitCallback): boolean {\n const store = ormContext.getStore();\n if (store?.tx === undefined || store.afterCommit === undefined) return false;\n\n store.afterCommit.push(callback);\n return true;\n}\n\n/**\n * Run `callback` once the open transaction commits, or now when none is open.\n * Never when the transaction rolls back, nor when a savepoint it was\n * registered inside rolls back.\n *\n * The application-facing form of `deferUntilCommit`, exported from `gemi/orm`\n * (#786). The difference is the `false` branch: `deferUntilCommit` hands the\n * \"no transaction\" case back to the caller, who must remember to run the work\n * itself, and this runs it. A caller that wants a side effect only once its\n * writes are durable — waking a long-poll, notifying another process — has\n * nothing left to get wrong.\n *\n * Inside a transaction the callback joins the same list `static afterCommit`\n * events use, so it is drained after `begin` resolves, outside the\n * transaction, in registration order with them.\n *\n * The returned promise resolves once the callback has run (no transaction) or\n * been queued (inside one). It never rejects: a callback that throws is\n * reported on stderr, as a deferred one is at the drain, so a caller that does\n * not await — the usual case — cannot leave an unhandled rejection behind, and\n * the two branches fail the same way. A sync callback outside a transaction\n * runs before this returns.\n */\nexport function afterCommit(\n callback: () => void | Promise<void>,\n): Promise<void> {\n if (deferUntilCommit(callback)) return Promise.resolve();\n\n const report = (error: unknown) => {\n console.error(\n `An after-commit callback threw. No transaction was open, so it ran ` +\n `immediately.`,\n error,\n );\n };\n try {\n return Promise.resolve(callback()).catch(report);\n } catch (error) {\n report(error);\n return Promise.resolve();\n }\n}\n\n/**\n * Make the open transaction's commit depend on `write`, a statement issued on\n * its handle: the transaction does not commit until `write` settles, and\n * rolls back — rejecting with `TransactionDependencyError` — if it rejected.\n *\n * For a write the caller may not await. A queued listener's dispatch never is\n * (`EventManager` pushes it and moves on), and on Postgres a statement that\n * fails aborts the whole transaction: every statement after it is refused and\n * Bun's `COMMIT` quietly becomes a rollback. Without this, the callback's\n * promise resolved, `begin` resolved, and the rows the caller wrote were gone\n * with nothing to say so. MySQL does not abort on a failed statement, and is\n * failed here anyway, so that a joined write means the same thing on both:\n * it commits with the transaction or the transaction does not commit.\n *\n * `false` when there is no transaction to depend on, as for\n * `deferUntilCommit`.\n */\nexport function commitDependsOn(write: Promise<unknown>): boolean {\n const store = ormContext.getStore();\n if (store?.tx === undefined || store.commitDependsOn === undefined) {\n return false;\n }\n store.commitDependsOn.push(write);\n return true;\n}\n\n/**\n * A write the transaction's commit depended on failed, so the transaction —\n * or the savepoint the write was made in — rolled back. `cause` is the write's\n * own error.\n */\nexport class TransactionDependencyError extends Error {\n constructor(cause: unknown) {\n super(\n `A statement this transaction depended on failed after being issued on ` +\n `it, so the transaction rolled back instead of committing: ` +\n `${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n );\n this.name = \"TransactionDependencyError\";\n }\n}\n\n/**\n * Wait for the writes registered from `mark` on, and throw if one failed.\n *\n * Called at the end of a transaction's or savepoint's callback, *inside*\n * `begin`/`savepoint`, so a throw is what makes Bun roll back rather than\n * commit — after `begin` has resolved it is too late to do anything but\n * report. Every write is settled before throwing, so none is still running on\n * the handle when the rollback is issued.\n */\nasync function awaitDependencies(\n writes: Promise<unknown>[],\n mark: number,\n): Promise<void> {\n if (writes.length === mark) return;\n const settled = await Promise.allSettled(writes.slice(mark));\n const failed = settled.find(\n (outcome): outcome is PromiseRejectedResult => outcome.status === \"rejected\",\n );\n if (failed) throw new TransactionDependencyError(failed.reason);\n}\n\n/** How deeply nested the current transaction is; `null` outside one. */\nexport function transactionDepth(): number | null {\n const store = ormContext.getStore();\n return store?.tx === undefined ? null : store.depth;\n}\n\n/** Whether policies are suspended for the current async scope. */\nexport function isSystemScope(): boolean {\n return ormContext.getStore()?.system === true;\n}\n\n/**\n * Run `fn` with policies suspended.\n *\n * The escape hatch the deny-by-default rule needs to be usable: a cron tick, a\n * queue worker or a seed script has no user, and under deny-by-default every\n * policied model would refuse it. This makes that intent explicit *at the call\n * site*, which is the property that matters — unscoped access must never be\n * what happens when a user simply fails to turn up.\n *\n * It nests inside a transaction and a transaction nests inside it: the scope is\n * merged rather than replaced, so `asSystem` does not silently drop an open\n * handle.\n */\nexport function runAsSystem<T>(fn: () => Promise<T>): Promise<T> {\n const current = ormContext.getStore();\n return ormContext.run({ ...current, depth: current?.depth ?? 0, system: true }, fn);\n}\n\n/**\n * How `model`'s trashed rows are treated in this async scope, or `undefined`\n * for the default (hidden). See `OrmScope.trashed`.\n */\nexport function trashedMode(model: string): TrashedMode | undefined {\n return ormContext.getStore()?.trashed?.get(model);\n}\n\n/**\n * Run `fn` with `model`'s soft-delete scope lifted (`\"with\"`) or inverted\n * (`\"only\"`). Merged into the current scope like `runAsSystem`, so it keeps an\n * open transaction, the system flag and the actor — and every other policy.\n */\nexport function runWithTrashed<T>(\n model: string,\n mode: TrashedMode,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = ormContext.getStore();\n const trashed = new Map(current?.trashed);\n trashed.set(model, mode);\n return ormContext.run(\n { ...current, depth: current?.depth ?? 0, trashed },\n fn,\n );\n}\n\n/** The explicitly-set actor, or `undefined` when none was. */\nexport function currentActor(): { user: unknown } | undefined {\n return ormContext.getStore()?.actor;\n}\n\n/**\n * Run `fn` with policies scoped to `user`, for code with no request to read one\n * from.\n *\n * The counterpart to `runAsSystem`, and the reason that one is not the only\n * escape hatch. A queue worker processing \"send the invoice for organisation 7\"\n * genuinely acts *as somebody*; giving it `asSystem` would suspend policies\n * entirely and leave it hand-scoping every query — which is precisely the\n * unscoped-by-accident failure the deny-by-default rule exists to prevent. The\n * narrow tool should be the easy one.\n *\n * It is also what makes policies testable without reaching into\n * `RequestContext`'s internals.\n *\n * Takes precedence over the request store, so a job that says who it is acting\n * as is not quietly overridden by an ambient request that happens to enclose it.\n *\n * It also **clears `system`**, which is the more surprising half. Acting as a\n * user is strictly narrower than acting as the system, so naming one inside an\n * `asSystem` block has to narrow back — and the spread would otherwise carry\n * `system: true` forward, leaving `$exec` to skip policies entirely while\n * `currentUser()` cheerfully returned the actor. Silently unscoped, from the\n * realistic shape: a worker enters `asSystem` to read its job queue, then\n * narrows to the job's owner for the work itself. The reverse nesting —\n * `asSystem` inside `asUser` — suspends policies, which is what it should do.\n */\nexport function runAsUser<T>(user: unknown, fn: () => Promise<T>): Promise<T> {\n const current = ormContext.getStore();\n return ormContext.run(\n {\n ...current,\n depth: current?.depth ?? 0,\n system: false,\n actor: { user: user ?? null },\n },\n fn,\n );\n}\n\n/**\n * The warning threshold in milliseconds, or `null` when the warning is off.\n *\n * `configured` is `database.slowTransactionThreshold` — see `DatabaseConfig`.\n * It arrives as a value rather than being read from here so that this file\n * keeps knowing nothing about the container: `withTransaction` is reachable\n * with a bare pool, and its tests use one.\n *\n * Exported for its own tests. The behaviour worth pinning is the fallback —\n * that a malformed threshold lands on the default rather than disabling — and\n * that cannot be observed through `withTransaction`: \"no warning fired\" is what\n * a disabled warning looks like too, so a behavioural test of it passes just as\n * happily when the fallback is gone. Asserting the number directly is the only\n * form of that test that can fail.\n */\nexport function slowTransactionThreshold(\n configured?: number | false,\n): number | null {\n // Read per call, never cached at module scope. `scripts/build.ts` rewrites\n // `process.env.NODE_ENV` to `Bun.env.NODE_ENV` precisely so mode stays a\n // runtime question in the built framework; caching it here would undo that.\n if (process.env.NODE_ENV !== \"development\") return null;\n\n // The one way to switch it off, and it has to be spelled. Everything else\n // falls back, so the warning is never lost to a mistyped value — only to an\n // explicit `false`.\n if (configured === false) return null;\n\n if (configured === undefined) return SLOW_TRANSACTION_THRESHOLD;\n if (!Number.isFinite(configured) || configured <= 0) {\n return SLOW_TRANSACTION_THRESHOLD;\n }\n return configured;\n}\n\n/**\n * Warn, in development only, about a transaction that has been open too long.\n *\n * The risk is structural rather than occasional: an open transaction holds one\n * reserved connection for as long as its callback runs, and nothing about\n * `Model.transaction(async () => { ... })` stops that callback from awaiting a\n * `fetch`, an S3 upload or a slow queue push. Under concurrency that drains the\n * pool, and the symptom — every unrelated query in the process blocking on\n * connection acquisition — names neither the callback nor the I/O in it.\n *\n * A timer rather than measuring elapsed time on the way out, for one reason:\n * the worst case is the transaction that *never* settles (a hung request, a\n * lock wait, a deadlock). After-the-fact measurement is silent for exactly that\n * case; a timer fires while it is still open and still holding the connection.\n *\n * The `Error` is constructed up front and read only if the timer fires — V8\n * formats `.stack` lazily on first access, so an ordinary fast transaction pays\n * for an object allocation and nothing else.\n *\n * The clock starts at the `begin` call, not at the moment a connection is\n * acquired, and stops when `begin` settles rather than when the callback\n * returns — so it spans the pool wait and the commit round-trip as well as the\n * callback. That is deliberate: all three are time this transaction is in\n * flight, and a warning that only covered the callback would stay silent for a\n * transaction stuck waiting on an exhausted pool, which is the exact situation\n * a long transaction elsewhere creates. Hence \"not settled\" rather than \"open\n * for\" — the message must not claim a connection was held for the whole span.\n */\nfunction watchForSlowTransaction(configured?: number | false): () => void {\n const threshold = slowTransactionThreshold(configured);\n if (threshold === null) return () => {};\n\n const site = new Error(\"transaction opened here\");\n\n const timer = setTimeout(() => {\n const stack = site.stack?.split(\"\\n\").slice(1).join(\"\\n\") ?? \"\";\n console.warn(\n `[gemi] A database transaction has not settled after ${threshold}ms. It ` +\n `reserves a pooled connection until it does — check for network or ` +\n `filesystem I/O inside the callback, and move it outside the ` +\n `transaction if you find any.\\n${stack}\\n` +\n `(development only; set database.slowTransactionThreshold to change ` +\n `the threshold, or false to switch this off)`,\n );\n }, threshold);\n\n // Otherwise the warning timer is itself a reason the process stays alive,\n // which would turn a diagnostic into a hang in short-lived commands and\n // scripts.\n timer.unref?.();\n\n return () => clearTimeout(timer);\n}\n\n/**\n * Runs what a committed transaction deferred, outside the transaction it was\n * deferred by.\n *\n * `outside` is the scope that was ambient before `begin` — an `asSystem` block,\n * a named connection, or nothing at all — and re-entering it explicitly is the\n * guarantee rather than a tidy-up. The alternative is relying on where a `.then`\n * happens to have captured its context, and the failure that produces is the\n * one the whole feature is about: a listener that runs \"after commit\" while\n * still holding the closed transaction's handle joins nothing, because Bun's\n * handle stays callable and simply runs on the pool. So the scope is rebuilt\n * with `tx` and the drained list cleared, and a listener that opens its own\n * transaction gets a real one.\n *\n * Errors are caught per callback and the next one still runs, for the reason\n * the event subsystem catches per listener: these are independent side effects\n * whose order came from a filesystem walk. And the transaction is not failed by\n * one — it committed, the database kept the rows, and reporting a rejection to\n * the caller would have it roll back or retry work that is already durable.\n * stderr is all that is left, and it is enough: the caller has no decision to\n * make here.\n *\n * The transaction's own promise does not resolve until this has finished, which\n * is the one thing about `afterCommit` that a caller can feel. Deliberate: the\n * alternative is a floating promise whose rejection nobody sees and whose work\n * a short-lived process — a command, a seed — exits out from under.\n */\nasync function drainAfterCommit(\n callbacks: AfterCommitCallback[],\n outside: OrmScope | undefined,\n): Promise<void> {\n if (callbacks.length === 0) return;\n\n await ormContext.run(\n {\n ...outside,\n tx: undefined,\n afterCommit: undefined,\n commitDependsOn: undefined,\n depth: outside?.depth ?? 0,\n },\n async () => {\n for (const callback of callbacks) {\n try {\n await callback();\n } catch (error) {\n console.error(\n `An after-commit callback threw. The transaction it was waiting ` +\n `on had already committed and stays committed, and the ` +\n `callbacks after it still ran.`,\n error,\n );\n }\n }\n },\n );\n}\n\n/**\n * Run `fn` inside a transaction, entering the ambient scope for its whole async\n * subtree.\n *\n * The single implementation behind both `Model.transaction` and\n * `DB.transaction`, so the two cannot become transaction systems that ignore\n * each other: a `Model.create` inside a `DB.transaction` joins it, and a raw\n * `DB.sql` inside a `Model.transaction` can join it through\n * `currentTransaction()`.\n *\n * Nesting becomes a savepoint. Not a preference — Bun refuses the alternative\n * outright (`cannot call begin inside a transaction use savepoint() instead`),\n * and a savepoint is the semantics worth having anyway: an inner failure rolls\n * back to it and leaves the outer transaction usable, which a caller that\n * catches can rely on. Verified on SQLite and Postgres.\n *\n * Note Bun hands the savepoint callback the *same* handle object as the outer\n * transaction (`sp === tx`), so the depth counter is the only thing that\n * actually changes on the way in. The callback's argument is still what gets\n * stored, so this keeps working if that ever stops being true. The cast is\n * because Bun types a savepoint handle as plain `SQL` — without `savepoint` on\n * it — while the runtime object does carry the method, which is what makes\n * three levels of nesting work.\n *\n * Anything `deferUntilCommit` queued is drained once `begin` resolves, outside\n * the transaction and only on the outermost call — a savepoint has committed\n * nothing durable, so draining there would run work that a later rollback of\n * the enclosing transaction was meant to have prevented. See `drainAfterCommit`\n * for what that costs the caller.\n *\n * In development, an outermost transaction that stays open past\n * `options.slowTransactionThreshold` (2s by default, `false` to disable) warns\n * — see `watchForSlowTransaction`. Nothing here *prevents* a long transaction;\n * the warning exists because the cost of one is paid by unrelated queries\n * elsewhere in the process, which makes it hard to trace back.\n *\n * The threshold is passed in rather than read from `app(DatabaseManager)` here.\n * Every caller already holds the manager — it is where `pool` came from — and\n * taking it as an argument keeps this file free of the container, so a bare\n * `SQL` is still enough to call it. Its tests rely on that.\n *\n * `options.connection` is the name `pool` belongs to, and follows the same rule\n * for the same reason: the pool cannot be asked what it is called. Passing it\n * is what lets a nested `withTransaction` tell \"the same connection, so take a\n * savepoint\" from \"a different one, so refuse\" — omitting it means the default\n * connection, which is what a two-argument call always meant.\n *\n * The return type is asserted rather than inferred for one reason worth\n * knowing: Bun's `begin` unwraps a callback that resolves to an *array of\n * promises*, awaiting each. So `Model.transaction(async () => [a, b])` where\n * `a` and `b` are promises resolves to their values, not to the promises. That\n * is Bun's behaviour and is left alone; it is only surprising if unmentioned.\n */\nexport function withTransaction<T>(\n pool: SQL,\n fn: (tx: TransactionSQL) => Promise<T>,\n options?: { slowTransactionThreshold?: number | false; connection?: string },\n): Promise<T> {\n const current = ormContext.getStore();\n\n // THE SINGLE-CONNECTION ASSUMPTION, WHICH IS NOW CHECKED RATHER THAN PINNED.\n //\n // The savepoint branch below ignores `pool` entirely. That was correct while\n // there was one `DatabaseManager` and one `SQL` — the ambient handle and\n // whatever pool the caller passed were necessarily the same database — and\n // the note that stood here said what would happen when a second connection\n // became configurable (#327): a `DB.transaction` on B inside a\n // `Model.transaction` on A would savepoint on **A** and hand the callback A's\n // handle, so statements landed in the wrong database with no error at all.\n //\n // So the name is compared before the branch is taken, and a mismatch raises.\n // Refusing is the whole answer rather than half of one — there is no way to\n // make one transaction span two pools, and the alternatives are covered on\n // `CrossConnectionTransactionError`.\n //\n // A caller that passes no `connection` is treated as naming the default,\n // which is what `withTransaction(pool, fn)` meant before this argument\n // existed.\n const name = options?.connection ?? DEFAULT_CONNECTION;\n assertConnectionUsable(name);\n\n // `current?.tx` rather than `current`: since iteration 6 a scope can exist\n // with no open transaction — `Model.asSystem` enters one — and a savepoint\n // needs an actual handle, not merely a store.\n if (current?.tx) {\n // WHERE THE SHARED AFTER-COMMIT LIST IS PUT RIGHT.\n //\n // The savepoint's scope is a spread of this one, so it appends to the\n // transaction's list rather than to a list of its own — which is what makes\n // \"the outer transaction rolled back, so nothing runs\" free. The case that\n // is not free is this one: the savepoint rolls back and the transaction\n // goes on to commit. Its entries have to go, or a dispatch made inside a\n // block the database threw away runs anyway, which is the same wrong answer\n // as before with an extra step.\n //\n // A mark on the way in and a truncate on the way out, rather than tagging\n // each entry with its depth and dropping everything at or below the failing\n // one. Depth cannot tell two *siblings* apart: a savepoint that committed\n // and one that rolled back both left entries at the same depth, adjacent in\n // the list, and dropping by depth would discard the committed sibling's\n // work as well. The index is exact because the ORM issues one statement at\n // a time on a transaction handle — see `OrmScope.tx` — so nothing appends\n // between the mark and the failure but this savepoint's own subtree.\n const deferred = current.afterCommit;\n const mark = deferred?.length ?? 0;\n // The same mark for the writes the commit depends on. The savepoint waits\n // for its own before it releases, so one that failed rolls back only the\n // savepoint — which a caller that catches can survive, exactly as it\n // survives a statement that threw inside it — and is then forgotten\n // rather than failing the transaction a second time.\n const dependencies = current.commitDependsOn;\n const dependencyMark = dependencies?.length ?? 0;\n\n return current.tx\n .savepoint((sp) => {\n const nested = sp as TransactionSQL;\n return ormContext.run(\n { ...current, tx: nested, depth: current.depth + 1 },\n async () => {\n const result = await fn(nested);\n if (dependencies) {\n await awaitDependencies(dependencies, dependencyMark);\n }\n return result;\n },\n );\n })\n .catch((error: unknown) => {\n if (deferred) deferred.length = mark;\n if (dependencies) dependencies.length = dependencyMark;\n throw error;\n }) as Promise<T>;\n }\n\n // Only the outermost scope is watched. A savepoint reserves no connection of\n // its own — its lifetime is bounded by the transaction it sits in, which is\n // already being timed — so warning per depth would report one slow block as\n // several warnings and point at the innermost frame rather than the one\n // holding the connection.\n const stopWatching = watchForSlowTransaction(\n options?.slowTransactionThreshold,\n );\n\n // Built out here rather than inside the `begin` callback, because the drain\n // below needs it *after* that callback's scope is gone, and reading it off\n // the store then is exactly what is no longer possible.\n const deferred: AfterCommitCallback[] = [];\n const dependencies: Promise<unknown>[] = [];\n\n // The `try` covers a *synchronous* throw from `begin` — a closed pool, say.\n // `.finally` alone would not: it is only attached once `begin` has returned a\n // promise, so a synchronous throw escapes with the timer still armed and\n // eventually warns about a transaction that never opened. `unref` keeps that\n // from holding the process, which makes it cosmetic rather than a leak, but\n // it is the same gap the `.finally` below exists to close.\n try {\n // Spread rather than replace: a `Model.transaction` inside a\n // `Model.asSystem` must not silently re-enable policies for its subtree.\n //\n // The connection goes into the scope alongside the handle, and the pair is\n // what makes the check at the top of this function possible: \"which\n // connection is this transaction on\" has to be answerable from the store,\n // because the handle itself does not say. It is also what makes an\n // unqualified query inside `DB.connection(\"analytics\").transaction(...)`\n // *join* the transaction instead of being refused by it — the query\n // inherits the name rather than defaulting to the hot path.\n return (\n pool\n .begin((tx) =>\n ormContext.run(\n {\n ...current,\n tx,\n depth: 0,\n connection: name === DEFAULT_CONNECTION ? undefined : name,\n // A fresh list per outermost transaction, assigned rather than\n // left to the spread. `current` holds no list today — the drain\n // clears the field before it runs anything — and assigning is\n // what keeps that from being load-bearing: a transaction opened\n // by a callback during a drain gets its own list either way,\n // rather than appending to the array it is being run out of.\n afterCommit: deferred,\n commitDependsOn: dependencies,\n },\n async () => {\n const result = await fn(tx);\n await awaitDependencies(dependencies, 0);\n return result;\n },\n ),\n )\n // `finally` and not a `then`/`catch` pair: the connection is released on\n // rollback exactly as it is on commit, so a throwing callback must clear\n // the timer too or every failed transaction leaves a warning armed\n // against a connection that has already gone back to the pool.\n //\n // Before the drain, so that a slow after-commit listener is not\n // reported as a transaction that will not settle. The connection went\n // back to the pool at the commit; the warning is about holding it.\n .finally(stopWatching)\n // Only here, on the fulfilled path. A rejected `begin` rolled back, so\n // the scope and everything queued on it are discarded unread — which is\n // the whole of what `afterCommit` promises.\n .then(async (result) => {\n await drainAfterCommit(deferred, current);\n return result;\n }) as Promise<T>\n );\n } catch (error) {\n stopWatching();\n throw error;\n }\n}\n"
6
6
  ],
7
7
  "mappings": ";yDACA,4BAAS,oBAmJF,IAAM,EAAa,IAAI,EAavB,SAAS,CAAkB,EAA+B,CAC/D,OAAO,EAAW,SAAS,GAAG,GAUzB,SAAS,CAAqB,EAAW,CAC9C,OAAO,EAAW,SAAS,GAAG,YAAc,EAgBvC,SAAS,CAAkB,CAChC,EACA,EACY,CACZ,IAAM,EAAU,EAAW,SAAS,EACpC,GAAI,EAAsB,IAAM,EAAM,OAAO,EAAG,EAehD,OAFA,EAAuB,CAAI,EAEpB,EAAW,IAChB,IACK,EACH,MAAO,GAAS,OAAS,EACzB,WAAY,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tD,YAAa,EACb,gBAAiB,CACnB,EACA,SAAY,CACV,IAAM,EAAS,MAAM,EAAG,CAAE,EAE1B,OADA,MAAM,EAAkB,EAAc,CAAC,EAChC,EAEX,CACF,EASC,QAAQ,CAAY,EAIpB,KAAK,MAAO,IAAW,CAEtB,OADA,MAAM,EAAiB,EAAU,CAAO,EACjC,EACR,EAEL,MAAO,EAAO,CAEd,MADA,EAAa,EACP",
8
- "debugId": "4C5B7052CD785D8164756E2164756E21",
8
+ "debugId": "F7275DB827209D4D64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ri as LC}from"./chunk-vw8849ys.js";var OC=LC((QC,A)=>{var P,h,j,I,b,y,g,k,f,m,u,x,l,D,z,_,d,c,E,v,n,p,i,s,a,o,t,r,w,e,CC,HC;(function(X){var R=typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:{};if(typeof define==="function"&&define.amd)define("tslib",["exports"],function(G){X(q(R,q(G)))});else if(typeof A==="object"&&typeof QC==="object")X(q(R,q(QC)));else X(q(R));function q(G,S){if(G!==R)if(typeof Object.create==="function")Object.defineProperty(G,"__esModule",{value:!0});else G.__esModule=!0;return function(C,H){return G[C]=S?S(C,H):H}}})(function(X){var R=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(C,H){C.__proto__=H}||function(C,H){for(var L in H)if(Object.prototype.hasOwnProperty.call(H,L))C[L]=H[L]};P=function(C,H){if(typeof H!=="function"&&H!==null)throw TypeError("Class extends value "+String(H)+" is not a constructor or null");R(C,H);function L(){this.constructor=C}C.prototype=H===null?Object.create(H):(L.prototype=H.prototype,new L)},h=Object.assign||function(C){for(var H,L=1,O=arguments.length;L<O;L++){H=arguments[L];for(var Q in H)if(Object.prototype.hasOwnProperty.call(H,Q))C[Q]=H[Q]}return C},j=function(C,H){var L={};for(var O in C)if(Object.prototype.hasOwnProperty.call(C,O)&&H.indexOf(O)<0)L[O]=C[O];if(C!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var Q=0,O=Object.getOwnPropertySymbols(C);Q<O.length;Q++)if(H.indexOf(O[Q])<0&&Object.prototype.propertyIsEnumerable.call(C,O[Q]))L[O[Q]]=C[O[Q]]}return L},I=function(C,H,L,O){var Q=arguments.length,T=Q<3?H:O===null?O=Object.getOwnPropertyDescriptor(H,L):O,U;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")T=Reflect.decorate(C,H,L,O);else for(var Y=C.length-1;Y>=0;Y--)if(U=C[Y])T=(Q<3?U(T):Q>3?U(H,L,T):U(H,L))||T;return Q>3&&T&&Object.defineProperty(H,L,T),T},b=function(C,H){return function(L,O){H(L,O,C)}},y=function(C,H,L,O,Q,T){function U(K){if(K!==void 0&&typeof K!=="function")throw TypeError("Function expected");return K}var Y=O.kind,J=Y==="getter"?"get":Y==="setter"?"set":"value",W=!H&&C?O.static?C:C.prototype:null,$=H||(W?Object.getOwnPropertyDescriptor(W,O.name):{}),M,F=!1;for(var Z=L.length-1;Z>=0;Z--){var N={};for(var B in O)N[B]=B==="access"?{}:O[B];for(var B in O.access)N.access[B]=O.access[B];N.addInitializer=function(K){if(F)throw TypeError("Cannot add initializers after decoration has completed");T.push(U(K||null))};var V=(0,L[Z])(Y==="accessor"?{get:$.get,set:$.set}:$[J],N);if(Y==="accessor"){if(V===void 0)continue;if(V===null||typeof V!=="object")throw TypeError("Object expected");if(M=U(V.get))$.get=M;if(M=U(V.set))$.set=M;if(M=U(V.init))Q.unshift(M)}else if(M=U(V))if(Y==="field")Q.unshift(M);else $[J]=M}if(W)Object.defineProperty(W,O.name,$);F=!0},g=function(C,H,L){var O=arguments.length>2;for(var Q=0;Q<H.length;Q++)L=O?H[Q].call(C,L):H[Q].call(C);return O?L:void 0},k=function(C){return typeof C==="symbol"?C:"".concat(C)},f=function(C,H,L){if(typeof H==="symbol")H=H.description?"[".concat(H.description,"]"):"";return Object.defineProperty(C,"name",{configurable:!0,value:L?"".concat(L," ",H):H})},m=function(C,H){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(C,H)},u=function(C,H,L,O){function Q(T){return T instanceof L?T:new L(function(U){U(T)})}return new(L||(L=Promise))(function(T,U){function Y($){try{W(O.next($))}catch(M){U(M)}}function J($){try{W(O.throw($))}catch(M){U(M)}}function W($){$.done?T($.value):Q($.value).then(Y,J)}W((O=O.apply(C,H||[])).next())})},x=function(C,H){var L={label:0,sent:function(){if(T[0]&1)throw T[1];return T[1]},trys:[],ops:[]},O,Q,T,U=Object.create((typeof Iterator==="function"?Iterator:Object).prototype);return U.next=Y(0),U.throw=Y(1),U.return=Y(2),typeof Symbol==="function"&&(U[Symbol.iterator]=function(){return this}),U;function Y(W){return function($){return J([W,$])}}function J(W){if(O)throw TypeError("Generator is already executing.");while(U&&(U=0,W[0]&&(L=0)),L)try{if(O=1,Q&&(T=W[0]&2?Q.return:W[0]?Q.throw||((T=Q.return)&&T.call(Q),0):Q.next)&&!(T=T.call(Q,W[1])).done)return T;if(Q=0,T)W=[W[0]&2,T.value];switch(W[0]){case 0:case 1:T=W;break;case 4:return L.label++,{value:W[1],done:!1};case 5:L.label++,Q=W[1],W=[0];continue;case 7:W=L.ops.pop(),L.trys.pop();continue;default:if((T=L.trys,!(T=T.length>0&&T[T.length-1]))&&(W[0]===6||W[0]===2)){L=0;continue}if(W[0]===3&&(!T||W[1]>T[0]&&W[1]<T[3])){L.label=W[1];break}if(W[0]===6&&L.label<T[1]){L.label=T[1],T=W;break}if(T&&L.label<T[2]){L.label=T[2],L.ops.push(W);break}if(T[2])L.ops.pop();L.trys.pop();continue}W=H.call(C,L)}catch($){W=[6,$],Q=0}finally{O=T=0}if(W[0]&5)throw W[1];return{value:W[0]?W[1]:void 0,done:!0}}},l=function(C,H){for(var L in C)if(L!=="default"&&!Object.prototype.hasOwnProperty.call(H,L))w(H,C,L)},w=Object.create?function(C,H,L,O){if(O===void 0)O=L;var Q=Object.getOwnPropertyDescriptor(H,L);if(!Q||("get"in Q?!H.__esModule:Q.writable||Q.configurable))Q={enumerable:!0,get:function(){return H[L]}};Object.defineProperty(C,O,Q)}:function(C,H,L,O){if(O===void 0)O=L;C[O]=H[L]},D=function(C){var H=typeof Symbol==="function"&&Symbol.iterator,L=H&&C[H],O=0;if(L)return L.call(C);if(C&&typeof C.length==="number")return{next:function(){if(C&&O>=C.length)C=void 0;return{value:C&&C[O++],done:!C}}};throw TypeError(H?"Object is not iterable.":"Symbol.iterator is not defined.")},z=function(C,H){var L=typeof Symbol==="function"&&C[Symbol.iterator];if(!L)return C;var O=L.call(C),Q,T=[],U;try{while((H===void 0||H-- >0)&&!(Q=O.next()).done)T.push(Q.value)}catch(Y){U={error:Y}}finally{try{if(Q&&!Q.done&&(L=O.return))L.call(O)}finally{if(U)throw U.error}}return T},_=function(){for(var C=[],H=0;H<arguments.length;H++)C=C.concat(z(arguments[H]));return C},d=function(){for(var C=0,H=0,L=arguments.length;H<L;H++)C+=arguments[H].length;for(var O=Array(C),Q=0,H=0;H<L;H++)for(var T=arguments[H],U=0,Y=T.length;U<Y;U++,Q++)O[Q]=T[U];return O},c=function(C,H,L){if(L||arguments.length===2){for(var O=0,Q=H.length,T;O<Q;O++)if(T||!(O in H)){if(!T)T=Array.prototype.slice.call(H,0,O);T[O]=H[O]}}return C.concat(T||Array.prototype.slice.call(H))},E=function(C){return this instanceof E?(this.v=C,this):new E(C)},v=function(C,H,L){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var O=L.apply(C,H||[]),Q,T=[];return Q=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),Y("next"),Y("throw"),Y("return",U),Q[Symbol.asyncIterator]=function(){return this},Q;function U(Z){return function(N){return Promise.resolve(N).then(Z,M)}}function Y(Z,N){if(O[Z]){if(Q[Z]=function(B){return new Promise(function(V,K){T.push([Z,B,V,K])>1||J(Z,B)})},N)Q[Z]=N(Q[Z])}}function J(Z,N){try{W(O[Z](N))}catch(B){F(T[0][3],B)}}function W(Z){Z.value instanceof E?Promise.resolve(Z.value.v).then($,M):F(T[0][2],Z)}function $(Z){J("next",Z)}function M(Z){J("throw",Z)}function F(Z,N){if(Z(N),T.shift(),T.length)J(T[0][0],T[0][1])}},n=function(C){var H,L;return H={},O("next"),O("throw",function(Q){throw Q}),O("return"),H[Symbol.iterator]=function(){return this},H;function O(Q,T){H[Q]=C[Q]?function(U){return(L=!L)?{value:E(C[Q](U)),done:!1}:T?T(U):U}:T}},p=function(C){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var H=C[Symbol.asyncIterator],L;return H?H.call(C):(C=typeof D==="function"?D(C):C[Symbol.iterator](),L={},O("next"),O("throw"),O("return"),L[Symbol.asyncIterator]=function(){return this},L);function O(T){L[T]=C[T]&&function(U){return new Promise(function(Y,J){U=C[T](U),Q(Y,J,U.done,U.value)})}}function Q(T,U,Y,J){Promise.resolve(J).then(function(W){T({value:W,done:Y})},U)}},i=function(C,H){if(Object.defineProperty)Object.defineProperty(C,"raw",{value:H});else C.raw=H;return C};var q=Object.create?function(C,H){Object.defineProperty(C,"default",{enumerable:!0,value:H})}:function(C,H){C.default=H},G=function(C){return G=Object.getOwnPropertyNames||function(H){var L=[];for(var O in H)if(Object.prototype.hasOwnProperty.call(H,O))L[L.length]=O;return L},G(C)};s=function(C){if(C&&C.__esModule)return C;var H={};if(C!=null){for(var L=G(C),O=0;O<L.length;O++)if(L[O]!=="default")w(H,C,L[O])}return q(H,C),H},a=function(C){return C&&C.__esModule?C:{default:C}},o=function(C,H,L,O){if(L==="a"&&!O)throw TypeError("Private accessor was defined without a getter");if(typeof H==="function"?C!==H||!O:!H.has(C))throw TypeError("Cannot read private member from an object whose class did not declare it");return L==="m"?O:L==="a"?O.call(C):O?O.value:H.get(C)},t=function(C,H,L,O,Q){if(O==="m")throw TypeError("Private method is not writable");if(O==="a"&&!Q)throw TypeError("Private accessor was defined without a setter");if(typeof H==="function"?C!==H||!Q:!H.has(C))throw TypeError("Cannot write private member to an object whose class did not declare it");return O==="a"?Q.call(C,L):Q?Q.value=L:H.set(C,L),L},r=function(C,H){if(H===null||typeof H!=="object"&&typeof H!=="function")throw TypeError("Cannot use 'in' operator on non-object");return typeof C==="function"?H===C:C.has(H)},e=function(C,H,L){if(H!==null&&H!==void 0){if(typeof H!=="object"&&typeof H!=="function")throw TypeError("Object expected.");var O,Q;if(L){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");O=H[Symbol.asyncDispose]}if(O===void 0){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");if(O=H[Symbol.dispose],L)Q=O}if(typeof O!=="function")throw TypeError("Object not disposable.");if(Q)O=function(){try{Q.call(this)}catch(T){return Promise.reject(T)}};C.stack.push({value:H,dispose:O,async:L})}else if(L)C.stack.push({async:!0});return H};var S=typeof SuppressedError==="function"?SuppressedError:function(C,H,L){var O=Error(L);return O.name="SuppressedError",O.error=C,O.suppressed=H,O};CC=function(C){function H(T){C.error=C.hasError?new S(T,C.error,"An error was suppressed during disposal."):T,C.hasError=!0}var L,O=0;function Q(){while(L=C.stack.pop())try{if(!L.async&&O===1)return O=0,C.stack.push(L),Promise.resolve().then(Q);if(L.dispose){var T=L.dispose.call(L.value);if(L.async)return O|=2,Promise.resolve(T).then(Q,function(U){return H(U),Q()})}else O|=1}catch(U){H(U)}if(O===1)return C.hasError?Promise.reject(C.error):Promise.resolve();if(C.hasError)throw C.error}return Q()},HC=function(C,H){if(typeof C==="string"&&/^\.\.?\//.test(C))return C.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(L,O,Q,T,U){return O?H?".jsx":".js":Q&&(!T||!U)?L:Q+T+"."+U.toLowerCase()+"js"});return C},X("__extends",P),X("__assign",h),X("__rest",j),X("__decorate",I),X("__param",b),X("__esDecorate",y),X("__runInitializers",g),X("__propKey",k),X("__setFunctionName",f),X("__metadata",m),X("__awaiter",u),X("__generator",x),X("__exportStar",l),X("__createBinding",w),X("__values",D),X("__read",z),X("__spread",_),X("__spreadArrays",d),X("__spreadArray",c),X("__await",E),X("__asyncGenerator",v),X("__asyncDelegator",n),X("__asyncValues",p),X("__makeTemplateObject",i),X("__importStar",s),X("__importDefault",a),X("__classPrivateFieldGet",o),X("__classPrivateFieldSet",t),X("__classPrivateFieldIn",r),X("__addDisposableResource",e),X("__disposeResources",CC),X("__rewriteRelativeImportExtension",HC)})});
3
- export{OC as ka};
2
+ import{fj as LC}from"./chunk-hm9cjxy2.js";var OC=LC((QC,A)=>{var P,h,j,I,b,y,g,k,f,m,u,x,l,D,z,_,d,c,E,v,n,p,i,s,a,o,t,r,w,e,CC,HC;(function(X){var R=typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:{};if(typeof define==="function"&&define.amd)define("tslib",["exports"],function(G){X(q(R,q(G)))});else if(typeof A==="object"&&typeof QC==="object")X(q(R,q(QC)));else X(q(R));function q(G,S){if(G!==R)if(typeof Object.create==="function")Object.defineProperty(G,"__esModule",{value:!0});else G.__esModule=!0;return function(C,H){return G[C]=S?S(C,H):H}}})(function(X){var R=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(C,H){C.__proto__=H}||function(C,H){for(var L in H)if(Object.prototype.hasOwnProperty.call(H,L))C[L]=H[L]};P=function(C,H){if(typeof H!=="function"&&H!==null)throw TypeError("Class extends value "+String(H)+" is not a constructor or null");R(C,H);function L(){this.constructor=C}C.prototype=H===null?Object.create(H):(L.prototype=H.prototype,new L)},h=Object.assign||function(C){for(var H,L=1,O=arguments.length;L<O;L++){H=arguments[L];for(var Q in H)if(Object.prototype.hasOwnProperty.call(H,Q))C[Q]=H[Q]}return C},j=function(C,H){var L={};for(var O in C)if(Object.prototype.hasOwnProperty.call(C,O)&&H.indexOf(O)<0)L[O]=C[O];if(C!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var Q=0,O=Object.getOwnPropertySymbols(C);Q<O.length;Q++)if(H.indexOf(O[Q])<0&&Object.prototype.propertyIsEnumerable.call(C,O[Q]))L[O[Q]]=C[O[Q]]}return L},I=function(C,H,L,O){var Q=arguments.length,T=Q<3?H:O===null?O=Object.getOwnPropertyDescriptor(H,L):O,U;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")T=Reflect.decorate(C,H,L,O);else for(var Y=C.length-1;Y>=0;Y--)if(U=C[Y])T=(Q<3?U(T):Q>3?U(H,L,T):U(H,L))||T;return Q>3&&T&&Object.defineProperty(H,L,T),T},b=function(C,H){return function(L,O){H(L,O,C)}},y=function(C,H,L,O,Q,T){function U(K){if(K!==void 0&&typeof K!=="function")throw TypeError("Function expected");return K}var Y=O.kind,J=Y==="getter"?"get":Y==="setter"?"set":"value",W=!H&&C?O.static?C:C.prototype:null,$=H||(W?Object.getOwnPropertyDescriptor(W,O.name):{}),M,F=!1;for(var Z=L.length-1;Z>=0;Z--){var N={};for(var B in O)N[B]=B==="access"?{}:O[B];for(var B in O.access)N.access[B]=O.access[B];N.addInitializer=function(K){if(F)throw TypeError("Cannot add initializers after decoration has completed");T.push(U(K||null))};var V=(0,L[Z])(Y==="accessor"?{get:$.get,set:$.set}:$[J],N);if(Y==="accessor"){if(V===void 0)continue;if(V===null||typeof V!=="object")throw TypeError("Object expected");if(M=U(V.get))$.get=M;if(M=U(V.set))$.set=M;if(M=U(V.init))Q.unshift(M)}else if(M=U(V))if(Y==="field")Q.unshift(M);else $[J]=M}if(W)Object.defineProperty(W,O.name,$);F=!0},g=function(C,H,L){var O=arguments.length>2;for(var Q=0;Q<H.length;Q++)L=O?H[Q].call(C,L):H[Q].call(C);return O?L:void 0},k=function(C){return typeof C==="symbol"?C:"".concat(C)},f=function(C,H,L){if(typeof H==="symbol")H=H.description?"[".concat(H.description,"]"):"";return Object.defineProperty(C,"name",{configurable:!0,value:L?"".concat(L," ",H):H})},m=function(C,H){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(C,H)},u=function(C,H,L,O){function Q(T){return T instanceof L?T:new L(function(U){U(T)})}return new(L||(L=Promise))(function(T,U){function Y($){try{W(O.next($))}catch(M){U(M)}}function J($){try{W(O.throw($))}catch(M){U(M)}}function W($){$.done?T($.value):Q($.value).then(Y,J)}W((O=O.apply(C,H||[])).next())})},x=function(C,H){var L={label:0,sent:function(){if(T[0]&1)throw T[1];return T[1]},trys:[],ops:[]},O,Q,T,U=Object.create((typeof Iterator==="function"?Iterator:Object).prototype);return U.next=Y(0),U.throw=Y(1),U.return=Y(2),typeof Symbol==="function"&&(U[Symbol.iterator]=function(){return this}),U;function Y(W){return function($){return J([W,$])}}function J(W){if(O)throw TypeError("Generator is already executing.");while(U&&(U=0,W[0]&&(L=0)),L)try{if(O=1,Q&&(T=W[0]&2?Q.return:W[0]?Q.throw||((T=Q.return)&&T.call(Q),0):Q.next)&&!(T=T.call(Q,W[1])).done)return T;if(Q=0,T)W=[W[0]&2,T.value];switch(W[0]){case 0:case 1:T=W;break;case 4:return L.label++,{value:W[1],done:!1};case 5:L.label++,Q=W[1],W=[0];continue;case 7:W=L.ops.pop(),L.trys.pop();continue;default:if((T=L.trys,!(T=T.length>0&&T[T.length-1]))&&(W[0]===6||W[0]===2)){L=0;continue}if(W[0]===3&&(!T||W[1]>T[0]&&W[1]<T[3])){L.label=W[1];break}if(W[0]===6&&L.label<T[1]){L.label=T[1],T=W;break}if(T&&L.label<T[2]){L.label=T[2],L.ops.push(W);break}if(T[2])L.ops.pop();L.trys.pop();continue}W=H.call(C,L)}catch($){W=[6,$],Q=0}finally{O=T=0}if(W[0]&5)throw W[1];return{value:W[0]?W[1]:void 0,done:!0}}},l=function(C,H){for(var L in C)if(L!=="default"&&!Object.prototype.hasOwnProperty.call(H,L))w(H,C,L)},w=Object.create?function(C,H,L,O){if(O===void 0)O=L;var Q=Object.getOwnPropertyDescriptor(H,L);if(!Q||("get"in Q?!H.__esModule:Q.writable||Q.configurable))Q={enumerable:!0,get:function(){return H[L]}};Object.defineProperty(C,O,Q)}:function(C,H,L,O){if(O===void 0)O=L;C[O]=H[L]},D=function(C){var H=typeof Symbol==="function"&&Symbol.iterator,L=H&&C[H],O=0;if(L)return L.call(C);if(C&&typeof C.length==="number")return{next:function(){if(C&&O>=C.length)C=void 0;return{value:C&&C[O++],done:!C}}};throw TypeError(H?"Object is not iterable.":"Symbol.iterator is not defined.")},z=function(C,H){var L=typeof Symbol==="function"&&C[Symbol.iterator];if(!L)return C;var O=L.call(C),Q,T=[],U;try{while((H===void 0||H-- >0)&&!(Q=O.next()).done)T.push(Q.value)}catch(Y){U={error:Y}}finally{try{if(Q&&!Q.done&&(L=O.return))L.call(O)}finally{if(U)throw U.error}}return T},_=function(){for(var C=[],H=0;H<arguments.length;H++)C=C.concat(z(arguments[H]));return C},d=function(){for(var C=0,H=0,L=arguments.length;H<L;H++)C+=arguments[H].length;for(var O=Array(C),Q=0,H=0;H<L;H++)for(var T=arguments[H],U=0,Y=T.length;U<Y;U++,Q++)O[Q]=T[U];return O},c=function(C,H,L){if(L||arguments.length===2){for(var O=0,Q=H.length,T;O<Q;O++)if(T||!(O in H)){if(!T)T=Array.prototype.slice.call(H,0,O);T[O]=H[O]}}return C.concat(T||Array.prototype.slice.call(H))},E=function(C){return this instanceof E?(this.v=C,this):new E(C)},v=function(C,H,L){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var O=L.apply(C,H||[]),Q,T=[];return Q=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),Y("next"),Y("throw"),Y("return",U),Q[Symbol.asyncIterator]=function(){return this},Q;function U(Z){return function(N){return Promise.resolve(N).then(Z,M)}}function Y(Z,N){if(O[Z]){if(Q[Z]=function(B){return new Promise(function(V,K){T.push([Z,B,V,K])>1||J(Z,B)})},N)Q[Z]=N(Q[Z])}}function J(Z,N){try{W(O[Z](N))}catch(B){F(T[0][3],B)}}function W(Z){Z.value instanceof E?Promise.resolve(Z.value.v).then($,M):F(T[0][2],Z)}function $(Z){J("next",Z)}function M(Z){J("throw",Z)}function F(Z,N){if(Z(N),T.shift(),T.length)J(T[0][0],T[0][1])}},n=function(C){var H,L;return H={},O("next"),O("throw",function(Q){throw Q}),O("return"),H[Symbol.iterator]=function(){return this},H;function O(Q,T){H[Q]=C[Q]?function(U){return(L=!L)?{value:E(C[Q](U)),done:!1}:T?T(U):U}:T}},p=function(C){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var H=C[Symbol.asyncIterator],L;return H?H.call(C):(C=typeof D==="function"?D(C):C[Symbol.iterator](),L={},O("next"),O("throw"),O("return"),L[Symbol.asyncIterator]=function(){return this},L);function O(T){L[T]=C[T]&&function(U){return new Promise(function(Y,J){U=C[T](U),Q(Y,J,U.done,U.value)})}}function Q(T,U,Y,J){Promise.resolve(J).then(function(W){T({value:W,done:Y})},U)}},i=function(C,H){if(Object.defineProperty)Object.defineProperty(C,"raw",{value:H});else C.raw=H;return C};var q=Object.create?function(C,H){Object.defineProperty(C,"default",{enumerable:!0,value:H})}:function(C,H){C.default=H},G=function(C){return G=Object.getOwnPropertyNames||function(H){var L=[];for(var O in H)if(Object.prototype.hasOwnProperty.call(H,O))L[L.length]=O;return L},G(C)};s=function(C){if(C&&C.__esModule)return C;var H={};if(C!=null){for(var L=G(C),O=0;O<L.length;O++)if(L[O]!=="default")w(H,C,L[O])}return q(H,C),H},a=function(C){return C&&C.__esModule?C:{default:C}},o=function(C,H,L,O){if(L==="a"&&!O)throw TypeError("Private accessor was defined without a getter");if(typeof H==="function"?C!==H||!O:!H.has(C))throw TypeError("Cannot read private member from an object whose class did not declare it");return L==="m"?O:L==="a"?O.call(C):O?O.value:H.get(C)},t=function(C,H,L,O,Q){if(O==="m")throw TypeError("Private method is not writable");if(O==="a"&&!Q)throw TypeError("Private accessor was defined without a setter");if(typeof H==="function"?C!==H||!Q:!H.has(C))throw TypeError("Cannot write private member to an object whose class did not declare it");return O==="a"?Q.call(C,L):Q?Q.value=L:H.set(C,L),L},r=function(C,H){if(H===null||typeof H!=="object"&&typeof H!=="function")throw TypeError("Cannot use 'in' operator on non-object");return typeof C==="function"?H===C:C.has(H)},e=function(C,H,L){if(H!==null&&H!==void 0){if(typeof H!=="object"&&typeof H!=="function")throw TypeError("Object expected.");var O,Q;if(L){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");O=H[Symbol.asyncDispose]}if(O===void 0){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");if(O=H[Symbol.dispose],L)Q=O}if(typeof O!=="function")throw TypeError("Object not disposable.");if(Q)O=function(){try{Q.call(this)}catch(T){return Promise.reject(T)}};C.stack.push({value:H,dispose:O,async:L})}else if(L)C.stack.push({async:!0});return H};var S=typeof SuppressedError==="function"?SuppressedError:function(C,H,L){var O=Error(L);return O.name="SuppressedError",O.error=C,O.suppressed=H,O};CC=function(C){function H(T){C.error=C.hasError?new S(T,C.error,"An error was suppressed during disposal."):T,C.hasError=!0}var L,O=0;function Q(){while(L=C.stack.pop())try{if(!L.async&&O===1)return O=0,C.stack.push(L),Promise.resolve().then(Q);if(L.dispose){var T=L.dispose.call(L.value);if(L.async)return O|=2,Promise.resolve(T).then(Q,function(U){return H(U),Q()})}else O|=1}catch(U){H(U)}if(O===1)return C.hasError?Promise.reject(C.error):Promise.resolve();if(C.hasError)throw C.error}return Q()},HC=function(C,H){if(typeof C==="string"&&/^\.\.?\//.test(C))return C.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(L,O,Q,T,U){return O?H?".jsx":".js":Q&&(!T||!U)?L:Q+T+"."+U.toLowerCase()+"js"});return C},X("__extends",P),X("__assign",h),X("__rest",j),X("__decorate",I),X("__param",b),X("__esDecorate",y),X("__runInitializers",g),X("__propKey",k),X("__setFunctionName",f),X("__metadata",m),X("__awaiter",u),X("__generator",x),X("__exportStar",l),X("__createBinding",w),X("__values",D),X("__read",z),X("__spread",_),X("__spreadArrays",d),X("__spreadArray",c),X("__await",E),X("__asyncGenerator",v),X("__asyncDelegator",n),X("__asyncValues",p),X("__makeTemplateObject",i),X("__importStar",s),X("__importDefault",a),X("__classPrivateFieldGet",o),X("__classPrivateFieldSet",t),X("__classPrivateFieldIn",r),X("__addDisposableResource",e),X("__disposeResources",CC),X("__rewriteRelativeImportExtension",HC)})});
3
+ export{OC as la};
4
4
 
5
- //# debugId=0AA9F7CCF55E50DB64756E2164756E21
5
+ //# debugId=F79BDED2890C891F64756E2164756E21