gemi 0.86.1 → 0.88.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 (233) hide show
  1. package/dist/ai/Agent.d.ts +44 -2
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentController.d.ts +5 -0
  4. package/dist/ai/AgentController.d.ts.map +1 -1
  5. package/dist/ai/Schema.d.ts +102 -0
  6. package/dist/ai/Schema.d.ts.map +1 -1
  7. package/dist/ai/index.d.ts +3 -3
  8. package/dist/ai/index.d.ts.map +1 -1
  9. package/dist/ai/index.js +12 -12
  10. package/dist/ai/index.js.map +5 -5
  11. package/dist/ai/signing.d.ts +34 -1
  12. package/dist/ai/signing.d.ts.map +1 -1
  13. package/dist/app/index.js +1 -1
  14. package/dist/auth/AuthController.d.ts +45 -3
  15. package/dist/auth/AuthController.d.ts.map +1 -1
  16. package/dist/auth/AuthManager.d.ts +42 -1
  17. package/dist/auth/AuthManager.d.ts.map +1 -1
  18. package/dist/auth/UserProvider.d.ts +18 -1
  19. package/dist/auth/UserProvider.d.ts.map +1 -1
  20. package/dist/auth/config.d.ts +109 -0
  21. package/dist/auth/config.d.ts.map +1 -1
  22. package/dist/auth/oneTimeCode.d.ts +99 -0
  23. package/dist/auth/oneTimeCode.d.ts.map +1 -0
  24. package/dist/auth/routes.d.ts +13 -0
  25. package/dist/auth/routes.d.ts.map +1 -1
  26. package/dist/auth/types.d.ts +8 -0
  27. package/dist/auth/types.d.ts.map +1 -1
  28. package/dist/bin/gemi.js +198 -39
  29. package/dist/bin/gemi.js.map +5 -4
  30. package/dist/bun/plugin.js +1 -1
  31. package/dist/bun/preload.js +1 -1
  32. package/dist/{chunk-swhyp0yw.js → chunk-0808z3mq.js} +2 -2
  33. package/dist/{chunk-swhyp0yw.js.map → chunk-0808z3mq.js.map} +1 -1
  34. package/dist/{chunk-d3jkypc7.js → chunk-0efykzjy.js} +3 -3
  35. package/dist/{chunk-d3jkypc7.js.map → chunk-0efykzjy.js.map} +1 -1
  36. package/dist/{chunk-zs90w6ke.js → chunk-16mnpn6c.js} +2 -2
  37. package/dist/{chunk-zs90w6ke.js.map → chunk-16mnpn6c.js.map} +1 -1
  38. package/dist/{chunk-1jcp8m8h.js → chunk-17nh5gfm.js} +2 -2
  39. package/dist/{chunk-1jcp8m8h.js.map → chunk-17nh5gfm.js.map} +1 -1
  40. package/dist/{chunk-mszy6cfw.js → chunk-3ph0aj0x.js} +2 -2
  41. package/dist/{chunk-mszy6cfw.js.map → chunk-3ph0aj0x.js.map} +1 -1
  42. package/dist/{chunk-qje4kdff.js → chunk-3rb5ht8v.js} +3 -3
  43. package/dist/{chunk-qje4kdff.js.map → chunk-3rb5ht8v.js.map} +1 -1
  44. package/dist/chunk-3w65ra1s.js +5 -0
  45. package/dist/{chunk-1yzdxv2a.js.map → chunk-3w65ra1s.js.map} +1 -1
  46. package/dist/{chunk-v8nf45gt.js → chunk-443dm19c.js} +2 -2
  47. package/dist/{chunk-v8nf45gt.js.map → chunk-443dm19c.js.map} +1 -1
  48. package/dist/{chunk-4ysar3ev.js → chunk-49v5xq8q.js} +2 -2
  49. package/dist/{chunk-4ysar3ev.js.map → chunk-49v5xq8q.js.map} +1 -1
  50. package/dist/chunk-4v4v5wkh.js +7 -0
  51. package/dist/chunk-4v4v5wkh.js.map +11 -0
  52. package/dist/{chunk-2yw23zhn.js → chunk-523t3bcz.js} +4 -4
  53. package/dist/{chunk-2yw23zhn.js.map → chunk-523t3bcz.js.map} +1 -1
  54. package/dist/{chunk-1yq1e6sb.js → chunk-56p9a7nx.js} +3 -3
  55. package/dist/{chunk-1yq1e6sb.js.map → chunk-56p9a7nx.js.map} +1 -1
  56. package/dist/{chunk-fbwe0agk.js → chunk-61rs7kxf.js} +2 -2
  57. package/dist/{chunk-fbwe0agk.js.map → chunk-61rs7kxf.js.map} +1 -1
  58. package/dist/{chunk-cbycz5z3.js → chunk-64z2zt41.js} +2 -2
  59. package/dist/{chunk-cbycz5z3.js.map → chunk-64z2zt41.js.map} +1 -1
  60. package/dist/{chunk-saqfc6vp.js → chunk-6dyt8w27.js} +4 -4
  61. package/dist/{chunk-saqfc6vp.js.map → chunk-6dyt8w27.js.map} +1 -1
  62. package/dist/{chunk-ha705bcz.js → chunk-6rc6yec4.js} +3 -3
  63. package/dist/{chunk-ha705bcz.js.map → chunk-6rc6yec4.js.map} +1 -1
  64. package/dist/{chunk-09sr33ff.js → chunk-6s6fj97j.js} +2 -2
  65. package/dist/{chunk-09sr33ff.js.map → chunk-6s6fj97j.js.map} +1 -1
  66. package/dist/{chunk-7nj2t2gm.js → chunk-6tt3ynm7.js} +2 -2
  67. package/dist/{chunk-7nj2t2gm.js.map → chunk-6tt3ynm7.js.map} +1 -1
  68. package/dist/{chunk-trdwxm5x.js → chunk-6y62ccam.js} +3 -3
  69. package/dist/{chunk-trdwxm5x.js.map → chunk-6y62ccam.js.map} +1 -1
  70. package/dist/{chunk-81v4c4b1.js → chunk-713fezaz.js} +2 -2
  71. package/dist/{chunk-81v4c4b1.js.map → chunk-713fezaz.js.map} +1 -1
  72. package/dist/{chunk-xckeyg3v.js → chunk-78gs7xvn.js} +2 -2
  73. package/dist/{chunk-xckeyg3v.js.map → chunk-78gs7xvn.js.map} +1 -1
  74. package/dist/{chunk-ndat0nf0.js → chunk-7r78cdyd.js} +2 -2
  75. package/dist/{chunk-ndat0nf0.js.map → chunk-7r78cdyd.js.map} +1 -1
  76. package/dist/chunk-86p57tjw.js +5 -0
  77. package/dist/{chunk-hmh79ezn.js.map → chunk-86p57tjw.js.map} +3 -6
  78. package/dist/{chunk-ct7wxm98.js → chunk-8dpnghvk.js} +2 -2
  79. package/dist/{chunk-ct7wxm98.js.map → chunk-8dpnghvk.js.map} +1 -1
  80. package/dist/{chunk-zf4r4kat.js → chunk-8pesk2wm.js} +2 -2
  81. package/dist/{chunk-zf4r4kat.js.map → chunk-8pesk2wm.js.map} +1 -1
  82. package/dist/{chunk-8gexb1gt.js → chunk-8r7xhy1g.js} +2 -2
  83. package/dist/{chunk-8gexb1gt.js.map → chunk-8r7xhy1g.js.map} +1 -1
  84. package/dist/{chunk-gx0x772p.js → chunk-8y08amzz.js} +2 -2
  85. package/dist/{chunk-gx0x772p.js.map → chunk-8y08amzz.js.map} +1 -1
  86. package/dist/{chunk-y7qnx8vm.js → chunk-9c1zx81w.js} +2 -2
  87. package/dist/{chunk-y7qnx8vm.js.map → chunk-9c1zx81w.js.map} +1 -1
  88. package/dist/{chunk-7c33ngqs.js → chunk-ak3yy4za.js} +2 -2
  89. package/dist/{chunk-7c33ngqs.js.map → chunk-ak3yy4za.js.map} +1 -1
  90. package/dist/{chunk-z6cgama8.js → chunk-aqtf14yz.js} +2 -2
  91. package/dist/{chunk-z6cgama8.js.map → chunk-aqtf14yz.js.map} +1 -1
  92. package/dist/{chunk-z4k18gnp.js → chunk-bsbn7qtd.js} +2 -2
  93. package/dist/{chunk-z4k18gnp.js.map → chunk-bsbn7qtd.js.map} +1 -1
  94. package/dist/{chunk-2gdhcswa.js → chunk-d1r618e8.js} +1 -1
  95. package/dist/{chunk-v4ngf77f.js → chunk-d5h5v4rj.js} +2 -2
  96. package/dist/{chunk-v4ngf77f.js.map → chunk-d5h5v4rj.js.map} +1 -1
  97. package/dist/{chunk-7n5775qx.js → chunk-e3fnjj0h.js} +2 -2
  98. package/dist/{chunk-7n5775qx.js.map → chunk-e3fnjj0h.js.map} +1 -1
  99. package/dist/chunk-efzvxta5.js +24 -0
  100. package/dist/{chunk-gs8x0k68.js.map → chunk-efzvxta5.js.map} +6 -5
  101. package/dist/{chunk-sjckrbr2.js → chunk-fkt43zw1.js} +2 -2
  102. package/dist/{chunk-sjckrbr2.js.map → chunk-fkt43zw1.js.map} +1 -1
  103. package/dist/{chunk-p7r3ecpk.js → chunk-g2bsmw1m.js} +2 -2
  104. package/dist/{chunk-9tsw1bmt.js.map → chunk-g2bsmw1m.js.map} +1 -1
  105. package/dist/{chunk-1w5a11cd.js → chunk-gzfat1x1.js} +2 -2
  106. package/dist/{chunk-1w5a11cd.js.map → chunk-gzfat1x1.js.map} +1 -1
  107. package/dist/{chunk-wwzg4dmy.js → chunk-hnbj9jx2.js} +3 -3
  108. package/dist/{chunk-wwzg4dmy.js.map → chunk-hnbj9jx2.js.map} +1 -1
  109. package/dist/{chunk-dadygfkf.js → chunk-j0fgc58k.js} +2 -2
  110. package/dist/{chunk-dadygfkf.js.map → chunk-j0fgc58k.js.map} +1 -1
  111. package/dist/{chunk-6nnq3rjj.js → chunk-j3y6pdqp.js} +2 -2
  112. package/dist/{chunk-6nnq3rjj.js.map → chunk-j3y6pdqp.js.map} +1 -1
  113. package/dist/{chunk-v2hvnxsf.js → chunk-jfgjscq6.js} +2 -2
  114. package/dist/{chunk-v2hvnxsf.js.map → chunk-jfgjscq6.js.map} +1 -1
  115. package/dist/{chunk-k5j65f2c.js → chunk-ngq4n2b3.js} +2 -2
  116. package/dist/{chunk-k5j65f2c.js.map → chunk-ngq4n2b3.js.map} +1 -1
  117. package/dist/{chunk-kmsrzbx1.js → chunk-pqydkns8.js} +2 -2
  118. package/dist/{chunk-kmsrzbx1.js.map → chunk-pqydkns8.js.map} +1 -1
  119. package/dist/{chunk-pzwyg474.js → chunk-pw95y0fx.js} +2 -2
  120. package/dist/{chunk-pzwyg474.js.map → chunk-pw95y0fx.js.map} +1 -1
  121. package/dist/{chunk-9tv5j3b2.js → chunk-pwaftx6n.js} +3 -3
  122. package/dist/{chunk-9tv5j3b2.js.map → chunk-pwaftx6n.js.map} +1 -1
  123. package/dist/{chunk-p0m3qgs5.js → chunk-q6ydpt33.js} +2 -2
  124. package/dist/{chunk-p0m3qgs5.js.map → chunk-q6ydpt33.js.map} +1 -1
  125. package/dist/{chunk-81k26w39.js → chunk-r1sj312m.js} +2 -2
  126. package/dist/{chunk-81k26w39.js.map → chunk-r1sj312m.js.map} +1 -1
  127. package/dist/{chunk-55x9kkdt.js → chunk-r78aqvne.js} +2 -2
  128. package/dist/{chunk-55x9kkdt.js.map → chunk-r78aqvne.js.map} +1 -1
  129. package/dist/{chunk-1b5s4w5f.js → chunk-r9qzgvpx.js} +2 -2
  130. package/dist/{chunk-1b5s4w5f.js.map → chunk-r9qzgvpx.js.map} +1 -1
  131. package/dist/{chunk-174jkg6d.js → chunk-rhe7s1fm.js} +3 -3
  132. package/dist/{chunk-174jkg6d.js.map → chunk-rhe7s1fm.js.map} +1 -1
  133. package/dist/{chunk-vwp1g8wh.js → chunk-rp0reqjn.js} +2 -2
  134. package/dist/{chunk-vwp1g8wh.js.map → chunk-rp0reqjn.js.map} +1 -1
  135. package/dist/{chunk-cfykfnqx.js → chunk-rw0t90pf.js} +2 -2
  136. package/dist/{chunk-cfykfnqx.js.map → chunk-rw0t90pf.js.map} +1 -1
  137. package/dist/{chunk-mk8m3ffx.js → chunk-s72y1w84.js} +2 -2
  138. package/dist/{chunk-mk8m3ffx.js.map → chunk-s72y1w84.js.map} +1 -1
  139. package/dist/{chunk-9tsw1bmt.js → chunk-t93t317r.js} +2 -2
  140. package/dist/{chunk-p7r3ecpk.js.map → chunk-t93t317r.js.map} +1 -1
  141. package/dist/{chunk-dwqh79e5.js → chunk-ttckhvew.js} +2 -2
  142. package/dist/{chunk-dwqh79e5.js.map → chunk-ttckhvew.js.map} +1 -1
  143. package/dist/{chunk-rdnm6rem.js → chunk-whjhrz97.js} +2 -2
  144. package/dist/{chunk-rdnm6rem.js.map → chunk-whjhrz97.js.map} +1 -1
  145. package/dist/{chunk-sejnmn1q.js → chunk-x85x83pa.js} +1 -1
  146. package/dist/{chunk-s046a984.js → chunk-xc90ycw2.js} +2 -2
  147. package/dist/{chunk-s046a984.js.map → chunk-xc90ycw2.js.map} +1 -1
  148. package/dist/{chunk-jhe0t7yj.js → chunk-xqyx8kzr.js} +2 -2
  149. package/dist/{chunk-jhe0t7yj.js.map → chunk-xqyx8kzr.js.map} +2 -2
  150. package/dist/{chunk-c3gzpjba.js → chunk-yafxbmy3.js} +1 -1
  151. package/dist/{chunk-pmmrhak1.js → chunk-yc3n6zhr.js} +3 -3
  152. package/dist/{chunk-pmmrhak1.js.map → chunk-yc3n6zhr.js.map} +1 -1
  153. package/dist/chunk-ymgehegb.js +17 -0
  154. package/dist/{chunk-tag4fdmj.js.map → chunk-ymgehegb.js.map} +12 -8
  155. package/dist/{chunk-m7y8d3k7.js → chunk-zf8bgrnj.js} +2 -2
  156. package/dist/{chunk-m7y8d3k7.js.map → chunk-zf8bgrnj.js.map} +1 -1
  157. package/dist/{chunk-fc2je244.js → chunk-zn5bqe6m.js} +3 -3
  158. package/dist/{chunk-fc2je244.js.map → chunk-zn5bqe6m.js.map} +1 -1
  159. package/dist/{chunk-4zj05vry.js → chunk-ztzd90gp.js} +2 -2
  160. package/dist/{chunk-4zj05vry.js.map → chunk-ztzd90gp.js.map} +1 -1
  161. package/dist/chunks/{ThemeProvider-D1kDfCwY.js → ThemeProvider-z_MW40tl.js} +126 -6
  162. package/dist/chunks/ThemeProvider-z_MW40tl.js.map +1 -0
  163. package/dist/client/ClientRouter.d.ts.map +1 -1
  164. package/dist/client/ClientRouterContext.d.ts.map +1 -1
  165. package/dist/client/ComponentContext.d.ts +8 -1
  166. package/dist/client/ComponentContext.d.ts.map +1 -1
  167. package/dist/client/MutationError.d.ts +4 -4
  168. package/dist/client/auth/useEmailCode.d.ts +36 -0
  169. package/dist/client/auth/useEmailCode.d.ts.map +1 -0
  170. package/dist/client/chunkLoadRecovery.d.ts +96 -0
  171. package/dist/client/chunkLoadRecovery.d.ts.map +1 -0
  172. package/dist/client/index.d.ts +4 -0
  173. package/dist/client/index.d.ts.map +1 -1
  174. package/dist/client/index.js +53 -4
  175. package/dist/client/index.js.map +1 -1
  176. package/dist/client/init.d.ts +9 -0
  177. package/dist/client/init.d.ts.map +1 -1
  178. package/dist/config/index.d.ts +12 -0
  179. package/dist/config/index.d.ts.map +1 -1
  180. package/dist/config/index.js +1 -1
  181. package/dist/config/index.js.map +2 -2
  182. package/dist/console/run.js +2 -2
  183. package/dist/console/run.js.map +1 -1
  184. package/dist/container/index.js +2 -2
  185. package/dist/container/index.js.map +1 -1
  186. package/dist/database/index.js +2 -2
  187. package/dist/database/index.js.map +1 -1
  188. package/dist/email/index.js +2 -2
  189. package/dist/email/index.js.map +1 -1
  190. package/dist/facades/index.js +2 -2
  191. package/dist/facades/index.js.map +1 -1
  192. package/dist/foundation/index.js +2 -2
  193. package/dist/foundation/index.js.map +1 -1
  194. package/dist/http/Error.d.ts +2 -2
  195. package/dist/http/index.js +2 -2
  196. package/dist/http/index.js.map +1 -1
  197. package/dist/i18n/dictionaryRuntime.js +2 -2
  198. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  199. package/dist/i18n/index.js +2 -2
  200. package/dist/i18n/index.js.map +1 -1
  201. package/dist/kernel/index.d.ts +2 -0
  202. package/dist/kernel/index.d.ts.map +1 -1
  203. package/dist/kernel/index.js +3 -3
  204. package/dist/kernel/index.js.map +2 -2
  205. package/dist/orm/index.js +3 -3
  206. package/dist/orm/index.js.map +1 -1
  207. package/dist/server/forwardedFor.d.ts +1 -1
  208. package/dist/server/index.js +2 -2
  209. package/dist/server/index.js.map +1 -1
  210. package/dist/server/staticAssetMiss.d.ts +7 -0
  211. package/dist/server/staticAssetMiss.d.ts.map +1 -1
  212. package/dist/services/index.d.ts +1 -1
  213. package/dist/services/index.d.ts.map +1 -1
  214. package/dist/services/index.js +3 -3
  215. package/dist/services/index.js.map +1 -1
  216. package/dist/services/queue/work.js +2 -2
  217. package/dist/services/queue/work.js.map +1 -1
  218. package/dist/services/rate-limiter/drivers/InMemoryRateLimiterDriver.d.ts +10 -1
  219. package/dist/services/rate-limiter/drivers/InMemoryRateLimiterDriver.d.ts.map +1 -1
  220. package/dist/support/index.js +2 -2
  221. package/dist/support/index.js.map +1 -1
  222. package/dist/testing/index.js +1 -1
  223. package/package.json +1 -1
  224. package/dist/chunk-1yzdxv2a.js +0 -5
  225. package/dist/chunk-gs8x0k68.js +0 -24
  226. package/dist/chunk-hmh79ezn.js +0 -5
  227. package/dist/chunk-tag4fdmj.js +0 -17
  228. package/dist/chunk-w312e9nx.js +0 -5
  229. package/dist/chunk-w312e9nx.js.map +0 -11
  230. package/dist/chunks/ThemeProvider-D1kDfCwY.js.map +0 -1
  231. /package/dist/{chunk-2gdhcswa.js.map → chunk-d1r618e8.js.map} +0 -0
  232. /package/dist/{chunk-sejnmn1q.js.map → chunk-x85x83pa.js.map} +0 -0
  233. /package/dist/{chunk-c3gzpjba.js.map → chunk-yafxbmy3.js.map} +0 -0
