gemi 0.56.0 → 0.58.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 (257) hide show
  1. package/dist/app/index.js +1 -1
  2. package/dist/broadcasting/index.js +1 -1
  3. package/dist/bun/plugin.js +1 -1
  4. package/dist/bun/preload.js +1 -1
  5. package/dist/{chunk-jdj7k3r9.js → chunk-0a2xgcj3.js} +2 -2
  6. package/dist/{chunk-jdj7k3r9.js.map → chunk-0a2xgcj3.js.map} +1 -1
  7. package/dist/{chunk-3e88tyee.js → chunk-3337e5g0.js} +2 -2
  8. package/dist/{chunk-3e88tyee.js.map → chunk-3337e5g0.js.map} +1 -1
  9. package/dist/chunk-3aa287k7.js +6 -0
  10. package/dist/{chunk-cv9w5cmb.js.map → chunk-3aa287k7.js.map} +2 -2
  11. package/dist/{chunk-01am9k5v.js → chunk-3g5bjvdf.js} +2 -2
  12. package/dist/{chunk-01am9k5v.js.map → chunk-3g5bjvdf.js.map} +1 -1
  13. package/dist/{chunk-w9k9s4wh.js → chunk-3xadx444.js} +2 -2
  14. package/dist/{chunk-w9k9s4wh.js.map → chunk-3xadx444.js.map} +1 -1
  15. package/dist/{chunk-npg72mez.js → chunk-3zxwscmf.js} +2 -2
  16. package/dist/{chunk-kgmr9qxx.js.map → chunk-3zxwscmf.js.map} +1 -1
  17. package/dist/{chunk-64s1pzz1.js → chunk-437085pe.js} +2 -2
  18. package/dist/{chunk-64s1pzz1.js.map → chunk-437085pe.js.map} +1 -1
  19. package/dist/{chunk-eqrd31ye.js → chunk-4yt5x8s2.js} +2 -2
  20. package/dist/{chunk-eqrd31ye.js.map → chunk-4yt5x8s2.js.map} +1 -1
  21. package/dist/{chunk-9r0sb4zn.js → chunk-5athahgr.js} +2 -2
  22. package/dist/{chunk-9r0sb4zn.js.map → chunk-5athahgr.js.map} +1 -1
  23. package/dist/{chunk-g30q4n5y.js → chunk-5n2rvfh3.js} +2 -2
  24. package/dist/{chunk-g30q4n5y.js.map → chunk-5n2rvfh3.js.map} +1 -1
  25. package/dist/{chunk-1zfsgffv.js → chunk-6235kb30.js} +3 -3
  26. package/dist/{chunk-1zfsgffv.js.map → chunk-6235kb30.js.map} +1 -1
  27. package/dist/{chunk-javjeayw.js → chunk-7b0x860b.js} +2 -2
  28. package/dist/{chunk-javjeayw.js.map → chunk-7b0x860b.js.map} +1 -1
  29. package/dist/{chunk-4qwwy968.js → chunk-7ef5n8k2.js} +2 -2
  30. package/dist/{chunk-4qwwy968.js.map → chunk-7ef5n8k2.js.map} +1 -1
  31. package/dist/{chunk-q0waxxz5.js → chunk-7j6wbv12.js} +2 -2
  32. package/dist/{chunk-q0waxxz5.js.map → chunk-7j6wbv12.js.map} +1 -1
  33. package/dist/chunk-86jebsm4.js +9 -0
  34. package/dist/{chunk-kry5vwam.js.map → chunk-86jebsm4.js.map} +3 -3
  35. package/dist/chunk-87qab82w.js +5 -0
  36. package/dist/chunk-87qab82w.js.map +37 -0
  37. package/dist/{chunk-36pg61vt.js → chunk-8gew8b9a.js} +2 -2
  38. package/dist/{chunk-36pg61vt.js.map → chunk-8gew8b9a.js.map} +1 -1
  39. package/dist/{chunk-v6v6sem5.js → chunk-9m2tbf3n.js} +2 -2
  40. package/dist/{chunk-v6v6sem5.js.map → chunk-9m2tbf3n.js.map} +1 -1
  41. package/dist/{chunk-gzdf2025.js → chunk-a2sgjpvq.js} +2 -2
  42. package/dist/{chunk-gzdf2025.js.map → chunk-a2sgjpvq.js.map} +1 -1
  43. package/dist/chunk-b35e128b.js +5 -0
  44. package/dist/{chunk-b50zmz3t.js.map → chunk-b35e128b.js.map} +1 -1
  45. package/dist/{chunk-ct274qts.js → chunk-cyaz97p5.js} +2 -2
  46. package/dist/{chunk-ct274qts.js.map → chunk-cyaz97p5.js.map} +1 -1
  47. package/dist/{chunk-v06qcyj5.js → chunk-d125j8t0.js} +3 -3
  48. package/dist/{chunk-v06qcyj5.js.map → chunk-d125j8t0.js.map} +1 -1
  49. package/dist/{chunk-hs5v3eqj.js → chunk-dgsgjg53.js} +2 -2
  50. package/dist/{chunk-hs5v3eqj.js.map → chunk-dgsgjg53.js.map} +1 -1
  51. package/dist/{chunk-xjy5apyr.js → chunk-eejmhtnc.js} +2 -2
  52. package/dist/{chunk-xjy5apyr.js.map → chunk-eejmhtnc.js.map} +1 -1
  53. package/dist/{chunk-3y75q5a2.js → chunk-fjm4y8bn.js} +2 -2
  54. package/dist/{chunk-3y75q5a2.js.map → chunk-fjm4y8bn.js.map} +1 -1
  55. package/dist/{chunk-9c89q2mz.js → chunk-grdahng8.js} +2 -2
  56. package/dist/{chunk-9c89q2mz.js.map → chunk-grdahng8.js.map} +1 -1
  57. package/dist/{chunk-699z6d8y.js → chunk-gw6agevz.js} +3 -3
  58. package/dist/{chunk-699z6d8y.js.map → chunk-gw6agevz.js.map} +1 -1
  59. package/dist/{chunk-62ke19q4.js → chunk-hppagzz4.js} +4 -4
  60. package/dist/{chunk-62ke19q4.js.map → chunk-hppagzz4.js.map} +1 -1
  61. package/dist/chunk-hwa5sqw5.js +19 -0
  62. package/dist/{chunk-tmnhkphv.js.map → chunk-hwa5sqw5.js.map} +12 -6
  63. package/dist/chunk-hxf1re93.js +4 -0
  64. package/dist/{chunk-vkngcrzq.js.map → chunk-hxf1re93.js.map} +6 -5
  65. package/dist/{chunk-d36dfqxw.js → chunk-j0c6ytkj.js} +3 -3
  66. package/dist/{chunk-d36dfqxw.js.map → chunk-j0c6ytkj.js.map} +1 -1
  67. package/dist/{chunk-kgmr9qxx.js → chunk-jhkjz9jr.js} +2 -2
  68. package/dist/{chunk-npg72mez.js.map → chunk-jhkjz9jr.js.map} +1 -1
  69. package/dist/{chunk-62723jyy.js → chunk-k0fvsyeh.js} +1 -1
  70. package/dist/{chunk-31kcf7dq.js → chunk-keehyx51.js} +2 -2
  71. package/dist/{chunk-31kcf7dq.js.map → chunk-keehyx51.js.map} +1 -1
  72. package/dist/{chunk-enhkf60v.js → chunk-m3xy5xyf.js} +2 -2
  73. package/dist/{chunk-enhkf60v.js.map → chunk-m3xy5xyf.js.map} +1 -1
  74. package/dist/{chunk-c75mymmq.js → chunk-mkfpnymy.js} +1 -1
  75. package/dist/{chunk-rgb69nh1.js → chunk-mwpdp09e.js} +2 -2
  76. package/dist/{chunk-rgb69nh1.js.map → chunk-mwpdp09e.js.map} +1 -1
  77. package/dist/chunk-pmhd6zfc.js +37 -0
  78. package/dist/chunk-pmhd6zfc.js.map +20 -0
  79. package/dist/chunk-qb5mv6pj.js +5 -0
  80. package/dist/chunk-qb5mv6pj.js.map +12 -0
  81. package/dist/{chunk-1pwwrpa3.js → chunk-qgxr0g36.js} +2 -2
  82. package/dist/{chunk-1pwwrpa3.js.map → chunk-qgxr0g36.js.map} +1 -1
  83. package/dist/{chunk-4yafsffx.js → chunk-sy7jbdeb.js} +2 -2
  84. package/dist/{chunk-4yafsffx.js.map → chunk-sy7jbdeb.js.map} +1 -1
  85. package/dist/{chunk-gasdfwva.js → chunk-szss069z.js} +2 -2
  86. package/dist/{chunk-gasdfwva.js.map → chunk-szss069z.js.map} +1 -1
  87. package/dist/{chunk-m0ggfy1m.js → chunk-tss5svjr.js} +2 -2
  88. package/dist/{chunk-m0ggfy1m.js.map → chunk-tss5svjr.js.map} +1 -1
  89. package/dist/{chunk-dzzmqv0j.js → chunk-vr90r27j.js} +2 -2
  90. package/dist/{chunk-dzzmqv0j.js.map → chunk-vr90r27j.js.map} +1 -1
  91. package/dist/{chunk-pvdbrt4z.js → chunk-w62m5f0n.js} +3 -3
  92. package/dist/{chunk-pvdbrt4z.js.map → chunk-w62m5f0n.js.map} +1 -1
  93. package/dist/{chunk-cn2r5jfj.js → chunk-w7rf99w6.js} +2 -2
  94. package/dist/{chunk-cn2r5jfj.js.map → chunk-w7rf99w6.js.map} +1 -1
  95. package/dist/{chunk-tja0c815.js → chunk-wbrj0gya.js} +2 -2
  96. package/dist/{chunk-tja0c815.js.map → chunk-wbrj0gya.js.map} +1 -1
  97. package/dist/{chunk-rsdg619q.js → chunk-xdv1b8mr.js} +2 -2
  98. package/dist/{chunk-rsdg619q.js.map → chunk-xdv1b8mr.js.map} +1 -1
  99. package/dist/{chunk-h3mwgbg7.js → chunk-xey9cbap.js} +2 -2
  100. package/dist/{chunk-h3mwgbg7.js.map → chunk-xey9cbap.js.map} +1 -1
  101. package/dist/{chunk-wgpa04jb.js → chunk-xzk827r3.js} +2 -2
  102. package/dist/{chunk-wgpa04jb.js.map → chunk-xzk827r3.js.map} +1 -1
  103. package/dist/{chunk-x14sk95v.js → chunk-y6a8r2bn.js} +3 -3
  104. package/dist/{chunk-x14sk95v.js.map → chunk-y6a8r2bn.js.map} +1 -1
  105. package/dist/{chunk-33wjsw4r.js → chunk-yed5whgs.js} +3 -3
  106. package/dist/{chunk-33wjsw4r.js.map → chunk-yed5whgs.js.map} +1 -1
  107. package/dist/{chunk-02gdzs5t.js → chunk-yf7vz71n.js} +1 -1
  108. package/dist/{chunk-y9fp58bg.js → chunk-yjzs247s.js} +2 -2
  109. package/dist/{chunk-y9fp58bg.js.map → chunk-yjzs247s.js.map} +1 -1
  110. package/dist/{chunk-kgg1eqne.js → chunk-yy0eb9wn.js} +2 -2
  111. package/dist/{chunk-kgg1eqne.js.map → chunk-yy0eb9wn.js.map} +1 -1
  112. package/dist/{chunk-4xx78ba9.js → chunk-zbxgbr12.js} +2 -2
  113. package/dist/{chunk-4xx78ba9.js.map → chunk-zbxgbr12.js.map} +1 -1
  114. package/dist/{chunk-8k1zqrvh.js → chunk-zh2egcyb.js} +2 -2
  115. package/dist/{chunk-8k1zqrvh.js.map → chunk-zh2egcyb.js.map} +1 -1
  116. package/dist/chunks/ThemeProvider-li1J_igh.js.map +1 -1
  117. package/dist/client/ClientRouter.d.ts.map +1 -1
  118. package/dist/client/ProgressManager.d.ts +1 -1
  119. package/dist/client/RouteStateContext.d.ts +9 -0
  120. package/dist/client/RouteStateContext.d.ts.map +1 -1
  121. package/dist/client/ServerDataProvider.d.ts +7 -0
  122. package/dist/client/ServerDataProvider.d.ts.map +1 -1
  123. package/dist/client/index.d.ts +2 -1
  124. package/dist/client/index.d.ts.map +1 -1
  125. package/dist/client/index.js +68 -10
  126. package/dist/client/index.js.map +1 -1
  127. package/dist/client/rpc.d.ts +42 -0
  128. package/dist/client/rpc.d.ts.map +1 -1
  129. package/dist/client/useFeature.d.ts +40 -0
  130. package/dist/client/useFeature.d.ts.map +1 -0
  131. package/dist/config/index.js +1 -1
  132. package/dist/console/run.js +2 -2
  133. package/dist/console/run.js.map +1 -1
  134. package/dist/container/index.js +2 -2
  135. package/dist/container/index.js.map +1 -1
  136. package/dist/database/index.js +2 -2
  137. package/dist/database/index.js.map +1 -1
  138. package/dist/email/index.js +2 -2
  139. package/dist/email/index.js.map +1 -1
  140. package/dist/facades/Features.d.ts +57 -0
  141. package/dist/facades/Features.d.ts.map +1 -0
  142. package/dist/facades/index.d.ts +1 -0
  143. package/dist/facades/index.d.ts.map +1 -1
  144. package/dist/facades/index.js +2 -2
  145. package/dist/facades/index.js.map +1 -1
  146. package/dist/foundation/index.js +2 -2
  147. package/dist/foundation/index.js.map +1 -1
  148. package/dist/gemi.d.ts +13 -5
  149. package/dist/http/ApiRouter.d.ts +3 -2
  150. package/dist/http/ApiRouter.d.ts.map +1 -1
  151. package/dist/http/HttpRequest.d.ts +4 -0
  152. package/dist/http/HttpRequest.d.ts.map +1 -1
  153. package/dist/http/ViewRouter.d.ts +127 -4
  154. package/dist/http/ViewRouter.d.ts.map +1 -1
  155. package/dist/http/index.d.ts +1 -0
  156. package/dist/http/index.d.ts.map +1 -1
  157. package/dist/http/index.js +2 -2
  158. package/dist/http/index.js.map +1 -1
  159. package/dist/http/middlewareList.d.ts +25 -0
  160. package/dist/http/middlewareList.d.ts.map +1 -0
  161. package/dist/http/requestContext.d.ts +57 -0
  162. package/dist/http/requestContext.d.ts.map +1 -1
  163. package/dist/i18n/dictionaryRuntime.js +2 -2
  164. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  165. package/dist/i18n/index.js +2 -2
  166. package/dist/i18n/index.js.map +1 -1
  167. package/dist/ide/typescript-plugin/index.js +1206 -0
  168. package/dist/ide/typescript-plugin/index.js.map +17 -0
  169. package/dist/kernel/index.js +3 -3
  170. package/dist/kernel/index.js.map +3 -3
  171. package/dist/kernel/providers.d.ts +16 -4
  172. package/dist/kernel/providers.d.ts.map +1 -1
  173. package/dist/orm/context.d.ts +65 -0
  174. package/dist/orm/context.d.ts.map +1 -1
  175. package/dist/orm/index.js +2 -2
  176. package/dist/orm/index.js.map +1 -1
  177. package/dist/server/index.js +2 -2
  178. package/dist/server/index.js.map +1 -1
  179. package/dist/services/discovery.d.ts +27 -0
  180. package/dist/services/discovery.d.ts.map +1 -1
  181. package/dist/services/events/Event.d.ts +208 -0
  182. package/dist/services/events/Event.d.ts.map +1 -0
  183. package/dist/services/events/EventManager.d.ts +285 -0
  184. package/dist/services/events/EventManager.d.ts.map +1 -0
  185. package/dist/services/events/EventServiceProvider.d.ts +46 -0
  186. package/dist/services/events/EventServiceProvider.d.ts.map +1 -0
  187. package/dist/services/events/FakeEventManager.d.ts +155 -0
  188. package/dist/services/events/FakeEventManager.d.ts.map +1 -0
  189. package/dist/services/events/FakeEventManager.test-d.d.ts +2 -0
  190. package/dist/services/events/FakeEventManager.test-d.d.ts.map +1 -0
  191. package/dist/services/events/Listener.d.ts +189 -0
  192. package/dist/services/events/Listener.d.ts.map +1 -0
  193. package/dist/services/events/Listener.test-d.d.ts +2 -0
  194. package/dist/services/events/Listener.test-d.d.ts.map +1 -0
  195. package/dist/services/events/config.d.ts +55 -0
  196. package/dist/services/events/config.d.ts.map +1 -0
  197. package/dist/services/events/listenerJob.d.ts +43 -0
  198. package/dist/services/events/listenerJob.d.ts.map +1 -0
  199. package/dist/services/features/FeatureFlagStore.d.ts +60 -0
  200. package/dist/services/features/FeatureFlagStore.d.ts.map +1 -0
  201. package/dist/services/features/FeatureManager.d.ts +82 -0
  202. package/dist/services/features/FeatureManager.d.ts.map +1 -0
  203. package/dist/services/features/FeaturesServiceProvider.d.ts +6 -0
  204. package/dist/services/features/FeaturesServiceProvider.d.ts.map +1 -0
  205. package/dist/services/features/bucket.d.ts +57 -0
  206. package/dist/services/features/bucket.d.ts.map +1 -0
  207. package/dist/services/features/config.d.ts +57 -0
  208. package/dist/services/features/config.d.ts.map +1 -0
  209. package/dist/services/features/context.d.ts +31 -0
  210. package/dist/services/features/context.d.ts.map +1 -0
  211. package/dist/services/features/defineFeature.d.ts +145 -0
  212. package/dist/services/features/defineFeature.d.ts.map +1 -0
  213. package/dist/services/features/evaluate.d.ts +74 -0
  214. package/dist/services/features/evaluate.d.ts.map +1 -0
  215. package/dist/services/features/sources/DatabaseFeatureFlagSource.d.ts +19 -0
  216. package/dist/services/features/sources/DatabaseFeatureFlagSource.d.ts.map +1 -0
  217. package/dist/services/features/sources/FeatureFlagSource.d.ts +30 -0
  218. package/dist/services/features/sources/FeatureFlagSource.d.ts.map +1 -0
  219. package/dist/services/features/sources/StaticFeatureFlagSource.d.ts +24 -0
  220. package/dist/services/features/sources/StaticFeatureFlagSource.d.ts.map +1 -0
  221. package/dist/services/features/types.d.ts +63 -0
  222. package/dist/services/features/types.d.ts.map +1 -0
  223. package/dist/services/index.d.ts +18 -1
  224. package/dist/services/index.d.ts.map +1 -1
  225. package/dist/services/index.js +8 -8
  226. package/dist/services/index.js.map +8 -4
  227. package/dist/services/queue/QueueManager.d.ts +31 -0
  228. package/dist/services/queue/QueueManager.d.ts.map +1 -1
  229. package/dist/services/router/ViewRouteDispatcher.d.ts +8 -0
  230. package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
  231. package/dist/services/router/createFlatViewRoutes.d.ts +14 -0
  232. package/dist/services/router/createFlatViewRoutes.d.ts.map +1 -1
  233. package/dist/services/router/streamQueryInjection.d.ts.map +1 -1
  234. package/dist/support/index.js +2 -2
  235. package/dist/support/index.js.map +1 -1
  236. package/dist/testing/Page.d.ts +12 -0
  237. package/dist/testing/Page.d.ts.map +1 -1
  238. package/dist/testing/index.d.ts +24 -0
  239. package/dist/testing/index.d.ts.map +1 -1
  240. package/dist/testing/index.js +7 -3
  241. package/dist/testing/index.js.map +1 -1
  242. package/ide/typescript-plugin/package.json +5 -0
  243. package/package.json +4 -2
  244. package/dist/chunk-4t80js0n.js +0 -33
  245. package/dist/chunk-4t80js0n.js.map +0 -18
  246. package/dist/chunk-98a576s9.js +0 -5
  247. package/dist/chunk-98a576s9.js.map +0 -30
  248. package/dist/chunk-b50zmz3t.js +0 -5
  249. package/dist/chunk-cv9w5cmb.js +0 -6
  250. package/dist/chunk-f9mfw82d.js +0 -5
  251. package/dist/chunk-f9mfw82d.js.map +0 -12
  252. package/dist/chunk-kry5vwam.js +0 -9
  253. package/dist/chunk-tmnhkphv.js +0 -19
  254. package/dist/chunk-vkngcrzq.js +0 -4
  255. /package/dist/{chunk-62723jyy.js.map → chunk-k0fvsyeh.js.map} +0 -0
  256. /package/dist/{chunk-c75mymmq.js.map → chunk-mkfpnymy.js.map} +0 -0
  257. /package/dist/{chunk-02gdzs5t.js.map → chunk-yf7vz71n.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{w as r}from"./chunk-tja0c815.js";import{N as mc}from"./chunk-9c89q2mz.js";import"./chunk-dzzmqv0j.js";import"./chunk-m0ggfy1m.js";import{Y as _}from"./chunk-h3mwgbg7.js";import{ef as u,hf as O}from"./chunk-kgmr9qxx.js";import{Buffer as hc}from"buffer";import{request as Yc}from"http";function E(c){return new Promise((I,x)=>{let N=Yc({method:"GET",...c,hostname:c.hostname?.replace(/^\[(.+)\]$/,"$1")});N.on("error",(T)=>{x(Object.assign(new K.ProviderError("Unable to connect to instance metadata service"),T)),N.destroy()}),N.on("timeout",()=>{x(new K.ProviderError("TimeoutError from instance metadata service")),N.destroy()}),N.on("response",(T)=>{let{statusCode:y=400}=T;if(y<200||300<=y)x(Object.assign(new K.ProviderError("Error response received from instance metadata service"),{statusCode:y})),N.destroy();let $=[];T.on("data",(w)=>{$.push(w)}),T.on("end",()=>{I(hc.concat($)),N.destroy()})}),N.end()})}var K;var D=O(()=>{K=u(_(),1)});var G=(c)=>Boolean(c)&&typeof c==="object"&&typeof c.AccessKeyId==="string"&&typeof c.SecretAccessKey==="string"&&typeof c.Token==="string"&&typeof c.Expiration==="string",L=(c)=>({accessKeyId:c.AccessKeyId,secretAccessKey:c.SecretAccessKey,sessionToken:c.Token,expiration:new Date(c.Expiration),...c.AccountId&&{accountId:c.AccountId}});var W=()=>{};var Hc=1000,qc=0,Q=({maxRetries:c=0,timeout:I=1000})=>({maxRetries:c,timeout:I});var X=()=>{};var v=(c,I)=>{let x=c();for(let N=0;N<I;N++)x=x.catch(c);return x};var b=()=>{};import{parse as Sc}from"url";var z,H="AWS_CONTAINER_CREDENTIALS_FULL_URI",q="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",M="AWS_CONTAINER_AUTHORIZATION_TOKEN",kc=(c={})=>{let{timeout:I,maxRetries:x}=Q(c);return()=>v(async()=>{let N=await jc({logger:c.logger}),T=JSON.parse(await fc(I,N));if(!G(T))throw new z.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:c.logger});return L(T)},x)},fc=async(c,I)=>{if(process.env[M])I.headers={...I.headers,Authorization:process.env[M]};return(await E({...I,timeout:c})).toString()},uc="169.254.170.2",Ec,$c,jc=async({logger:c})=>{if(process.env[q])return{hostname:uc,path:process.env[q]};if(process.env[H]){let I=Sc(process.env[H]);if(!I.hostname||!(I.hostname in Ec))throw new z.CredentialsProviderError(`${I.hostname} is not a valid container metadata service hostname`,{tryNextLink:!1,logger:c});if(!I.protocol||!(I.protocol in $c))throw new z.CredentialsProviderError(`${I.protocol} is not a valid container metadata service protocol`,{tryNextLink:!1,logger:c});return{...I,port:I.port?parseInt(I.port,10):void 0}}throw new z.CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${q} or ${H} environment variable is set`,{tryNextLink:!1,logger:c})};var p=O(()=>{D();W();X();b();z=u(_(),1),Ec={localhost:!0,"127.0.0.1":!0},$c={"http:":!0,"https:":!0}});var C,Z;var a=O(()=>{C=u(_(),1);Z=class Z extends C.CredentialsProviderError{tryNextLink;name="InstanceMetadataV1FallbackError";constructor(c,I=!0){super(c,I);this.tryNextLink=I,Object.setPrototypeOf(this,Z.prototype)}}});var J;var B=O(()=>{(function(c){c.IPv4="http://169.254.169.254",c.IPv6="http://[fd00:ec2::254]"})(J||(J={}))});var n;var o=O(()=>{n={environmentVariableSelector:(c)=>c.AWS_EC2_METADATA_SERVICE_ENDPOINT,configFileSelector:(c)=>c.ec2_metadata_service_endpoint,default:void 0}});var f;var t=O(()=>{(function(c){c.IPv4="IPv4",c.IPv6="IPv6"})(f||(f={}))});var Ac="AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",Jc="ec2_metadata_service_endpoint_mode",s;var g=O(()=>{t();s={environmentVariableSelector:(c)=>c[Ac],configFileSelector:(c)=>c[Jc],default:f.IPv4}});var U,l,F=async()=>l.parseUrl(await vc()||await zc()),vc=async()=>U.loadConfig(n)(),zc=async()=>{let c=await U.loadConfig(s)();switch(c){case f.IPv4:return J.IPv4;case f.IPv6:return J.IPv6;default:throw Error(`Unsupported endpoint mode: ${c}. Select from ${Object.values(f)}`)}};var P=O(()=>{B();o();t();g();U=u(r(),1),l=u(mc(),1)});var V=(c,I)=>{let x=300+Math.floor(Math.random()*300),N=new Date(Date.now()+x*1000);I.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(N)}.
2
+ import{w as r}from"./chunk-wbrj0gya.js";import{N as mc}from"./chunk-grdahng8.js";import"./chunk-vr90r27j.js";import"./chunk-tss5svjr.js";import{Y as _}from"./chunk-xey9cbap.js";import{Df as u,Gf as O}from"./chunk-jhkjz9jr.js";import{Buffer as hc}from"buffer";import{request as Yc}from"http";function E(c){return new Promise((I,x)=>{let N=Yc({method:"GET",...c,hostname:c.hostname?.replace(/^\[(.+)\]$/,"$1")});N.on("error",(T)=>{x(Object.assign(new K.ProviderError("Unable to connect to instance metadata service"),T)),N.destroy()}),N.on("timeout",()=>{x(new K.ProviderError("TimeoutError from instance metadata service")),N.destroy()}),N.on("response",(T)=>{let{statusCode:y=400}=T;if(y<200||300<=y)x(Object.assign(new K.ProviderError("Error response received from instance metadata service"),{statusCode:y})),N.destroy();let $=[];T.on("data",(w)=>{$.push(w)}),T.on("end",()=>{I(hc.concat($)),N.destroy()})}),N.end()})}var K;var D=O(()=>{K=u(_(),1)});var G=(c)=>Boolean(c)&&typeof c==="object"&&typeof c.AccessKeyId==="string"&&typeof c.SecretAccessKey==="string"&&typeof c.Token==="string"&&typeof c.Expiration==="string",L=(c)=>({accessKeyId:c.AccessKeyId,secretAccessKey:c.SecretAccessKey,sessionToken:c.Token,expiration:new Date(c.Expiration),...c.AccountId&&{accountId:c.AccountId}});var W=()=>{};var Hc=1000,qc=0,Q=({maxRetries:c=0,timeout:I=1000})=>({maxRetries:c,timeout:I});var X=()=>{};var v=(c,I)=>{let x=c();for(let N=0;N<I;N++)x=x.catch(c);return x};var b=()=>{};import{parse as Sc}from"url";var z,H="AWS_CONTAINER_CREDENTIALS_FULL_URI",q="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",M="AWS_CONTAINER_AUTHORIZATION_TOKEN",kc=(c={})=>{let{timeout:I,maxRetries:x}=Q(c);return()=>v(async()=>{let N=await jc({logger:c.logger}),T=JSON.parse(await fc(I,N));if(!G(T))throw new z.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:c.logger});return L(T)},x)},fc=async(c,I)=>{if(process.env[M])I.headers={...I.headers,Authorization:process.env[M]};return(await E({...I,timeout:c})).toString()},uc="169.254.170.2",Ec,$c,jc=async({logger:c})=>{if(process.env[q])return{hostname:uc,path:process.env[q]};if(process.env[H]){let I=Sc(process.env[H]);if(!I.hostname||!(I.hostname in Ec))throw new z.CredentialsProviderError(`${I.hostname} is not a valid container metadata service hostname`,{tryNextLink:!1,logger:c});if(!I.protocol||!(I.protocol in $c))throw new z.CredentialsProviderError(`${I.protocol} is not a valid container metadata service protocol`,{tryNextLink:!1,logger:c});return{...I,port:I.port?parseInt(I.port,10):void 0}}throw new z.CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${q} or ${H} environment variable is set`,{tryNextLink:!1,logger:c})};var p=O(()=>{D();W();X();b();z=u(_(),1),Ec={localhost:!0,"127.0.0.1":!0},$c={"http:":!0,"https:":!0}});var C,Z;var a=O(()=>{C=u(_(),1);Z=class Z extends C.CredentialsProviderError{tryNextLink;name="InstanceMetadataV1FallbackError";constructor(c,I=!0){super(c,I);this.tryNextLink=I,Object.setPrototypeOf(this,Z.prototype)}}});var J;var B=O(()=>{(function(c){c.IPv4="http://169.254.169.254",c.IPv6="http://[fd00:ec2::254]"})(J||(J={}))});var n;var o=O(()=>{n={environmentVariableSelector:(c)=>c.AWS_EC2_METADATA_SERVICE_ENDPOINT,configFileSelector:(c)=>c.ec2_metadata_service_endpoint,default:void 0}});var f;var t=O(()=>{(function(c){c.IPv4="IPv4",c.IPv6="IPv6"})(f||(f={}))});var Ac="AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",Jc="ec2_metadata_service_endpoint_mode",s;var g=O(()=>{t();s={environmentVariableSelector:(c)=>c[Ac],configFileSelector:(c)=>c[Jc],default:f.IPv4}});var U,l,F=async()=>l.parseUrl(await vc()||await zc()),vc=async()=>U.loadConfig(n)(),zc=async()=>{let c=await U.loadConfig(s)();switch(c){case f.IPv4:return J.IPv4;case f.IPv6:return J.IPv6;default:throw Error(`Unsupported endpoint mode: ${c}. Select from ${Object.values(f)}`)}};var P=O(()=>{B();o();t();g();U=u(r(),1),l=u(mc(),1)});var V=(c,I)=>{let x=300+Math.floor(Math.random()*300),N=new Date(Date.now()+x*1000);I.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(N)}.
3
3
  For more information, please visit: https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html`);let T=c.originalExpiration??c.expiration;return{...c,...T?{originalExpiration:T}:{},expiration:N}};var d=()=>{};var e=(c,I={})=>{let x=I?.logger||console,N;return async()=>{let T;try{if(T=await c(),T.expiration&&T.expiration.getTime()<Date.now())T=V(T,x)}catch(y){if(N)x.warn("Credential renew failed: ",y),T=V(N,x);else throw y}return N=T,T}};var i=O(()=>{d()});var Nc,k,Tc="/latest/meta-data/iam/security-credentials/",Kc="/latest/api/token",R="AWS_EC2_METADATA_V1_DISABLED",cc="ec2_metadata_v1_disabled",Ic="x-aws-ec2-metadata-token",YI=(c={})=>e(_c(c),{logger:c.logger}),_c=(c={})=>{let I=!1,{logger:x,profile:N}=c,{timeout:T,maxRetries:y}=Q(c),$=async(w,j)=>{if(I||j.headers?.[Ic]==null){let h=!1,Y=!1,wc=await Nc.loadConfig({environmentVariableSelector:(S)=>{let A=S[R];if(Y=!!A&&A!=="false",A===void 0)throw new k.CredentialsProviderError(`${R} not set in env, checking config file next.`,{logger:c.logger});return Y},configFileSelector:(S)=>{let A=S[cc];return h=!!A&&A!=="false",h},default:!1},{profile:N})();if(c.ec2MetadataV1Disabled||wc){let S=[];if(c.ec2MetadataV1Disabled)S.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");if(h)S.push(`config file profile (${cc})`);if(Y)S.push(`process environment variable (${R})`);throw new Z(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${S.join(", ")}].`)}}let yc=(await v(async()=>{let h;try{h=await Gc(j)}catch(Y){if(Y.statusCode===401)I=!1;throw Y}return h},w)).trim();return v(async()=>{let h;try{h=await Lc(yc,j,c)}catch(Y){if(Y.statusCode===401)I=!1;throw Y}return h},w)};return async()=>{let w=await F();if(I)return x?.debug("AWS SDK Instance Metadata","using v1 fallback (no token fetch)"),$(y,{...w,timeout:T});else{let j;try{j=(await Dc({...w,timeout:T})).toString()}catch(m){if(m?.statusCode===400)throw Object.assign(m,{message:"EC2 Metadata token request returned error"});else if(m.message==="TimeoutError"||[403,404,405].includes(m.statusCode))I=!0;return x?.debug("AWS SDK Instance Metadata","using v1 fallback (initial)"),$(y,{...w,timeout:T})}return $(y,{...w,headers:{[Ic]:j},timeout:T})}}},Dc=async(c)=>E({...c,path:Kc,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"21600"}}),Gc=async(c)=>(await E({...c,path:Tc})).toString(),Lc=async(c,I,x)=>{let N=JSON.parse((await E({...I,path:Tc+c})).toString());if(!G(N))throw new k.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:x.logger});return L(N)};var xc=O(()=>{a();D();W();X();b();P();i();Nc=u(r(),1),k=u(_(),1)});var Oc=()=>{};var Qc=O(()=>{D();P();B();p();xc();X();Oc()});Qc();export{Q as providerConfigFromInit,E as httpRequest,F as getInstanceMetadataEndpoint,YI as fromInstanceMetadata,kc as fromContainerMetadata,J as Endpoint,q as ENV_CMDS_RELATIVE_URI,H as ENV_CMDS_FULL_URI,M as ENV_CMDS_AUTH_TOKEN,Hc as DEFAULT_TIMEOUT,qc as DEFAULT_MAX_RETRIES};