@@ -13,6 +13,6 @@
13
13
  "import { existsSync } from \"node:fs\";\nimport { dirname, isAbsolute, join } from \"node:path\";\n\nimport {\n discoverClasses,\n DiscoveryError,\n projectRoot,\n} from \"../support/discover\";\nimport { Command, type CommandClass } from \"../console/Command\";\nimport { commandConfigDefaults } from \"../console/config\";\nimport { isUnfinishedBuilder } from \"../console/builder\";\nimport { CronJob } from \"./cron/CronJob\";\nimport { scheduleConfigDefaults } from \"./cron/config\";\nimport { eventConfigDefaults } from \"./events/config\";\nimport type { EventClass } from \"./events/Event\";\nimport { Listener, type ListenerClass } from \"./events/Listener\";\nimport { Job } from \"./queue/Job\";\nimport { queueConfigDefaults } from \"./queue/config\";\n\n/**\n * Reading an application's jobs off the filesystem, for the two subsystems that\n * were asking every app to write its job list twice.\n *\n * Both functions here are the same call to `discoverClasses` with a different\n * base class, which is deliberate: one walk, one set of skip rules, one answer\n * to \"what does this app have\". They are exported from `gemi/services` rather\n * than kept private to the providers because the list stopped being something\n * an app could import — a test that used to walk the exported `jobs` array\n * needs somewhere to ask the same question, and so does a script.\n *\n * What the providers add on top of these is the decision of *whether* to ask,\n * which is the config's to make and not this file's.\n */\n\n/**\n * A directory the app named, resolved the way the app meant it.\n *\n * Relative paths hang off the project root rather than `process.cwd()` at the\n * moment of the call, because a config slice saying `app/jobs` means the app's\n * `app/jobs` and not whatever directory somebody happened to launch a script\n * from. Absolute paths are taken as given, which is what makes these callable\n * from a test that has no project around it.\n */\nfunction resolveDir(dir: string): string {\n return isAbsolute(dir) ? dir : join(projectRoot(), dir);\n}\n\n/**\n * Says something when the directory is missing *and so is the tree it lives in*.\n *\n * A missing directory has two readings and they want opposite responses. An app\n * that has never written a cron job has no `app/cron`, and warning about that on\n * every boot for the rest of its life is noise — the answer \"you have no cron\n * jobs\" is correct and uninteresting. But a deploy that ships `dist/` and\n * `node_modules/` without the source has no `app/cron` *and no `app/`*, and\n * there discovery quietly returns nothing while the app very much does have\n * jobs: the exact silence #322 and #323 exist to remove, reintroduced one layer\n * down and in production only.\n *\n * The parent directory is what tells them apart. If neither the directory nor\n * the one above it is there, the tree this was pointed into is not there\n * either, and that is worth a sentence.\n */\nfunction warnIfSourceIsMissing(\n resolved: string,\n subject: string,\n slice: string,\n) {\n if (existsSync(resolved) || existsSync(dirname(resolved))) return;\n\n console.warn(\n `No ${subject} were discovered: neither ${resolved} nor the directory ` +\n `above it exists, so this process cannot see the application's source. ` +\n `If this is a deploy that ships only the build output, list the classes ` +\n `explicitly in app/config/${slice}.ts so they travel with it.`,\n );\n}\n\n/**\n * The `Job` subclasses under `dir`, defaulting to the config slice's `app/jobs`.\n *\n * This is what a `queue` config slice with no `jobs` key resolves to. Call it\n * directly to ask the question a test used to answer by importing the array:\n * every job this application would register, in the order it would register\n * them.\n *\n * Every file underneath is imported, so calling this runs the app's job modules\n * — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverJobs(\n dir: string = queueConfigDefaults().jobsDir,\n): Promise<Array<new () => Job>> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"queue jobs\", \"queue\");\n const jobs = await discoverClasses(resolved, Job);\n warnIfNameWillNotSurviveTheBuild(jobs);\n return jobs;\n}\n\n/**\n * Says something about a discovered job that never declared `static name`.\n *\n * This is the one hazard discovery introduces rather than removes, and it is\n * production-only. `gemi build` minifies the server entry, and app code\n * reachable from it — a controller, and every job class that controller\n * imports to dispatch — is bundled and minified with it. Minification renames\n * the class binding, and a class's implicit `.name` is that binding: a\n * `TestJob` in the bundle reports `\"D\"`. Discovery, meanwhile, imports\n * `app/jobs/TestJob.ts` from source at runtime, where it is still `\"TestJob\"`.\n * The queue is keyed by that name, so the two halves stop agreeing and the\n * dispatch is dropped — in production, and only there.\n *\n * A declared `static name = \"TestJob\"` is a string literal, which survives\n * minification intact, and the two halves agree again. `docs/jobs-and-queues.md`\n * has always called it required; before discovery an app could get away without\n * it, because the explicit `jobs` array was bundled too and both sides were\n * wrong in the same way.\n *\n * The check is exact rather than a guess: a `static name = \"...\"` class field\n * defines a *writable* own property, while the implicit class name is\n * non-writable. Cron is unaffected — `CronJob.name` is an instance field\n * holding a string literal, not the class binding.\n */\nfunction warnIfNameWillNotSurviveTheBuild(jobs: Array<new () => Job>) {\n for (const job of jobs) {\n if (Object.getOwnPropertyDescriptor(job, \"name\")?.writable) continue;\n\n console.warn(\n `Queued job ${job.name} does not declare \\`static name\\`, so it is ` +\n `registered under its class name. A production build minifies the ` +\n `class that dispatches it and renames it, while discovery reads this ` +\n `file from source and does not — so the dispatch would be dropped in ` +\n `production and nowhere else. Add: static name = \"${job.name}\";`,\n );\n }\n}\n\n/**\n * The `CronJob` subclasses under `dir`, defaulting to the config slice's\n * `app/cron`.\n *\n * This is what a `schedule` config slice with no `jobs` key resolves to. Call it\n * directly to ask the question a test used to answer by importing the array —\n * though after boot `app(Scheduler).jobs` is the better one, because it is what\n * the scheduler actually took rather than what this would find if asked again.\n *\n * Every file underneath is imported, so calling this runs the app's cron\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverCronJobs(\n dir: string = scheduleConfigDefaults().jobsDir,\n): Promise<Array<new () => CronJob>> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"cron jobs\", \"schedule\");\n return await discoverClasses(resolved, CronJob);\n}\n\n/**\n * The `Command` subclasses under `dir`, defaulting to the config slice's\n * `app/commands`.\n *\n * This is what a `commands`-less `command` slice resolves to, and what\n * `gemi run` lists. Unlike the two above it is not called during boot — a\n * command registry has one consumer, and importing every file under\n * `app/commands` into every server process would be a cost paid on every start\n * for code no request reaches.\n *\n * Every file underneath is imported, so calling this runs the app's command\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverCommands(\n dir: string = commandConfigDefaults().commandsDir,\n): Promise<CommandClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"commands\", \"command\");\n\n const unfinished: string[] = [];\n\n const commands = await discoverClasses(\n resolved,\n Command,\n [],\n (value, file) => {\n if (isUnfinishedBuilder(value)) unfinished.push(file);\n },\n );\n\n refuseUnfinishedBuilders(unfinished);\n\n return commands as CommandClass[];\n}\n\n/**\n * Stops the walk for a builder chain that was never finished.\n *\n * This is the one silence the builder introduces, and it is the exact shape\n * #322 and #323 exist to remove. `defineCommand(...).arg(...)` without a\n * trailing `.handle(...)` is a plain object rather than a class, so\n * `discoverClasses` discards it along with every constant and helper a command\n * file happens to export — and the command disappears from `gemi run` with\n * nothing raised. The author sees a listing containing every command except the\n * one they just wrote.\n *\n * A throw rather than a warning, because there is no reading of an unfinished\n * builder under which the author meant it: the chain builds a description of a\n * command and then discards it.\n *\n * \"Unfinished\" is decided by `.handle()` clearing the brand, not by the export\n * still being a builder object. Those differ for the natural way to share\n * declarations —\n *\n * export const base = defineCommand(\"reindex\").option(\"verbose\", …);\n * export default base.handle(async () => {});\n *\n * — where `base` is a builder that *did* produce a command. Keying off the shape\n * alone made that file abort the whole of `gemi run`, taking every other command\n * in the project down with it, under a message that was untrue for it.\n */\nfunction refuseUnfinishedBuilders(files: string[]): void {\n if (files.length === 0) return;\n\n const subject =\n files.length === 1\n ? `${files[0]} exports a command builder that never called \\`.handle()\\``\n : `${files.length} files export a command builder that never called ` +\n `\\`.handle()\\`:\\n ${files.join(\"\\n \")}`;\n\n throw new DiscoveryError(\n `${subject}, so there is no command to run. \\`.handle()\\` is what turns ` +\n `the chain into a command — finish it:\\n\\n` +\n ` export default defineCommand(\"my-command\")\\n` +\n ` .handle(async ({ line }) => { line(\"hello\") })`,\n );\n}\n\n/**\n * The `Listener` subclasses under `dir`, defaulting to the config slice's\n * `app/listeners`.\n *\n * This is what an `events` config slice with no `listeners` key resolves to.\n * Call it directly to ask what an application would register: every listener,\n * in the order it would register them.\n *\n * Only listeners are walked. Event classes are never discovered — each is\n * imported by the listener that binds to it and by the code that dispatches it,\n * so there is nothing a walk over them would find that is not already in the\n * module graph.\n *\n * **Known residual, matching jobs and cron.** `discoverClasses` excludes the\n * `base` it is handed and not intermediates, so an abstract listener base\n * written in `listenersDir` and extended by its siblings is discovered and\n * registered alongside them — constructed, with its `handle` called, on every\n * dispatch of whatever event it declares. Keep shared bases outside the\n * directory.\n *\n * Every file underneath is imported, so calling this runs the app's listener\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n *\n * @throws DiscoveryError if a discovered listener declares no `static event`.\n */\nexport async function discoverListeners(\n dir: string = eventConfigDefaults().listenersDir,\n): Promise<ListenerClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"event listeners\", \"events\");\n\n const listeners = (await discoverClasses(\n resolved,\n Listener,\n )) as ListenerClass[];\n\n refuseListenersWithNoEvent(listeners);\n warnIfListenerNameWillNotSurviveTheBuild(listeners);\n warnIfEventNameWillNotSurviveTheBuild(listeners);\n\n return listeners;\n}\n\n/**\n * Stops the walk for a listener that binds to nothing.\n *\n * `static event` is declared as required on the base and the compiler still\n * cannot see it missing: every subclass inherits the declaration whether or not\n * it assigns to one, so `typeof SomeListener` type-checks either way. What the\n * author gets instead is a file that is imported, registered under no name, and\n * never called — the silence this whole module is arranged against.\n *\n * A throw rather than a warning, because there is no reading of a listener with\n * no event under which the author meant it. The usual cause is the residual\n * above: an abstract base sharing a gate between two listeners, sitting in\n * `listenersDir` where the walk finds it. Moving it out is the fix, and the\n * message says so — the alternative, excluding it by some guess about\n * abstractness, is how a discovery pass ends up quietly covering less than the\n * directory holds.\n */\nfunction refuseListenersWithNoEvent(listeners: ListenerClass[]): void {\n const orphans = listeners.filter((listener) => !listener.event);\n if (orphans.length === 0) return;\n\n throw new DiscoveryError(\n `${orphans\n .map((listener) => listener.name)\n .join(\", \")} declare no \\`static event\\`, so there is no event name to ` +\n `register them under and their \\`handle\\` would never run. Every ` +\n `listener binds to exactly one event:\\n\\n` +\n ` static event = UserRegistered;\\n\\n` +\n `If this is an abstract base its subclasses extend, move it out of the ` +\n `listeners directory — the walk excludes gemi's \\`Listener\\` and ` +\n `nothing else, so a base sitting beside its subclasses is registered ` +\n `and run like one of them.`,\n );\n}\n\n/**\n * Says something about a discovered listener that never declared `static name`.\n *\n * The hazard is `warnIfNameWillNotSurviveTheBuild`'s, one subsystem over: a\n * `static name = \"...\"` class field defines a *writable* own property while the\n * implicit class binding does not, and a minifier renames the binding while\n * leaving the string literal alone. The two spellings are indistinguishable by\n * value — both read `\"SendWelcomeEmail\"` in development — so the descriptor is\n * the only thing that tells them apart, and the difference only becomes visible\n * in a production build.\n *\n * A warning rather than a refusal, because a *sync* listener's name has no\n * second half to disagree with: every reader of it comes from this same\n * source-side walk, so a minified build and this walk cannot produce two\n * different strings for it. A **queued** listener does have one — the name is\n * the queue's key and it crosses a JSON boundary — and that case is refused\n * outright, by `jobForListener`, at the point the listener is registered with\n * the queue rather than here. This walk cannot tell the two apart without\n * constructing every listener it found; the registry constructs them anyway.\n */\nfunction warnIfListenerNameWillNotSurviveTheBuild(listeners: ListenerClass[]) {\n for (const listener of listeners) {\n if (Object.getOwnPropertyDescriptor(listener, \"name\")?.writable) continue;\n\n console.warn(\n `Event listener ${listener.name} does not declare \\`static name\\`, so ` +\n `it is registered under its class name, which a production build ` +\n `renames. Nothing reads that name across a build boundary while the ` +\n `listener is sync, which is why this is a warning — but adding ` +\n `\\`queued = true\\` to it is refused at boot for the same reason, ` +\n `because the queue's key is that string. Add: static name = ` +\n `\"${listener.name}\";`,\n );\n }\n}\n\n/**\n * Says something about the *event* a discovered listener binds to, when that\n * event's name is the implicit class binding.\n *\n * This is the check that matters from the first dispatch, and it is the reason\n * `discoverListeners` reads `static event` at all. The registry is keyed by the\n * event's name; the dispatcher supplies that name from the class it constructs.\n * A production build minifies the server entry and the app code reachable from\n * it — the controller, and the event class it imports in order to dispatch —\n * while discovery imports `app/listeners/*.ts` from source, and those files\n * import `app/events/*.ts` from source too. Two module graphs, two class\n * objects, and an implicit `.name` that reads `\"UserRegistered\"` on one side\n * and `\"D\"` on the other. The dispatch then finds no listeners, which is legal,\n * normal, and completely silent.\n *\n * A declared `static name` is a string literal, which survives minification\n * intact, and the two halves agree again.\n *\n * Checked through the descriptor rather than the string, and not by comparing\n * `event.name` to anything: in development the two spellings produce the same\n * value, so a check on the string would be a tautology that passes forever.\n */\nfunction warnIfEventNameWillNotSurviveTheBuild(listeners: ListenerClass[]) {\n const warned = new Set<EventClass>();\n\n for (const { event } of listeners) {\n if (warned.has(event)) continue;\n if (Object.getOwnPropertyDescriptor(event, \"name\")?.writable) continue;\n warned.add(event);\n\n console.warn(\n `Event ${event.name} does not declare \\`static name\\`, so it is ` +\n `dispatched under its class name. A production build minifies the ` +\n `code that dispatches it and renames the class, while discovery reads ` +\n `the listener's copy from source and does not — so the dispatch would ` +\n `reach no listener in production and nowhere else. Add: ` +\n `static name = \"${event.name}\";`,\n );\n }\n}\n"
14
14
  ],
15
15
  "mappings": ";+JA4GO,AAAM,IAAsB,KAAM,CAG5B,KAFX,WAAW,CACT,EACS,EAAe,EACxB,CACA,MAAM,CAAO,EAFJ,YAGT,KAAK,KAAO,gBAEhB,CAYO,MAAM,CAAQ,OAKZ,aAAc,cAGd,aAAc,SAGd,MAA0B,CAAC,QAG3B,SAA2B,CAAC,EAWnC,GAAG,CAAC,EAA0B,EAChC,CC1GO,SAAS,CAAmB,CAAC,EAAsC,CACxE,OAAO,EAGF,SAAS,CAAqB,EAA4B,CAC/D,MAAO,CACL,SAAU,CAAC,EACX,YAAa,cACf,ECDK,IAAM,EAA+B,OAAO,IAAI,sBAAsB,EA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// @bun
2
- import{G as r}from"./chunk-v8nf45gt.js";import"./chunk-xckeyg3v.js";import{Z as mc}from"./chunk-pzwyg474.js";import"./chunk-y7qnx8vm.js";import{$ as _}from"./chunk-81v4c4b1.js";import{Jg as u,Mg as O}from"./chunk-9tsw1bmt.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{G as r}from"./chunk-443dm19c.js";import"./chunk-78gs7xvn.js";import{Z as mc}from"./chunk-pw95y0fx.js";import"./chunk-9c1zx81w.js";import{$ as _}from"./chunk-713fezaz.js";import{Mg as u,Pg as O}from"./chunk-t93t317r.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=6A0A4F9CA242AEF864756E2164756E21
5
+ //# debugId=7CED34F686744AA864756E2164756E21
@@ -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,OAAO,OAAO,IAAI,gBAAc,gDAAgD,EAAG,CAAG,CAAC,EAC9F,EAAI,QAAQ,EACf,EACD,EAAI,GAAG,UAAW,IAAM,CACpB,EAAO,IAAI,gBAAc,6CAA6C,CAAC,EACvE,EAAI,QAAQ,EACf,EACD,EAAI,GAAG,WAAY,CAAC,IAAQ,CACxB,IAAQ,aAAa,KAAQ,EAC7B,GAAI,EAAa,KAAO,KAAO,EAC3B,EAAO,OAAO,OAAO,IAAI,gBAAc,wDAAwD,EAAG,CAAE,YAAW,CAAC,CAAC,EACjH,EAAI,QAAQ,EAEhB,IAAM,EAAS,CAAC,EAChB,EAAI,GAAG,OAAQ,CAAC,IAAU,CACtB,EAAO,KAAK,CAAK,EACpB,EACD,EAAI,GAAG,MAAO,IAAM,CAChB,EAAQ,GAAO,OAAO,CAAM,CAAC,EAC7B,EAAI,QAAQ,EACf,EACJ,EACD,EAAI,IAAI,EACX,MAlCL,gCCAa,EAAoB,CAAC,IAAQ,QAAQ,CAAG,GACjD,OAAO,IAAQ,UACf,OAAO,EAAI,cAAgB,UAC3B,OAAO,EAAI,kBAAoB,UAC/B,OAAO,EAAI,QAAU,UACr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xE,EAAe,EAAY,IAAK,EAAU,SAAQ,CAAC,EAEzD,KACD,IAAI,EACJ,GAAI,CACA,GAAS,MAAM,GAAiB,IAAK,EAAU,SAAQ,CAAC,GAAG,SAAS,EAExE,MAAO,EAAO,CACV,GAAI,GAAO,aAAe,IACtB,MAAM,OAAO,OAAO,EAAO,CACvB,QAAS,2CACb,CAAC,EAEA,QAAI,EAAM,UAAY,gBAAkB,CAAC,IAAK,IAAK,GAAG,EAAE,SAAS,EAAM,UAAU,EAClF,EAAoB,GAGxB,OADA,GAAQ,MAAM,4BAA6B,6BAA6B,EACjE,EAAe,EAAY,IAAK,EAAU,SAAQ,CAAC,EAE9D,OAAO,EAAe,EAAY,IAC3B,EACH,QAAS,EACJ,IAA2B,CAChC,EACA,SACJ,CAAC,KAIP,GAAmB,MAAO,IAAY,EAAY,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": "6A0A4F9CA242AEF864756E2164756E21",
22
+ "debugId": "7CED34F686744AA864756E2164756E21",
23
23
  "names": []
24
24
  }
@@ -2,6 +2,6 @@
2
2
  import{existsSync as $,readdirSync as B}from"fs";import{join as Y,relative as G}from"path";function J(K,Q=[]){let U=[],X=(H)=>{let z=G(K,H).split("\\").join("/");return Q.some((q)=>z===q||z.startsWith(`${q}/`))},V=(H)=>{for(let z of B(H,{withFileTypes:!0}).sort((q,Z)=>q.name<Z.name?-1:q.name>Z.name?1:0)){let q=Y(H,z.name);if(X(q))continue;if(z.isDirectory()){if(z.name.startsWith(".")||z.name==="node_modules")continue;if($(Y(q,"package.json")))continue;V(q);continue}if(!z.name.endsWith(".ts")&&!z.name.endsWith(".tsx"))continue;if(z.name.endsWith(".d.ts"))continue;if(/\.(test|test-d|spec|bench)\.tsx?$/.test(z.name))continue;U.push(q)}};if(!$(K))return U;return V(K),U}class A extends Error{constructor(K,Q){super(K,Q);this.name="DiscoveryError"}}async function W(K,Q,U=[],X){let V=new Set;for(let H of J(K,U)){let z;try{z=await import(H)}catch(q){throw new A(`${H} could not be imported, so the classes in it could not be discovered:
3
3
  ${q.message}
4
4
  List the classes explicitly in the config slice for this directory to skip the walk.`,{cause:q})}for(let q of Object.values(z)){if(typeof q==="function"&&q!==Q&&Object.prototype.isPrototypeOf.call(Q,q)){V.add(q);continue}X?.(q,H)}}return[...V]}function F(){return Y(process.cwd(),process.env.GEMI_PROJECT_DIR??"")}
5
- export{J as Dg,A as Eg,W as Fg,F as Gg};
5
+ export{J as Gg,A as Hg,W as Ig,F as Jg};
6
6
 
7
- //# debugId=DCFCF2855FE1A16664756E2164756E21
7
+ //# debugId=FD44A49680A823F364756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "import { existsSync, readdirSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\n\n/**\n * Finding the classes an application declared and never imported — the walk\n * #322 and #323 both end at.\n *\n * ### Why it has to run the files\n *\n * A job that is written and not listed does not fail; it disappears.\n * `QueueManager.run` looks a dispatched name up in the map its config built and\n * drops what is not there, so the dispatch is simply lost. A cron drifts worse:\n * nothing is waiting on a tick, so a job that never fires reports nothing to\n * anyone. What both come down to is that `app/config/queue.ts` naming every\n * `Job` subclass is the *only* thing putting those classes in the module graph —\n * the list and the directory are two spellings of one set, kept in step by hand.\n *\n * The way out of that is to read the directory, and there is no static read that\n * will do: the class does not exist until its module has run. So **every file\n * walked here is imported**, and a file that *does something* when imported does\n * it here — at boot, in production, on every start. `gemi check models` makes\n * the same trade for the same reason and pays it once per CI run; a caller of\n * this pays it once per process.\n *\n * ### What that asks of a caller\n *\n * **Point it at a directory of class declarations, not at `app/`.** The skip\n * rules on `sourceFiles` drop what certainly is not one — tests, benchmarks,\n * `.d.ts`, vendored packages — and nothing else. Widening the guesses is how a\n * discovery pass ends up quietly covering less than the directory holds, which\n * is the same silence in a new place.\n *\n * **Let a broken file stop the boot.** `discoverClasses` rethrows an import\n * failure naming the file rather than dropping it and carrying on, for the same\n * reason: four classes found out of five looks exactly like five out of five.\n *\n * **Leave a way out.** Discovery is what should happen when an app said\n * nothing. An app that lists its classes explicitly must not reach this file at\n * all — that is the escape hatch for a directory holding something this cannot\n * import, and it is the sentence an error from here should point at.\n *\n * ### One more thing worth knowing\n *\n * This imports by absolute path, while the application imports the same files\n * through the `@/app/*` alias. Bun keys its module registry by the *resolved*\n * path, so those two specifiers land on one module: a job already reached from\n * a controller is not evaluated a second time here, and the class object is the\n * same one. `gemi build` leaves that true in production — `packages: \"external\"`\n * keeps the app's own code out of `dist/server/server.mjs` and resolves it from\n * source at runtime, exactly as `gemi dev` does.\n *\n * Nothing here depends on that holding, and deliberately: `QueueManager` and the\n * `Scheduler`'s cross-reload registry are both keyed by name rather than by\n * class identity, so a build that did inline the app's modules would produce a\n * duplicate class object and still register the right job. Worth knowing before\n * writing a registry keyed the other way.\n */\n\n/**\n * The files under `dir` that could declare a class.\n *\n * Everything underneath it, because apps do group classes into folders, minus\n * what cannot be one. Each of these is going to be *imported*, so the exclusions\n * are about what is certainly not source rather than about what is probably not:\n *\n * - **Declaration files.** `.d.ts` has no runtime module behind it.\n * - **Tests, type tests and benchmarks**, by the suffix a runner already\n * recognises.\n * - **Dot-directories and `node_modules`.**\n * - **Any directory holding a `package.json`.** That is a package that happens\n * to live here — a vendored client, a generated SDK — not this app's source,\n * and importing its entry point runs somebody else's module graph. The\n * template has two under `app/models`.\n *\n * `ignore` is the escape hatch for the rest: a path prefix, relative to `dir`,\n * naming a file or a directory of adjacent code that runs something on import.\n * Nothing is ignored by default.\n *\n * The order is the same on every run over the same tree, which matters because\n * the caller is going to import in it: entries are sorted per directory before\n * recursing, and `readdirSync` order is the filesystem's rather than\n * alphabetical — a tree written `A.ts` then `B.ts` reads back `B.ts` first on\n * the machines this was tested on. Sorting per directory rather than sorting the\n * finished list is deliberate: for a tree holding both `a.ts` and `a/b.ts`, this\n * emits `a/b.ts` first, because the directory sorts before the file.\n *\n * A directory that does not exist yields an empty list rather than throwing.\n * \"The app has no jobs yet\" is an ordinary state and not this function's to\n * complain about — but it is indistinguishable from \"the app's source did not\n * ship\", so a caller that boots on the answer owes the reader a word about which\n * one it got.\n */\nexport function sourceFiles(dir: string, ignore: string[] = []): string[] {\n const out: string[] = [];\n\n const ignored = (path: string) => {\n const rel = relative(dir, path).split(\"\\\\\").join(\"/\");\n return ignore.some(\n (pattern) => rel === pattern || rel.startsWith(`${pattern}/`),\n );\n };\n\n const walk = (current: string) => {\n for (const entry of readdirSync(current, { withFileTypes: true }).sort(\n (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),\n )) {\n const path = join(current, entry.name);\n if (ignored(path)) continue;\n\n if (entry.isDirectory()) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\")\n continue;\n if (existsSync(join(path, \"package.json\"))) continue;\n walk(path);\n continue;\n }\n\n if (!entry.name.endsWith(\".ts\") && !entry.name.endsWith(\".tsx\")) continue;\n if (entry.name.endsWith(\".d.ts\")) continue;\n if (/\\.(test|test-d|spec|bench)\\.tsx?$/.test(entry.name)) continue;\n\n out.push(path);\n }\n };\n\n if (!existsSync(dir)) return out;\n\n walk(dir);\n return out;\n}\n\n/**\n * A class, as much of one as this file can name. `abstract` so that a base an\n * app never instantiates directly is a legal argument.\n */\ntype ClassLike = abstract new (...args: never[]) => unknown;\n\n/**\n * A file that would not import, reported with the file that would not import.\n *\n * Separate from a bare rethrow because the stack of a failed dynamic import\n * names the module that failed to *resolve*, several frames deep, and says\n * nothing about the walk that asked for it — so the reader learns that some\n * `?raw` specifier is unresolvable without learning that discovery is what\n * imported it, or that listing the classes explicitly is how they get their boot\n * back.\n */\nexport class DiscoveryError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"DiscoveryError\";\n }\n}\n\n/**\n * Every exported class under `dir` whose prototype chain reaches `base`.\n *\n * `base` is a parameter rather than an import so that this file names no\n * service and stays cheap to depend on — `bin/check-models.ts` uses the walker\n * above and is bundled into `dist/bin/gemi.js`, which is not somewhere gemi's\n * service layer should end up. It is also what lets a test hand in a base class\n * of its own instead of standing up a project that can resolve `gemi/services`.\n *\n * `base` itself is never returned. A directory whose files import their base\n * from a sibling — the shape an app reaches for when several jobs share a gate —\n * re-exports it as often as not, and a framework that scheduled the abstract\n * base along with its subclasses would be running a job nobody wrote.\n *\n * A class is returned once no matter how many exports name it. A barrel in the\n * directory re-exporting everything beside it is the ordinary case, and it makes\n * every class reachable twice.\n *\n * The order is the walk's, and within a file the module namespace's, which the\n * language sorts by name. So the answer is the same on every run — worth having\n * where the caller is a scheduler and the alternative is a boot order that\n * depends on the filesystem.\n *\n * `onSkipped` is handed every export that did *not* match, with the file it came\n * from. Discovery's characteristic failure is a thing the author wrote and this\n * walk cannot see, and by the time an export has been discarded here the\n * information about why is gone — the caller is left holding \"four classes\"\n * where the directory holds five. A caller that can recognise its own\n * near-misses, as `discoverCommands` recognises a builder chain that was never\n * finished, uses this to say so by name instead.\n *\n * @throws DiscoveryError if a walked file cannot be imported. Not a skip: a file\n * that will not load is a class the caller was going to be told about and now is\n * not, which is the failure discovery exists to remove.\n */\nexport async function discoverClasses<T extends ClassLike>(\n dir: string,\n base: T,\n ignore: string[] = [],\n onSkipped?: (value: unknown, file: string) => void,\n): Promise<T[]> {\n const found = new Set<T>();\n\n for (const path of sourceFiles(dir, ignore)) {\n let module: Record<string, unknown>;\n\n try {\n module = (await import(path)) as Record<string, unknown>;\n } catch (error) {\n throw new DiscoveryError(\n `${path} could not be imported, so the classes in it could not be ` +\n `discovered:\\n ${(error as Error).message}\\n` +\n `List the classes explicitly in the config slice for this directory ` +\n `to skip the walk.`,\n { cause: error },\n );\n }\n\n for (const value of Object.values(module)) {\n if (\n typeof value === \"function\" &&\n value !== base &&\n Object.prototype.isPrototypeOf.call(base, value)\n ) {\n found.add(value as unknown as T);\n continue;\n }\n\n onSkipped?.(value, path);\n }\n }\n\n return [...found];\n}\n\n/**\n * The directory an app's `app/` sits in, as the running process can know it.\n *\n * `ROOT_DIR` is the obvious answer and is not available: `Server.start` awaits\n * `waitForBoot()` — every provider's `register` and `boot` — and only then\n * imports the http layer that sets it. Anything resolving paths during boot is\n * earlier than the variable it would want.\n *\n * What it can use is the same rule `httpProd` computes `ROOT_DIR` with a moment\n * later, which is why that file now calls this instead of repeating it. `gemi\n * dev` and `gemi start` both spawn the server with no `cwd`, so the process\n * inherits the CLI's, and the CLI takes `process.cwd()` for the project root\n * itself — `bun/preload.ts` reads `gemi.config` from it on the same assumption.\n *\n * `httpDev` computes a bare `process.cwd()`, so it and `httpProd` already\n * disagree whenever `GEMI_PROJECT_DIR` is set. Nothing in this repo sets it and\n * `gemi start` ignores it when locating the built entry point, so the two rules\n * are the same rule for every configuration that runs today; the divergence is\n * older than this function and wants its own fix.\n */\nexport function projectRoot(): string {\n return join(process.cwd(), process.env.GEMI_PROJECT_DIR ?? \"\");\n}\n"
6
6
  ],