4
4
 
5
- //# debugId=CE3FA0E72CE06DFA64756E2164756E21
5
+ //# debugId=ACB727322E86353964756E2164756E21
@@ -19,6 +19,6 @@
19
19
  "export * from \"./fromContainerMetadata\";\nexport * from \"./fromInstanceMetadata\";\nexport * from \"./remoteProvider/RemoteProviderInit\";\nexport * from \"./types\";\nexport { httpRequest } from \"./remoteProvider/httpRequest\";\nexport { getInstanceMetadataEndpoint } from \"./utils/getInstanceMetadataEndpoint\";\nexport { Endpoint } from \"./config/Endpoint\";\n"
20
20
  ],
21
21
  "mappings": ";gQACA,WAAS,UACT,YAAS,QACF,GAAS,CAAW,CAAC,EAAS,CACjC,OAAO,IAAI,QAAQ,CAAC,EAAS,IAAW,CACpC,IAAM,EAAM,GAAQ,CAChB,OAAQ,SACL,EACH,SAAU,EAAQ,UAAU,QAAQ,aAAc,IAAI,CAC1D,CAAC,EACD,EAAI,GAAG,QAAS,CAAC,IAAQ,CACrB,EAAO,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AAY,IACjD,EACH,KAAM,GACN,OAAQ,MACR,QAAS,CACL,uCAAwC,OAC5C,CACJ,CAAC,EACK,GAAa,MAAO,KAAa,MAAM,EAAY,IAAK,EAAS,KAAM,EAAU,CAAC,GAAG,SAAS,EAC9F,GAA4B,MAAO,EAAS,EAAS,IAAS,CAChE,IAAM,EAAsB,KAAK,OAAO,MAAM,EAAY,IACnD,EACH,KAAM,GAAY,CACtB,CAAC,GAAG,SAAS,CAAC,EACd,GAAI,CAAC,EAAkB,CAAmB,EACtC,MAAM,IAAI,2BAAyB,4DAA6D,CAC5F,OAAQ,EAAK,MACjB,CAAC,EAEL,OAAO,EAAoB,CAAmB,iBAlIlD,IACA,IACA,IACA,IACA,IACA,IACA,IARA,YACA,yCCGA,IACA,IACA,IANA,IACA,KACA,IACA",