7
7
  "mappings": ";AAAA,qBAAS,iBAAY,WACrB,eAAS,cAAM,aA2FR,SAAS,CAAW,CAAC,EAAa,EAAmB,CAAC,EAAa,CACxE,IAAM,EAAgB,CAAC,EAEjB,EAAU,CAAC,IAAiB,CAChC,IAAM,EAAM,EAAS,EAAK,CAAI,EAAE,MAAM,IAAI,EAAE,KAAK,GAAG,EACpD,OAAO,EAAO,KACZ,CAAC,IAAY,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AK,EAC/C,CACA,EAAM,IAAI,CAAqB,EAC/B,SAGF,IAAY,EAAO,CAAI,GAI3B,MAAO,CAAC,GAAG,CAAK,EAuBX,SAAS,CAAW,EAAW,CACpC,OAAO,EAAK,QAAQ,IAAI,EAAG,QAAQ,IAAI,kBAAoB,EAAE",
8
- "debugId": "DCFCF2855FE1A16664756E2164756E21",
8
+ "debugId": "FD44A49680A823F364756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Af as S,Df as A,Ef as U,zf as W}from"./chunk-trdwxm5x.js";import{_f as C}from"./chunk-1w5a11cd.js";import{jg as I}from"./chunk-dwqh79e5.js";import{ug as E}from"./chunk-8gexb1gt.js";import{xg as N}from"./chunk-gx0x772p.js";class K{table;sql;dialect;connection;busyTimeout;configured;constructor(z,G={}){let V=G.table??"gemi_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(V))throw Error(`The queue table name "${V}" is not a plain identifier. Use letters, digits and underscores.`);let Y=G.busyTimeout??1000;if(!Number.isInteger(Y)||Y<0)throw Error(`The queue's busyTimeout must be a whole number of milliseconds, 0 or more; got ${Y}.`);this.table=V,this.sql=z.sql,this.dialect=z.dialect,this.connection=z.name,this.busyTimeout=Y}configure(){if(this.dialect!=="sqlite"||this.busyTimeout===0)return Promise.resolve();return this.configured??=(async()=>{let[z]=await this.sql.unsafe("PRAGMA busy_timeout");if(Number(z?.timeout??0)!==0)return;await this.sql.unsafe(`PRAGMA busy_timeout = ${this.busyTimeout}`)})().catch((z)=>{throw this.configured=void 0,z}),this.configured}async createTable(){await this.configure();for(let z of R(this.dialect,this.table))await this.sql.unsafe(z)}enqueue(z){let G=this.transaction(),V=this.insert(G??this.sql,z);if(G)U(V);return V}async insert(z,{name:G,args:V,delayMs:Y=0,id:Z=Bun.randomUUIDv7()}){await this.configure();let $=this.now(z);return await z`
2
+ import{Cf as W,Df as S,Gf as A,Hf as U}from"./chunk-6y62ccam.js";import{bg as E}from"./chunk-gzfat1x1.js";import{mg as I}from"./chunk-ttckhvew.js";import{xg as C}from"./chunk-8r7xhy1g.js";import{Ag as N}from"./chunk-8y08amzz.js";class K{table;sql;dialect;connection;busyTimeout;configured;constructor(z,G={}){let V=G.table??"gemi_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(V))throw Error(`The queue table name "${V}" is not a plain identifier. Use letters, digits and underscores.`);let Y=G.busyTimeout??1000;if(!Number.isInteger(Y)||Y<0)throw Error(`The queue's busyTimeout must be a whole number of milliseconds, 0 or more; got ${Y}.`);this.table=V,this.sql=z.sql,this.dialect=z.dialect,this.connection=z.name,this.busyTimeout=Y}configure(){if(this.dialect!=="sqlite"||this.busyTimeout===0)return Promise.resolve();return this.configured??=(async()=>{let[z]=await this.sql.unsafe("PRAGMA busy_timeout");if(Number(z?.timeout??0)!==0)return;await this.sql.unsafe(`PRAGMA busy_timeout = ${this.busyTimeout}`)})().catch((z)=>{throw this.configured=void 0,z}),this.configured}async createTable(){await this.configure();for(let z of R(this.dialect,this.table))await this.sql.unsafe(z)}enqueue(z){let G=this.transaction(),V=this.insert(G??this.sql,z);if(G)U(V);return V}async insert(z,{name:G,args:V,delayMs:Y=0,id:Z=Bun.randomUUIDv7()}){await this.configure();let $=this.now(z);return await z`
3
3
  INSERT INTO ${this.name(z)}
4
4
  (id, name, payload, status, attempts, available_at, created_at, updated_at)
5
5
  VALUES
@@ -136,7 +136,7 @@ import{Af as S,Df as A,Ef as U,zf as W}from"./chunk-trdwxm5x.js";import{_f as C}
136
136
  self.postMessage({result});
137
137
  }
138
138
  };