22
- "debugId": "CE3FA0E72CE06DFA64756E2164756E21",
22
+ "debugId": "ACB727322E86353964756E2164756E21",
23
23
  "names": []
24
24
  }
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{M}from"./chunk-v6v6sem5.js";import{hf as E}from"./chunk-kgmr9qxx.js";class x{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:i,serializer:n,deserializer:o,serdeContext:c,defaultContentType:y}){this.marshaller=i,this.serializer=n,this.deserializer=o,this.serdeContext=c,this.defaultContentType=y}async serializeEventStream({eventStream:i,requestSchema:n,initialRequest:o}){let c=this.marshaller,y=n.getEventStreamMember(),p=n.getMemberSchema(y),d=this.serializer,f=this.defaultContentType,h=Symbol("initialRequestMarker"),S={async*[Symbol.asyncIterator](){if(o){let r={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:f}};d.write(n,o);let t=d.flush();yield{[h]:!0,headers:r,body:t}}for await(let r of i)yield r}};return c.serialize(S,(r)=>{if(r[h])return{headers:r.headers,body:r.body};let t=Object.keys(r).find((s)=>{return s!=="__type"})??"",{additionalHeaders:e,body:a,eventType:l,explicitPayloadContentType:m}=this.writeEventBody(t,p,r);return{headers:{":event-type":{type:"string",value:l},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:m??f},...e},body:a}})}async deserializeEventStream({response:i,responseSchema:n,initialResponseContainer:o}){let c=this.marshaller,y=n.getEventStreamMember(),d=n.getMemberSchema(y).getMemberSchemas(),f=Symbol("initialResponseMarker"),h=c.deserialize(i.body,async(t)=>{let e=Object.keys(t).find((l)=>{return l!=="__type"})??"",a=t[e].body;if(e==="initial-response"){let l=await this.deserializer.read(n,a);return delete l[y],{[f]:!0,...l}}else if(e in d){let l=d[e];if(l.isStructSchema()){let m={},u=!1;for(let[s,g]of l.structIterator()){let{eventHeader:v,eventPayload:w}=g.getMergedTraits();if(u=u||Boolean(v||w),w){if(g.isBlobSchema())m[s]=a;else if(g.isStringSchema())m[s]=(this.serdeContext?.utf8Encoder??z.toUtf8)(a);else if(g.isStructSchema())m[s]=await this.deserializer.read(g,a)}else if(v){let b=t[e].headers[s]?.value;if(b!=null)if(g.isNumericSchema())if(b&&typeof b==="object"&&"bytes"in b)m[s]=BigInt(b.toString());else m[s]=Number(b);else m[s]=b}}if(u)return{[e]:m};if(a.byteLength===0)return{[e]:{}}}return{[e]:await this.deserializer.read(l,a)}}else return{$unknown:t}}),S=h[Symbol.asyncIterator](),r=await S.next();if(r.done)return h;if(r.value?.[f]){if(!n)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let[t,e]of Object.entries(r.value))o[t]=e}return{async*[Symbol.asyncIterator](){if(!r?.value?.[f])yield r.value;while(!0){let{done:t,value:e}=await S.next();if(t)break;yield e}}}}writeEventBody(i,n,o){let c=this.serializer,y=i,p=null,d,f=(()=>{return n.getSchema()[4].includes(i)})(),h={};if(!f){let[t,e]=o[i];y=t,c.write(15,e)}else{let t=n.getMemberSchema(i);if(t.isStructSchema()){for(let[e,a]of t.structIterator()){let{eventHeader:l,eventPayload:m}=a.getMergedTraits();if(m)p=e;else if(l){let u=o[i][e],s="binary";if(a.isNumericSchema())if(-2147483648<=u&&u<=2147483647)s="integer";else s="long";else if(a.isTimestampSchema())s="timestamp";else if(a.isStringSchema())s="string";else if(a.isBooleanSchema())s="boolean";if(u!=null)h[e]={type:s,value:u},delete o[i][e]}}if(p!==null){let e=t.getMemberSchema(p);if(e.isBlobSchema())d="application/octet-stream";else if(e.isStringSchema())d="text/plain";c.write(e,o[i][p])}else c.write(t,o[i])}else if(t.isUnitSchema())c.write(t,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let S=c.flush()??new Uint8Array;return{body:typeof S==="string"?(this.serdeContext?.utf8Decoder??z.fromUtf8)(S):S,eventType:y,explicitPayloadContentType:d,additionalHeaders:h}}}var z,T;var C=E(()=>{z=M();T=x});C();export{T as EventStreamSerde};export default {get EventStreamSerde(){return T}};
2
+ import{M}from"./chunk-9m2tbf3n.js";import{Gf as E}from"./chunk-jhkjz9jr.js";class x{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:i,serializer:n,deserializer:o,serdeContext:c,defaultContentType:y}){this.marshaller=i,this.serializer=n,this.deserializer=o,this.serdeContext=c,this.defaultContentType=y}async serializeEventStream({eventStream:i,requestSchema:n,initialRequest:o}){let c=this.marshaller,y=n.getEventStreamMember(),p=n.getMemberSchema(y),d=this.serializer,f=this.defaultContentType,h=Symbol("initialRequestMarker"),S={async*[Symbol.asyncIterator](){if(o){let r={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:f}};d.write(n,o);let t=d.flush();yield{[h]:!0,headers:r,body:t}}for await(let r of i)yield r}};return c.serialize(S,(r)=>{if(r[h])return{headers:r.headers,body:r.body};let t=Object.keys(r).find((s)=>{return s!=="__type"})??"",{additionalHeaders:e,body:a,eventType:l,explicitPayloadContentType:m}=this.writeEventBody(t,p,r);return{headers:{":event-type":{type:"string",value:l},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:m??f},...e},body:a}})}async deserializeEventStream({response:i,responseSchema:n,initialResponseContainer:o}){let c=this.marshaller,y=n.getEventStreamMember(),d=n.getMemberSchema(y).getMemberSchemas(),f=Symbol("initialResponseMarker"),h=c.deserialize(i.body,async(t)=>{let e=Object.keys(t).find((l)=>{return l!=="__type"})??"",a=t[e].body;if(e==="initial-response"){let l=await this.deserializer.read(n,a);return delete l[y],{[f]:!0,...l}}else if(e in d){let l=d[e];if(l.isStructSchema()){let m={},u=!1;for(let[s,g]of l.structIterator()){let{eventHeader:v,eventPayload:w}=g.getMergedTraits();if(u=u||Boolean(v||w),w){if(g.isBlobSchema())m[s]=a;else if(g.isStringSchema())m[s]=(this.serdeContext?.utf8Encoder??z.toUtf8)(a);else if(g.isStructSchema())m[s]=await this.deserializer.read(g,a)}else if(v){let b=t[e].headers[s]?.value;if(b!=null)if(g.isNumericSchema())if(b&&typeof b==="object"&&"bytes"in b)m[s]=BigInt(b.toString());else m[s]=Number(b);else m[s]=b}}if(u)return{[e]:m};if(a.byteLength===0)return{[e]:{}}}return{[e]:await this.deserializer.read(l,a)}}else return{$unknown:t}}),S=h[Symbol.asyncIterator](),r=await S.next();if(r.done)return h;if(r.value?.[f]){if(!n)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let[t,e]of Object.entries(r.value))o[t]=e}return{async*[Symbol.asyncIterator](){if(!r?.value?.[f])yield r.value;while(!0){let{done:t,value:e}=await S.next();if(t)break;yield e}}}}writeEventBody(i,n,o){let c=this.serializer,y=i,p=null,d,f=(()=>{return n.getSchema()[4].includes(i)})(),h={};if(!f){let[t,e]=o[i];y=t,c.write(15,e)}else{let t=n.getMemberSchema(i);if(t.isStructSchema()){for(let[e,a]of t.structIterator()){let{eventHeader:l,eventPayload:m}=a.getMergedTraits();if(m)p=e;else if(l){let u=o[i][e],s="binary";if(a.isNumericSchema())if(-2147483648<=u&&u<=2147483647)s="integer";else s="long";else if(a.isTimestampSchema())s="timestamp";else if(a.isStringSchema())s="string";else if(a.isBooleanSchema())s="boolean";if(u!=null)h[e]={type:s,value:u},delete o[i][e]}}if(p!==null){let e=t.getMemberSchema(p);if(e.isBlobSchema())d="application/octet-stream";else if(e.isStringSchema())d="text/plain";c.write(e,o[i][p])}else c.write(t,o[i])}else if(t.isUnitSchema())c.write(t,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let S=c.flush()??new Uint8Array;return{body:typeof S==="string"?(this.serdeContext?.utf8Decoder??z.fromUtf8)(S):S,eventType:y,explicitPayloadContentType:d,additionalHeaders:h}}}var z,T;var C=E(()=>{z=M();T=x});C();export{T as EventStreamSerde};export default {get EventStreamSerde(){return T}};
3
3
 
4
- //# debugId=E0D47C34ED80807164756E2164756E21
4
+ //# debugId=539E7A834F9F9CB364756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "'use strict';\n\nvar utilUtf8 = require('@smithy/util-utf8');\n\nclass EventStreamSerde {\n marshaller;\n serializer;\n deserializer;\n serdeContext;\n defaultContentType;\n constructor({ marshaller, serializer, deserializer, serdeContext, defaultContentType, }) {\n this.marshaller = marshaller;\n this.serializer = serializer;\n this.deserializer = deserializer;\n this.serdeContext = serdeContext;\n this.defaultContentType = defaultContentType;\n }\n async serializeEventStream({ eventStream, requestSchema, initialRequest, }) {\n const marshaller = this.marshaller;\n const eventStreamMember = requestSchema.getEventStreamMember();\n const unionSchema = requestSchema.getMemberSchema(eventStreamMember);\n const serializer = this.serializer;\n const defaultContentType = this.defaultContentType;\n const initialRequestMarker = Symbol(\"initialRequestMarker\");\n const eventStreamIterable = {\n async *[Symbol.asyncIterator]() {\n if (initialRequest) {\n const headers = {\n \":event-type\": { type: \"string\", value: \"initial-request\" },\n \":message-type\": { type: \"string\", value: \"event\" },\n \":content-type\": { type: \"string\", value: defaultContentType },\n };\n serializer.write(requestSchema, initialRequest);\n const body = serializer.flush();\n yield {\n [initialRequestMarker]: true,\n headers,\n body,\n };\n }\n for await (const page of eventStream) {\n yield page;\n }\n },\n };\n return marshaller.serialize(eventStreamIterable, (event) => {\n if (event[initialRequestMarker]) {\n return {\n headers: event.headers,\n body: event.body,\n };\n }\n const unionMember = Object.keys(event).find((key) => {\n return key !== \"__type\";\n }) ?? \"\";\n const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody(unionMember, unionSchema, event);\n const headers = {\n \":event-type\": { type: \"string\", value: eventType },\n \":message-type\": { type: \"string\", value: \"event\" },\n \":content-type\": { type: \"string\", value: explicitPayloadContentType ?? defaultContentType },\n ...additionalHeaders,\n };\n return {\n headers,\n body,\n };\n });\n }\n async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) {\n const marshaller = this.marshaller;\n const eventStreamMember = responseSchema.getEventStreamMember();\n const unionSchema = responseSchema.getMemberSchema(eventStreamMember);\n const memberSchemas = unionSchema.getMemberSchemas();\n const initialResponseMarker = Symbol(\"initialResponseMarker\");\n const asyncIterable = marshaller.deserialize(response.body, async (event) => {\n const unionMember = Object.keys(event).find((key) => {\n return key !== \"__type\";\n }) ?? \"\";\n const body = event[unionMember].body;\n if (unionMember === \"initial-response\") {\n const dataObject = await this.deserializer.read(responseSchema, body);\n delete dataObject[eventStreamMember];\n return {\n [initialResponseMarker]: true,\n ...dataObject,\n };\n }\n else if (unionMember in memberSchemas) {\n const eventStreamSchema = memberSchemas[unionMember];\n if (eventStreamSchema.isStructSchema()) {\n const out = {};\n let hasBindings = false;\n for (const [name, member] of eventStreamSchema.structIterator()) {\n const { eventHeader, eventPayload } = member.getMergedTraits();\n hasBindings = hasBindings || Boolean(eventHeader || eventPayload);\n if (eventPayload) {\n if (member.isBlobSchema()) {\n out[name] = body;\n }\n else if (member.isStringSchema()) {\n out[name] = (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)(body);\n }\n else if (member.isStructSchema()) {\n out[name] = await this.deserializer.read(member, body);\n }\n }\n else if (eventHeader) {\n const value = event[unionMember].headers[name]?.value;\n if (value != null) {\n if (member.isNumericSchema()) {\n if (value && typeof value === \"object\" && \"bytes\" in value) {\n out[name] = BigInt(value.toString());\n }\n else {\n out[name] = Number(value);\n }\n }\n else {\n out[name] = value;\n }\n }\n }\n }\n if (hasBindings) {\n return {\n [unionMember]: out,\n };\n }\n if (body.byteLength === 0) {\n return {\n [unionMember]: {},\n };\n }\n }\n return {\n [unionMember]: await this.deserializer.read(eventStreamSchema, body),\n };\n }\n else {\n return {\n $unknown: event,\n };\n }\n });\n const asyncIterator = asyncIterable[Symbol.asyncIterator]();\n const firstEvent = await asyncIterator.next();\n if (firstEvent.done) {\n return asyncIterable;\n }\n if (firstEvent.value?.[initialResponseMarker]) {\n if (!responseSchema) {\n throw new Error(\"@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.\");\n }\n for (const [key, value] of Object.entries(firstEvent.value)) {\n initialResponseContainer[key] = value;\n }\n }\n return {\n async *[Symbol.asyncIterator]() {\n if (!firstEvent?.value?.[initialResponseMarker]) {\n yield firstEvent.value;\n }\n while (true) {\n const { done, value } = await asyncIterator.next();\n if (done) {\n break;\n }\n yield value;\n }\n },\n };\n }\n writeEventBody(unionMember, unionSchema, event) {\n const serializer = this.serializer;\n let eventType = unionMember;\n let explicitPayloadMember = null;\n let explicitPayloadContentType;\n const isKnownSchema = (() => {\n const struct = unionSchema.getSchema();\n return struct[4].includes(unionMember);\n })();\n const additionalHeaders = {};\n if (!isKnownSchema) {\n const [type, value] = event[unionMember];\n eventType = type;\n serializer.write(15, value);\n }\n else {\n const eventSchema = unionSchema.getMemberSchema(unionMember);\n if (eventSchema.isStructSchema()) {\n for (const [memberName, memberSchema] of eventSchema.structIterator()) {\n const { eventHeader, eventPayload } = memberSchema.getMergedTraits();\n if (eventPayload) {\n explicitPayloadMember = memberName;\n }\n else if (eventHeader) {\n const value = event[unionMember][memberName];\n let type = \"binary\";\n if (memberSchema.isNumericSchema()) {\n if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) {\n type = \"integer\";\n }\n else {\n type = \"long\";\n }\n }\n else if (memberSchema.isTimestampSchema()) {\n type = \"timestamp\";\n }\n else if (memberSchema.isStringSchema()) {\n type = \"string\";\n }\n else if (memberSchema.isBooleanSchema()) {\n type = \"boolean\";\n }\n if (value != null) {\n additionalHeaders[memberName] = {\n type,\n value,\n };\n delete event[unionMember][memberName];\n }\n }\n }\n if (explicitPayloadMember !== null) {\n const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember);\n if (payloadSchema.isBlobSchema()) {\n explicitPayloadContentType = \"application/octet-stream\";\n }\n else if (payloadSchema.isStringSchema()) {\n explicitPayloadContentType = \"text/plain\";\n }\n serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]);\n }\n else {\n serializer.write(eventSchema, event[unionMember]);\n }\n }\n else if (eventSchema.isUnitSchema()) {\n serializer.write(eventSchema, {});\n }\n else {\n throw new Error(\"@smithy/core/event-streams - non-struct member not supported in event stream union.\");\n }\n }\n const messageSerialization = serializer.flush() ?? new Uint8Array();\n const body = typeof messageSerialization === \"string\"\n ? (this.serdeContext?.utf8Decoder ?? utilUtf8.fromUtf8)(messageSerialization)\n : messageSerialization;\n return {\n body,\n eventType,\n explicitPayloadContentType,\n additionalHeaders,\n };\n }\n}\n\nexports.EventStreamSerde = EventStreamSerde;\n"
6
6
  ],