139
- `],"worker.ts"),Z=URL.createObjectURL(Y);return new Worker(Z)}async function T(z,G){let V=M();return V.postMessage({jobName:z,args:G}),await new Promise((Y,Z)=>{V.onmessage=($)=>{let B=$.data;if("error"in B)Z(B.error);else Y(B.result)}})}var D=new P("gemi.queue"),k=60000;class x{static token="queue";jobs={};config;driver;application;inFlight=new Map;state="idle";looping=!1;claiming;woken=!1;claimFailures=0;resume;unsubscribe;heartbeatTimer;releasedNames=new Set;constructor(z={},G={}){this.config=I(_(),z),this.application=G.application,this.driver=q(this.config.driver,this.application),this.useJobs(this.config.jobs)}useJobs(z){this.config.jobs=z,this.jobs={};for(let G of z)this.claim(G)}registerJob(z){this.config.jobs=[...this.config.jobs,z],this.claim(z)}claim(z){if(this.jobs[z.name]){console.error(`Two queued jobs are named "${z.name}" \u2014 the first is registered `+"and this one is not, so dispatching either would have run one of them. A class name is the queue's key, so only one job can hold it. Rename one.");return}this.jobs[z.name]=z}get registeredJobs(){return[...this.config.jobs]}dispatchJob(z,G){if(this.jobs[z])return new this.jobs[z]().run(JSON.parse(G))}push(z,G,V={}){let Y=this.driver.joinsTransaction?.()===!0;if(!Y){let Z=Bun.randomUUIDv7();if(A(()=>this.record(z,G,{id:Z,reportFailure:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(Z)}return this.record(z,G,{reportFailure:V.reportFailure,joins:Y})}record(z,G,V){let Y=this.driver.enqueue({name:z.name,args:G,...V.id===void 0?{}:{id:V.id}});this.startIfIdle();let Z=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),$=V.joins===!0&&A(Z);return Y.then(()=>$||Z(),(B)=>{if(V.reportFailure===!1)return;console.error(`[gemi] The queue driver could not record ${z.name}`+(V.committed?", which was held until its transaction committed. The transaction stays committed; the job did not run and will not be retried.":", so it did not run and will not be retried."),B)}),Y}async retryDead(z){if(!this.driver.retryDead)throw Error("This queue's driver keeps nothing of a dead-lettered job, so there is nothing to retry. The database driver keeps them.");let G=await this.driver.retryDead(z);if(G)this.claimSoon();return G}startIfIdle(){if(this.state==="idle"&&(!this.durable||this.mayClaimHere()))this.start()}claimSoon(){if(this.startIfIdle(),!this.driver.subscribe&&this.state==="running")this.wake()}start(){if(this.state==="running")return;if(this.state="running",this.durable&&this.application&&this.mayClaimHere()&&!v())globalThis.__gemiDevQueue=this;if(this.unsubscribe=this.driver.subscribe?.(()=>this.wake()),this.looping)return this.wake();D.runInAsyncScope(()=>void this.loop())}async drain(z=1/0){if(this.state="stopped",globalThis.__gemiDevQueue===this)globalThis.__gemiDevQueue=void 0;this.unsubscribe?.(),this.unsubscribe=void 0,this.wake();let G,V=new Promise((Z)=>{if(z!==1/0)G=setTimeout(Z,z)}),Y=(async()=>{await this.claiming?.catch(()=>{}),await Promise.allSettled([...this.inFlight.values()].map((Z)=>Z.done))})();return await Promise.race([Y,V]),clearTimeout(G),{unfinished:[...this.inFlight.values()].map((Z)=>({...Z.job}))}}stop(){return this.drain(0)}get running(){return this.inFlight.size}async loop(){this.looping=!0;try{await this.claimWhileRunning()}finally{this.looping=!1}}async claimWhileRunning(){while(this.state==="running"){let z=this.durable&&N()?0:this.config.concurrency-this.inFlight.size;if(z>0){this.woken=!1;let G=this.driver.claim(z,{...this.lease(),registered:{names:Object.keys(this.jobs),graceMs:this.config.unknownJobGrace}});this.claiming=G;let V=[];try{V=await G,this.claimFailures=0}catch(Y){this.claimFailures++,console.error(`The queue could not claim jobs from its driver; it will try again in ${this.retryDelay()}ms.`,Y)}finally{this.claiming=void 0}for(let Y of V)this.execute(Y);if(V.length===z)continue;if(this.woken&&this.inFlight.size<this.config.concurrency)continue}await this.sleep()}}sleep(){return new Promise((z)=>{let G,V=this.claimFailures>0?this.retryDelay():this.driver.subscribe?void 0:this.config.pollInterval;if(V!==void 0)G=setTimeout(()=>this.wake(),V),G.unref?.();this.resume=()=>{clearTimeout(G),z()}})}retryDelay(){let z=Math.min(Math.max(0,this.claimFailures-1),30);return Math.min(this.config.pollInterval*2**z,k)}wake(){this.woken=!0;let z=this.resume;this.resume=void 0,z?.()}get durable(){return!(this.driver instanceof X)}mayClaimHere(){return!this.application||g()}lease(){return{visibilityTimeoutMs:this.config.visibilityTimeout}}execute(z){let G=`${z.id}:${z.attempt}`,V=()=>this.run(z),Y=(this.application?E.run(this.application,V):V()).catch((Z)=>{console.error(`The queue could not record the outcome of ${z.name}.`,Z)}).finally(()=>{this.inFlight.delete(G),this.wake()});this.inFlight.set(G,{job:z,done:Y}),this.heartbeat()}heartbeat(){let z=this.driver;if(!z.heartbeat||this.heartbeatTimer)return;this.heartbeatTimer=setInterval(()=>{if(this.inFlight.size===0){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0;return}let G=[...this.inFlight.values()].map((V)=>V.job);z.heartbeat(G,this.lease()).catch((V)=>{console.error("The queue could not extend its job leases.",V)})},Math.max(1,Math.floor(this.config.visibilityTimeout/3))),this.heartbeatTimer.unref?.()}async run(z){let G=this.jobs[z.name];if(!G){let Z=Date.now()-z.createdAt;if(this.durable&&Z<this.config.unknownJobGrace){if(!this.releasedNames.has(z.name))this.releasedNames.add(z.name),console.error(`Left a queued "${z.name}" for another replica: nothing is registered here under that name. It is dead-lettered if no replica has run it within unknownJobGrace (${this.config.unknownJobGrace}ms) of its dispatch.`);await this.driver.release(z,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}console.error(`Dropped a queued job: nothing is registered under the name "${z.name}". If the class exists, it was not `+"discovered \u2014 check that it is under the queue slice's jobsDir "+"(app/jobs by default), or list it in app/config/queue.ts."),await this.driver.fail(z,{error:`No job is registered under the name "${z.name}".`,retryInMs:null});return}let V;try{V=new G}catch(Z){console.error(`Dropped a queued ${z.name}: it could not be constructed.`,Z),await this.driver.fail(z,{error:`The job could not be constructed: ${String(Z)}`,retryInMs:null});return}let Y;try{Y=JSON.parse(z.args)}catch(Z){console.error(`Dropped a queued ${z.name}: its arguments are not JSON.`,Z),await this.driver.fail(z,{error:`The arguments are not JSON: ${String(Z)}`,retryInMs:null});return}if(z.attempt>Math.max(1,V.maxAttempts)){let Z=Error(`${z.name} was claimed for attempt ${z.attempt} of ${V.maxAttempts}: an earlier attempt never finished, most likely because the process running it exited. Dead-lettered without running it again.`);L(`${z.name}.onDeadletter`,()=>V.onDeadletter(Z,...Y)),await this.driver.fail(z,{error:Z.message,retryInMs:null});return}try{let Z=await(V.worker?T(z.name,z.args):V.run(...Y));V.onSuccess(Z,...Y)}catch(Z){let $=Z,B=String($?.stack??$);if(L(`${z.name}.onFail`,()=>V.onFail($,...Y)),z.attempt>=V.maxAttempts)L(`${z.name}.onDeadletter`,()=>V.onDeadletter($,...Y)),await this.driver.fail(z,{error:B,retryInMs:null});else await this.driver.fail(z,{error:B,retryInMs:f(V.backoff,z.attempt)});return}await this.driver.complete(z)}}function L(z,G){try{G()}catch(V){console.error(`${z} threw; the job's claim was ended anyway.`,V)}}function v(){return Bun.env.NODE_ENV==="production"}function g(){if(!Q)return!1;if(h())return!0;return process.env.ROOT_DIR!==void 0&&!y()}function y(z=process.env){return(z.GEMI_QUEUE_CLAIM??"").trim().toLowerCase()==="off"}var O=Symbol.for("gemi.queue.worker");function o(z=!0){globalThis[O]=z}function h(){return globalThis[O]===!0}function f(z,G){let V=Array.isArray(z)?z[Math.min(G,z.length)-1]:z;return Math.max(0,V??0)}function q(z,G){if(z==="memory")return new X;if(z==="database"||typeof z==="function"){if(!G&&(z==="database"||z.length>0))throw Error("The queue driver needs the application it belongs to, and this QueueManager was built without one. Pass { application }.");if(z==="database")return new K(G.make(C));return z(G)}if(typeof z==="string")throw Error(`Unknown queue driver "${z}". The queue slice's driver is "memory", "database", a QueueDriver, or a function returning one.`);return z}
140
- export{K as _b,j as $b,_ as ac,X as bc,x as cc,g as dc,y as ec,o as fc,h as gc};
139
+ `],"worker.ts"),Z=URL.createObjectURL(Y);return new Worker(Z)}async function T(z,G){let V=M();return V.postMessage({jobName:z,args:G}),await new Promise((Y,Z)=>{V.onmessage=($)=>{let B=$.data;if("error"in B)Z(B.error);else Y(B.result)}})}var D=new P("gemi.queue"),k=60000;class x{static token="queue";jobs={};config;driver;application;inFlight=new Map;state="idle";looping=!1;claiming;woken=!1;claimFailures=0;resume;unsubscribe;heartbeatTimer;releasedNames=new Set;constructor(z={},G={}){this.config=I(_(),z),this.application=G.application,this.driver=q(this.config.driver,this.application),this.useJobs(this.config.jobs)}useJobs(z){this.config.jobs=z,this.jobs={};for(let G of z)this.claim(G)}registerJob(z){this.config.jobs=[...this.config.jobs,z],this.claim(z)}claim(z){if(this.jobs[z.name]){console.error(`Two queued jobs are named "${z.name}" \u2014 the first is registered `+"and this one is not, so dispatching either would have run one of them. A class name is the queue's key, so only one job can hold it. Rename one.");return}this.jobs[z.name]=z}get registeredJobs(){return[...this.config.jobs]}dispatchJob(z,G){if(this.jobs[z])return new this.jobs[z]().run(JSON.parse(G))}push(z,G,V={}){let Y=this.driver.joinsTransaction?.()===!0;if(!Y){let Z=Bun.randomUUIDv7();if(A(()=>this.record(z,G,{id:Z,reportFailure:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(Z)}return this.record(z,G,{reportFailure:V.reportFailure,joins:Y})}record(z,G,V){let Y=this.driver.enqueue({name:z.name,args:G,...V.id===void 0?{}:{id:V.id}});this.startIfIdle();let Z=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),$=V.joins===!0&&A(Z);return Y.then(()=>$||Z(),(B)=>{if(V.reportFailure===!1)return;console.error(`[gemi] The queue driver could not record ${z.name}`+(V.committed?", which was held until its transaction committed. The transaction stays committed; the job did not run and will not be retried.":", so it did not run and will not be retried."),B)}),Y}async retryDead(z){if(!this.driver.retryDead)throw Error("This queue's driver keeps nothing of a dead-lettered job, so there is nothing to retry. The database driver keeps them.");let G=await this.driver.retryDead(z);if(G)this.claimSoon();return G}startIfIdle(){if(this.state==="idle"&&(!this.durable||this.mayClaimHere()))this.start()}claimSoon(){if(this.startIfIdle(),!this.driver.subscribe&&this.state==="running")this.wake()}start(){if(this.state==="running")return;if(this.state="running",this.durable&&this.application&&this.mayClaimHere()&&!v())globalThis.__gemiDevQueue=this;if(this.unsubscribe=this.driver.subscribe?.(()=>this.wake()),this.looping)return this.wake();D.runInAsyncScope(()=>void this.loop())}async drain(z=1/0){if(this.state="stopped",globalThis.__gemiDevQueue===this)globalThis.__gemiDevQueue=void 0;this.unsubscribe?.(),this.unsubscribe=void 0,this.wake();let G,V=new Promise((Z)=>{if(z!==1/0)G=setTimeout(Z,z)}),Y=(async()=>{await this.claiming?.catch(()=>{}),await Promise.allSettled([...this.inFlight.values()].map((Z)=>Z.done))})();return await Promise.race([Y,V]),clearTimeout(G),{unfinished:[...this.inFlight.values()].map((Z)=>({...Z.job}))}}stop(){return this.drain(0)}get running(){return this.inFlight.size}async loop(){this.looping=!0;try{await this.claimWhileRunning()}finally{this.looping=!1}}async claimWhileRunning(){while(this.state==="running"){let z=this.durable&&N()?0:this.config.concurrency-this.inFlight.size;if(z>0){this.woken=!1;let G=this.driver.claim(z,{...this.lease(),registered:{names:Object.keys(this.jobs),graceMs:this.config.unknownJobGrace}});this.claiming=G;let V=[];try{V=await G,this.claimFailures=0}catch(Y){this.claimFailures++,console.error(`The queue could not claim jobs from its driver; it will try again in ${this.retryDelay()}ms.`,Y)}finally{this.claiming=void 0}for(let Y of V)this.execute(Y);if(V.length===z)continue;if(this.woken&&this.inFlight.size<this.config.concurrency)continue}await this.sleep()}}sleep(){return new Promise((z)=>{let G,V=this.claimFailures>0?this.retryDelay():this.driver.subscribe?void 0:this.config.pollInterval;if(V!==void 0)G=setTimeout(()=>this.wake(),V),G.unref?.();this.resume=()=>{clearTimeout(G),z()}})}retryDelay(){let z=Math.min(Math.max(0,this.claimFailures-1),30);return Math.min(this.config.pollInterval*2**z,k)}wake(){this.woken=!0;let z=this.resume;this.resume=void 0,z?.()}get durable(){return!(this.driver instanceof X)}mayClaimHere(){return!this.application||g()}lease(){return{visibilityTimeoutMs:this.config.visibilityTimeout}}execute(z){let G=`${z.id}:${z.attempt}`,V=()=>this.run(z),Y=(this.application?C.run(this.application,V):V()).catch((Z)=>{console.error(`The queue could not record the outcome of ${z.name}.`,Z)}).finally(()=>{this.inFlight.delete(G),this.wake()});this.inFlight.set(G,{job:z,done:Y}),this.heartbeat()}heartbeat(){let z=this.driver;if(!z.heartbeat||this.heartbeatTimer)return;this.heartbeatTimer=setInterval(()=>{if(this.inFlight.size===0){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0;return}let G=[...this.inFlight.values()].map((V)=>V.job);z.heartbeat(G,this.lease()).catch((V)=>{console.error("The queue could not extend its job leases.",V)})},Math.max(1,Math.floor(this.config.visibilityTimeout/3))),this.heartbeatTimer.unref?.()}async run(z){let G=this.jobs[z.name];if(!G){let Z=Date.now()-z.createdAt;if(this.durable&&Z<this.config.unknownJobGrace){if(!this.releasedNames.has(z.name))this.releasedNames.add(z.name),console.error(`Left a queued "${z.name}" for another replica: nothing is registered here under that name. It is dead-lettered if no replica has run it within unknownJobGrace (${this.config.unknownJobGrace}ms) of its dispatch.`);await this.driver.release(z,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}console.error(`Dropped a queued job: nothing is registered under the name "${z.name}". If the class exists, it was not `+"discovered \u2014 check that it is under the queue slice's jobsDir "+"(app/jobs by default), or list it in app/config/queue.ts."),await this.driver.fail(z,{error:`No job is registered under the name "${z.name}".`,retryInMs:null});return}let V;try{V=new G}catch(Z){console.error(`Dropped a queued ${z.name}: it could not be constructed.`,Z),await this.driver.fail(z,{error:`The job could not be constructed: ${String(Z)}`,retryInMs:null});return}let Y;try{Y=JSON.parse(z.args)}catch(Z){console.error(`Dropped a queued ${z.name}: its arguments are not JSON.`,Z),await this.driver.fail(z,{error:`The arguments are not JSON: ${String(Z)}`,retryInMs:null});return}if(z.attempt>Math.max(1,V.maxAttempts)){let Z=Error(`${z.name} was claimed for attempt ${z.attempt} of ${V.maxAttempts}: an earlier attempt never finished, most likely because the process running it exited. Dead-lettered without running it again.`);L(`${z.name}.onDeadletter`,()=>V.onDeadletter(Z,...Y)),await this.driver.fail(z,{error:Z.message,retryInMs:null});return}try{let Z=await(V.worker?T(z.name,z.args):V.run(...Y));V.onSuccess(Z,...Y)}catch(Z){let $=Z,B=String($?.stack??$);if(L(`${z.name}.onFail`,()=>V.onFail($,...Y)),z.attempt>=V.maxAttempts)L(`${z.name}.onDeadletter`,()=>V.onDeadletter($,...Y)),await this.driver.fail(z,{error:B,retryInMs:null});else await this.driver.fail(z,{error:B,retryInMs:f(V.backoff,z.attempt)});return}await this.driver.complete(z)}}function L(z,G){try{G()}catch(V){console.error(`${z} threw; the job's claim was ended anyway.`,V)}}function v(){return Bun.env.NODE_ENV==="production"}function g(){if(!Q)return!1;if(h())return!0;return process.env.ROOT_DIR!==void 0&&!y()}function y(z=process.env){return(z.GEMI_QUEUE_CLAIM??"").trim().toLowerCase()==="off"}var O=Symbol.for("gemi.queue.worker");function o(z=!0){globalThis[O]=z}function h(){return globalThis[O]===!0}function f(z,G){let V=Array.isArray(z)?z[Math.min(G,z.length)-1]:z;return Math.max(0,V??0)}function q(z,G){if(z==="memory")return new X;if(z==="database"||typeof z==="function"){if(!G&&(z==="database"||z.length>0))throw Error("The queue driver needs the application it belongs to, and this QueueManager was built without one. Pass { application }.");if(z==="database")return new K(G.make(E));return z(G)}if(typeof z==="string")throw Error(`Unknown queue driver "${z}". The queue slice's driver is "memory", "database", a QueueDriver, or a function returning one.`);return z}
140
+ export{K as Xb,j as Yb,_ as Zb,X as _b,x as $b,g as ac,y as bc,o as cc,h as dc};
141
141
 
142
- //# debugId=03CF131ABB43BDD564756E2164756E21
142
+ //# debugId=F2F621850514CC1C64756E2164756E21
@@ -8,6 +8,6 @@
8
8
  "import { AsyncResource } from \"node:async_hooks\";\nimport { isMainThread } from \"node:worker_threads\";\n\nimport type { Application } from \"../../foundation/Application\";\nimport { DatabaseManager } from \"../../database/DatabaseManager\";\nimport { kernelContext } from \"../../kernel/context\";\nimport { deferUntilCommit } from \"../../orm/context\";\nimport { isShuttingDown } from \"../../server/shutdown\";\nimport { DatabaseQueueDriver } from \"./DatabaseQueueDriver\";\nimport { Job } from \"./Job\";\nimport { queueConfigDefaults, type QueueConfig } from \"./config\";\nimport { MemoryQueueDriver } from \"./MemoryQueueDriver\";\nimport type { ClaimOptions, ClaimedJob, QueueDriver } from \"./QueueDriver\";\nimport { withDefaults } from \"../../support/withDefaults\";\n\n/**\n * The thread a `worker = true` job runs in.\n *\n * The `await` on `dispatchJob` is load-bearing and its absence was a hang.\n * `postMessage` structured-clones its argument and a Promise is not cloneable,\n * so an un-awaited `dispatchJob` posted the pending promise, threw\n * `DataCloneError` inside this handler, and posted nothing at all. `runInWorker`\n * then never settled: `run` below never returned, its concurrency slot was\n * never decremented, and neither the retry path nor `onDeadletter` ever fired —\n * after `concurrency` such jobs the queue sits at its limit forever, with no\n * error anywhere. Any job whose `run` is `async` hit it, which is every job\n * that touches IO; a queued listener hits it unconditionally, because the\n * synthetic job's `run` awaits `handle`.\n *\n * The await earns two more things. A rejecting job now reaches the `catch` and\n * comes back as `{error}`, where the queue's ordinary retry-then-dead-letter\n * path can have it, instead of being lost with the promise. And `destroy()` now\n * runs after the job rather than under it, so the cloned kernel — its database\n * connections included — outlives the work it was cloned for.\n */\nfunction createWorker() {\n const APP_DIR = process.env.APP_DIR;\n const ROOT_DIR = process.env.ROOT_DIR;\n\n const appPath =\n process.env.NODE_ENV === \"production\"\n ? `${ROOT_DIR}/dist/server/bootstrap.mjs`\n : `${APP_DIR}/bootstrap.ts`;\n\n const file = new File(\n [\n `\n import { app } from \"${appPath}\"\n self.onmessage = async (event) => {\n const clone = app.clone()\n let result = null;\n let error = null;\n try {\n result = await clone.dispatchJob(event.data.jobName, event.data.args)\n } catch (err) {\n error = err\n }\n clone.destroy()\n if(error) {\n self.postMessage({error});\n } else {\n self.postMessage({result});\n }\n };\n `,\n ],\n \"worker.ts\",\n );\n const url = URL.createObjectURL(file);\n return new Worker(url);\n}\n\n// TODO: terminate worker after the job is done\nasync function runInWorker(jobName: string, args: string) {\n const worker = createWorker();\n worker.postMessage({ jobName, args });\n return await new Promise((resolve, reject) => {\n worker.onmessage = (e) => {\n const data = e.data;\n if (\"error\" in data) {\n reject(data.error);\n } else {\n resolve(data.result);\n }\n };\n });\n}\n\n/**\n * The async context every job runs in: the one this module was evaluated in,\n * which is boot, outside any request.\n *\n * The worker loop is long-lived and started lazily, by the first dispatch, and\n * an async function keeps the context it was started in across every `await`.\n * Started from a request, it would run every later job — dispatched by any\n * request at all — inside the first one's `RequestContext`, and with its ORM\n * transaction handle if it had one open: one user's identity leaking into\n * another's work. Captured here, where no request exists, and entered by `start()`, a job\n * sees no request at all; the Application is entered separately, per job.\n */\nconst bootScope = new AsyncResource(\"gemi.queue\");\n\n/**\n * The longest the loop waits between retries while `claim` keeps rejecting.\n *\n * Long enough that a database which is properly down is not asked once a\n * second by every worker process for as long as it stays down, short enough\n * that the queue is claiming again within a minute of it coming back.\n */\nconst maxClaimBackoff = 60_000;\n\ndeclare global {\n /**\n * The queue loop a `gemi dev` server is running over a driver that outlives\n * the process, kept where a `bun --hot` reload cannot lose it. A reload\n * re-evaluates every module and boots a new application, but the previous\n * application's loop is a live closure and keeps claiming — from the same\n * table, with the code it was loaded with. This is how the next\n * application finds it to stop it; see `startClaimingIfServing`.\n *\n * Typed by what is called on it, not as `QueueManager`: after a reload the\n * one held here is an instance of the previous module graph's class.\n */\n var __gemiDevQueue: { stop(): Promise<unknown> } | undefined;\n}\n\n/** What `drain` could not wait out. */\nexport type DrainResult = {\n /**\n * Jobs still running when the timeout elapsed. They keep running, and keep\n * their leases, until they settle or the process exits; with a driver that\n * outlives the process, an exit leaves them to be reclaimed once their lease\n * runs out. Waiting jobs are not listed — they were never taken, and are\n * wherever the driver keeps them.\n */\n unfinished: ClaimedJob[];\n};\n\nexport class QueueManager {\n static token = \"queue\";\n\n jobs: Record<string, new () => Job> = {};\n\n readonly config: Required<QueueConfig>;\n readonly driver: QueueDriver;\n\n private readonly application: Application | undefined;\n /**\n * Keyed by claim, `id:attempt`, not by job id. A lease that lapses while\n * its job is still running here — heartbeats failing through a database\n * blip, or an event loop blocked past the visibility timeout — lets this\n * same process claim the job again. Both runs are then really running, so\n * both take a slot. Keyed by id alone, the second claim overwrote the first\n * and the first one's `finally` then deleted it: the live run stopped being\n * counted, drained or heartbeated, so its lease lapsed in turn and the job\n * was claimed again into a slot that was never free.\n */\n private readonly inFlight = new Map<\n string,\n { job: ClaimedJob; done: Promise<void> }\n >();\n private state: \"idle\" | \"running\" | \"stopped\" = \"idle\";\n private looping = false;\n private claiming: Promise<unknown> | undefined;\n private woken = false;\n /** Consecutive `claim` rejections; see `sleep`. Cleared by a claim that returns. */\n private claimFailures = 0;\n private resume: (() => void) | undefined;\n private unsubscribe: (() => void) | undefined;\n private heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n /** Unknown names already reported as left for another replica; see `run`. */\n private readonly releasedNames = new Set<string>();\n\n /**\n * `application` is entered around every job, so `app()` inside one resolves\n * to it rather than to whichever application happens to be the static\n * fallback. The provider always passes it; a manager built bare, as the unit\n * tests do, runs jobs with no application entered.\n */\n constructor(\n config: QueueConfig = {},\n options: { application?: Application } = {},\n ) {\n this.config = withDefaults(queueConfigDefaults(), config);\n this.application = options.application;\n this.driver = resolveDriver(this.config.driver, this.application);\n this.useJobs(this.config.jobs);\n }\n\n /**\n * Replaces the registered set, for the provider to hand over what it found\n * under `app/jobs`.\n *\n * This exists because the two phases disagree about when the answer is\n * knowable. The manager is constructed in `register()`, which is synchronous\n * and must resolve nothing; reading a directory and importing what is in it is\n * neither. So the manager is built from whatever the config slice declared —\n * nothing, when the app left `jobs` out — and the discovered set arrives in\n * `boot()`.\n *\n * The consequence worth knowing: anything that constructs an application and\n * skips phase two sees an empty registry, and every dispatch against an empty\n * registry is dropped — loudly on stderr, but after `Job.dispatch` has already\n * returned, so no caller finds out. On a durable driver not even that is\n * immediate: the job is left for another replica, and the stderr line comes\n * only once `unknownJobGrace` has passed. An app that lists its jobs explicitly is\n * unaffected, because that list is already in place by the end of `register()`.\n */\n useJobs(jobs: Array<new () => Job>) {\n this.config.jobs = jobs;\n\n // Built one at a time rather than by `Object.fromEntries`, which resolves a\n // repeated key by keeping the last and saying nothing.\n //\n // Two classes with one name is the worst failure in this subsystem, and it\n // is worse than the dropped dispatch the rest of this file is about: the\n // registry is keyed by class name, a dispatch carries a class name, so\n // `SendEmail.dispatch(...)` on the one under `app/jobs/auth` would run the\n // body of the one under `app/jobs/billing`. Nothing is dropped and nothing\n // errors — the wrong work happens and reports success.\n //\n // Discovery is what makes it ordinary. A hand-written list forces an import\n // alias in one visible file the moment two names clash; a directory walk\n // does not, and `auth/SendEmail.ts` beside `billing/SendEmail.ts` is a\n // perfectly natural thing to write. So the first claim wins and the second\n // is refused out loud — the same rule `Scheduler.start` applies to a cron\n // name, and the reverse of the silent last-wins this replaces.\n this.jobs = {};\n for (const job of jobs) {\n this.claim(job);\n }\n }\n\n /**\n * Registers one more job beside whatever `useJobs` already took.\n *\n * This exists for the queued-listener adapter, which registers a synthetic\n * job per queued listener from `EventServiceProvider.boot()` — after the\n * queue's own `boot()` has filled the registry. `useJobs` cannot serve that\n * caller: it *replaces* the registry, so a second call would discard every\n * job the app wrote and leave the queue holding listeners alone. Reading\n * `registeredJobs` back, concatenating and calling `useJobs` again avoids\n * that and is still the wrong shape — it re-runs the collision check over\n * jobs that already passed it, so a duplicate the author has already been\n * told about is reported a second time on every boot.\n *\n * Same rule as `useJobs`, deliberately: the first claim on a name wins and\n * the second is refused out loud. And recorded in `config.jobs` either way,\n * so `registeredJobs` keeps reporting everything the manager was handed\n * rather than what it accepted — a refused job is visible to a test there.\n *\n * A new array rather than a `push`, because `useJobs` keeps the caller's\n * array by reference and appending to it would edit the config slice or the\n * discovered list under whoever else is holding it.\n */\n registerJob(job: new () => Job) {\n this.config.jobs = [...this.config.jobs, job];\n this.claim(job);\n }\n\n /**\n * Puts one job in the registry, or refuses it because the name is taken.\n *\n * The rule and the reason are in `useJobs` above; this is only the shape both\n * entry points share, so that a job arriving one at a time cannot be admitted\n * on terms the batch would have refused.\n */\n private claim(job: new () => Job) {\n if (this.jobs[job.name]) {\n console.error(\n `Two queued jobs are named \"${job.name}\" — the first is registered ` +\n `and this one is not, so dispatching either would have run one of ` +\n `them. A class name is the queue's key, so only one job can hold ` +\n `it. Rename one.`,\n );\n return;\n }\n this.jobs[job.name] = job;\n }\n\n /**\n * What the manager was handed, discovered or declared.\n *\n * The registry is keyed by name, and a name is exactly what a dispatch\n * carries, so \"is this job registered?\" is a question with a silent wrong\n * answer — `run()` drops an unknown name long after the caller moved on.\n * This is where a test asks it out loud.\n *\n * It reports what came in, not what the registry accepted, so a name claimed\n * twice appears twice here — deliberately, the same way `Scheduler.jobs`\n * does. A test walking this should see the collision rather than have it\n * tidied away. A copy, so that walk cannot edit the registry underneath it.\n */\n get registeredJobs(): ReadonlyArray<new () => Job> {\n return [...this.config.jobs];\n }\n\n dispatchJob(jobName: string, args: string) {\n if (this.jobs[jobName]) {\n const job = new this.jobs[jobName]();\n return job.run(JSON.parse(args));\n }\n }\n\n /**\n * Queues a job and resolves to its id once the driver has recorded it, then\n * makes sure the worker loop is running — unless `drain` stopped it, in which\n * case the job waits in the driver for whichever process claims next. With\n * the memory driver that is nobody; see `drain`. A durable driver's job also\n * waits there when this process does not claim: it is not a server, or it is\n * one started with `GEMI_QUEUE_CLAIM=off`; see `claimsInThisProcess`.\n *\n * Inside an open ORM transaction the job belongs to the transaction. A\n * driver that can write it on the transaction does (`joinsTransaction`);\n * for any other, it is held and recorded once the transaction commits, and\n * never if it rolls back. Either way no claimer can see the job before the\n * data it was dispatched about exists. A held dispatch resolves at once, to\n * the id the job will be recorded under: the transaction does not commit\n * until its callback returns, so a caller awaiting a promise that waited for\n * the commit would never return.\n */\n push(\n job: new () => Job,\n args: string,\n options: {\n /**\n * Whether a driver that cannot record the job is reported from here.\n * On by default, because the usual caller is a fire-and-forget\n * `Job.dispatch(...)` whose promise nobody reads. A caller with\n * something better to say — `EventManager`, which knows the event and\n * the listener — turns it off and says that instead. A held dispatch is\n * reported here whatever this says, because its promise has already\n * resolved and the caller has nothing left to catch.\n */\n reportFailure?: boolean;\n } = {},\n ): Promise<string> {\n // Asked before anything is written, and in the caller's async context,\n // which is where the transaction is. The held branch is the fallback\n // rather than the rule because it loses the job to a crash between the\n // commit and the enqueue; written on the transaction, the job commits\n // with the rows or not at all.\n const joins = this.driver.joinsTransaction?.() === true;\n if (!joins) {\n // `deferUntilCommit` is the ORM's commit hook, and the same one an\n // `afterCommit` event waits on: a savepoint that rolls back takes its\n // held dispatches with it, and the callback runs outside the\n // transaction, so the enqueue cannot be pulled back into it.\n const id = Bun.randomUUIDv7();\n const held = deferUntilCommit(() =>\n // Awaited, so the transaction's own promise waits for the enqueue and\n // a script that exits after its last transaction does not exit under\n // it. The rejection is swallowed only because `record` has already\n // reported it; rethrown, the drain would report it a second time.\n this.record(job, args, {\n id,\n reportFailure: true,\n committed: true,\n }).then(\n () => {},\n () => {},\n ),\n );\n if (held) return Promise.resolve(id);\n }\n return this.record(job, args, {\n reportFailure: options.reportFailure,\n joins,\n });\n }\n\n /** `push`, once it is known that the job is recorded now. */\n private record(\n job: new () => Job,\n args: string,\n options: {\n id?: string;\n reportFailure?: boolean;\n /** Written on the caller's open transaction; see `push`. */\n joins?: boolean;\n /** Held until a transaction committed; changes only the error line. */\n committed?: boolean;\n },\n ): Promise<string> {\n const id = this.driver.enqueue({\n name: job.name,\n args,\n ...(options.id === undefined ? {} : { id: options.id }),\n });\n // A driver that outlives the process is shared with every other one, so\n // a script or console command that dispatches would otherwise claim up to\n // `concurrency` of the table's jobs — other replicas' included — and exit\n // under them, costing each an attempt and a lease's wait. There the job\n // waits in the driver for a server or a worker. A manager built by hand,\n // with no application, is its caller's to run and keeps starting.\n this.startIfIdle();\n // A driver without `subscribe` is only polled, so without the wake a job\n // dispatched here would wait up to `pollInterval` in a queue with room.\n // A spurious wake just claims nothing.\n //\n // A job written on the caller's transaction is not claimable until that\n // commits, so its wake waits for the commit too — woken now, the loop\n // would claim nothing and then sleep a whole `pollInterval` past it.\n // Registered here, synchronously, because the commit hook is found\n // through the caller's async context, and this is the one place that is\n // certainly still current.\n const wake = () =>\n !this.driver.subscribe && this.state === \"running\" && this.wake();\n const wakeAtCommit = options.joins === true && deferUntilCommit(wake);\n\n // The rejection is reported here unless the caller says it will do it\n // itself, and whatever the driver is. It used to depend on both, and was\n // lost either way: a polled driver got an empty rejection arm, which marks\n // `id` handled — and `id` is what `push` returns — so a fire-and-forget\n // `SendReceiptJob.dispatch(...)` whose INSERT failed (a failover, a pool\n // timeout, a table not migrated yet) produced no unhandled rejection and\n // no line anywhere, and the job simply never ran. A subscribing driver got\n // no arm at all, so the same failure surfaced as a bare unhandled\n // rejection. A caller that awaits still gets the rejection either way and\n // can still decide what to do about it.\n id.then(\n () => wakeAtCommit || wake(),\n (error: unknown) => {\n if (options.reportFailure === false) return;\n console.error(\n `[gemi] The queue driver could not record ${job.name}` +\n (options.committed\n ? `, which was held until its transaction committed. The ` +\n `transaction stays committed; the job did not run and will ` +\n `not be retried.`\n : `, so it did not run and will not be retried.`),\n error,\n );\n },\n );\n return id;\n }\n\n /**\n * Runs a dead-lettered job again, from attempt 1 with its whole\n * `maxAttempts`, and resolves to whether a dead job was found under `id`.\n * `false` for an id that is waiting, running, finished or unknown: only a\n * dead job is brought back, so this cannot restart one that is running\n * somewhere.\n *\n * The job is claimed the way a dispatch's is. On a server it is run here as\n * soon as there is room; from a console command it waits in the driver for\n * a server or a worker, which with a polling driver means up to\n * `pollInterval`.\n *\n * Refused for a driver without `retryDead`. The memory driver keeps nothing\n * of a dead job, so there is no id it could bring back, and resolving\n * `false` would read as \"no such job\" to someone holding an id they just saw\n * in a log.\n */\n async retryDead(id: string): Promise<boolean> {\n if (!this.driver.retryDead) {\n throw new Error(\n `This queue's driver keeps nothing of a dead-lettered job, so there ` +\n `is nothing to retry. The database driver keeps them.`,\n );\n }\n const found = await this.driver.retryDead(id);\n if (found) this.claimSoon();\n return found;\n }\n\n /**\n * Starts the loop unless `drain` stopped it or this process should leave a\n * shared driver's jobs to a server — the rule `push` explains.\n */\n private startIfIdle() {\n if (this.state === \"idle\" && (!this.durable || this.mayClaimHere())) {\n this.start();\n }\n }\n\n /**\n * For a job the driver has just made claimable: start the loop, or wake a\n * running one that only polls, as `push` does for a dispatch.\n */\n private claimSoon() {\n this.startIfIdle();\n if (!this.driver.subscribe && this.state === \"running\") this.wake();\n }\n\n /**\n * Starts claiming. Idempotent, and called by the first `push`, so an app\n * does not need to; it is public for a process that should run jobs it\n * never dispatched — ones a driver kept across a restart — and for resuming\n * after `drain`.\n */\n start() {\n if (this.state === \"running\") return;\n this.state = \"running\";\n // Only a development server's loop over a shared driver: a memory queue\n // is only ever fed by its own application, and a hand-built manager or a\n // test's is its caller's to stop.\n if (this.durable && this.application && this.mayClaimHere() && !isProduction()) {\n globalThis.__gemiDevQueue = this;\n }\n this.unsubscribe = this.driver.subscribe?.(() => this.wake());\n // A loop a `drain` has not yet seen off picks the new state up itself;\n // starting a second would claim twice per wake.\n if (this.looping) return this.wake();\n bootScope.runInAsyncScope(() => void this.loop());\n }\n\n /**\n * Stops claiming, waits up to `timeoutMs` for the jobs already running, and\n * reports the ones that did not finish.\n *\n * Nothing is cancelled — a job has no way to be told — so an unfinished job\n * keeps running after this resolves. What happens to it then is the\n * driver's: the memory driver loses it with the process, along with every\n * job still waiting; one that outlives the process lets another claim it\n * once the lease runs out.\n *\n * A later `push` records its job but does not restart the loop. `start()`\n * does.\n */\n async drain(timeoutMs = Infinity): Promise<DrainResult> {\n this.state = \"stopped\";\n if (globalThis.__gemiDevQueue === this) globalThis.__gemiDevQueue = undefined;\n this.unsubscribe?.();\n this.unsubscribe = undefined;\n this.wake();\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<void>((resolve) => {\n if (timeoutMs !== Infinity) timer = setTimeout(resolve, timeoutMs);\n });\n // The claim in progress first, because what it returns is run: those jobs\n // are leased to this process already, and handing them back would cost\n // each of them an attempt it never made.\n const settled = (async () => {\n await this.claiming?.catch(() => {});\n await Promise.allSettled([...this.inFlight.values()].map((e) => e.done));\n })();\n await Promise.race([settled, deadline]);\n clearTimeout(timer);\n\n return {\n unfinished: [...this.inFlight.values()].map((e) => ({ ...e.job })),\n };\n }\n\n /** `drain(0)`: stop claiming, and report what is running without waiting. */\n stop(): Promise<DrainResult> {\n return this.drain(0);\n }\n\n /** How many jobs this process is running right now. */\n get running(): number {\n return this.inFlight.size;\n }\n\n /**\n * Claims while there is room, runs what it claims, and otherwise sleeps\n * until something changes: a job finishing frees a slot, or the driver's\n * `subscribe` says there is work. A driver without `subscribe` is polled\n * every `pollInterval` instead. This replaces a one-second timer that\n * spun while the queue was full.\n *\n * `woken` records a wake that arrived while a claim was in flight, when\n * there was nothing yet to resume; without it that job would wait for the\n * next unrelated wake.\n */\n private async loop() {\n this.looping = true;\n try {\n await this.claimWhileRunning();\n } finally {\n this.looping = false;\n }\n }\n\n private async claimWhileRunning() {\n while (this.state === \"running\") {\n // Once the server has been told to stop, a driver that outlives the\n // process gets nothing new taken from it: a job claimed now would likely\n // be cut off by the exit, and cost an attempt and a lease's wait, when\n // another replica can run it instead. The memory driver keeps claiming\n // until the provider's `drain()` stops it, because nobody else can run\n // its jobs — one waiting at the signal, or dispatched by a request\n // still draining, is run here or not at all.\n const room = this.durable && isShuttingDown()\n ? 0\n : this.config.concurrency - this.inFlight.size;\n\n if (room > 0) {\n this.woken = false;\n const claim = this.driver.claim(room, {\n ...this.lease(),\n registered: {\n names: Object.keys(this.jobs),\n graceMs: this.config.unknownJobGrace,\n },\n });\n this.claiming = claim;\n let claimed: ClaimedJob[] = [];\n try {\n claimed = await claim;\n this.claimFailures = 0;\n } catch (error) {\n this.claimFailures++;\n console.error(\n `The queue could not claim jobs from its driver; it will try ` +\n `again in ${this.retryDelay()}ms.`,\n error,\n );\n } finally {\n this.claiming = undefined;\n }\n for (const job of claimed) this.execute(job);\n\n // A full batch may have left more behind; the next pass either claims\n // it or, with no room left, sleeps until a slot frees.\n if (claimed.length === room) continue;\n if (this.woken && this.inFlight.size < this.config.concurrency) {\n continue;\n }\n }\n\n await this.sleep();\n }\n }\n\n /**\n * Waits for the next thing worth waking for: a slot freeing, a `subscribe`\n * driver saying there is work, or the poll timer a driver without\n * `subscribe` gets.\n *\n * A claim that rejected arms a timer whatever the driver does, and that is\n * the whole reason this is not just the `subscribe` test. The wake that\n * prompted the lost claim has already been consumed, so a driver that only\n * speaks up on an enqueue — LISTEN/NOTIFY, say — has nothing left to\n * announce: an idle worker whose one claim died on a connection reset would\n * sit there, with every job already waiting, until some unrelated process\n * enqueued again. On a busy worker an in-flight job's `wake` covers it; an\n * idle one has nothing to be rescued by.\n *\n * The delay doubles per consecutive failure so that storage which is\n * properly down is not asked once a `pollInterval` for as long as it stays\n * down, and the first claim that returns clears the count.\n */\n private sleep() {\n return new Promise<void>((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const delay = this.claimFailures > 0\n ? this.retryDelay()\n : this.driver.subscribe\n ? undefined\n : this.config.pollInterval;\n if (delay !== undefined) {\n // Unref'd: a polling queue alone should not hold the process open.\n timer = setTimeout(() => this.wake(), delay);\n timer.unref?.();\n }\n this.resume = () => {\n clearTimeout(timer);\n resolve();\n };\n });\n }\n\n /** `pollInterval`, doubled once per consecutive claim failure, capped. */\n private retryDelay() {\n const doublings = Math.min(Math.max(0, this.claimFailures - 1), 30);\n return Math.min(this.config.pollInterval * 2 ** doublings, maxClaimBackoff);\n }\n\n private wake() {\n this.woken = true;\n const resume = this.resume;\n this.resume = undefined;\n resume?.();\n }\n\n /**\n * Whether the driver keeps jobs past this process: anything but memory.\n * Only such a queue can be fed by one process and drained by another.\n */\n get durable() {\n return !(this.driver instanceof MemoryQueueDriver);\n }\n\n /** See `claimsInThisProcess`. A manager built by hand always may. */\n private mayClaimHere() {\n return !this.application || claimsInThisProcess();\n }\n\n private lease(): ClaimOptions {\n return { visibilityTimeoutMs: this.config.visibilityTimeout };\n }\n\n private execute(claimed: ClaimedJob) {\n const key = `${claimed.id}:${claimed.attempt}`;\n const attempt = () => this.run(claimed);\n const done = (\n this.application\n ? kernelContext.run(this.application, attempt)\n : attempt()\n )\n .catch((error) => {\n // Only the driver's own reports reach here. The claim was not ended,\n // so its lease runs out and the job is claimed again.\n console.error(\n `The queue could not record the outcome of ${claimed.name}.`,\n error,\n );\n })\n .finally(() => {\n this.inFlight.delete(key);\n this.wake();\n });\n this.inFlight.set(key, { job: claimed, done });\n this.heartbeat();\n }\n\n /**\n * Keeps every running job's lease alive, at a third of the visibility\n * timeout so one late tick does not lose it. Stops itself once nothing is\n * running, and is unref'd, like the poll.\n */\n private heartbeat() {\n const driver = this.driver;\n if (!driver.heartbeat || this.heartbeatTimer) return;\n this.heartbeatTimer = setInterval(\n () => {\n if (this.inFlight.size === 0) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = undefined;\n return;\n }\n const jobs = [...this.inFlight.values()].map((e) => e.job);\n driver.heartbeat!(jobs, this.lease()).catch((error) => {\n console.error(`The queue could not extend its job leases.`, error);\n });\n },\n Math.max(1, Math.floor(this.config.visibilityTimeout / 3)),\n );\n this.heartbeatTimer.unref?.();\n }\n\n /**\n * One attempt at one claimed job, ending the claim either way.\n *\n * `onSuccess` is inside the `try`, as it always was, so a throw from it is a\n * failed attempt and is retried. `onFail` and `onDeadletter` are not: a\n * throw from either is logged and the claim still ends, where it used to\n * escape the queue with the job's slot still counted as taken.\n */\n private async run(claimed: ClaimedJob) {\n const Job = this.jobs[claimed.name];\n\n if (!Job) {\n // A driver other processes share may have handed this out because it\n // cannot filter by name, and while a blue/green ramp has both releases\n // claiming from one table, a name this replica lacks is usually one only\n // the other release has. So it goes back, without spending an attempt,\n // for a replica that has the class — until `unknownJobGrace` has passed\n // since the dispatch, after which the name is taken to be gone. Measured\n // from `createdAt` because that is all a claim carries; it is the\n // driver's clock against this one, and the skew is seconds against a\n // window of minutes. A driver that does filter only hands out an unknown\n // name once it has waited out the same window, so it normally lands\n // below; with this clock a few seconds behind the driver's, one handed\n // out right at the boundary is released instead, and — its window now\n // restarting from the release — waits one more `unknownJobGrace`. Late,\n // not lost, so no slack is subtracted for it.\n const age = Date.now() - claimed.createdAt;\n if (this.durable && age < this.config.unknownJobGrace) {\n // Once per name: with a driver that cannot filter, every poll can\n // claim the same job again, and a line per poll would bury the one\n // that matters — a replica whose discovery missed a job, say.\n if (!this.releasedNames.has(claimed.name)) {\n this.releasedNames.add(claimed.name);\n console.error(\n `Left a queued \"${claimed.name}\" for another replica: nothing is ` +\n `registered here under that name. It is dead-lettered if no ` +\n `replica has run it within unknownJobGrace ` +\n `(${this.config.unknownJobGrace}ms) of its dispatch.`,\n );\n }\n // Off this replica's own rhythm, and differently each time. It claims\n // again the moment the release lands, finds nothing due, and then\n // polls every `pollInterval`; a delay of exactly one interval made the\n // job due at the instant of that next poll, so the replica that could\n // not run it won the race for it every time. Any fixed fraction has\n // the same flaw for a replica whose polls happen to fall just before\n // the due moment each cycle — it loses every race, for good. Random\n // within one interval, every other replica's next poll has a chance.\n await this.driver.release(claimed, {\n retryInMs: Math.round(\n this.config.pollInterval * (1 + Math.random()),\n ),\n });\n return;\n }\n\n // The one place this is observable. A dispatch carries a name, the\n // registry is keyed by name, and a name nobody registered matches\n // nothing — which is exactly the silence #322 is about, except here it\n // has already happened and the work is gone. Saying so is all that is\n // left to do about it. Dead-lettered, which for the memory driver is the\n // drop it always was and for a durable one leaves a record to find.\n console.error(\n `Dropped a queued job: nothing is registered under the name ` +\n `\"${claimed.name}\". If the class exists, it was not ` +\n `discovered — check that it is under the queue slice's jobsDir ` +\n `(app/jobs by default), or list it in app/config/queue.ts.`,\n );\n await this.driver.fail(claimed, {\n error: `No job is registered under the name \"${claimed.name}\".`,\n retryInMs: null,\n });\n return;\n }\n\n let job: InstanceType<typeof Job>;\n try {\n job = new Job();\n } catch (error) {\n // A constructor or a class field that throws — `private mailer =\n // app(Mailer)` with nothing bound, say. Every other failure in here is\n // reported against the instance, and this one has no instance to report\n // against, which is exactly why it has to be caught here rather than\n // left to the generic path: that path never ends the claim, so the lease\n // lapses, the job is claimed again, and the constructor throws again,\n // once per visibility timeout, forever. The `maxAttempts` guard below\n // would normally stop that, and it cannot — answering \"how many attempts\n // does this job get?\" needs the instance that cannot be built. So it is\n // dead-lettered unrun, like a job whose arguments are not JSON: no\n // attempt of it can ever do anything but this.\n console.error(\n `Dropped a queued ${claimed.name}: it could not be constructed.`,\n error,\n );\n await this.driver.fail(claimed, {\n error: `The job could not be constructed: ${String(error)}`,\n retryInMs: null,\n });\n return;\n }\n\n let args: any[];\n try {\n args = JSON.parse(claimed.args);\n } catch (error) {\n // Not something `Job.dispatch` writes, so a driver changed it. Left\n // alone, the claim would never end and the job would be reclaimed,\n // unparseable, forever.\n console.error(\n `Dropped a queued ${claimed.name}: its arguments are not JSON.`,\n error,\n );\n await this.driver.fail(claimed, {\n error: `The arguments are not JSON: ${String(error)}`,\n retryInMs: null,\n });\n return;\n }\n\n // Claimed past its last attempt: an earlier claim used that attempt up and\n // never reported, which is what a process exiting mid-run looks like from\n // here. Running it again would exceed `maxAttempts`, so it is dead-lettered\n // unrun. `Math.max` keeps a `maxAttempts` below one meaning what it always\n // did — one attempt.\n if (claimed.attempt > Math.max(1, job.maxAttempts)) {\n const error = new Error(\n `${claimed.name} was claimed for attempt ${claimed.attempt} of ` +\n `${job.maxAttempts}: an earlier attempt never finished, most likely ` +\n `because the process running it exited. Dead-lettered without ` +\n `running it again.`,\n );\n hook(`${claimed.name}.onDeadletter`, () =>\n job.onDeadletter(error, ...args),\n );\n await this.driver.fail(claimed, {\n error: error.message,\n retryInMs: null,\n });\n return;\n }\n\n try {\n const result = await (job.worker\n ? runInWorker(claimed.name, claimed.args)\n : job.run(...args));\n\n job.onSuccess(result, ...args);\n } catch (err) {\n const error = err as Error;\n const recorded = String(error?.stack ?? error);\n hook(`${claimed.name}.onFail`, () => job.onFail(error, ...args));\n\n if (claimed.attempt >= job.maxAttempts) {\n hook(`${claimed.name}.onDeadletter`, () =>\n job.onDeadletter(error, ...args),\n );\n await this.driver.fail(claimed, { error: recorded, retryInMs: null });\n } else {\n await this.driver.fail(claimed, {\n error: recorded,\n retryInMs: backoffFor(job.backoff, claimed.attempt),\n });\n }\n return;\n }\n\n await this.driver.complete(claimed);\n }\n}\n\nfunction hook(name: string, fn: () => void) {\n try {\n fn();\n } catch (error) {\n console.error(`${name} threw; the job's claim was ended anyway.`, error);\n }\n}\n\nfunction isProduction() {\n return process.env.NODE_ENV === \"production\";\n}\n\n/**\n * Whether this process should claim from a driver shared with other\n * processes: a `gemi queue:work` worker, or a server's main thread unless\n * `GEMI_QUEUE_CLAIM=off` hands its jobs to workers. `ROOT_DIR` is set only by\n * a starting server or worker, so a console command, a seed\n * or a migration — which boot the same providers — is not one, and neither is\n * a `worker` job's thread, which clones the application and exits after it.\n *\n * A worker claims whatever `GEMI_QUEUE_CLAIM` says, because the variable is\n * for the web process, and a deploy that sets it once for every container\n * would otherwise leave nothing claiming at all.\n */\nexport function claimsInThisProcess() {\n if (!isMainThread) return false;\n if (isQueueWorker()) return true;\n return process.env.ROOT_DIR !== undefined && !claimingTurnedOff();\n}\n\n/**\n * `GEMI_QUEUE_CLAIM=off` (any case): this server dispatches into a shared\n * driver and leaves the claiming to `gemi queue:work` processes. Anything else\n * claims, as before. An environment variable rather than a config field for\n * the reason `GEMI_NO_SCHEDULE` is one: the web and the worker run the same\n * build with the same config, and only the process knows which it is.\n */\nexport function claimingTurnedOff(env: Record<string, string | undefined> = process.env) {\n return (env.GEMI_QUEUE_CLAIM ?? \"\").trim().toLowerCase() === \"off\";\n}\n\n// On `globalThis` under a registry symbol, like the shutdown flag, so the mark\n// the worker entry sets is the one this module reads if two copies of it are\n// loaded. Not an environment variable: a job that spawns a child process\n// would hand it on, and the child, a script, would start claiming.\nconst QUEUE_WORKER = Symbol.for(\"gemi.queue.worker\");\n\n/** Marks this process as a `gemi queue:work` worker; see `claimsInThisProcess`. */\nexport function markQueueWorker(worker = true) {\n (globalThis as { [QUEUE_WORKER]?: boolean })[QUEUE_WORKER] = worker;\n}\n\nexport function isQueueWorker(): boolean {\n return (globalThis as { [QUEUE_WORKER]?: boolean })[QUEUE_WORKER] === true;\n}\n\n/**\n * The delay before the retry that follows attempt `attempt`: the number\n * itself, or the array's entry for that retry with its last entry repeated.\n */\nexport function backoffFor(backoff: number | number[], attempt: number) {\n const delay = Array.isArray(backoff)\n ? backoff[Math.min(attempt, backoff.length) - 1]\n : backoff;\n return Math.max(0, delay ?? 0);\n}\n\nfunction resolveDriver(\n driver: Required<QueueConfig>[\"driver\"],\n application: Application | undefined,\n): QueueDriver {\n if (driver === \"memory\") return new MemoryQueueDriver();\n if (driver === \"database\" || typeof driver === \"function\") {\n // Only a manager built by hand has no application. A factory that takes\n // one would otherwise fail on `undefined` with a TypeError that names\n // neither the queue nor what is missing.\n if (!application && (driver === \"database\" || driver.length > 0)) {\n throw new Error(\n `The queue driver needs the application it belongs to, and this ` +\n `QueueManager was built without one. Pass { application }.`,\n );\n }\n if (driver === \"database\") {\n return new DatabaseQueueDriver(application!.make(DatabaseManager));\n }\n return driver(application!);\n }\n if (typeof driver === \"string\") {\n throw new Error(\n `Unknown queue driver \"${driver}\". The queue slice's driver is ` +\n `\"memory\", \"database\", a QueueDriver, or a function returning one.`,\n );\n }\n return driver;\n}\n"
9
9
  ],
10
10
  "mappings": ";6PAqGO,AAAM,LAA2C,LAC7C,AACQ,IACA,QAEA,WACA,YACT,WAER,WAAW,CACT,EAEA,EAAsC,CAAC,EACvC,CACA,IAAM,EAAQ,EAAQ,OAAS,YAC/B,GAAI,CAAC,2BAA2B,KAAK,CAAK,EACxC,MAAU,MACR,yBAAyB,oEAE3B,EAEF,IAAM,EAAc,EAAQ,aAAe,KAC3C,GAAI,CAAC,OAAO,UAAU,CAAW,GAAK,EAAc,EAClD,MAAU,MACR,kFAAkF,IACpF,EAEF,KAAK,MAAQ,EACb,KAAK,IAAM,EAAW,IACtB,KAAK,QAAU,EAAW,QAC1B,KAAK,WAAa,EAAW,KAC7B,KAAK,YAAc,EAgCb,SAAS,EAAkB,CACjC,GAAI,KAAK,UAAY,UAAY,KAAK,cAAgB,EAAG,OAAO,QAAQ,QAAQ,EAWhF,OAVA,KAAK,cAAgB,SAAY,CAC/B,IAAO,GAAY,MAAM,KAAK,IAAI,OAAO,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M,EAAQ,MAAM,QAAQ,CAAO,EAC/B,EAAQ,KAAK,IAAI,EAAS,EAAQ,MAAM,EAAI,GAC5C,EACJ,OAAO,KAAK,IAAI,EAAG,GAAS,CAAC,EAG/B,SAAS,CAAa,CACpB,EACA,EACa,CACb,GAAI,IAAW,SAAU,OAAO,IAAI,EACpC,GAAI,IAAW,YAAc,OAAO,IAAW,WAAY,CAIzD,GAAI,CAAC,IAAgB,IAAW,YAAc,EAAO,OAAS,GAC5D,MAAU,MACR,0HAEF,EAEF,GAAI,IAAW,WACb,OAAO,IAAI,EAAoB,EAAa,KAAK,CAAe,CAAC,EAEnE,OAAO,EAAO,CAAY,EAE5B,GAAI,OAAO,IAAW,SACpB,MAAU,MACR,yBAAyB,mGAE3B,EAEF,OAAO",
11
- "debugId": "03CF131ABB43BDD564756E2164756E21",
11
+ "debugId": "F2F621850514CC1C64756E2164756E21",
12
12
  "names": []
13
13
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ce as K,Rd as O,Sd as Z,le as _,pe as R,qe as W,re as F,se as C,te as G,ue as Y,ve as N,we as S}from"./chunk-k5j65f2c.js";import{Lg as P}from"./chunk-9tsw1bmt.js";var E={};P(E,{registeredNames:()=>b,register:()=>T,has:()=>y,get:()=>A,clearRegistry:()=>x});var J=new Map;function T(q,z){J.set(q,z)}function y(q){return J.has(q)}function A(q){let z=J.get(q);if(z===void 0)throw new _(q,[...J.keys()]);return z}function b(){return[...J.keys()]}function x(){J.clear()}var w=/^\s*::\s*(?:text\s*::\s*)?(jsonb|json)\b(?!\s*\[)/i,h=/^\s*as\s+(jsonb|json)\s*\)/i,c=/\bcast\s*\(\s*$/i,f=new Set;function U(q,z){if(!z.typesParametersFromStatement)return{fragment:q,jsonParameters:f};let B=C(q),D=new Set,H;for(let X=0;X<B.length-1;X++){let $=B[X+1],Q=w.exec($);if(Q){H??=[...B],H[X+1]=`::text::${Q[1]}${$.slice(Q[0].length)}`,D.add(X);continue}let V=h.exec($);if(V&&c.test((H??B)[X]))H??=[...B],H[X+1]=` as text)::${V[1]}${$.slice(V[0].length)}`,D.add(X)}if(!H)return{fragment:q,jsonParameters:D};return{fragment:G(H,q.binders),jsonParameters:D}}function M(q,z){if(q===null||q===void 0)return null;let B=K(q);if(B==="db")return null;if(B==="json")return"null";if(B==="any")throw new Z(z,"DB",z,"Prisma.AnyNull is a filter operand \u2014 it asks for a SQL NULL *or* a JSON "+"null \u2014 so it has no single value to bind. Write the one you mean: "+"Prisma.DbNull for the column being NULL, Prisma.JsonNull for the JSON value.");if(typeof q==="string")return q;let D;try{D=JSON.stringify(q)}catch(H){throw new Z(z,"DB",z,`A parameter cast to json could not be serialised: ${H instanceof Error?H.message:String(H)}. `+"Bind text you have serialised yourself if the value is not JSON \u2014 a "+"bigint has no JSON form, and neither does a cycle.")}if(D===void 0)throw new Z(z,"DB",z,`A ${typeof q} was bound to a parameter cast to json, and has no JSON form. Bind the value it stands for.`);return D}var I=new WeakSet;function L(q){return I.add(q),q}function k(q){return typeof q==="object"&&q!==null&&I.has(q)}function t(q,...z){if(!Array.isArray(q)||!("raw"in q))throw new O("sql","DB","sql","'sql' is a tagged template \u2014 write sql`select 1`, not sql(\"select 1\"). "+"To put text that is not a value into a statement, use 'unsafeSql', and read what it says first.");let B=[];for(let D=0;D<q.length;D++)if(B.push(W(q[D])),D<z.length)B.push(j(z[D]));return L(Y(...B))}function r(q,z=", "){if(!Array.isArray(q))throw new Z("join","DB","sql",`Expected an array of fragments or values, got ${typeof q}.`);if(q.length===0)return p;let B=q.map(j);if(k(z)){let D=[];for(let H=0;H<B.length;H++){if(H>0)D.push(z);D.push(B[H])}return L(Y(...D))}return v(z),L(N(B,z))}var g=/^[\s,]*$|^\s*(?:and|or)\s*$/i;function v(q){if(typeof q==="string"&&g.test(q))return;throw new Z("join","DB","sql",typeof q==="string"?`A separator is written into the SQL text, so it may only be glue: whitespace, commas, or 'and' / 'or'. Got ${JSON.stringify(q)}. If that is deliberate, say so with `+"unsafeSql(...) \u2014 and never build one from anything that came from "+"outside the program.":`Expected a separator string or a fragment, got ${q===null?"null":typeof q}.`)}var p=L(Object.freeze({text:"",binders:Object.freeze([])}));function a(q){if(typeof q!=="string")throw new Z("unsafeSql","DB","sql",`Expected a string literal, got ${Array.isArray(q)?"an array":typeof q}. 'unsafeSql' is a plain call, not a tagged template \u2014 a template would `+"interpolate values into the SQL text, which is the one thing it must never do.");return L(W(q))}function e(q,z,B="query"){if(!k(q))throw new Z(B,"DB",B,`Expected a fragment built with 'sql', got ${q===null?"null":typeof q}. A plain string is not accepted here on purpose \u2014 it would be the one `+"path into the SQL text that nobody had to think about.");let D=U(q,z),H=S(D.fragment,z,{model:"DB",operation:B});return{text:H.text,values:R(H.binders)(void 0).map((X,$)=>D.jsonParameters.has($)?M(X,B):X===null||X===void 0?X??null:z.encodeUntyped(X))}}function j(q){if(k(q))return q;return F(()=>q)}
3
- export{T as Hd,y as Id,A as Jd,b as Kd,E as Ld,t as Md,r as Nd,p as Od,a as Pd,e as Qd};
2
+ import{Fe as K,Ud as O,Vd as Z,oe as _,se as R,te as W,ue as F,ve as C,we as G,xe as Y,ye as N,ze as S}from"./chunk-ngq4n2b3.js";import{Og as P}from"./chunk-t93t317r.js";var E={};P(E,{registeredNames:()=>b,register:()=>T,has:()=>y,get:()=>A,clearRegistry:()=>x});var J=new Map;function T(q,z){J.set(q,z)}function y(q){return J.has(q)}function A(q){let z=J.get(q);if(z===void 0)throw new _(q,[...J.keys()]);return z}function b(){return[...J.keys()]}function x(){J.clear()}var w=/^\s*::\s*(?:text\s*::\s*)?(jsonb|json)\b(?!\s*\[)/i,h=/^\s*as\s+(jsonb|json)\s*\)/i,c=/\bcast\s*\(\s*$/i,f=new Set;function U(q,z){if(!z.typesParametersFromStatement)return{fragment:q,jsonParameters:f};let B=C(q),D=new Set,H;for(let X=0;X<B.length-1;X++){let $=B[X+1],Q=w.exec($);if(Q){H??=[...B],H[X+1]=`::text::${Q[1]}${$.slice(Q[0].length)}`,D.add(X);continue}let V=h.exec($);if(V&&c.test((H??B)[X]))H??=[...B],H[X+1]=` as text)::${V[1]}${$.slice(V[0].length)}`,D.add(X)}if(!H)return{fragment:q,jsonParameters:D};return{fragment:G(H,q.binders),jsonParameters:D}}function M(q,z){if(q===null||q===void 0)return null;let B=K(q);if(B==="db")return null;if(B==="json")return"null";if(B==="any")throw new Z(z,"DB",z,"Prisma.AnyNull is a filter operand \u2014 it asks for a SQL NULL *or* a JSON "+"null \u2014 so it has no single value to bind. Write the one you mean: "+"Prisma.DbNull for the column being NULL, Prisma.JsonNull for the JSON value.");if(typeof q==="string")return q;let D;try{D=JSON.stringify(q)}catch(H){throw new Z(z,"DB",z,`A parameter cast to json could not be serialised: ${H instanceof Error?H.message:String(H)}. `+"Bind text you have serialised yourself if the value is not JSON \u2014 a "+"bigint has no JSON form, and neither does a cycle.")}if(D===void 0)throw new Z(z,"DB",z,`A ${typeof q} was bound to a parameter cast to json, and has no JSON form. Bind the value it stands for.`);return D}var I=new WeakSet;function L(q){return I.add(q),q}function k(q){return typeof q==="object"&&q!==null&&I.has(q)}function t(q,...z){if(!Array.isArray(q)||!("raw"in q))throw new O("sql","DB","sql","'sql' is a tagged template \u2014 write sql`select 1`, not sql(\"select 1\"). "+"To put text that is not a value into a statement, use 'unsafeSql', and read what it says first.");let B=[];for(let D=0;D<q.length;D++)if(B.push(W(q[D])),D<z.length)B.push(j(z[D]));return L(Y(...B))}function r(q,z=", "){if(!Array.isArray(q))throw new Z("join","DB","sql",`Expected an array of fragments or values, got ${typeof q}.`);if(q.length===0)return p;let B=q.map(j);if(k(z)){let D=[];for(let H=0;H<B.length;H++){if(H>0)D.push(z);D.push(B[H])}return L(Y(...D))}return v(z),L(N(B,z))}var g=/^[\s,]*$|^\s*(?:and|or)\s*$/i;function v(q){if(typeof q==="string"&&g.test(q))return;throw new Z("join","DB","sql",typeof q==="string"?`A separator is written into the SQL text, so it may only be glue: whitespace, commas, or 'and' / 'or'. Got ${JSON.stringify(q)}. If that is deliberate, say so with `+"unsafeSql(...) \u2014 and never build one from anything that came from "+"outside the program.":`Expected a separator string or a fragment, got ${q===null?"null":typeof q}.`)}var p=L(Object.freeze({text:"",binders:Object.freeze([])}));function a(q){if(typeof q!=="string")throw new Z("unsafeSql","DB","sql",`Expected a string literal, got ${Array.isArray(q)?"an array":typeof q}. 'unsafeSql' is a plain call, not a tagged template \u2014 a template would `+"interpolate values into the SQL text, which is the one thing it must never do.");return L(W(q))}function e(q,z,B="query"){if(!k(q))throw new Z(B,"DB",B,`Expected a fragment built with 'sql', got ${q===null?"null":typeof q}. A plain string is not accepted here on purpose \u2014 it would be the one `+"path into the SQL text that nobody had to think about.");let D=U(q,z),H=S(D.fragment,z,{model:"DB",operation:B});return{text:H.text,values:R(H.binders)(void 0).map((X,$)=>D.jsonParameters.has($)?M(X,B):X===null||X===void 0?X??null:z.encodeUntyped(X))}}function j(q){if(k(q))return q;return F(()=>q)}
3
+ export{T as Kd,y as Ld,A as Md,b as Nd,E as Od,t as Pd,r as Qd,p as Rd,a as Sd,e as Td};
4
4
 
5
- //# debugId=A30ECF00C8B68FD264756E2164756E21
5
+ //# debugId=917F182155661E5164756E2164756E21
@@ -7,6 +7,6 @@
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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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": "A30ECF00C8B68FD264756E2164756E21",
10
+ "debugId": "917F182155661E5164756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Y as M}from"./chunk-rdnm6rem.js";import{Mg as E}from"./chunk-9tsw1bmt.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{Y as M}from"./chunk-whjhrz97.js";import{Pg as E}from"./chunk-t93t317r.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=648CFA343B6053E564756E2164756E21
4
+ //# debugId=F505A7A258E4FCD064756E2164756E21
@@ -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": ";uFAIA,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,iBAAkB,EAC1D,gBAAiB,CAAE,KAAM,SAAU,MAAO,OAAQ,EAClD,gBAAiB,CAAE,KAAM,SAAU,MAAO,CAAmB,CACjE,EACA,EAAW,MAAM,EAAe,CAAc,EAC9C,IAAM,EAAO,EAAW,MAAM,EAC9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ugId": "F505A7A258E4FCD064756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{qa as B,ra as C,ta as E}from"./chunk-9a8qz3s7.js";import{$f as x,bg as z,cg as A}from"./chunk-4ysar3ev.js";function M(b,f={}){let j=B(b,f.sourceLocale);return G(E(b),j,(q)=>C(b,q,j))}function N(b,f){let j=Object.keys(f);return G(b,j,(q)=>{let v=f[q]??f[j[0]];if(!v)return{};return v().then((k)=>k.default)})}function G(b,f,j){let q={id:b,locales:f,load:j};x(q);let v=()=>x(q);return{id:b,locales:f,load:(k)=>{return v(),z(b,k)},loadForRender:(k)=>{return v(),A(b,k)},get:(k)=>{v();let w=z(b,k);if(w instanceof Promise){w.catch(()=>{});return}return w}}}
2
+ import{qa as B,ra as C,ta as E}from"./chunk-9a8qz3s7.js";import{cg as x,eg as z,fg as A}from"./chunk-49v5xq8q.js";function M(b,f={}){let j=B(b,f.sourceLocale);return G(E(b),j,(q)=>C(b,q,j))}function N(b,f){let j=Object.keys(f);return G(b,j,(q)=>{let v=f[q]??f[j[0]];if(!v)return{};return v().then((k)=>k.default)})}function G(b,f,j){let q={id:b,locales:f,load:j};x(q);let v=()=>x(q);return{id:b,locales:f,load:(k)=>{return v(),z(b,k)},loadForRender:(k)=>{return v(),A(b,k)},get:(k)=>{v();let w=z(b,k);if(w instanceof Promise){w.catch(()=>{});return}return w}}}
3
3
  export{M as aa,N as ba};
4
4
 
5
- //# debugId=0EC5BAC6421748F264756E2164756E21
5
+ //# debugId=E6207D130C41F91464756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "import {\n dictionaryId,\n dictionaryLocales,\n localeStrings,\n type DictionaryTranslations,\n type LocaleStrings,\n} from \"./dictionaryShape\";\nimport {\n loadDictionary,\n loadDictionaryForRender,\n registerDictionary,\n type RenderThenable,\n} from \"./dictionaryRegistry\";\n\ndeclare const brand: unique symbol;\n\nexport interface DictionaryHandle<\n T extends DictionaryTranslations = DictionaryTranslations,\n> {\n readonly id: string;\n /** Locales this dictionary declares, source language first. */\n readonly locales: readonly string[];\n /**\n * Strings for `locale`. Synchronous when they are already in memory —\n * always, for an unbundled dictionary; after a preload or the SSR seed, for a\n * bundled one.\n */\n load(locale: string): LocaleStrings | Promise<LocaleStrings>;\n /**\n * `load`, but as the exact thing React's `use()` wants: never rejecting, so\n * a failed locale chunk degrades the component to rendering keys instead of\n * unmounting it into an error boundary; and always a thenable, even when the\n * strings are already in memory. The caller skips `use()` only for a\n * thenable built from strings already in hand, which carries them as\n * `inHand`; every thenable a render could have suspended on still goes\n * through it. `loadDictionaryForRender` has the whole reasoning.\n */\n loadForRender(locale: string): RenderThenable;\n get(locale: string): LocaleStrings | undefined;\n /** Type-only: carries the literal's shape through to `useDictionary`. */\n readonly [brand]?: T;\n}\n\n/**\n * Declare the strings a component needs, next to the component.\n *\n * ```ts\n * export const homeDict = defineDictionary({\n * title: { \"en-US\": \"Welcome {{name}}\", \"tr-TR\": \"Hoş geldin {{name}}\" },\n * });\n * ```\n *\n * As written this holds every locale. Under gemi's Vite plugin the call is\n * rewritten so each locale becomes its own chunk and a page downloads only the\n * one it renders in — but the plugin is strictly an optimization, and the\n * behaviour is identical without it (in `bun test`, and in server code that\n * does not go through the bundler).\n *\n * The first locale in the literal is the source language: a key missing from\n * another locale falls back to it rather than rendering as its own key.\n */\nexport interface DefineDictionaryOptions {\n /**\n * The locale this dictionary is authored in. Keys missing from another locale\n * fall back to it, and it is what renders when the app has no locale\n * configured.\n *\n * Optional, but worth setting on any dictionary that is not uniformly\n * translated: without it the source language is whichever locale appears\n * first in the literal, so adding a key at the top can re-point every\n * fallback in the dictionary.\n */\n sourceLocale?: string;\n}\n\nexport function defineDictionary<const T extends DictionaryTranslations>(\n translations: T,\n options: DefineDictionaryOptions = {},\n): DictionaryHandle<T> {\n const locales = dictionaryLocales(translations, options.sourceLocale);\n return createHandle(dictionaryId(translations), locales, (locale) =>\n localeStrings(translations, locale, locales),\n );\n}\n\n/**\n * The rewritten form of a `defineDictionary` call — emitted by\n * `packages/gemi/vite/dictionaryPlugin.ts`, never written by hand. `loaders`\n * holds one dynamic import per locale so the bundler emits one chunk per\n * locale and the untaken ones never reach the browser.\n */\nexport function __gemi_dict__<\n const T extends DictionaryTranslations = DictionaryTranslations,\n>(\n id: string,\n loaders: Record<string, () => Promise<{ default: LocaleStrings }>>,\n): DictionaryHandle<T> {\n const locales = Object.keys(loaders);\n return createHandle(id, locales, (locale) => {\n // An unknown locale falls back to the source language, matching what\n // `localeStrings` does per key on the unbundled path.\n const load = loaders[locale] ?? loaders[locales[0]];\n if (!load) {\n return {};\n }\n return load().then((mod) => mod.default);\n });\n}\n\nfunction createHandle<T extends DictionaryTranslations>(\n id: string,\n locales: string[],\n load: (locale: string) => LocaleStrings | Promise<LocaleStrings>,\n): DictionaryHandle<T> {\n const entry = { id, locales, load };\n registerDictionary(entry);\n\n // Re-asserted on every read rather than only at construction. A handle is\n // created once, at module scope, but the registry it delegates to can be\n // emptied under it — a test's `afterEach` reset, an HMR boundary — and the\n // handle would then be permanently orphaned, throwing \"Unknown dictionary\"\n // for a dictionary the caller is holding. `registerDictionary` is a no-op\n // when the id is already there, so this costs one Map lookup.\n const ensure = () => registerDictionary(entry);\n\n return {\n id,\n locales,\n // Routed through the registry rather than calling `load` directly so\n // concurrent readers share one in-flight import and results are cached.\n load: (locale: string) => {\n ensure();\n return loadDictionary(id, locale);\n },\n loadForRender: (locale: string) => {\n ensure();\n return loadDictionaryForRender(id, locale);\n },\n get: (locale: string) => {\n ensure();\n const strings = loadDictionary(id, locale);\n if (strings instanceof Promise) {\n // Nothing downstream awaits this one — `get` is the synchronous peek,\n // and the caller is about to discard it. An unattached rejection (a\n // locale chunk that 404s mid-deploy) would surface as an\n // `unhandledRejection`, which under Node's default handler takes the\n // process down over one missing translation file. The load itself is\n // still cached and still retried through `loadDictionary`.\n strings.catch(() => {});\n return undefined;\n }\n return strings;\n },\n };\n}\n\n"
6
6
  ],
7
7
  "mappings": ";wHA2EO,GAAS,CAAwD,CACtE,EACA,EAAmC,CAAC,EACf,CACrB,IAAM,EAAU,EAAkB,EAAc,EAAQ,YAAY,EACpE,OAAO,EAAa,EAAa,CAAY,EAAG,EAAS,CAAC,IACxD,EAAc,EAAc,EAAQ,CAAO,CAC7C,EASK,SAAS,CAEf,CACC,EACA,EACqB,CACrB,IAAM,EAAU,OAAO,KAAK,CAAO,EACnC,OAAO,EAAa,EAAI,EAAS,CAAC,IAAW,CAG3C,IAAM,EAAO,EAAQ,IAAW,EAAQ,EAAQ,IAChD,GAAI,CAAC,EACH,MAAO,CAAC,EAEV,OAAO,EAAK,EAAE,KAAK,CAAC,IAAQ,EAAI,OAAO,EACxC,EAGH,SAAS,CAA8C,CACrD,EACA,EACA,EACqB,CACrB,IAAM,EAAQ,CAAE,KAAI,UAAS,MAAK,EAClC,EAAmB,CAAK,EAQxB,IAAM,EAAS,IAAM,EAAmB,CAAK,EAE7C,MAAO,CACL,KACA,UAGA,KAAM,CAAC,IAAmB,CAExB,OADA,EAAO,EACA,EAAe,EAAI,CAAM,GAElC,cAAe,CAAC,IAAmB,CAEjC,OADA,EAAO,EACA,EAAwB,EAAI,CAAM,GAE3C,IAAK,CAAC,IAAmB,CACvB,EAAO,EACP,IAAM,EAAU,EAAe,EAAI,CAAM,EACzC,GAAI,aAAmB,QAAS,CAO9B,EAAQ,MAAM,IAAM,EAAE,EACtB,OAEF,OAAO,EAEX",
8
- "debugId": "0EC5BAC6421748F264756E2164756E21",
8
+ "debugId": "E6207D130C41F91464756E2164756E21",
9
9
  "names": []
10
10
  }