7
7
  "mappings": ";kFAIA,AAAM,CAAiB,CACnB,WACA,WACA,aACA,aACA,mBACA,WAAW,EAAG,aAAY,aAAY,eAAc,eAAc,sBAAuB,CACrF,KAAK,WAAa,EAClB,KAAK,WAAa,EAClB,KAAK,aAAe,EACpB,KAAK,aAAe,EACpB,KAAK,mBAAqB,OAExB,qBAAoB,EAAG,cAAa,gBAAe,kBAAmB,CACxE,IAAM,EAAa,KAAK,WAClB,EAAoB,EAAc,qBAAqB,EACvD,EAAc,EAAc,gBAAgB,CAAiB,EAC7D,EAAa,KAAK,WAClB,EAAqB,KAAK,mBAC1B,EAAuB,OAAO,sBAAsB,EACpD,EAAsB,QAChB,OAAO,cAAc,EAAG,CAC5B,GAAI,EAAgB,CAChB,IAAM,EAAU,CACZ,cAAe,CAAE,KAAM,SAAU,MAAO,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OAAO,IAAyB,UACtC,KAAK,cAAc,aAAe,EAAS,UAAU,CAAoB,EAC1E,EAGF,YACA,6BACA,mBACJ,EAER,KA9PI,EAgQI,eAhQJ,MAgQI,EAAmB",
8
- "debugId": "E0D47C34ED80807164756E2164756E21",
8
+ "debugId": "539E7A834F9F9CB364756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
2
  var $=globalThis.__GEMI_DICTIONARY_REGISTRY__??={registry:new Map,resolved:new Map,inFlight:new Map,degraded:new Map,order:[],warmed:new Map,activeLocale:null},{registry:V,resolved:X,inFlight:Q,degraded:E,order:j,warmed:W}=$;function G(q,x){return`${q}\x00${x}`}function U(q){if(V.has(q.id))return;V.set(q.id,q),j.push(q.id)}function Y(){return j.length}function I(q,x){return X.get(q)?.get(x)}function Z(q,x,A){let z=X.get(q);if(!z)z=new Map,X.set(q,z);z.set(x,A)}function M(q,x){let A=I(q,x);if(A)return A;let z=G(q,x),C=Q.get(z);if(C)return C;let B=V.get(q);if(!B)throw Error(`Unknown dictionary "${q}". A dictionary must be created with defineDictionary() and its module must have been evaluated before it is read.`);let H=B.load(x);if(!(H instanceof Promise))return Z(q,x,H),H;let J=H.then((O)=>{return Z(q,x,O),Q.delete(z),O},(O)=>{throw Q.delete(z),O});return Q.set(z,J),J}function _(q,x){let A=I(q,x);if(A)return A;let z=G(q,x),C=E.get(z);if(C)return C;let B=M(q,x);if(!(B instanceof Promise))return B;let H=B.then((J)=>J,(J)=>{return console.error(`Failed to load dictionary ${q} for locale ${x}; rendering keys instead.`,J),N});return E.set(z,H),H}var N={};async function D(q,x){let A=x??W.get(q)??0,z=j.slice(A);if(z.length===0)return;let C=await Promise.all(z.map(async(B)=>{try{return await M(B,P(B,q)),!0}catch{return!1}}));if(x===void 0){let B=C.indexOf(!1),H=B===-1?z.length:B;W.set(q,Math.max(W.get(q)??0,A+H))}}function P(q,x){if(x)return x;return V.get(q)?.locales[0]??x}function K(q,x){if(!q)return;for(let[A,z]of Object.entries(q))Z(A,x,z)}function S(q){if(q)$.activeLocale=q}function T(){return $.activeLocale}if(typeof window<"u"){let q=window,x=([z,C,B])=>{Z(z,C,B)},A=Array.isArray(q.__GEMI_DICT__)?q.__GEMI_DICT__:[];q.__GEMI_DICT__={push:x};for(let z of A)x(z)}function L(){V.clear(),X.clear(),Q.clear(),E.clear(),W.clear(),j.length=0,$.activeLocale=null}function w(){let q=new Set,x=[],A=[];return{use(z,C,B){let H=`${z} ${C}`;if(q.has(H))return;q.add(H);let J={id:z,locale:C,strings:B};if(x.length===0){A.push(J);return}for(let O of x)O(J)},onUse(z){x.push(z);while(A.length>0)z(A.shift())}}}
3
- export{U as rd,Y as sd,M as td,_ as ud,D as vd,K as wd,S as xd,T as yd,L as zd,w as Ad};
3
+ export{U as Nd,Y as Od,M as Pd,_ as Qd,D as Rd,K as Sd,S as Td,T as Ud,L as Vd,w as Wd};
4
4
 
5
- //# debugId=5BCF267C861A364D64756E2164756E21
5
+ //# debugId=50334249C8DBF76664756E2164756E21
@@ -6,6 +6,6 @@
6
6
  "import type { LocaleStrings } from \"./dictionaryShape\";\n\n/**\n * Collects the dictionaries one SSR render actually read.\n *\n * Scoped per request by living in React context rather than in module state: a\n * streaming server has several renders in flight at once, so a module-level\n * collector would mix one page's dictionaries into another's payload. Context\n * is per render tree, which is exactly the boundary wanted, and it needs no\n * async-local storage to survive React's internal scheduling.\n *\n * Why stream these rather than put them in `__GEMI_DATA__`: that snapshot is\n * serialized before `renderToReadableStream` is even called, and which\n * dictionaries a page reads is only known once it has rendered. A suspended\n * segment reveals later still, long after the shell has flushed.\n *\n * The sink deliberately emits data, not markup — `streamQueryInjection` owns\n * script formatting and the `</script>`-safe encoding that goes with it.\n */\nexport interface DictionaryUse {\n id: string;\n locale: string;\n strings: LocaleStrings;\n}\n\nexport interface DictionarySink {\n /** Called during render, the first time a dictionary is read. */\n use(id: string, locale: string, strings: LocaleStrings): void;\n /** The response injector subscribes to receive uses as they happen. */\n onUse(cb: (use: DictionaryUse) => void): void;\n}\n\nexport function createDictionarySink(): DictionarySink {\n const seen = new Set<string>();\n const listeners: Array<(use: DictionaryUse) => void> = [];\n // Uses recorded before the injector subscribed — the render begins before the\n // response stream is wrapped.\n const pending: DictionaryUse[] = [];\n\n return {\n use(id, locale, strings) {\n const key = `${id} ${locale}`;\n if (seen.has(key)) return;\n seen.add(key);\n const entry: DictionaryUse = { id, locale, strings };\n if (listeners.length === 0) {\n pending.push(entry);\n return;\n }\n for (const listener of listeners) listener(entry);\n },\n onUse(cb) {\n listeners.push(cb);\n while (pending.length > 0) {\n cb(pending.shift()!);\n }\n },\n };\n}\n"
7
7
  ],
8
8
  "mappings": ";AA4EA,IAAM,EAAyB,WAFZ,+BAE+C,CAChE,SAAU,IAAI,IACd,SAAU,IAAI,IACd,SAAU,IAAI,IACd,SAAU,IAAI,IACd,MAAO,CAAC,EACR,OAAQ,IAAI,IACZ,aAAc,IAChB,GAEQ,WAAU,WAAU,WAAU,WAAU,QAAO,UAAW,EAElE,SAAS,CAAQ,CAAC,EAAY,EAAgB,CAC5C,MAAO,GAAG,QAAO,IAGZ,SAAS,CAAkB,CAAC,EAA6B,CAM9D,GAAI,EAAS,IAAI,EAAM,EAAE,EACvB,OAEF,EAAS,IAAI,EAAM,GAAI,CAAK,EAC5B,EAAM,KAAK,EAAM,EAAE,EAId,SAAS,CAA0B,EAAW,CACnD,OAAO,EAAM,OAGR,SAAS,CAAW,CACzB,EACA,EAC2B,CAC3B,OAAO,EAAS,IAAI,CAAE,GAAG,IAAI,CAAM,EAGrC,SAAS,CAAW,CAAC,EAAY,EAAgB,EAAwB,CACvE,IAAI,EAAW,EAAS,IAAI,CAAE,EAC9B,GAAI,CAAC,EACH,EAAW,IAAI,IACf,EAAS,IAAI,EAAI,CAAQ,EAE3B,EAAS,IAAI,EAAQ,CAAO,EAQvB,SAAS,CAAc,CAC5B,EACA,EACwC,CACxC,IAAM,EAAU,EAAY,EAAI,CAAM,EACtC,GA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B,CAAE,KAAI,SAAQ,SAAQ,EACnD,GAAI,EAAU,SAAW,EAAG,CAC1B,EAAQ,KAAK,CAAK,EAClB,OAEF,QAAW,KAAY,EAAW,EAAS,CAAK,GAElD,KAAK,CAAC,EAAI,CACR,EAAU,KAAK,CAAE,EACjB,MAAO,EAAQ,OAAS,EACtB,EAAG,EAAQ,MAAM,CAAE,EAGzB",
9
- "debugId": "5BCF267C861A364D64756E2164756E21",
9
+ "debugId": "50334249C8DBF76664756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -0,0 +1,9 @@
1
+ // @bun
2
+ import{Ad as b,Bd as A,Hd as F,kd as M,nd as P,sd as W,ud as O,vd as D,wd as w,xd as j,yd as L,zd as y}from"./chunk-y6a8r2bn.js";import{We as S,Xe as Y}from"./chunk-3g5bjvdf.js";import{AsyncLocalStorage as E}from"async_hooks";var J=new E;function o(){return J.getStore()?.tx}function T(){return J.getStore()?.connection??M}function n(q,z){let B=J.getStore();if(T()===q)return z();return U(q),J.run({...B,depth:B?.depth??0,connection:q===M?void 0:q},z)}function U(q){let z=J.getStore();if(z?.tx===void 0)return;let B=z.connection??M;if(B===q)return;throw new P(B,q)}function t(q){let z=J.getStore();if(z?.tx===void 0||z.afterCommit===void 0)return!1;return z.afterCommit.push(q),!0}function a(){let q=J.getStore();return q?.tx===void 0?null:q.depth}function r(){return J.getStore()?.system===!0}function e(q){let z=J.getStore();return J.run({...z,depth:z?.depth??0,system:!0},q)}function qq(){return J.getStore()?.actor}function zq(q,z){let B=J.getStore();return J.run({...B,depth:B?.depth??0,system:!1,actor:{user:q??null}},z)}function x(q){if(Bun.env.NODE_ENV!=="development")return null;if(q===!1)return null;if(q===void 0)return W;if(!Number.isFinite(q)||q<=0)return W;return q}function C(q){let z=x(q);if(z===null)return()=>{};let B=Error("transaction opened here"),X=setTimeout(()=>{let Z=B.stack?.split(`
3
+ `).slice(1).join(`
4
+ `)??"";console.warn(`[gemi] A database transaction has not settled after ${z}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
+ ${Z}
6
+ (development only; set database.slowTransactionThreshold to change the threshold, or false to switch this off)`)},z);return X.unref?.(),()=>clearTimeout(X)}async function v(q,z){if(q.length===0)return;await J.run({...z,tx:void 0,afterCommit:void 0,depth:z?.depth??0},async()=>{for(let B of q)try{await B()}catch(X){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.",X)}})}function Bq(q,z,B){let X=J.getStore(),Z=B?.connection??M;if(U(Z),X?.tx){let Q=X.afterCommit,G=Q?.length??0;return X.tx.savepoint((K)=>{let k=K;return J.run({...X,tx:k,depth:X.depth+1},()=>z(k))}).catch((K)=>{if(Q)Q.length=G;throw K})}let $=C(B?.slowTransactionThreshold),V=[];try{return q.begin((Q)=>J.run({...X,tx:Q,depth:0,connection:Z===M?void 0:Z,afterCommit:V},()=>z(Q))).finally($).then(async(Q)=>{return await v(V,X),Q})}catch(Q){throw $(),Q}}var f=/^\s*::\s*(?:text\s*::\s*)?(jsonb|json)\b(?!\s*\[)/i,g=/^\s*as\s+(jsonb|json)\s*\)/i,p=/\bcast\s*\(\s*$/i,c=new Set;function _(q,z){if(!z.typesParametersFromStatement)return{fragment:q,jsonParameters:c};let B=j(q),X=new Set,Z;for(let $=0;$<B.length-1;$++){let V=B[$+1],Q=f.exec(V);if(Q){Z??=[...B],Z[$+1]=`::text::${Q[1]}${V.slice(Q[0].length)}`,X.add($);continue}let G=g.exec(V);if(G&&p.test((Z??B)[$]))Z??=[...B],Z[$+1]=` as text)::${G[1]}${V.slice(G[0].length)}`,X.add($)}if(!Z)return{fragment:q,jsonParameters:X};return{fragment:L(Z,q.binders),jsonParameters:X}}function I(q,z){if(q===null||q===void 0)return null;let B=F(q);if(B==="db")return null;if(B==="json")return"null";if(B==="any")throw new Y(z,"DB",z,"Prisma.AnyNull is a filter operand \u2014 it asks for a SQL NULL *or* a JSON "+"null \u2014 so it has no single value to bind. Write the one you mean: "+"Prisma.DbNull for the column being NULL, Prisma.JsonNull for the JSON value.");if(typeof q==="string")return q;let X;try{X=JSON.stringify(q)}catch(Z){throw new Y(z,"DB",z,`A parameter cast to json could not be serialised: ${Z instanceof Error?Z.message:String(Z)}. `+"Bind text you have serialised yourself if the value is not JSON \u2014 a "+"bigint has no JSON form, and neither does a cycle.")}if(X===void 0)throw new Y(z,"DB",z,`A ${typeof q} was bound to a parameter cast to json, and has no JSON form. Bind the value it stands for.`);return X}var h=new WeakSet;function H(q){return h.add(q),q}function R(q){return typeof q==="object"&&q!==null&&h.has(q)}function Gq(q,...z){if(!Array.isArray(q)||!("raw"in q))throw new S("sql","DB","sql","'sql' is a tagged template \u2014 write sql`select 1`, not sql(\"select 1\"). "+"To put text that is not a value into a statement, use 'unsafeSql', and read what it says first.");let B=[];for(let X=0;X<q.length;X++)if(B.push(D(q[X])),X<z.length)B.push(N(z[X]));return H(y(...B))}function Hq(q,z=", "){if(!Array.isArray(q))throw new Y("join","DB","sql",`Expected an array of fragments or values, got ${typeof q}.`);if(q.length===0)return u;let B=q.map(N);if(R(z)){let X=[];for(let Z=0;Z<B.length;Z++){if(Z>0)X.push(z);X.push(B[Z])}return H(y(...X))}return m(z),H(b(B,z))}var d=/^[\s,]*$|^\s*(?:and|or)\s*$/i;function m(q){if(typeof q==="string"&&d.test(q))return;throw new Y("join","DB","sql",typeof q==="string"?`A separator is written into the SQL text, so it may only be glue: whitespace, commas, or 'and' / 'or'. Got ${JSON.stringify(q)}. If that is deliberate, say so with `+"unsafeSql(...) \u2014 and never build one from anything that came from "+"outside the program.":`Expected a separator string or a fragment, got ${q===null?"null":typeof q}.`)}var u=H(Object.freeze({text:"",binders:Object.freeze([])}));function Kq(q){if(typeof q!=="string")throw new Y("unsafeSql","DB","sql",`Expected a string literal, got ${Array.isArray(q)?"an array":typeof q}. 'unsafeSql' is a plain call, not a tagged template \u2014 a template would `+"interpolate values into the SQL text, which is the one thing it must never do.");return H(D(q))}function Wq(q,z,B="query"){if(!R(q))throw new Y(B,"DB",B,`Expected a fragment built with 'sql', got ${q===null?"null":typeof q}. A plain string is not accepted here on purpose \u2014 it would be the one `+"path into the SQL text that nobody had to think about.");let X=_(q,z),Z=A(X.fragment,z,{model:"DB",operation:B});return{text:Z.text,values:O(Z.binders)(void 0).map(($,V)=>X.jsonParameters.has(V)?I($,B):$===null||$===void 0?$??null:z.encodeUntyped($))}}function N(q){if(R(q))return q;return w(()=>q)}
7
+ export{J as Qc,o as Rc,T as Sc,n as Tc,U as Uc,t as Vc,a as Wc,r as Xc,e as Yc,qq as Zc,zq as _c,Bq as $c,Gq as ad,Hq as bd,u as cd,Kq as dd,Wq as ed};
8
+
9
+ //# debugId=14B2E80CDD7EF77E64756E2164756E21
@@ -2,11 +2,11 @@
2
2
  "version": 3,
3
3
  "sources": ["../orm/context.ts", "../orm/json-param.ts", "../orm/sql.ts"],
4
4
  "sourcesContent": [
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,\n * `services/pubsub/BroadcastManager.ts` a socket's headers. 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\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/** 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/** 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 * 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 * 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 return current.tx.savepoint((sp) => {\n const nested = sp as TransactionSQL;\n return ormContext.run(\n { ...current, tx: nested, depth: current.depth + 1 },\n () => fn(nested),\n );\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 // 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 },\n () => fn(tx),\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 .finally(stopWatching) as Promise<T>\n );\n } catch (error) {\n stopWatching();\n throw error;\n }\n}\n",
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,\n * `services/pubsub/BroadcastManager.ts` a socket's headers. 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\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/** 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/** 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 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\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 () => fn(nested),\n );\n })\n .catch((error: unknown) => {\n if (deferred) deferred.length = mark;\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\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 },\n () => fn(tx),\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
  "import {\n type Fragment,\n fromParamSegments,\n paramSegments,\n} from \"./compile/fragment\";\nimport type { SqlDialect } from \"./dialect\";\nimport { InvalidArgumentError } from \"./errors\";\nimport { jsonNullKind } from \"./json-null\";\n\n/**\n * A raw parameter the caller cast to `json`/`jsonb` carries **JSON text**.\n *\n * ## The statement that changes meaning between the two clients\n *\n * ```sql\n * update \"AsyncJob\" set payload = payload || $1::jsonb where id = $2\n * ```\n *\n * Byte-identical under Prisma's `$executeRaw` and under `DB.execute`, and it\n * did two different things. Measured on Postgres 16 through Bun 1.3.14 and a\n * generated `@prisma/client` 6.19.2, binding the JS string\n * `'{\"version\":1}'` into a `jsonb` column:\n *\n * form prisma bun\n * $1 error: jsonb vs text \"{\\\"version\\\":1}\" (a jsonb string)\n * $1::jsonb {\"version\": 1} \"{\\\"version\\\":1}\"\n * cast($1 as jsonb) {\"version\": 1} \"{\\\"version\\\":1}\"\n * $1::text::jsonb {\"version\": 1} {\"version\": 1}\n *\n * The mechanism is the parameter's *type*, not the cast's. Prisma sends a JS\n * string as `text` and lets Postgres parse it into the target type; Bun asks\n * the server what the statement wants, is told `jsonb`, and JSON-encodes the\n * string it was handed — so the string becomes a jsonb **string** rather than\n * the object it spells. `::text::jsonb` pins the parameter back to `text`,\n * which is what Prisma did implicitly and what `compile/cast.ts` already emits\n * for a typed `Json` column (#209).\n *\n * **The `||` case is the sharp end.** Concatenating an object with a jsonb\n * *string* is array concatenation, not a merge:\n *\n * payload || $1::jsonb [{\"attribution\": …}, \"{\\\"version\\\":1}\"]\n * payload || $1::text::jsonb {\"attribution\": …, \"version\": 1}\n *\n * A statement written to merge metadata into a document appends the serialised\n * text as a new array element instead. The write succeeds, nothing raises, the\n * SQL reads correctly by eye, and the corruption is found by whatever reads the\n * column next.\n *\n * ## So the cast is read, and the parameter retyped\n *\n * A `::json`/`::jsonb` the caller wrote onto their own placeholder is the one\n * thing in a raw statement that says \"this parameter is JSON\" — there is no\n * field to ask, which is the whole difference between this and `fieldParam`.\n * When it is there, the placeholder is rewritten to cast through `text` and the\n * value is serialised to match, so the Prisma-shaped statement does the Prisma\n * thing.\n *\n * **Rewriting a caller's SQL text needs a reason, and this is it:** the cast is\n * preserved exactly — `::text::jsonb` and `::jsonb` denote the same type and\n * the expression's result is unchanged — while the *parameter's* type, which is\n * the thing that differs from Prisma and the thing no caller can otherwise\n * reach, is set to what Prisma set it to. The raw path was never\n * byte-preserving in any case: it is what turns a marker into `$1` or `?`.\n *\n * ## A string passes through, unlike the typed path — and Prisma agrees twice\n *\n * `fieldParam` serialises *every* value, so a `Json` column set to the JS string\n * `\"42\"` stores the jsonb string `\"42\"`. Here a string is handed over as it\n * arrived, so `${'{\"a\":1}'}::jsonb` stores the object. That is not an\n * inconsistency to be tidied away: it is which of the two Prisma does, on each\n * path, and both were measured against 6.19.2.\n *\n * prisma.doc.create({ data: { payload: '{\"version\":1}' } }) -> jsonb string\n * prisma.$executeRaw`… values (${'{\"version\":1}'}::jsonb)` -> jsonb object\n *\n * The distinction that explains both: with a field, nobody wrote a cast and the\n * value is a JSON *value*; with a caller-written cast, the caller has said the\n * parameter is JSON *text* being cast. Somebody who wants the jsonb string\n * writes the serialisation they mean — `${JSON.stringify(v)}::jsonb`.\n *\n * ## What is left, and why the remainder is the right remainder\n *\n * A bare `$1` into a `jsonb` column is the same fault and is not detectable\n * here: no cast, no field, nothing to read. It is also the shape a Prisma port\n * cannot contain — Prisma *refuses* it (`column \"payload\" is of type jsonb but\n * expression is of type text`), so a statement that ran under Prisma with a\n * string operand had a cast on it. An object there works on both clients and is\n * untouched. `docs/orm.md` carries the residue; this covers what a port can\n * actually be carrying.\n *\n * Schema-qualified spellings (`$1::pg_catalog.jsonb`) and `jsonb[]` are\n * deliberately not matched. The first is not what anyone writes and the second\n * is a different operand — an array of documents, where serialising the JS\n * array to one JSON text would be wrong. Nor is a cast on an *expression\n * around* the placeholder: `(${v})::jsonb` and `cast(coalesce(${v}) as jsonb)`\n * read as an untyped parameter and still mis-store. Detection is textual, and\n * parsing parentheses to reach a spelling nobody writes buys less than it\n * costs; `docs/orm.md` says so where a reader looking for the covered set will\n * find it.\n *\n * ## Postgres only, and that is a dialect capability rather than a regex's luck\n *\n * The first version of this ran on both dialects, on the argument that `::` is\n * not SQLite syntax and SQLite has no `jsonb`, so nothing could match a\n * statement SQLite could run. **The first half of that is true and the second\n * is not.** SQLite's `CAST` accepts an arbitrary type name, so `cast(? as\n * json)` parses and runs there — and means something else entirely, since a\n * type name matching none of INT/CHAR/CLOB/TEXT/BLOB/REAL/FLOA/DOUB gets\n * NUMERIC affinity:\n *\n * select cast(? as jsonb) -> 0\n * select json_set('{\"a\":1}','$.b', cast(? as json)) -> {\"a\":1,\"b\":2} (the cast\n * is what makes it the number\n * 2 rather than the string)\n * select cast(? as text)::json -> unrecognized token: \":\"\n *\n * So the rewrite would have turned a working SQLite statement into a syntax\n * error. The gate is {@link SqlDialect.typesParametersFromStatement}, asked\n * rather than matched on `dialect.name`, because \"cannot fire\" was exactly the\n * kind of claim that should have been a capability someone can typecheck\n * instead of a property of two regular expressions.\n */\n\n/**\n * `::jsonb` / `::json` applied to the placeholder that precedes it.\n *\n * Whitespace is allowed on both sides of the operator because Postgres allows\n * it and `$1 :: jsonb` mis-stores identically — measured, not assumed. The\n * lookahead keeps `::jsonb[]` out: that operand is an array of documents, and\n * the serialisation this triggers would flatten it into one.\n *\n * **`::text::jsonb` matches too**, and is then rewritten to itself. The cast is\n * already right there — it is the spelling this whole note recommends, and the\n * one a caller who has already been bitten will have written — but the *value*\n * still has to be serialised, or an object bound to it reaches Postgres as\n * `[object Object]`. Matching both spellings is what makes them mean the same\n * thing, which is the only defensible relationship between them.\n */\nconst OPERATOR_CAST = /^\\s*::\\s*(?:text\\s*::\\s*)?(jsonb|json)\\b(?!\\s*\\[)/i;\n\n/**\n * The same cast written as a function: `cast($1 as jsonb)`.\n *\n * **This is the branch that is reachable on SQLite, and the reason the whole\n * function is gated on a dialect capability rather than on the shape of these\n * two patterns.** `::` is Postgres-only *syntax* — SQLite's parser rejects it,\n * so `OPERATOR_CAST` genuinely cannot fire on a statement SQLite could run.\n * `cast(… as …)` is not: SQLite takes any type name there, `cast(? as json)`\n * parses and runs, and the rewrite this pairs with emits `as text)::json`,\n * which SQLite refuses. \"SQLite has no jsonb type\" is a claim about semantics;\n * what matters here is what the parser accepts. See\n * {@link SqlDialect.typesParametersFromStatement}.\n */\nconst FUNCTION_CAST = /^\\s*as\\s+(jsonb|json)\\s*\\)/i;\n\n/**\n * ...which is only that when a `cast(` opened immediately before the\n * placeholder. Without this, `select ${x} as jsonb)` — nonsense, but nonsense\n * the caller wrote — would have its parameter serialised on the strength of two\n * keywords that mean nothing here.\n */\nconst CAST_OPEN = /\\bcast\\s*\\(\\s*$/i;\n\n/** The answer on a dialect that is gated out, before any set is built. */\nconst EMPTY: ReadonlySet<number> = new Set<number>();\n\n/**\n * The fragment with every JSON-cast parameter retyped through `text`, and the\n * positions of the parameters that were.\n *\n * Returns the fragment unchanged, and an empty set, when there is no such cast\n * — which is every statement in the compiler and nearly every raw one — and on\n * any dialect that does not type a parameter from the statement, which today is\n * SQLite. See the header: there the correction is unnecessary, the cast means\n * NUMERIC affinity rather than JSON, and the rewrite does not parse.\n */\nexport function retypeJsonParameters(\n fragment: Fragment,\n dialect: SqlDialect,\n): {\n fragment: Fragment;\n jsonParameters: ReadonlySet<number>;\n} {\n if (!dialect.typesParametersFromStatement) {\n return { fragment, jsonParameters: EMPTY };\n }\n\n const segments = paramSegments(fragment);\n const jsonParameters = new Set<number>();\n let rewritten: string[] | undefined;\n\n // `segments[i]` is the text before parameter `i` and `segments[i + 1]` the\n // text after it, so the last segment trails the final parameter and has no\n // parameter of its own.\n for (let index = 0; index < segments.length - 1; index++) {\n const after = segments[index + 1];\n\n const operator = OPERATOR_CAST.exec(after);\n if (operator) {\n rewritten ??= [...segments];\n rewritten[index + 1] =\n `::text::${operator[1]}${after.slice(operator[0].length)}`;\n jsonParameters.add(index);\n continue;\n }\n\n const fn = FUNCTION_CAST.exec(after);\n // The preceding segment is read from the rewrite when there is one: a\n // previous parameter's rewrite replaces the head of this segment and leaves\n // its tail — the `cast(` this is looking for — where it was, but reading the\n // live array is what keeps that a fact rather than an assumption.\n if (fn && CAST_OPEN.test((rewritten ?? segments)[index])) {\n rewritten ??= [...segments];\n rewritten[index + 1] = ` as text)::${fn[1]}${after.slice(fn[0].length)}`;\n jsonParameters.add(index);\n }\n }\n\n if (!rewritten) return { fragment, jsonParameters };\n return {\n fragment: fromParamSegments(rewritten, fragment.binders),\n jsonParameters,\n };\n}\n\n/**\n * The value for one such parameter: JSON text, or SQL NULL.\n *\n * `dialect.encodeUntyped` deliberately does not run on these. Its two\n * conversions are for a value being compared against a column the ORM wrote — a\n * `Date` as milliseconds, a boolean as `0`/`1` — and neither is JSON. A `Date`\n * here becomes the ISO string `JSON.stringify` gives it, because that is what\n * putting a `Date` in a JSON document means.\n */\nexport function jsonTextParameter(value: unknown, operation: string): unknown {\n // SQL NULL rather than the JSON value `null`, the same reading `fieldParam`\n // takes for a nullable `Json` column: an absent value is not a stored null.\n // Prisma binds a JS `null` at `$1::jsonb` to SQL NULL too — which follows\n // from the parameter being declared `text` (the `values ($1)` error text in\n // the table above is what shows that it is), since `NULL::text::jsonb` is SQL\n // NULL. Reasoned, not measured: it is the one row of that table nobody ran.\n if (value === null || value === undefined) return null;\n\n // Prisma's null sentinels, which `JSON.stringify` turns into `{}` — #259's\n // mis-store arrived at by a third route. `DbNull` is the column being NULL and\n // `JsonNull` is the JSON value, exactly as in `compile/cast.ts`.\n const nullKind = jsonNullKind(value);\n if (nullKind === \"db\") return null;\n if (nullKind === \"json\") return \"null\";\n if (nullKind === \"any\") {\n throw new InvalidArgumentError(\n operation,\n \"DB\",\n operation,\n `Prisma.AnyNull is a filter operand — it asks for a SQL NULL *or* a JSON ` +\n `null — so it has no single value to bind. Write the one you mean: ` +\n `Prisma.DbNull for the column being NULL, Prisma.JsonNull for the JSON ` +\n `value.`,\n );\n }\n\n // Already JSON text. See the header: at a cast the caller wrote, a string is\n // the document rather than a JSON string value, which is Prisma's reading of\n // the same parameter.\n if (typeof value === \"string\") return value;\n\n let text: string | undefined;\n try {\n text = JSON.stringify(value);\n } catch (cause) {\n // A `bigint` and a circular structure are the two that get here. Prisma\n // fails on the first as well (`cannot cast type bigint to jsonb`), and this\n // says which parameter rather than which JSON.stringify.\n throw new InvalidArgumentError(\n operation,\n \"DB\",\n operation,\n `A parameter cast to json could not be serialised: ` +\n `${cause instanceof Error ? cause.message : String(cause)}. ` +\n `Bind text you have serialised yourself if the value is not JSON — a ` +\n `bigint has no JSON form, and neither does a cycle.`,\n );\n }\n\n // `undefined` back from `JSON.stringify` means the value has no JSON form at\n // all — a function, a symbol. Binding it would be SQL NULL, which is a\n // successfully-written wrong answer.\n if (text === undefined) {\n throw new InvalidArgumentError(\n operation,\n \"DB\",\n operation,\n `A ${typeof value} was bound to a parameter cast to json, and has no ` +\n `JSON form. Bind the value it stands for.`,\n );\n }\n\n return text;\n}\n",
7
7
  "import type { SqlDialect } from \"./dialect\";\nimport {\n InvalidArgumentError,\n UnsupportedQueryError,\n} from \"./errors\";\nimport {\n type Fragment,\n bindValues,\n concat,\n joinFragments,\n param,\n render,\n sql as text,\n} from \"./compile/fragment\";\nimport { jsonTextParameter, retypeJsonParameters } from \"./json-param\";\n\n/**\n * SQL fragments as first-class values: `sql`, `join`, `empty`, and one door out.\n *\n * The ORM deliberately does not implement every SQL shape — `distinct`, cursor\n * pagination, window functions, recursive CTEs. That is the right call, but it\n * is only half a decision: the shapes it declines have to have somewhere to go,\n * and \"drop to raw SQL\" is not an answer if raw SQL cannot be *composed*.\n *\n * `DB.sql` — Bun's tagged template — covers a single self-contained statement,\n * and that is genuinely all it covers. The shape it cannot express is the common\n * one: a predicate list built conditionally, passed around as a value, and\n * interpolated into a larger statement.\n *\n * ```ts\n * const filters = []\n * if (q) filters.push(sql`name ilike ${`%${q}%`}`)\n * if (organizationId) filters.push(sql`\"organizationId\" = ${organizationId}`)\n *\n * const where = filters.length ? sql`where ${join(filters, \" and \")}` : empty\n * const rows = await DB.query(sql`select * from \"Product\" ${where} limit ${20}`)\n * ```\n *\n * ## This is the compiler's own `Fragment`, made public\n *\n * Not a parallel mechanism. `compile/fragment.ts` has held exactly this shape\n * since iteration 1 — text plus positional binders, composable, never\n * concatenating a value into the text — because that is what invariant 2 needs\n * internally. Reusing it means a public fragment binds by the same rule the\n * compiler's own SQL does, and it means the parameter ceiling, the placeholder\n * numbering and the dialect split are all already handled rather than\n * reimplemented one door down.\n *\n * **Placeholders are assigned at assembly, not at authoring.** SQLite writes\n * `?` and Postgres writes `$1`, `$2`, and a fragment does not know where in the\n * final statement it will land — so `sql` records a *position* and `render`\n * turns it into a placeholder once the whole statement exists. That is what lets\n * the same fragment be nested, reused twice in one statement, or built before\n * the dialect is even known.\n */\n\n/**\n * A composable piece of SQL. Its values are bound parameters, never text.\n *\n * Opaque on purpose: an application builds one with `sql`, combines it with\n * `join`, and hands it to `DB.query` / `DB.execute`. Reading `.text` off it is\n * not part of the contract — it holds parameter *markers* rather than the\n * dialect's placeholders, so it is not the statement that runs.\n */\nexport type SqlFragment = Fragment;\n\n/**\n * Every fragment this module has produced.\n *\n * **Identity, not shape, and the difference is a SQL injection.** `interpolate`\n * splices a fragment as text and binds everything else, so \"is this a fragment\"\n * decides whether a value reaches the statement or a parameter. Asking the\n * *shape* — a `text` string and a `binders` array — makes that decision\n * answerable by anything that can name two properties, and `{\"text\": \"…\",\n * \"binders\": []}` is two lines of JSON:\n *\n * ```ts\n * const body = await request.json()\n * await DB.query(sql`select \"email\" from \"User\" where \"email\" = ${body.email}`)\n * // body.email = { text: `'' union select \"password\" from \"User\"`, binders: [] }\n * // -> select \"email\" from \"User\" where \"email\" = '' union select \"password\" from \"User\"\n * ```\n *\n * That is the intended call site with the intended safe value, and it returned\n * the password column out of a statement selecting only `email`. The internal\n * `Fragment` never had the problem because nothing outside `compile/` could\n * construct one; making the type public is what turned \"text plus binders\" from\n * an implementation detail into a shape an attacker can name. `unsafeSql` is\n * built so that reaching for the escape hatch is a decision — a structural check\n * is a second, unmarked door beside it.\n *\n * A `WeakSet` the module owns cannot be forged: membership is granted only by\n * the constructors below. It registers the *returned* object rather than\n * stamping a property, because `concat` and `joinFragments` return fresh objects\n * — a marker property on the inputs would not survive them, and the version that\n * cannot drift is the one that brands what actually comes out.\n */\nconst FRAGMENTS = new WeakSet<object>();\n\nfunction brand(fragment: Fragment): SqlFragment {\n FRAGMENTS.add(fragment);\n return fragment;\n}\n\n/** Whether a value is a fragment *this module made*, so it splices rather than binds. */\nfunction isFragment(value: unknown): value is Fragment {\n return typeof value === \"object\" && value !== null && FRAGMENTS.has(value);\n}\n\n/**\n * A SQL fragment. Every `${value}` is bound as a parameter; a `${fragment}` is\n * spliced in, carrying its own parameters with it.\n *\n * ```ts\n * sql`where \"id\" = ${id}` // \"id\" = $1, with id bound\n * sql`where ${sql`\"a\" = ${1}`} and ${sql`\"b\" = ${2}`}` // nests to any depth\n * ```\n *\n * An interpolated **array** is bound as one value, not expanded — that is what\n * Postgres's `= any($1)` wants, and it is the only reading that does not depend\n * on the dialect. For a comma-separated list of placeholders, say so with\n * `join`.\n *\n * A value at a `::jsonb` cast the caller wrote is the one parameter with a type\n * behind it, and it is bound as **JSON text** so that the statement means what\n * the same statement meant under Prisma's `$executeRaw`:\n *\n * ```ts\n * sql`… set payload = payload || ${JSON.stringify(patch)}::jsonb` // merges\n * ```\n *\n * Without that the driver would JSON-encode the string and the column would\n * hold the document as a jsonb *string* — which `||` appends as an array\n * element rather than merging. `json-param.ts` has the measurements.\n */\nexport function sql(\n strings: TemplateStringsArray,\n ...values: unknown[]\n): SqlFragment {\n // A defensive check rather than a type error, because the interesting misuse\n // is `sql(userInput)` — a plain call with a string, which would otherwise\n // reach `strings.raw` as `undefined` and produce a fragment of `undefined`\n // text rather than an error. It is also the shape somebody reaches for when\n // they want the escape hatch and have not found `unsafeSql`.\n if (!Array.isArray(strings) || !(\"raw\" in (strings as object))) {\n throw new UnsupportedQueryError(\n \"sql\",\n \"DB\",\n \"sql\",\n `'sql' is a tagged template — write sql\\`select 1\\`, not sql(\"select 1\"). ` +\n `To put text that is not a value into a statement, use 'unsafeSql', ` +\n `and read what it says first.`,\n );\n }\n\n const parts: Fragment[] = [];\n\n for (let i = 0; i < strings.length; i++) {\n parts.push(text(strings[i]));\n if (i < values.length) parts.push(interpolate(values[i]));\n }\n\n return brand(concat(...parts));\n}\n\n/**\n * Fragments — or values — joined by a separator, the way `Array.join` reads.\n *\n * ```ts\n * join(filters, \" and \") // a and b and c\n * join([sql`\"a\" asc`, sql`\"b\" desc`]) // \"a\" asc, \"b\" desc\n * join(ids) // $1, $2, $3 — each bound\n * ```\n *\n * An **empty list produces `empty`**, not a separator and not a syntax error, so\n * `join` composes with a list that turned out to have nothing in it. That is the\n * case a caller forgets, and it is the one that would otherwise emit `where ` and\n * fail at the database rather than here.\n *\n * ## The separator is text, so it is not a free string\n *\n * It goes between the fragments *in the statement*, which makes it the one other\n * place a string could reach the SQL — and this module's whole claim is that\n * `unsafeSql` is **the** door. So a plain-string separator has to be glue and\n * nothing else: whitespace, commas, or a boolean connective. Anything more\n * expressive is legitimate and has to say so:\n *\n * ```ts\n * join(filters, \" and \") // fine\n * join(parts, unsafeSql(\") and (\")) // fine, and visibly a decision\n * join(ids, request.query.sep) // refused\n * ```\n *\n * A **blocklist would not do**, which is why this is an allowlist. The obvious\n * one — reject quotes, semicolons and comment markers — lets this through:\n *\n * join([1, 2], \") or 1=1 union select password from Users where 1=(1\")\n *\n * No quote, no `--`, still an injection. There is no sound way to say \"this\n * arbitrary text is safe glue\", so the rule is that glue is a small closed set\n * and everything else is a fragment somebody built on purpose.\n */\nexport function join(\n values: readonly unknown[],\n separator: string | SqlFragment = \", \",\n): SqlFragment {\n if (!Array.isArray(values)) {\n throw new InvalidArgumentError(\n \"join\",\n \"DB\",\n \"sql\",\n `Expected an array of fragments or values, got ${typeof values}.`,\n );\n }\n if (values.length === 0) return empty;\n\n const parts = values.map(interpolate);\n\n if (isFragment(separator)) {\n const woven: Fragment[] = [];\n for (let i = 0; i < parts.length; i++) {\n if (i > 0) woven.push(separator);\n woven.push(parts[i]);\n }\n return brand(concat(...woven));\n }\n\n assertGlue(separator);\n return brand(joinFragments(parts, separator));\n}\n\n/**\n * Whitespace and commas, or a boolean connective surrounded by whitespace.\n *\n * Deliberately small. Every separator a composed statement actually needs is in\n * here — `\", \"`, `\" and \"`, `\" or \"`, `\" \"` — and everything outside it is\n * expressive enough to change what the statement *does*, which is the property\n * that makes it a `unsafeSql` decision rather than a string argument.\n */\nconst GLUE = /^[\\s,]*$|^\\s*(?:and|or)\\s*$/i;\n\nfunction assertGlue(separator: unknown): void {\n if (typeof separator === \"string\" && GLUE.test(separator)) return;\n\n throw new InvalidArgumentError(\n \"join\",\n \"DB\",\n \"sql\",\n typeof separator === \"string\"\n ? `A separator is written into the SQL text, so it may only be glue: ` +\n `whitespace, commas, or 'and' / 'or'. Got ` +\n `${JSON.stringify(separator)}. If that is deliberate, say so with ` +\n `unsafeSql(...) — and never build one from anything that came from ` +\n `outside the program.`\n : `Expected a separator string or a fragment, got ${\n separator === null ? \"null\" : typeof separator\n }.`,\n );\n}\n\n/**\n * The fragment that contributes nothing.\n *\n * The point of it is that `where ${empty}` and `where ${filter}` are the same\n * expression — a conditional predicate is a value, not a branch around the\n * statement. Frozen, because it is shared by every caller and a fragment is read\n * as immutable everywhere else.\n */\nexport const empty: SqlFragment = brand(\n Object.freeze({ text: \"\", binders: Object.freeze([]) as [] }),\n);\n\n/**\n * **Text straight into the SQL, with no parameter around it.** The one door in\n * this ORM through which a value reaches the statement text.\n *\n * Everything else in the compiler exists to make this impossible — identifiers\n * come from the generated schema, values are bound — so reaching for it should\n * feel like reaching for it. **Never give it a value that came from a request, a\n * form, a URL, a header, a queue payload or a database row.** There is no\n * escaping here and there will not be: escaping that is \"usually right\" is worse\n * than none, because it survives review.\n *\n * ## Why it exists at all, since that is the fair question\n *\n * Plan quality can depend on *not* parameterising. A partial index declared as\n *\n * ```sql\n * create index … on \"Job\" (…) where \"name\" is distinct from 'reaper'\n * ```\n *\n * is only usable if the planner can prove the query's predicate matches the\n * index's. A bound parameter is opaque at plan time, so `where \"name\" is\n * distinct from $1` does not match — and the query falls back to a sequential\n * scan over the whole table. The constant has to be *in the text*:\n *\n * ```ts\n * const REAPER = unsafeSql(`'reaper'`) // a literal in this file, never input\n * await DB.query(sql`\n * select … from \"Job\" where \"name\" is distinct from ${REAPER} …\n * `)\n * ```\n *\n * A builder with no escape hatch cannot express that at any price, and the\n * workaround — hand-writing the whole statement — loses composition for every\n * other part of it.\n *\n * The same applies to the other things that cannot be parameters in SQL:\n * identifiers, a sort direction, a table name chosen from a fixed set in code.\n * All of them share the rule above — the value is written in the source file, or\n * chosen from a set written in the source file, never passed in.\n */\nexport function unsafeSql(literal: string): SqlFragment {\n if (typeof literal !== \"string\") {\n throw new InvalidArgumentError(\n \"unsafeSql\",\n \"DB\",\n \"sql\",\n `Expected a string literal, got ${\n Array.isArray(literal) ? \"an array\" : typeof literal\n }. 'unsafeSql' is a plain call, not a tagged template — a template would ` +\n `interpolate values into the SQL text, which is the one thing it must ` +\n `never do.`,\n );\n }\n return brand(text(literal));\n}\n\n/**\n * A fragment as the statement a driver can run: the dialect's placeholders in\n * the text, and the values in the order they appear.\n *\n * Separate from the executing, and exported, because it is the half that is a\n * pure function of `(fragment, dialect)` — so a test can assert what a\n * composition emits on both dialects without a database anywhere near it, which\n * is exactly how the rest of the compiler is tested.\n *\n * `render` also applies the parameter ceiling here, which matters more for a\n * hand-built fragment than for a compiled plan: `join(ids)` over a\n * request-derived list is one placeholder per element on SQLite, and 40 000 of\n * them is a driver error rather than a clear one.\n */\nexport function renderFragment(\n fragment: SqlFragment,\n dialect: SqlDialect,\n operation = \"query\",\n): { text: string; values: unknown[] } {\n if (!isFragment(fragment)) {\n throw new InvalidArgumentError(\n operation,\n \"DB\",\n operation,\n `Expected a fragment built with 'sql', got ${\n fragment === null ? \"null\" : typeof fragment\n }. A plain string is not accepted here on purpose — it would be the one ` +\n `path into the SQL text that nobody had to think about.`,\n );\n }\n\n // The one thing a raw parameter can be *told* about its type: a `::jsonb` the\n // caller wrote onto their own placeholder. Where there is one, the parameter\n // is retyped through `text` and its value serialised, because Bun otherwise\n // JSON-encodes a string bound to a `jsonb` parameter and stores the document\n // as a jsonb *string* where Prisma stored the object. See `json-param.ts` —\n // the mechanism, the measurements, and why a string is not serialised here\n // while `fieldParam` serialises one.\n //\n // The dialect is passed because this is not universal, and the reason is\n // narrower than it looks: `::` is Postgres-only syntax, but `cast(? as json)`\n // *parses and runs* on SQLite, where it means NUMERIC affinity — so retyping\n // it would rewrite a working statement into `cast(? as text)::json`, which\n // SQLite cannot parse. `typesParametersFromStatement` is false there.\n const json = retypeJsonParameters(fragment, dialect);\n\n const rendered = render(json.fragment, dialect, { model: \"DB\", operation });\n return {\n text: rendered.text,\n // `encodeUntyped` and not `encode`: there is no field here to ask, which is\n // the whole difference between a fragment's parameters and a compiled\n // plan's. It normalises the two JavaScript types whose SQL form the ORM has\n // already decided — a `Date` and a boolean — so a raw statement compares\n // against ORM-written rows on both dialects rather than only on Postgres.\n values: bindValues(rendered.binders)(undefined).map((value, index) =>\n json.jsonParameters.has(index)\n ? jsonTextParameter(value, operation)\n : value === null || value === undefined\n ? (value ?? null)\n : dialect.encodeUntyped(value),\n ),\n };\n}\n\n/**\n * One interpolated slot: a fragment splices, anything else binds.\n *\n * The binder ignores both its arguments. A compiled plan's binders read the\n * *call's* argument tree, because one plan serves many calls; a fragment is\n * built per call and closes over the value it was given, which is the whole\n * difference between the compiler's fragments and these.\n */\nfunction interpolate(value: unknown): Fragment {\n if (isFragment(value)) return value;\n return param(() => value);\n}\n"
8
8
  ],
9
- "mappings": ";wLACA,sBAAS,oBAmFF,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,IAAS,EAAqB,OAAY,CACxD,EACA,CACF,EAiBK,SAAS,CAAsB,CAAC,EAAoB,CACzD,IAAM,EAAQ,EAAW,SAAS,EAClC,GAAI,GAAO,KAAO,OAAW,OAE7B,IAAM,EAAO,EAAM,YAAc,EACjC,GAAI,IAAS,EAAM,OAEnB,MAAM,IAAI,EAAgC,EAAM,CAAI,EAI/C,SAAS,CAAgB,EAAkB,CAChD,IAAM,EAAQ,EAAW,SAAS,EAClC,OAAO,GAAO,KAAO,OAAY,KAAO,EAAM,MAIzC,SAAS,CAAa,EAAY,CACvC,OAAO,EAAW,SAAS,GAAG,SAAW,GAgBpC,SAAS,CAAc,CAAC,EAAkC,CAC/D,IAAM,EAAU,EAAW,SAAS,EACpC,OAAO,EAAW,IAAI,IAAK,EAAS,MAAO,GAAS,OAAS,EAAG,OAAQ,EAAK,EAAG,CAAE,EAI7E,SAAS,CAAY,EAAkC,CAC5D,OAAO,EAAW,SAAS,GAAG,MA6BzB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C,EAC1E,MAAO,CACL,KAAM,EAAS,KAMf,OAAQ,EAAW,EAAS,OAAO,EAAE,MAAS,EAAE,IAAI,CAAC,EAAO,IAC1D,EAAK,eAAe,IAAI,CAAK,EACzB,EAAkB,EAAO,CAAS,EAClC,IAAU,MAAQ,IAAU,OACzB,GAAS,KACV,EAAQ,cAAc,CAAK,CACnC,CACF,EAWF,SAAS,CAAW,CAAC,EAA0B,CAC7C,GAAI,EAAW,CAAK,EAAG,OAAO,EAC9B,OAAO,EAAM,IAAM,CAAK",
10
+ "debugId": "14B2E80CDD7EF77E64756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{Ab as a,Bb as O,Jb as M,Lb as Q,Nb as l,Ob as t,Pb as w,Rb as s}from"./chunk-pmhd6zfc.js";import{Yb as X}from"./chunk-4yt5x8s2.js";import{Cc as E,Ec as q,Fc as L,Kc as g,_b as f,gc as S,mc as D,nc as J,oc as k,tc as U,uc as j}from"./chunk-hwa5sqw5.js";import{Vc as i}from"./chunk-86jebsm4.js";import{De as T,He as v,ye as r}from"./chunk-hxf1re93.js";import{Se as c,Te as h}from"./chunk-qb5mv6pj.js";import{qf as Z}from"./chunk-sy7jbdeb.js";import{vf as N}from"./chunk-w62m5f0n.js";import{Af as W,xf as b}from"./chunk-d125j8t0.js";async function Hx(x){try{if(!await x.shouldRun.call(x))return}catch(B){console.error(`Error evaluating shouldRun for cron job ${x.name}:`,B);return}try{await x.onTick.call(x)}catch(B){console.error(`Error executing cron job ${x.name}:`,B)}try{await x.callback.call(x)}catch(B){console.error(`Error in cron job ${x.name}:`,B)}try{await x.onComplete.call(x)}catch(B){console.error(`Error completing cron job ${x.name}:`,B)}}class I{static token="scheduler";handles=[];resolved;constructor(x){this.resolved=x.jobs}get jobs(){return[...this.resolved]}useJobs(x){this.resolved=x}start(x=(B)=>B()){if(this.resolved.length===0)return;let B=globalThis.__gemiCronJobs??=new Map,C=new Map;for(let G of this.resolved){let H=new G;if(!H.name){console.error(`Cron job must have a name \u2014 ${G.name||"an anonymous class"} has none, so it is not scheduled. If this is a base class that other jobs extend, move it out of the discovered directory: \`abstract\` does not survive to runtime, so a class under app/cron is indistinguishable from a job.`);continue}if(!H.cron){console.error(`Cron job must have an expression. Job: ${H.name}`);continue}let Y=C.get(H.name);if(Y!==void 0){console.error(`Two cron jobs claim the name "${H.name}" \u2014 ${Y} is scheduled and ${G.name||"an anonymous class"} is not. A name is the scheduler's key, so only one job can hold it. Rename one.`);continue}C.set(H.name,G.name||"an anonymous class"),B.get(H.name)?.stop();let _=Bun.cron(H.cron,()=>x(()=>Hx(H)));B.set(H.name,_),this.handles.push(_)}}stop(){for(let x of this.handles)x.stop();this.handles=[]}}class Xx extends X{register(){this.app.singleton(T,()=>new T(this.app.config.get("auth",{})))}}class Yx extends X{register(){this.app.singleton(I,()=>new I(Z(M(),this.app.config.get("schedule",{}))))}async boot(){let x=this.app.make(I),B=this.app.config.get("schedule",{});if(B.jobs===void 0){let{jobsDir:G}=Z(M(),B);x.useJobs(await w(G))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let C=this.app;x.start((G)=>b.run(C,G))}}class R{}class F extends Error{modelName;kind="FeatureModelMissing";constructor(x){super(`No "${x}" model is registered, so every feature stays off. Add the model to prisma/schema.prisma and export it from app/models \u2014 see docs/feature-flags.md.`);this.modelName=x}}class A extends R{modelName;constructor(x="FeatureFlag"){super();this.modelName=x}get available(){return c(this.modelName)}async load(){if(!this.available)throw new F(this.modelName);let x=h(this.modelName);return await x.asSystem(()=>x.findMany())}}function cx(x){return x}function u(){return{features:void 0,enabled:!0,source:new A,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class Zx extends X{register(){this.app.singleton(E,()=>{let x=this.app.config.get("features",{}),B=Z(u(),x);if(x?.model!==void 0&&x?.source===void 0)B.source=new A(x.model);else if(x?.model!==void 0&&x.source instanceof A&&x.source.modelName!==x.model)U.warning(`app/config/features.ts sets \`model: "${x.model}"\` and a source reading "${x.source.modelName}". The source wins; drop \`model\` to silence this.`);return new E(B,(C)=>U.warning(C))})}async boot(){let x=this.app.make(E);if(!x.config.enabled)return;try{await x.refresh()}catch(B){U.error(`Could not warm the feature flag cache at boot. ${B instanceof Error?B.message:String(B)}`)}}}class _x extends X{register(){this.app.singleton(N,()=>new N(this.app.config.get("mail",{})))}}function $x(x){return`listener:${x}`}function d(x,B){Px(x);let{maxAttempts:C,worker:G}=B,H=x.event.name,Y=class extends l{maxAttempts=C;worker=G;async run(..._){let[$,P]=Ox(_),z=W(V).rehydrate($,P);await new x().handle(z)}onFail(_){console.error(`The listener ${x.name} threw while handling ${H} off the queue. The queue will retry it up to ${C} times in total; nothing the dispatcher did is waiting on it.`,_)}onDeadletter(_){console.error(`The listener ${x.name} failed every one of its ${C} attempts at ${H} and has been dead-lettered, so this side effect did not happen and will not be retried.`,_)}};return Object.defineProperty(Y,"name",{value:$x(x.name),writable:!0}),Y}function Px(x){if(Object.getOwnPropertyDescriptor(x,"name")?.writable)return;throw Error(`The listener ${x.name} sets \`queued = true\` but does not declare \`static name\`, so it would be registered with the queue `+"under its class name \u2014 which a production build renames while the "+`payload that names it does not. Add: static name = "${x.name}";`)}function Ox(x){return typeof x[0]==="string"?x:x[0]}class V{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor(x={}){this.config=Z(Q(),x),this.useListeners(this.config.listeners)}useListeners(x){this.config.listeners=x,this.listeners={},this.events={};let B=new Set;for(let C of x){if(!C.event){console.error(`Listener ${C.name} does not declare \`static event\`, so there is no event name to register it under and its handle will never run. Add: static event = SomeEvent;`);continue}if(B.has(C.name)){console.error(`Two event listeners are named "${C.name}" \u2014 the first is `+"registered and this one is not. A listener's name identifies it across the framework, so only one class can hold it. Rename one.");continue}B.add(C.name);let G=C.event.name,H=new C;this.events[G]??=C.event,(this.listeners[G]??=[]).push({listener:C,job:H.queued?d(C,H):null})}}get queuedListenerJobs(){return Object.values(this.listeners).flat().flatMap(({job:x})=>x?[x]:[])}get registeredListeners(){return[...this.config.listeners]}dispatch(x,B){if(this.deferToCommit(x,B,!1))return;this.runListeners(x,B)}async dispatchAndWait(x,B){if(this.deferToCommit(x,B,!0))return;return this.runListeners(x,B)}deferToCommit(x,B,C){let{name:G,afterCommit:H}=x.constructor;if(!H)return!1;let Y=i(()=>this.runListeners(x,B));if(Y&&C)this.warnNothingIsWaitedFor(G);return Y}async runListeners(x,B){let C=x.constructor.name,G=this.listeners[C];if(!G?.length){this.warnNothingIsListening(C);return}for(let{listener:H,job:Y}of G){if(Y){this.enqueue(Y,H,C,B);continue}try{await new H().handle(x)}catch(_){console.error(`The listener ${H.name} threw while handling ${C}. The `+"listeners after it still ran \u2014 a listener's failure is its own.",_)}}}rehydrate(x,B=[]){let C=this.events[x];if(!C)throw Error(`Cannot rebuild the event "${x}" that came off the queue: no registered listener binds to an event of that name, so there is no class to construct. A queued listener runs in an application that `+"discovered its own listeners \u2014 check that this process sees the "+`same app/listeners as the one that dispatched, and that the event declares \`static name = "${x}"\`.`);return new C(...B)}enqueue(x,B,C,G){if(G===void 0){console.error(`The listener ${B.name} is queued, but ${C} reached the dispatcher without its constructor arguments, so there is nothing for the queue to rebuild it from and the listener was skipped. Dispatch through ${C}.dispatch(...) or ${C}.dispatchAndWait(...), which carry them.`);return}try{W(O).push(x,JSON.stringify([C,G]))}catch(H){console.error(`The listener ${B.name} could not be queued for ${C}, so it did not run and will not be retried. The listeners after it still ran.`,H)}}warnNothingIsWaitedFor(x){if(Bun.env.NODE_ENV==="production")return;if(this.warnedAboutWaiting.has(x))return;this.warnedAboutWaiting.add(x),console.warn(`[gemi] ${x}.dispatchAndWait() was called inside a transaction and ${x} declares \`static afterCommit = true\`, so it resolved `+"immediately with no listener having run \u2014 they run when the "+"transaction commits. Await the transaction instead, or drop afterCommit if the caller needs the side effects first. Development only.")}warnNothingIsListening(x){if(Bun.env.NODE_ENV==="production")return;if(this.warnedFor.has(x))return;this.warnedFor.add(x),console.warn(`[gemi] ${x} was dispatched and nothing is listening for it. A listener registers under the name its event declares, so check that app/listeners holds a Listener with \`static event = ${x}\` and that ${x} declares \`static name = "${x}"\`. Development only.`)}}class zx extends X{register(){this.app.singleton(V,()=>new V(this.app.config.get("events",{})))}async boot(){let x=this.app.make(V),B=this.app.config.get("events",{});if(B.listeners===void 0){let{listenersDir:H}=Z(Q(),B);x.useListeners(await s(H))}let C=x.queuedListenerJobs;if(C.length===0)return;let G=this.app.make(O);for(let H of C)G.registerJob(H)}}class Kx extends X{register(){this.app.singleton(S,()=>new S(this.app.config.get("filesystem",{})))}}class Vx extends X{register(){this.app.singleton(D,()=>new D(this.app.config.get("image",{})))}}class Ax extends X{register(){this.app.instance(j,new j)}}function FB(x){return x}function o(){return{maxFileSize:10485760,onLogFileClosed:()=>{},onLogCreated:()=>{}}}class Ix extends X{register(){this.app.singleton(J,()=>new J(Z(o(),this.app.config.get("log",{}))))}async boot(){await this.app.make(J).boot()}}class Ux extends X{register(){this.app.singleton(k,()=>new k(Z(r(),this.app.config.get("middleware",{}))))}}function bB(x){return x}function n(){return{channels:{}}}class Ex extends X{register(){this.app.singleton(f,()=>new f(Z(n(),this.app.config.get("broadcast",{}))))}}class Wx extends X{register(){this.app.singleton(O,()=>new O(this.app.config.get("queue",{})))}async boot(){let x=this.app.config.get("queue",{});if(x.jobs!==void 0)return;let{jobsDir:B}=Z(a(),x);this.app.make(O).useJobs(await t(B))}}class y{}function e(x,B){return Math.floor(x/B)*B}function Qx(x,B){if(B<=0)return 0;return Math.min(1,Math.max(0,(B-x)/B))}function p(x,B,C,G){return B*Qx(C,G)+x}function Jx(x){let{current:B,previous:C,elapsed:G,window:H,limit:Y,cost:_}=x,$=Y-_;if($<0)return H;let P=Math.max(0,H-G);if(C>0){let K=H*(1-($-B)/C);if(K<=H)return Math.max(0,Math.ceil(K-G))}if(B<=$)return P;if(B<=0)return P;let z=H*(1-$/B);return P+Math.max(0,Math.ceil(z))}function xx(x){let{allowed:B,current:C,previous:G,now:H,elapsed:Y,window:_,limit:$,cost:P}=x;if(B){let K=p(C,G,Y,_);return{allowed:!0,limit:$,remaining:Math.max(0,Math.floor($-K)),resetAt:H-Y+_,retryAfter:0}}let z=Jx({current:C,previous:G,elapsed:Y,window:_,limit:$,cost:P});return{allowed:!1,limit:$,remaining:0,resetAt:H+z,retryAfter:z}}class m extends y{buckets=new Map;maxKeys;constructor(x={}){super();this.maxKeys=Math.max(1,x.maxKeys??1e5)}consume(x){let{key:B,limit:C,window:G}=x,H=x.cost??1,Y=Date.now(),_=e(Y,G),$=Y-_,P=this.roll(B,G,_),K=p(P.current,P.previous,$,G)+H<=C;if(K)P.current+=H;if(this.buckets.delete(B),this.buckets.set(B,P),this.buckets.size>this.maxKeys)this.evict(Y);return xx({allowed:K,current:P.current,previous:P.previous,now:Y,elapsed:$,window:G,limit:C,cost:H})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll(x,B,C){let G=this.buckets.get(x);if(!G||G.window!==B)return{window:B,windowStart:C,current:0,previous:0};if(G.windowStart===C)return G;if(G.windowStart+B===C)return G.previous=G.current,G.current=0,G.windowStart=C,G;return G.previous=0,G.current=0,G.windowStart=C,G}evict(x){for(let[B,C]of this.buckets)if(x-C.windowStart>=C.window*2)this.buckets.delete(B);for(let B of this.buckets.keys()){if(this.buckets.size<=this.maxKeys)break;this.buckets.delete(B)}}}function HC(x){return x}function Bx(){return{driver:new m,limit:1000,window:60}}class qx extends X{register(){this.app.singleton(v,()=>new v(Z(Bx(),this.app.config.get("ratelimiter",{}))))}}function OC(x){return x}function Cx(){return{url:process.env.REDIS_URL,options:void 0}}class Lx extends X{register(){this.app.singleton(g,()=>new g(Z(Cx(),this.app.config.get("redis",{}))))}}function Gx(x,B){let C=x.get(B);if(!C)throw Error(`Missing "${B}" configuration. Route dispatching needs a root router \u2014 declare it in "app/config/route.ts".`);return C}class Tx extends X{register(){this.app.singleton(L,()=>new L(Gx(this.app.config,"route.api"))),this.app.singleton(q,()=>new q(Gx(this.app.config,"route.view")))}boot(){this.app.make(L),this.app.make(q)}}
3
+ export{I as Ta,Xx as Ua,Yx as Va,R as Wa,F as Xa,A as Ya,cx as Za,u as _a,Zx as $a,_x as ab,V as bb,zx as cb,Kx as db,Vx as eb,Ax as fb,FB as gb,o as hb,Ix as ib,Ux as jb,bB as kb,n as lb,Ex as mb,Wx as nb,e as ob,xx as pb,y as qb,m as rb,HC as sb,Bx as tb,qx as ub,OC as vb,Cx as wb,Lx as xb,Tx as yb};
4
+
5
+ //# debugId=5D03A6748D65150C64756E2164756E21