gemi 0.117.0 → 0.118.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/app/index.js +1 -1
  4. package/dist/bun/plugin.js +1 -1
  5. package/dist/bun/preload.js +1 -1
  6. package/dist/{chunk-6y4nk9f1.js → chunk-01ehxca0.js} +2 -2
  7. package/dist/{chunk-6y4nk9f1.js.map → chunk-01ehxca0.js.map} +1 -1
  8. package/dist/chunk-0gtyects.js +10 -0
  9. package/dist/{chunk-2czfefn2.js.map → chunk-0gtyects.js.map} +3 -3
  10. package/dist/{chunk-gn7kne7r.js → chunk-1m3hvy3q.js} +2 -2
  11. package/dist/{chunk-gn7kne7r.js.map → chunk-1m3hvy3q.js.map} +1 -1
  12. package/dist/{chunk-1ckha5dt.js → chunk-1z1rj2zq.js} +2 -2
  13. package/dist/{chunk-1ckha5dt.js.map → chunk-1z1rj2zq.js.map} +1 -1
  14. package/dist/{chunk-n9jyjp4a.js → chunk-30xxc6r7.js} +2 -2
  15. package/dist/{chunk-n9jyjp4a.js.map → chunk-30xxc6r7.js.map} +1 -1
  16. package/dist/{chunk-077rea02.js → chunk-33s2xqv1.js} +1 -1
  17. package/dist/{chunk-5m8vvtvn.js → chunk-39kyz4k6.js} +2 -2
  18. package/dist/{chunk-5m8vvtvn.js.map → chunk-39kyz4k6.js.map} +1 -1
  19. package/dist/chunk-3nf95j9e.js +5 -0
  20. package/dist/{chunk-63ewmmhc.js.map → chunk-3nf95j9e.js.map} +1 -1
  21. package/dist/{chunk-kpn7f58a.js → chunk-3zxfd7pn.js} +3 -3
  22. package/dist/{chunk-kpn7f58a.js.map → chunk-3zxfd7pn.js.map} +1 -1
  23. package/dist/{chunk-62jw0vsf.js → chunk-453rmkpm.js} +2 -2
  24. package/dist/{chunk-62jw0vsf.js.map → chunk-453rmkpm.js.map} +1 -1
  25. package/dist/{chunk-mhteg4yz.js → chunk-47h12eme.js} +5 -5
  26. package/dist/{chunk-mhteg4yz.js.map → chunk-47h12eme.js.map} +1 -1
  27. package/dist/{chunk-x84as3vy.js → chunk-490sbcma.js} +2 -2
  28. package/dist/{chunk-x84as3vy.js.map → chunk-490sbcma.js.map} +1 -1
  29. package/dist/{chunk-stnd9qht.js → chunk-4c1kdd8p.js} +2 -2
  30. package/dist/{chunk-stnd9qht.js.map → chunk-4c1kdd8p.js.map} +1 -1
  31. package/dist/{chunk-j1453bn1.js → chunk-5cgq9c43.js} +2 -2
  32. package/dist/{chunk-j1453bn1.js.map → chunk-5cgq9c43.js.map} +1 -1
  33. package/dist/{chunk-hr61ekcr.js → chunk-5dbpgyrx.js} +2 -2
  34. package/dist/{chunk-hr61ekcr.js.map → chunk-5dbpgyrx.js.map} +1 -1
  35. package/dist/{chunk-wzzrz612.js → chunk-5ses4tcz.js} +2 -2
  36. package/dist/{chunk-wzzrz612.js.map → chunk-5ses4tcz.js.map} +1 -1
  37. package/dist/{chunk-pepzecrm.js → chunk-675kzd7z.js} +2 -2
  38. package/dist/{chunk-pepzecrm.js.map → chunk-675kzd7z.js.map} +1 -1
  39. package/dist/{chunk-yhp6bvhj.js → chunk-76p0rf4d.js} +3 -3
  40. package/dist/{chunk-yhp6bvhj.js.map → chunk-76p0rf4d.js.map} +1 -1
  41. package/dist/{chunk-bvqae0px.js → chunk-8t6dwwz6.js} +1 -1
  42. package/dist/{chunk-a32wfzdq.js → chunk-8wcpxm41.js} +2 -2
  43. package/dist/{chunk-a32wfzdq.js.map → chunk-8wcpxm41.js.map} +1 -1
  44. package/dist/{chunk-ntxsdchf.js → chunk-9pkj7sk6.js} +2 -2
  45. package/dist/{chunk-ntxsdchf.js.map → chunk-9pkj7sk6.js.map} +1 -1
  46. package/dist/{chunk-w4e480he.js → chunk-a1qt8aky.js} +2 -2
  47. package/dist/{chunk-w4e480he.js.map → chunk-a1qt8aky.js.map} +1 -1
  48. package/dist/{chunk-e7ezmag9.js → chunk-aedkrck1.js} +1 -1
  49. package/dist/{chunk-arwmvgrz.js → chunk-aqpaw4jq.js} +2 -2
  50. package/dist/{chunk-arwmvgrz.js.map → chunk-aqpaw4jq.js.map} +1 -1
  51. package/dist/{chunk-hvpn18bb.js → chunk-bgwtdbfw.js} +3 -3
  52. package/dist/{chunk-hvpn18bb.js.map → chunk-bgwtdbfw.js.map} +1 -1
  53. package/dist/{chunk-gjy2qjcr.js → chunk-bz8xssrc.js} +2 -2
  54. package/dist/{chunk-gjy2qjcr.js.map → chunk-bz8xssrc.js.map} +1 -1
  55. package/dist/{chunk-yvtmygrk.js → chunk-cte6ysqd.js} +4 -4
  56. package/dist/{chunk-yvtmygrk.js.map → chunk-cte6ysqd.js.map} +1 -1
  57. package/dist/{chunk-3w4hk6q2.js → chunk-cvfg88cx.js} +3 -3
  58. package/dist/{chunk-3w4hk6q2.js.map → chunk-cvfg88cx.js.map} +1 -1
  59. package/dist/{chunk-wk1tp1f1.js → chunk-d806cy7p.js} +2 -2
  60. package/dist/{chunk-wk1tp1f1.js.map → chunk-d806cy7p.js.map} +1 -1
  61. package/dist/{chunk-zkjs3m5m.js → chunk-dwpn6fze.js} +2 -2
  62. package/dist/{chunk-zkjs3m5m.js.map → chunk-dwpn6fze.js.map} +1 -1
  63. package/dist/{chunk-nb2gggba.js → chunk-ebret82e.js} +3 -3
  64. package/dist/{chunk-nb2gggba.js.map → chunk-ebret82e.js.map} +1 -1
  65. package/dist/{chunk-g2wncay4.js → chunk-eke2frrm.js} +3 -3
  66. package/dist/{chunk-g2wncay4.js.map → chunk-eke2frrm.js.map} +1 -1
  67. package/dist/{chunk-ffgmqwzy.js → chunk-fsj5k511.js} +2 -2
  68. package/dist/{chunk-ffgmqwzy.js.map → chunk-fsj5k511.js.map} +1 -1
  69. package/dist/{chunk-076jezzg.js → chunk-g5ppst76.js} +3 -3
  70. package/dist/{chunk-076jezzg.js.map → chunk-g5ppst76.js.map} +1 -1
  71. package/dist/{chunk-37pk2cjg.js → chunk-g9hhdcax.js} +2 -2
  72. package/dist/{chunk-37pk2cjg.js.map → chunk-g9hhdcax.js.map} +1 -1
  73. package/dist/{chunk-dz99g58c.js → chunk-gqfqnv3f.js} +2 -2
  74. package/dist/{chunk-dz99g58c.js.map → chunk-gqfqnv3f.js.map} +1 -1
  75. package/dist/{chunk-51w202vr.js → chunk-hkf2k2eq.js} +3 -3
  76. package/dist/{chunk-51w202vr.js.map → chunk-hkf2k2eq.js.map} +1 -1
  77. package/dist/{chunk-dcgvq79a.js → chunk-hm9cjxy2.js} +2 -2
  78. package/dist/{chunk-dcgvq79a.js.map → chunk-hm9cjxy2.js.map} +1 -1
  79. package/dist/{chunk-5w6kyxsj.js → chunk-hr1r3g0d.js} +2 -2
  80. package/dist/{chunk-5w6kyxsj.js.map → chunk-hr1r3g0d.js.map} +1 -1
  81. package/dist/{chunk-fnwbbmnk.js → chunk-hzepfrzy.js} +2 -2
  82. package/dist/{chunk-fnwbbmnk.js.map → chunk-hzepfrzy.js.map} +1 -1
  83. package/dist/{chunk-pgy3mfxw.js → chunk-j5858bz7.js} +2 -2
  84. package/dist/{chunk-pgy3mfxw.js.map → chunk-j5858bz7.js.map} +1 -1
  85. package/dist/{chunk-c2n6zdyd.js → chunk-jf6qqzat.js} +2 -2
  86. package/dist/{chunk-c2n6zdyd.js.map → chunk-jf6qqzat.js.map} +1 -1
  87. package/dist/{chunk-8gtc3s1y.js → chunk-jg79n382.js} +2 -2
  88. package/dist/{chunk-8gtc3s1y.js.map → chunk-jg79n382.js.map} +1 -1
  89. package/dist/{chunk-00n3gwr8.js → chunk-k31qfe7a.js} +3 -3
  90. package/dist/{chunk-00n3gwr8.js.map → chunk-k31qfe7a.js.map} +1 -1
  91. package/dist/{chunk-t65074mw.js → chunk-kkte8nze.js} +3 -3
  92. package/dist/{chunk-t65074mw.js.map → chunk-kkte8nze.js.map} +1 -1
  93. package/dist/{chunk-x7qwx07b.js → chunk-m4kmetpb.js} +2 -2
  94. package/dist/{chunk-x7qwx07b.js.map → chunk-m4kmetpb.js.map} +1 -1
  95. package/dist/{chunk-ge9xjwgq.js → chunk-n4sdm0jn.js} +3 -3
  96. package/dist/{chunk-ge9xjwgq.js.map → chunk-n4sdm0jn.js.map} +1 -1
  97. package/dist/chunk-nang3847.js +416 -0
  98. package/dist/chunk-nang3847.js.map +24 -0
  99. package/dist/{chunk-vj5necm0.js → chunk-nrezmscd.js} +1 -1
  100. package/dist/{chunk-v8vnxkvp.js → chunk-p83erprx.js} +2 -2
  101. package/dist/{chunk-v8vnxkvp.js.map → chunk-p83erprx.js.map} +1 -1
  102. package/dist/{chunk-sj4f7x4p.js → chunk-pkr5dsbk.js} +2 -2
  103. package/dist/{chunk-sj4f7x4p.js.map → chunk-pkr5dsbk.js.map} +1 -1
  104. package/dist/{chunk-f8vcwzgd.js → chunk-pqc16rrx.js} +2 -2
  105. package/dist/{chunk-f8vcwzgd.js.map → chunk-pqc16rrx.js.map} +1 -1
  106. package/dist/{chunk-hvgmqt6z.js → chunk-pvz90a49.js} +2 -2
  107. package/dist/{chunk-hvgmqt6z.js.map → chunk-pvz90a49.js.map} +1 -1
  108. package/dist/{chunk-s4f56035.js → chunk-q290tgza.js} +2 -2
  109. package/dist/{chunk-s4f56035.js.map → chunk-q290tgza.js.map} +1 -1
  110. package/dist/{chunk-wgb79ysr.js → chunk-qf4bmee9.js} +2 -2
  111. package/dist/{chunk-wgb79ysr.js.map → chunk-qf4bmee9.js.map} +1 -1
  112. package/dist/{chunk-a7r39713.js → chunk-qkxnvpaj.js} +2 -2
  113. package/dist/{chunk-a7r39713.js.map → chunk-qkxnvpaj.js.map} +1 -1
  114. package/dist/chunk-r1favzz4.js +19 -0
  115. package/dist/{chunk-rhmpphhc.js.map → chunk-r1favzz4.js.map} +5 -4
  116. package/dist/{chunk-veq07rp8.js → chunk-razjfecn.js} +1 -1
  117. package/dist/{chunk-a77586gv.js → chunk-scc0j5k9.js} +2 -2
  118. package/dist/{chunk-a77586gv.js.map → chunk-scc0j5k9.js.map} +1 -1
  119. package/dist/{chunk-cytss9mb.js → chunk-sce5jes2.js} +2 -2
  120. package/dist/{chunk-cytss9mb.js.map → chunk-sce5jes2.js.map} +1 -1
  121. package/dist/{chunk-t87w4h84.js → chunk-sd02ktf2.js} +2 -2
  122. package/dist/{chunk-t87w4h84.js.map → chunk-sd02ktf2.js.map} +1 -1
  123. package/dist/{chunk-1zzd39qg.js → chunk-sn04cyw0.js} +2 -2
  124. package/dist/{chunk-1zzd39qg.js.map → chunk-sn04cyw0.js.map} +1 -1
  125. package/dist/{chunk-wwdbgshx.js → chunk-tfdmvxza.js} +2 -2
  126. package/dist/{chunk-wwdbgshx.js.map → chunk-tfdmvxza.js.map} +1 -1
  127. package/dist/{chunk-jqrs16g2.js → chunk-tzdenj0n.js} +3 -3
  128. package/dist/{chunk-jqrs16g2.js.map → chunk-tzdenj0n.js.map} +1 -1
  129. package/dist/{chunk-qhw0hej0.js → chunk-x6v2zex2.js} +2 -2
  130. package/dist/{chunk-qhw0hej0.js.map → chunk-x6v2zex2.js.map} +1 -1
  131. package/dist/{chunk-yfwrbfnw.js → chunk-xfw8zyvn.js} +2 -2
  132. package/dist/{chunk-yfwrbfnw.js.map → chunk-xfw8zyvn.js.map} +1 -1
  133. package/dist/{chunk-sksmnjkn.js → chunk-xtzn0qfh.js} +2 -2
  134. package/dist/{chunk-sksmnjkn.js.map → chunk-xtzn0qfh.js.map} +1 -1
  135. package/dist/{chunk-jpetnpzn.js → chunk-xx3zvc3g.js} +2 -2
  136. package/dist/{chunk-jpetnpzn.js.map → chunk-xx3zvc3g.js.map} +1 -1
  137. package/dist/{chunk-fk6nxhxn.js → chunk-xzn2nmny.js} +2 -2
  138. package/dist/{chunk-fk6nxhxn.js.map → chunk-xzn2nmny.js.map} +1 -1
  139. package/dist/{chunk-vtc23xpk.js → chunk-xzyy896s.js} +2 -2
  140. package/dist/{chunk-vtc23xpk.js.map → chunk-xzyy896s.js.map} +1 -1
  141. package/dist/{chunk-fa37qzm3.js → chunk-y09r0wsw.js} +3 -3
  142. package/dist/{chunk-fa37qzm3.js.map → chunk-y09r0wsw.js.map} +1 -1
  143. package/dist/{chunk-5p4z1fgc.js → chunk-ygf0z7kk.js} +2 -2
  144. package/dist/{chunk-5p4z1fgc.js.map → chunk-ygf0z7kk.js.map} +1 -1
  145. package/dist/{chunk-zw6843j3.js → chunk-z759yah5.js} +2 -2
  146. package/dist/{chunk-zw6843j3.js.map → chunk-z759yah5.js.map} +1 -1
  147. package/dist/config/index.js +1 -1
  148. package/dist/console/run.js +2 -2
  149. package/dist/console/run.js.map +1 -1
  150. package/dist/container/index.js +2 -2
  151. package/dist/container/index.js.map +1 -1
  152. package/dist/database/index.js +2 -2
  153. package/dist/database/index.js.map +1 -1
  154. package/dist/email/index.js +2 -2
  155. package/dist/email/index.js.map +1 -1
  156. package/dist/facades/index.js +2 -2
  157. package/dist/facades/index.js.map +1 -1
  158. package/dist/foundation/index.js +2 -2
  159. package/dist/foundation/index.js.map +1 -1
  160. package/dist/http/index.js +2 -2
  161. package/dist/http/index.js.map +1 -1
  162. package/dist/i18n/dictionaryRuntime.js +2 -2
  163. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  164. package/dist/i18n/index.js +2 -2
  165. package/dist/i18n/index.js.map +1 -1
  166. package/dist/kernel/index.js +2 -2
  167. package/dist/kernel/index.js.map +1 -1
  168. package/dist/orm/index.js +2 -2
  169. package/dist/orm/index.js.map +1 -1
  170. package/dist/server/index.js +2 -2
  171. package/dist/server/index.js.map +1 -1
  172. package/dist/services/discovery.d.ts +8 -0
  173. package/dist/services/discovery.d.ts.map +1 -1
  174. package/dist/services/index.d.ts +8 -1
  175. package/dist/services/index.d.ts.map +1 -1
  176. package/dist/services/index.js +3 -3
  177. package/dist/services/index.js.map +2 -2
  178. package/dist/services/queue/DatabaseQueueDriver.d.ts +23 -2
  179. package/dist/services/queue/DatabaseQueueDriver.d.ts.map +1 -1
  180. package/dist/services/queue/Job.d.ts +3 -0
  181. package/dist/services/queue/Job.d.ts.map +1 -1
  182. package/dist/services/queue/MemoryQueueDriver.d.ts +10 -0
  183. package/dist/services/queue/MemoryQueueDriver.d.ts.map +1 -1
  184. package/dist/services/queue/QueueDriver.d.ts +9 -0
  185. package/dist/services/queue/QueueDriver.d.ts.map +1 -1
  186. package/dist/services/queue/QueueManager.d.ts +33 -7
  187. package/dist/services/queue/QueueManager.d.ts.map +1 -1
  188. package/dist/services/queue/QueueServiceProvider.d.ts.map +1 -1
  189. package/dist/services/queue/backoff.d.ts +6 -0
  190. package/dist/services/queue/backoff.d.ts.map +1 -0
  191. package/dist/services/queue/config.d.ts +9 -0
  192. package/dist/services/queue/config.d.ts.map +1 -1
  193. package/dist/services/queue/work.js +2 -2
  194. package/dist/services/queue/work.js.map +1 -1
  195. package/dist/services/queue/workflow/DatabaseWorkflowStore.d.ts +89 -0
  196. package/dist/services/queue/workflow/DatabaseWorkflowStore.d.ts.map +1 -0
  197. package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts +43 -0
  198. package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts.map +1 -0
  199. package/dist/services/queue/workflow/Step.d.ts +202 -0
  200. package/dist/services/queue/workflow/Step.d.ts.map +1 -0
  201. package/dist/services/queue/workflow/Workflow.d.ts +124 -0
  202. package/dist/services/queue/workflow/Workflow.d.ts.map +1 -0
  203. package/dist/services/queue/workflow/WorkflowRuntime.d.ts +60 -0
  204. package/dist/services/queue/workflow/WorkflowRuntime.d.ts.map +1 -0
  205. package/dist/services/queue/workflow/WorkflowStore.d.ts +184 -0
  206. package/dist/services/queue/workflow/WorkflowStore.d.ts.map +1 -0
  207. package/dist/services/queue/workflow/duration.d.ts +8 -0
  208. package/dist/services/queue/workflow/duration.d.ts.map +1 -0
  209. package/dist/services/queue/workflow/workflowContract.d.ts +30 -0
  210. package/dist/services/queue/workflow/workflowContract.d.ts.map +1 -0
  211. package/dist/stats/route-table.js +1 -1
  212. package/dist/support/index.js +2 -2
  213. package/dist/support/index.js.map +1 -1
  214. package/dist/vitest/index.js +1 -1
  215. package/package.json +1 -1
  216. package/dist/chunk-2czfefn2.js +0 -10
  217. package/dist/chunk-63ewmmhc.js +0 -5
  218. package/dist/chunk-rhmpphhc.js +0 -19
  219. package/dist/chunk-y0en07zh.js +0 -302
  220. package/dist/chunk-y0en07zh.js.map +0 -17
  221. /package/dist/{chunk-077rea02.js.map → chunk-33s2xqv1.js.map} +0 -0
  222. /package/dist/{chunk-bvqae0px.js.map → chunk-8t6dwwz6.js.map} +0 -0
  223. /package/dist/{chunk-e7ezmag9.js.map → chunk-aedkrck1.js.map} +0 -0
  224. /package/dist/{chunk-vj5necm0.js.map → chunk-nrezmscd.js.map} +0 -0
  225. /package/dist/{chunk-veq07rp8.js.map → chunk-razjfecn.js.map} +0 -0
@@ -0,0 +1,416 @@
1
+ // @bun
2
+ import{Kh as k,Mh as T0}from"./chunk-xx3zvc3g.js";import{Nh as S0}from"./chunk-gqfqnv3f.js";import{Ph as N0,Qh as R0,Rh as Q0,Th as C,Vh as q,ci as B0}from"./chunk-kkte8nze.js";import{ri as H0}from"./chunk-hr1r3g0d.js";import{Oi as W0,Ri as b}from"./chunk-g5ppst76.js";import{Ui as M0}from"./chunk-8wcpxm41.js";class p{entries=new Map;counters=new Map;async acquire(z,V,Y){let Z=Date.now(),$=this.entries.get(z);if($&&($.expiresAt>Z||$.fences>0))return null;let X=($?.token??0)+1;return this.entries.set(z,{owner:V,token:X,expiresAt:Z+Math.max(0,Y),fences:0}),X}async extend(z,V,Y,Z){let $=this.current(z,V,Y);if(!$)return!1;return $.expiresAt=Date.now()+Math.max(0,Z),!0}async release(z,V,Y){let Z=this.current(z,V,Y);if(!Z)return!1;return Z.owner="",Z.expiresAt=0,!0}async holder(z){let V=this.entries.get(z);if(!V||V.expiresAt<=Date.now())return null;return{owner:V.owner,token:V.token}}async held(z,V,Y){return this.current(z,V,Y)!==void 0}async advance(z,V){if((this.counters.get(z)??-1/0)>=V)return!1;return this.counters.set(z,V),!0}async fence(z,V,Y,Z){let $=this.current(z,V,Y);if(!$)throw new k(z,Y);$.fences++;try{return await Z()}finally{$.fences--}}windows=new Map;async hit(z,V,Y){let Z=Date.now(),$=this.windows.get(z);if(!$||$.endsAt<=Z)$={count:0,endsAt:Z+Math.max(1,Y)},this.windows.set(z,$);if($.count>=V)return{allowed:!1,resetInMs:$.endsAt-Z};return $.count++,{allowed:!0,resetInMs:$.endsAt-Z}}async refund(z){let V=this.windows.get(z);if(V&&V.endsAt>Date.now()&&V.count>0)V.count--}current(z,V,Y){let Z=this.entries.get(z);if(!Z||Z.owner!==V||Z.expiresAt<=Date.now())return;if(Y!==void 0&&Z.token!==Y)return;return Z}}class y{table;sql;dialect;connection;busyTimeout;configured;constructor(z,V={}){let Y=V.table??"gemi_locks";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Y))throw Error(`The lock table name "${Y}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Y,this.sql=z.sql,this.dialect=z.dialect,this.connection=z.name,this.busyTimeout=V.busyTimeout??1000}async createTable(){await this.configure();for(let z of v0(this.dialect,this.table))await this.sql.unsafe(z)}async acquire(z,V,Y){await this.configure();let Z=this.sql,$=this.now(Z);if(await this.seed(Z,z),this.mysql){let H=await Z`
3
+ UPDATE ${this.name(Z)}
4
+ SET owner = ${V}, token = token + 1, expires_at = ${$} + ${this.ms(Z,Y)},
5
+ updated_at = ${$}
6
+ WHERE name = ${z} AND expires_at <= ${$}
7
+ `;if(O(H)===0)return null;let[G]=await Z`
8
+ SELECT token FROM ${this.name(Z)} WHERE name = ${z} AND owner = ${V}
9
+ `;return G?Number(G.token):null}let X=await Z`
10
+ UPDATE ${this.name(Z)}
11
+ SET owner = ${V}, token = token + 1, expires_at = ${$} + ${this.ms(Z,Y)},
12
+ updated_at = ${$}
13
+ WHERE name = ${z} AND expires_at <= ${$}
14
+ RETURNING token
15
+ `;return X[0]?Number(X[0].token):null}async extend(z,V,Y,Z){await this.configure();let $=this.sql,X=this.now($),H=await $`
16
+ UPDATE ${this.name($)}
17
+ SET expires_at = ${X} + ${this.ms($,Z)}, updated_at = ${X}
18
+ WHERE name = ${z} AND owner = ${V} AND token = ${Y} AND expires_at > ${X}
19
+ `;if(O(H)>0)return!0;return this.mysql?this.held(z,V,Y):!1}async release(z,V,Y){await this.configure();let Z=this.sql,$=this.now(Z),X=Y===void 0?Z`1 = 1`:Z`token = ${Y}`,H=await Z`
20
+ UPDATE ${this.name(Z)}
21
+ SET owner = '', expires_at = 0, updated_at = ${$}
22
+ WHERE name = ${z} AND owner = ${V} AND ${X} AND expires_at > ${$}
23
+ `;return O(H)>0}async holder(z){await this.configure();let V=this.sql,[Y]=await V`
24
+ SELECT owner, token FROM ${this.name(V)}
25
+ WHERE name = ${z} AND expires_at > ${this.now(V)}
26
+ `;return Y?{owner:String(Y.owner),token:Number(Y.token)}:null}async held(z,V,Y){await this.configure();let Z=this.sql;return(await Z`
27
+ SELECT 1 AS held FROM ${this.name(Z)}
28
+ WHERE name = ${z} AND owner = ${V} AND token = ${Y} AND expires_at > ${this.now(Z)}
29
+ `).length>0}async advance(z,V){await this.configure();let Y=this.sql;await this.seed(Y,z);let Z=await Y`
30
+ UPDATE ${this.name(Y)}
31
+ SET token = ${this.int(Y,V)}, updated_at = ${this.now(Y)}
32
+ WHERE name = ${z} AND token < ${this.int(Y,V)}
33
+ `;return O(Z)>0}async fence(z,V,Y,Z){await this.configure();let $=async(H)=>{let G=this.now(H),Q;if(this.dialect==="sqlite"){let B=await H`
34
+ UPDATE ${this.name(H)} SET updated_at = ${G}
35
+ WHERE name = ${z} AND owner = ${V} AND token = ${Y} AND expires_at > ${G}
36
+ `;Q=O(B)>0}else Q=(await H`
37
+ SELECT 1 AS held FROM ${this.name(H)}
38
+ WHERE name = ${z} AND owner = ${V} AND token = ${Y} AND expires_at > ${G}
39
+ FOR UPDATE
40
+ `).length>0;if(!Q)throw new k(z,Y);return Z()},X=this.connection;if(X===void 0)return await this.sql.begin((H)=>$(H));return B0(this.sql,(H)=>Q0(X,()=>$(H)),{connection:X})}async hit(z,V,Y){await this.configure();let Z=this.sql,$=this.now(Z);await this.seed(Z,z);let X=this.ms(Z,Math.max(1,Y)),H=await Z`
41
+ UPDATE ${this.name(Z)}
42
+ SET token = CASE WHEN expires_at <= ${$} THEN 1 ELSE token + 1 END,
43
+ expires_at = CASE WHEN expires_at <= ${$} THEN ${$} + ${X} ELSE expires_at END,
44
+ updated_at = ${$}
45
+ WHERE name = ${z} AND (expires_at <= ${$} OR token < ${this.int(Z,V)})
46
+ `,G=O(H)>0,[Q]=await Z`
47
+ SELECT expires_at - ${$} AS reset FROM ${this.name(Z)} WHERE name = ${z}
48
+ `;return{allowed:G,resetInMs:Math.max(0,Number(Q?.reset??0))}}async refund(z){await this.configure();let V=this.sql,Y=this.now(V);await V`
49
+ UPDATE ${this.name(V)} SET token = token - 1, updated_at = ${Y}
50
+ WHERE name = ${z} AND token > 0 AND expires_at > ${Y}
51
+ `}async prune(z){await this.configure();let V=this.sql,Y=this.now(V),Z=await V`
52
+ DELETE FROM ${this.name(V)}
53
+ WHERE expires_at <= ${Y} AND updated_at <= ${Y} - ${this.ms(V,z)}
54
+ `;return O(Z)}async seed(z,V){let Y=this.now(z);if(this.mysql){await z`
55
+ INSERT IGNORE INTO ${this.name(z)} (name, owner, token, expires_at, updated_at)
56
+ VALUES (${V}, '', 0, 0, ${Y})
57
+ `;return}await z`
58
+ INSERT INTO ${this.name(z)} (name, owner, token, expires_at, updated_at)
59
+ VALUES (${V}, '', 0, 0, ${Y})
60
+ ON CONFLICT (name) DO NOTHING
61
+ `}get mysql(){return this.dialect==="mysql"||this.dialect==="mariadb"}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}name(z){return z.unsafe(this.mysql?`\`${this.table}\``:`"${this.table}"`)}now(z){switch(this.dialect){case"postgres":return z`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return z`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return z`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(z,V){return this.int(z,Math.max(0,Math.round(V)))}int(z,V){let Y=Math.round(V);return this.mysql?z`CAST(${Y} AS SIGNED)`:z`CAST(${Y} AS BIGINT)`}}function O(z){let V=z;return Math.max(Number(V.count??0),Number(V.affectedRows??0))}function v0(z,V){if(z==="mysql"||z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${V}\` (
62
+ \`name\` VARCHAR(191) NOT NULL,
63
+ \`owner\` VARCHAR(191) NOT NULL,
64
+ \`token\` BIGINT NOT NULL DEFAULT 0,
65
+ \`expires_at\` BIGINT NOT NULL,
66
+ \`updated_at\` BIGINT NOT NULL,
67
+
68
+ PRIMARY KEY (\`name\`)
69
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let Y=z==="sqlite"?'"name" TEXT NOT NULL PRIMARY KEY,':'"name" TEXT NOT NULL,',Z=z==="sqlite"?"":`,
70
+
71
+ CONSTRAINT "${V}_pkey" PRIMARY KEY ("name")`;return[`CREATE TABLE IF NOT EXISTS "${V}" (
72
+ ${Y}
73
+ "owner" TEXT NOT NULL,
74
+ "token" BIGINT NOT NULL DEFAULT 0,
75
+ "expires_at" BIGINT NOT NULL,
76
+ "updated_at" BIGINT NOT NULL${Z}
77
+ )`]}var I="gemi.WorkflowTick",t=262144;function w(z,V){let Y=(Z)=>Z.slice(0,Z.lastIndexOf(":"));return Y(z)===Y(V)}class R extends Error{constructor(z){super(`The tick running workflow ${z} lost its hold on it (another tick took it over after its lease ran out), so its writes were refused.`);this.name="WorkflowLeaseLostError"}}var j0=["completed","failed","cancelled"];class o{db;table;stepTable;constructor(z,V){this.db=z;this.table=V.table,this.stepTable=V.stepTable}joinsTransaction(){return this.db.transaction()!==void 0}create(z){let V=this.db.transaction(),Y=V?this.insertWorkflow(V,z):this.db.atomically((Z)=>this.insertWorkflow(Z,z));if(V)q(Y);return Y}async insertWorkflow(z,V){await this.db.configure();let Y=this.db.now(z);await T(z`
78
+ INSERT INTO ${this.workflows(z)}
79
+ (id, name, args, status, progress, retick, created_at, updated_at)
80
+ VALUES
81
+ (${V.id}, ${V.name}, ${V.args}, 'running',
82
+ ${this.db.fraction(z,0)}, 0, ${Y}, ${Y})
83
+ `,this.table),await this.db.insertJob(z,{name:I,args:JSON.stringify([V.id])})}async find(z,V={}){await this.db.configure();let Y=this.db.sql,[Z]=await T(Y`SELECT * FROM ${this.workflows(Y)} WHERE id = ${z}`,this.table);if(!Z)return null;return{workflow:P0(Z),steps:V.steps===!1?[]:await this.stepsOf(Y,z)}}acquire(z,V,Y){return this.db.atomically(async(Z)=>{let $=await this.lock(Z,z);if(!$)return{kind:"missing"};let X=await this.db.clock(Z);if($.lockedBy!==null&&!w($.lockedBy,V)&&($.lockedUntil??0)>X)return await Z`UPDATE ${this.workflows(Z)} SET retick = 1 WHERE id = ${z}`,{kind:"busy"};let H=X+Math.max(0,Math.round(Y));return await Z`
84
+ UPDATE ${this.workflows(Z)}
85
+ SET locked_by = ${V}, locked_until = ${this.db.ms(Z,H)}, retick = 0
86
+ WHERE id = ${z}
87
+ `,{kind:"acquired",workflow:{...$,lockedBy:V,lockedUntil:H,retick:!1},steps:await this.stepsOf(Z,z)}})}async renew(z,V,Y){await this.db.configure();let Z=this.db.sql,$=await Z`
88
+ UPDATE ${this.workflows(Z)}
89
+ SET locked_until = ${this.db.now(Z)} + ${this.db.ms(Z,Y)}
90
+ WHERE id = ${z} AND locked_by = ${V}
91
+ `;return K0($)>0}update(z,V,Y){return this.db.atomically(async(Z)=>{let $=await this.lock(Z,z);if(!$)return;if(V.owner!==void 0&&$.lockedBy!==V.owner)throw new R(z);let X=V.key===void 0?null:await this.stepOf(Z,z,V.key),H=V.allSteps?await this.stepsOf(Z,z):[],G=Y({workflow:$,step:X,steps:H,now:Date.now()});if(G.step){let F=G.step.key===V.key?X!==null:await this.stepOf(Z,z,G.step.key)!==null;await this.writeStep(Z,G.step,F)}if(G.batch)await this.db.insertBatch(Z,G.batch);for(let F of G.cancelBatches??[])await this.db.cancelBatch(Z,F);let Q={...$,...G.workflow},B=G.unlock===!0,K=Z`
92
+ status = ${Q.status}, current_step = ${Q.currentStep},
93
+ progress = ${this.db.fraction(Z,Q.progress)}, result = ${Q.result},
94
+ error = ${Q.error}, wake_at = ${this.db.timeOrNull(Z,Q.wakeAt)},
95
+ updated_at = ${this.db.now(Z)}
96
+ `;if(B)await Z`
97
+ UPDATE ${this.workflows(Z)}
98
+ SET ${K}, locked_by = NULL, locked_until = NULL, retick = 0
99
+ WHERE id = ${z}
100
+ `;else await Z`UPDATE ${this.workflows(Z)} SET ${K} WHERE id = ${z}`;let A=(F)=>this.db.insertJob(Z,{name:I,args:JSON.stringify([z]),delayMs:Math.max(0,Math.round(F))});if(G.tick)await A(G.tick.delayMs);if(B&&$.retick)await A(0);return G.result})}async prune(z){return this.db.atomically(async(V)=>{let Y=V`status IN (${j0.map((X)=>V`${X}`).reduce((X,H)=>V`${X}, ${H}`)})`,Z=V`${this.db.now(V)} - ${this.db.ms(V,z)}`;await V`
101
+ DELETE FROM ${this.steps(V)}
102
+ WHERE workflow_id IN (
103
+ SELECT id FROM ${this.workflows(V)} WHERE ${Y} AND updated_at <= ${Z}
104
+ )
105
+ `;let $=await V`
106
+ DELETE FROM ${this.workflows(V)} WHERE ${Y} AND updated_at <= ${Z}
107
+ `;return K0($)})}async writeStep(z,V,Y){let Z=this.db,$=this.keyColumn(z);if(Y){await z`
108
+ UPDATE ${this.steps(z)}
109
+ SET status = ${V.status}, attempt = ${V.attempt}, output = ${V.output},
110
+ error = ${V.error}, batch_id = ${V.batchId},
111
+ wake_at = ${Z.timeOrNull(z,V.wakeAt)},
112
+ started_at = ${Z.timeOrNull(z,V.startedAt)},
113
+ finished_at = ${Z.timeOrNull(z,V.finishedAt)}, updated_at = ${Z.now(z)}
114
+ WHERE workflow_id = ${V.workflowId} AND ${$} = ${V.key}
115
+ `;return}let X=Z.now(z);await z`
116
+ INSERT INTO ${this.steps(z)}
117
+ (workflow_id, ${$}, status, attempt, output, error, batch_id, wake_at,
118
+ started_at, finished_at, created_at, updated_at)
119
+ VALUES
120
+ (${V.workflowId}, ${V.key}, ${V.status}, ${V.attempt}, ${V.output},
121
+ ${V.error}, ${V.batchId}, ${Z.timeOrNull(z,V.wakeAt)},
122
+ ${Z.timeOrNull(z,V.startedAt)}, ${Z.timeOrNull(z,V.finishedAt)}, ${X}, ${X})
123
+ `}async lock(z,V){let Y;if(this.db.dialect==="sqlite")await T(z`UPDATE ${this.workflows(z)} SET updated_at = updated_at WHERE id = ${V}`,this.table),Y=await z`SELECT * FROM ${this.workflows(z)} WHERE id = ${V}`;else Y=await T(z`SELECT * FROM ${this.workflows(z)} WHERE id = ${V} FOR UPDATE`,this.table);return Y[0]?P0(Y[0]):void 0}async stepOf(z,V,Y){let[Z]=await T(z`SELECT * FROM ${this.steps(z)} WHERE workflow_id = ${V} AND ${this.keyColumn(z)} = ${Y}`,this.stepTable);return Z?J0(Z):null}async stepsOf(z,V){return(await T(z`
124
+ SELECT * FROM ${this.steps(z)} WHERE workflow_id = ${V}
125
+ ORDER BY created_at, ${this.keyColumn(z)}
126
+ `,this.stepTable)).map(J0)}workflows(z){return z.unsafe(this.db.quoted(this.table))}steps(z){return z.unsafe(this.db.quoted(this.stepTable))}keyColumn(z){return z.unsafe(this.db.quoted("key"))}}function f(z){return z==null?null:Number(z)}function L(z){return z==null?null:String(z)}function P0(z){return{id:String(z.id),name:String(z.name),args:String(z.args),status:String(z.status),currentStep:L(z.current_step),progress:Number(z.progress??0),result:L(z.result),error:L(z.error),wakeAt:f(z.wake_at),lockedBy:L(z.locked_by),lockedUntil:f(z.locked_until),retick:Number(z.retick??0)!==0,createdAt:Number(z.created_at),updatedAt:Number(z.updated_at)}}function J0(z){return{workflowId:String(z.workflow_id),key:String(z.key),status:String(z.status),attempt:Number(z.attempt??0),output:L(z.output),error:L(z.error),batchId:L(z.batch_id),wakeAt:f(z.wake_at),startedAt:f(z.started_at),finishedAt:f(z.finished_at),createdAt:Number(z.created_at),updatedAt:Number(z.updated_at)}}function K0(z){let V=z;return Math.max(Number(V.count??0),Number(V.affectedRows??0))}function g0(z){let V=String(z?.message??z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test(V)}async function T(z,V){try{return await z}catch(Y){if(!g0(Y))throw Y;throw Error(`Workflows need the "${V}" table, and the database says it is missing. Add the GemiWorkflow and GemiWorkflowStep models from the docs (docs/workflows.md#the-workflow-tables) and migrate, or call the queue driver's createTable().`,{cause:Y})}}function F0(z,V,Y){if(z==="mysql"||z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${V}\` (
127
+ \`id\` VARCHAR(191) NOT NULL,
128
+ \`name\` VARCHAR(191) NOT NULL,
129
+ \`args\` LONGTEXT NOT NULL,
130
+ \`status\` VARCHAR(191) NOT NULL,
131
+ \`current_step\` VARCHAR(191) NULL,
132
+ \`progress\` DOUBLE NOT NULL DEFAULT 0,
133
+ \`result\` LONGTEXT NULL,
134
+ \`error\` LONGTEXT NULL,
135
+ \`wake_at\` BIGINT NULL,
136
+ \`locked_by\` VARCHAR(191) NULL,
137
+ \`locked_until\` BIGINT NULL,
138
+ \`retick\` INTEGER NOT NULL DEFAULT 0,
139
+ \`created_at\` BIGINT NOT NULL,
140
+ \`updated_at\` BIGINT NOT NULL,
141
+
142
+ INDEX \`${V}_status_idx\`(\`status\`),
143
+ PRIMARY KEY (\`id\`)
144
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,`CREATE TABLE IF NOT EXISTS \`${Y}\` (
145
+ \`workflow_id\` VARCHAR(191) NOT NULL,
146
+ \`key\` VARCHAR(191) NOT NULL,
147
+ \`status\` VARCHAR(191) NOT NULL,
148
+ \`attempt\` INTEGER NOT NULL DEFAULT 0,
149
+ \`output\` LONGTEXT NULL,
150
+ \`error\` LONGTEXT NULL,
151
+ \`batch_id\` VARCHAR(191) NULL,
152
+ \`wake_at\` BIGINT NULL,
153
+ \`started_at\` BIGINT NULL,
154
+ \`finished_at\` BIGINT NULL,
155
+ \`created_at\` BIGINT NOT NULL,
156
+ \`updated_at\` BIGINT NOT NULL,
157
+
158
+ PRIMARY KEY (\`workflow_id\`, \`key\`)
159
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let Z=z==="sqlite";return[`CREATE TABLE IF NOT EXISTS "${V}" (
160
+ "id" TEXT NOT NULL${Z?" PRIMARY KEY":""},
161
+ "name" TEXT NOT NULL,
162
+ "args" TEXT NOT NULL,
163
+ "status" TEXT NOT NULL,
164
+ "current_step" TEXT,
165
+ "progress" ${Z?"REAL":"DOUBLE PRECISION"} NOT NULL DEFAULT 0,
166
+ "result" TEXT,
167
+ "error" TEXT,
168
+ "wake_at" BIGINT,
169
+ "locked_by" TEXT,
170
+ "locked_until" BIGINT,
171
+ "retick" INTEGER NOT NULL DEFAULT 0,
172
+ "created_at" BIGINT NOT NULL,
173
+ "updated_at" BIGINT NOT NULL${Z?"":`,
174
+
175
+ CONSTRAINT "${V}_pkey" PRIMARY KEY ("id")`}
176
+ )`,`CREATE TABLE IF NOT EXISTS "${Y}" (
177
+ "workflow_id" TEXT NOT NULL,
178
+ "key" TEXT NOT NULL,
179
+ "status" TEXT NOT NULL,
180
+ "attempt" INTEGER NOT NULL DEFAULT 0,
181
+ "output" TEXT,
182
+ "error" TEXT,
183
+ "batch_id" TEXT,
184
+ "wake_at" BIGINT,
185
+ "started_at" BIGINT,
186
+ "finished_at" BIGINT,
187
+ "created_at" BIGINT NOT NULL,
188
+ "updated_at" BIGINT NOT NULL,
189
+
190
+ ${Z?'PRIMARY KEY ("workflow_id", "key")':`CONSTRAINT "${Y}_pkey" PRIMARY KEY ("workflow_id","key")`}
191
+ )`,`CREATE INDEX IF NOT EXISTS "${V}_status_idx" ON "${V}"("status")`]}function d(z){return{id:z.id,name:z.name,total:z.total,pending:z.total,succeeded:0,failed:0,cancelled:0,failedJobIds:[],cancelledAt:null,finishedAt:null,createdAt:z.now,allowFailures:z.allowFailures,callbacks:z.callbacks}}function c(z,V,Y){if(z.pending<=0)return z;let Z={...z,pending:z.pending-1};if(V==="succeeded")Z.succeeded++;else if(V==="cancelled")Z.cancelled++;else Z.failed++,Z.failedJobIds=[...z.failedJobIds,Y];return Z}function l(z,V){return!V.allowFailures&&V.cancelledAt===null&&V.finishedAt===null&&V.failed>z.failed}function M(z,V,Y){let Z=Math.min(Math.max(0,Y),z.pending);return{...z,cancelledAt:z.cancelledAt??V,pending:z.pending-Z,cancelled:z.cancelled+Z}}function x(z,V,Y){let Z=V,$=[],X=V.callbacks,H=z.failed===0&&z.cancelledAt===null,G=V.failed===0&&V.cancelledAt===null;if(H&&!G&&X.catch)$.push(X.catch);if(V.pending===0&&V.finishedAt===null){if(Z={...V,finishedAt:Y},V.cancelledAt===null&&(V.failed===0||V.allowFailures)&&X.then)$.push(X.then);if(X.finally)$.push(X.finally)}let Q=W(Z);return{record:Z,calls:$.map((B)=>({name:B.name,args:JSON.stringify([...B.args,Q])}))}}function W(z,V=0){let{allowFailures:Y,callbacks:Z,...$}=z,X=z.total-z.pending,H=z.total===0?1:Math.min(1,Math.max(0,(X+Math.max(0,V))/z.total));return{...$,failedJobIds:[...z.failedJobIds],progress:H}}function E(z){if(typeof z!=="number"||!Number.isFinite(z))throw TypeError(`A job's progress is a number from 0 to 1; got ${String(z)}.`);return Math.min(1,Math.max(0,z))}var U0=200,h0="Its batch was cancelled before it ran.";class z0{table;batchTable;workflowTable;workflowStepTable;workflows;sql;dialect;connection;busyTimeout;configured;sqliteTail=Promise.resolve();constructor(z,V={}){let Y=V.table??"gemi_jobs",Z=V.batchTable??(Y==="gemi_jobs"?"gemi_job_batches":`${Y}_batches`),$=Y==="gemi_jobs",X=V.workflowTable??($?"gemi_workflows":`${Y}_workflows`),H=V.workflowStepTable??($?"gemi_workflow_steps":`${Y}_workflow_steps`);for(let Q of[Y,Z,X,H])if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The queue table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);let G=V.busyTimeout??1000;if(!Number.isInteger(G)||G<0)throw Error(`The queue's busyTimeout must be a whole number of milliseconds, 0 or more; got ${G}.`);this.table=Y,this.batchTable=Z,this.workflowTable=X,this.workflowStepTable=H,this.sql=z.sql,this.dialect=z.dialect,this.connection=z.name,this.busyTimeout=G}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();let[z,...V]=y0(this.dialect,this.table);if(await this.sql.unsafe(z),!await this.hasBatchColumns())for(let Y of f0(this.dialect,this.table))await this.sql.unsafe(Y);for(let Y of V)await this.sql.unsafe(Y);for(let Y of q0(this.dialect,this.batchTable))await this.sql.unsafe(Y);for(let Y of F0(this.dialect,this.workflowTable,this.workflowStepTable))await this.sql.unsafe(Y)}async hasBatchColumns(){try{return await this.sql.unsafe(`SELECT batch_id, progress FROM ${this.quoted(this.table)} WHERE 1 = 0`),!0}catch(z){if(_0(z))return!1;throw z}}enqueue(z){let V=this.transaction(),Y=this.insert(V??this.sql,z);if(V)q(Y);return Y}async insert(z,{name:V,args:Y,delayMs:Z=0,id:$=Bun.randomUUIDv7()}){await this.configure();let X=this.now(z);return await z`
192
+ INSERT INTO ${this.name(z)}
193
+ (id, name, payload, status, attempts, available_at, created_at, updated_at)
194
+ VALUES
195
+ (${$}, ${V}, ${Y}, 'pending', 0, ${X} + ${this.ms(z,Z)}, ${X}, ${X})
196
+ `,$}lockStore(){return new y({sql:this.sql,dialect:this.dialect,name:this.connection},{busyTimeout:this.busyTimeout})}joinsTransaction(){return this.transaction()!==void 0}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let z=N0();if(z===void 0||R0()!==this.connection)return;return z}async claim(z,V){let Y=Math.max(0,Math.floor(z));if(Y===0)return[];return await this.configure(),(this.dialect==="mysql"||this.dialect==="mariadb"?await this.claimLocking(Y,V):await this.claimUpdating(Y,V)).map(($)=>({order:Number($.available_at),job:{id:String($.id),name:String($.name),args:String($.payload),attempt:Number($.attempts),createdAt:Number($.created_at),...$.batch_id==null?{}:{batchId:String($.batch_id)}}})).sort(($,X)=>$.order-X.order||($.job.id<X.job.id?-1:1)).map(({job:$})=>$)}async complete(z){if(z.batchId!==void 0)return this.endBatchJob(z,"succeeded");await this.configure();let V=this.sql;await V`
197
+ DELETE FROM ${this.name(V)}
198
+ WHERE id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}
199
+ `}async fail(z,V){if(z.batchId!==void 0)return this.endBatchJob(z,"failed",V);await this.configure();let Y=this.sql,Z=this.now(Y);if(V.retryInMs===null){await Y`
200
+ UPDATE ${this.name(Y)}
201
+ SET status = 'dead', lease_expires_at = NULL, last_error = ${V.error},
202
+ updated_at = ${Z}
203
+ WHERE id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}
204
+ `;return}await Y`
205
+ UPDATE ${this.name(Y)}
206
+ SET status = 'pending', available_at = ${Z} + ${this.ms(Y,V.retryInMs)},
207
+ lease_expires_at = NULL, last_error = ${V.error}, updated_at = ${Z}
208
+ WHERE id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}
209
+ `}async release(z,V){let Y=this.sql,Z=this.now(Y);await Y`
210
+ UPDATE ${this.name(Y)}
211
+ SET status = 'pending', attempts = attempts - 1,
212
+ available_at = ${Z} + ${this.ms(Y,V.retryInMs)},
213
+ lease_expires_at = NULL, updated_at = ${Z}
214
+ WHERE id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}
215
+ `}async heartbeat(z,V){await this.configure();let Y=this.sql;await Promise.all(z.map((Z)=>{let $=this.now(Y);return Y`
216
+ UPDATE ${this.name(Y)}
217
+ SET lease_expires_at = ${$} + ${this.ms(Y,V.visibilityTimeoutMs)},
218
+ updated_at = ${$}
219
+ WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
220
+ `}))}async retryDead(z){await this.configure();let V=this.sql,[Y]=await V`
221
+ SELECT * FROM ${this.name(V)} WHERE id = ${z} AND status = 'dead'
222
+ `;if(!Y||Y.batch_id!=null)return!1;let Z=this.now(V),$=await V`
223
+ UPDATE ${this.name(V)}
224
+ SET status = 'pending', attempts = 0, available_at = ${Z}, lease_expires_at = NULL,
225
+ updated_at = ${Z}
226
+ WHERE id = ${z} AND status = 'dead'
227
+ `;return v($)>0}async prune(z){await this.configure();let V=this.sql,Y=await V`
228
+ DELETE FROM ${this.name(V)}
229
+ WHERE status = 'dead' AND updated_at <= ${this.now(V)} - ${this.ms(V,z)}
230
+ `;return v(Y)}enqueueBatch(z){let V=this.transaction(),Y=V?this.insertBatch(V,z):this.atomically((Z)=>this.insertBatch(Z,z));if(V)q(Y);return Y}async insertBatch(z,V){await this.configure();let Y=await this.clock(z),Z=d({...V,total:V.args.length,now:Y}),{record:$,calls:X}=x(Z,Z,Y);await e(z`
231
+ INSERT INTO ${this.batches(z)}
232
+ (id, name, total, pending, succeeded, failed, cancelled, failed_job_ids, options,
233
+ cancelled_at, finished_at, created_at, updated_at)
234
+ VALUES
235
+ (${$.id}, ${$.name}, ${$.total}, ${$.pending}, 0, 0, 0,
236
+ '[]', ${m0($)}, NULL, ${this.timeOrNull(z,$.finishedAt)},
237
+ ${this.ms(z,Y)}, ${this.ms(z,Y)})
238
+ `,this.batchTable);let H=this.ms(z,Y);for(let G=0;G<V.args.length;G+=U0){let Q=V.args.slice(G,G+U0).map((B)=>z`(${Bun.randomUUIDv7()}, ${V.job}, ${B}, 'pending', 0, ${H}, ${H}, ${H}, ${V.id}, 0)`).reduce((B,K)=>z`${B}, ${K}`);await e(z`
239
+ INSERT INTO ${this.name(z)}
240
+ (id, name, payload, status, attempts, available_at, created_at, updated_at, batch_id, progress)
241
+ VALUES ${Q}
242
+ `,this.table)}for(let G of X)await this.insert(z,G)}async findBatch(z,V={}){await this.configure();let Y=this.sql,[Z]=await e(Y`SELECT * FROM ${this.batches(Y)} WHERE id = ${z}`,this.batchTable);if(!Z)return null;let $=A0(Z);if(V.progress===!1||$.pending===0)return W($);let[X]=await Y`
243
+ SELECT COALESCE(SUM(progress), 0) AS running FROM ${this.name(Y)}
244
+ WHERE batch_id = ${z} AND status IN ('pending', 'claimed')
245
+ `;return W($,Number(X?.running??0))}async cancelBatch(z){return this.atomically((V)=>this.cancelBatchOn(V,z))}async cancelBatchOn(z,V){let Y=await this.lockBatch(z,V);if(!Y||Y.finishedAt!==null||Y.cancelledAt!==null)return!1;let Z=await this.clock(z),$=M(Y,Z,await this.cancelWaiting(z,V));return await this.saveBatch(z,Y,$,Z),!0}workflowStore(){return this.workflows??=new o({sql:this.sql,dialect:this.dialect,connection:this.connection,configure:()=>this.configure(),atomically:(z)=>this.atomically(z),transaction:()=>this.transaction(),now:(z)=>this.now(z),ms:(z,V)=>this.ms(z,V),timeOrNull:(z,V)=>this.timeOrNull(z,V),fraction:(z,V)=>this.fraction(z,V),clock:(z)=>this.clock(z),insertJob:(z,V)=>this.insert(z,V),insertBatch:(z,V)=>this.insertBatch(z,V),cancelBatch:(z,V)=>this.cancelBatchOn(z,V),quoted:(z)=>this.quoted(z)},{table:this.workflowTable,stepTable:this.workflowStepTable}),this.workflows}async reportProgress(z,V){let Y=E(V);await this.configure();let Z=this.sql;await Z`
246
+ UPDATE ${this.name(Z)} SET progress = ${this.fraction(Z,Y)}
247
+ WHERE id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}
248
+ `}async pruneBatches(z){await this.configure();let V=this.sql,Y=await V`
249
+ DELETE FROM ${this.batches(V)}
250
+ WHERE finished_at IS NOT NULL AND finished_at <= ${this.now(V)} - ${this.ms(V,z)}
251
+ `;return v(Y)}endBatchJob(z,V,Y){let Z=z.batchId;return this.atomically(async($)=>{let X=await this.lockBatch($,Z),H=$`id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}`,G=this.now($);if(V==="succeeded"){let K=await $`DELETE FROM ${this.name($)} WHERE ${H}`;if(v(K)===0||!X)return;return this.count($,X,"succeeded",z.id)}let Q=Y.cancelled===!0||Y.retryInMs!==null&&X!==void 0&&X.cancelledAt!==null;if(Y.retryInMs!==null&&!Q){await $`
252
+ UPDATE ${this.name($)}
253
+ SET status = 'pending', available_at = ${G} + ${this.ms($,Y.retryInMs)},
254
+ lease_expires_at = NULL, last_error = ${Y.error}, progress = 0,
255
+ updated_at = ${G}
256
+ WHERE ${H}
257
+ `;return}let B=await $`
258
+ UPDATE ${this.name($)}
259
+ SET status = 'dead', lease_expires_at = NULL, last_error = ${Y.error},
260
+ updated_at = ${G}
261
+ WHERE ${H}
262
+ `;if(v(B)===0||!X)return;return this.count($,X,Q?"cancelled":"failed",z.id)})}async count(z,V,Y,Z){let $=await this.clock(z),X=c(V,Y,Z);if(l(V,X))X=M(X,$,await this.cancelWaiting(z,V.id));await this.saveBatch(z,V,X,$)}async cancelWaiting(z,V){let Y=this.now(z),Z=await z`
263
+ UPDATE ${this.name(z)}
264
+ SET status = 'dead', last_error = ${h0}, updated_at = ${Y}
265
+ WHERE batch_id = ${V} AND status = 'pending'
266
+ `;return v(Z)}async saveBatch(z,V,Y,Z){let{record:$,calls:X}=x(V,Y,Z);await z`
267
+ UPDATE ${this.batches(z)}
268
+ SET pending = ${$.pending}, succeeded = ${$.succeeded}, failed = ${$.failed},
269
+ cancelled = ${$.cancelled}, failed_job_ids = ${JSON.stringify($.failedJobIds)},
270
+ cancelled_at = ${this.timeOrNull(z,$.cancelledAt)},
271
+ finished_at = ${this.timeOrNull(z,$.finishedAt)}, updated_at = ${this.ms(z,Z)}
272
+ WHERE id = ${$.id}
273
+ `;for(let H of X)await this.insert(z,H)}async lockBatch(z,V){let Y;if(this.dialect==="sqlite")await z`UPDATE ${this.batches(z)} SET updated_at = updated_at WHERE id = ${V}`,Y=await z`SELECT * FROM ${this.batches(z)} WHERE id = ${V}`;else Y=await z`SELECT * FROM ${this.batches(z)} WHERE id = ${V} FOR UPDATE`;return Y[0]?A0(Y[0]):void 0}atomically(z){let V=async()=>{await this.configure();for(let Z=0;;Z++)try{return await this.sql.begin(($)=>z($))}catch($){if(this.dialect!=="sqlite"||Z>=50||!/within a transaction/i.test(String($?.message??$)))throw $;await new Promise((X)=>setTimeout(X,20))}};if(this.dialect!=="sqlite")return V();let Y=this.sqliteTail.then(V,V);return this.sqliteTail=Y.catch(()=>{}),Y}async clock(z){let[V]=await z`SELECT ${this.now(z)} AS now`;return Number(V.now)}timeOrNull(z,V){return V===null?z`NULL`:this.ms(z,V)}fraction(z,V){return this.dialect==="postgres"?z`CAST(${V} AS DOUBLE PRECISION)`:z`${V}`}async claimUpdating(z,V){let Y=this.sql,Z=this.now(Y),$=this.ms(Y,V.visibilityTimeoutMs),X=this.name(Y);if(this.dialect==="postgres")return await Y`
274
+ WITH next AS (
275
+ SELECT id FROM ${X}
276
+ WHERE ${this.claimable(Y,V)}
277
+ ORDER BY available_at, id
278
+ LIMIT ${z}
279
+ FOR UPDATE SKIP LOCKED
280
+ )
281
+ UPDATE ${X} AS job
282
+ SET status = 'claimed', attempts = job.attempts + 1, claimed_at = ${Z},
283
+ lease_expires_at = ${Z} + ${$}, updated_at = ${Z}
284
+ FROM next
285
+ WHERE job.id = next.id
286
+ RETURNING job.*
287
+ `;return await Y`
288
+ UPDATE ${X}
289
+ SET status = 'claimed', attempts = attempts + 1, claimed_at = ${Z},
290
+ lease_expires_at = ${Z} + ${$}, updated_at = ${Z}
291
+ WHERE id IN (
292
+ SELECT id FROM ${X}
293
+ WHERE ${this.claimable(Y,V)}
294
+ ORDER BY available_at, id
295
+ LIMIT ${z}
296
+ )
297
+ RETURNING *
298
+ `}async claimLocking(z,V){let Y=await this.sql.reserve(),[Z]=await Y`
299
+ SELECT @@transaction_isolation AS level
300
+ `;await Y`SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED`;try{return await this.claimLockingOn(Y,z,V)}finally{let $=Z?.level?.replaceAll("-"," ");if($&&/^[A-Z ]+$/.test($))await Y.unsafe(`SET SESSION TRANSACTION ISOLATION LEVEL ${$}`);Y.release()}}async claimLockingOn(z,V,Y){return await z.begin(async(Z)=>{let $=this.name(Z),X=Z.unsafe("*"),H=await Z`
301
+ SELECT ${X} FROM ${$}
302
+ WHERE status = 'pending' AND available_at <= ${this.now(Z)}
303
+ AND ${this.runnable(Z,Y,"available_at")}
304
+ ORDER BY available_at, id
305
+ LIMIT ${V}
306
+ FOR UPDATE SKIP LOCKED
307
+ `;if(H.length<V){let G=await Z`
308
+ SELECT ${X} FROM ${$}
309
+ WHERE status = 'claimed' AND lease_expires_at <= ${this.now(Z)}
310
+ AND ${this.runnable(Z,Y,"lease_expires_at")}
311
+ ORDER BY lease_expires_at, id
312
+ LIMIT ${V-H.length}
313
+ FOR UPDATE SKIP LOCKED
314
+ `;H.push(...G)}for(let G of H){let Q=this.now(Z);await Z`
315
+ UPDATE ${$}
316
+ SET status = 'claimed', attempts = attempts + 1, claimed_at = ${Q},
317
+ lease_expires_at = ${Q} + ${this.ms(Z,Y.visibilityTimeoutMs)},
318
+ updated_at = ${Q}
319
+ WHERE id = ${G.id}
320
+ `}return H.map((G)=>({...G,attempts:Number(G.attempts)+1}))})}claimable(z,V){let Y=this.now(z);return z`(
321
+ (status = 'pending' AND available_at <= ${Y}
322
+ AND ${this.runnable(z,V,"available_at")})
323
+ OR (status = 'claimed' AND lease_expires_at <= ${Y}
324
+ AND ${this.runnable(z,V,"lease_expires_at")})
325
+ )`}runnable(z,V,Y){let Z=V.registered;if(!Z)return z`1 = 1`;let $=Z.names.length?z`name IN (${Z.names.map((H)=>z`${H}`).reduce((H,G)=>z`${H}, ${G}`)})`:z`1 = 0`;if(!Number.isFinite(Z.graceMs))return $;let X=z.unsafe(Y);return z`(${$} OR ${X} <= ${this.now(z)} - ${this.ms(z,Z.graceMs)})`}name(z){return z.unsafe(this.quoted(this.table))}batches(z){return z.unsafe(this.quoted(this.batchTable))}quoted(z){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${z}\``:`"${z}"`}now(z){switch(this.dialect){case"postgres":return z`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return z`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return z`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(z,V){let Y=Math.max(0,Math.round(V));return this.dialect==="mysql"||this.dialect==="mariadb"?z`CAST(${Y} AS SIGNED)`:z`CAST(${Y} AS BIGINT)`}}function v(z){let V=z;return Math.max(Number(V.count??0),Number(V.affectedRows??0))}function y0(z,V){if(z==="mysql"||z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${V}\` (
326
+ \`id\` VARCHAR(191) NOT NULL,
327
+ \`name\` VARCHAR(191) NOT NULL,
328
+ \`payload\` LONGTEXT NOT NULL,
329
+ \`status\` VARCHAR(191) NOT NULL,
330
+ \`attempts\` INTEGER NOT NULL DEFAULT 0,
331
+ \`available_at\` BIGINT NOT NULL,
332
+ \`claimed_at\` BIGINT NULL,
333
+ \`lease_expires_at\` BIGINT NULL,
334
+ \`last_error\` LONGTEXT NULL,
335
+ \`created_at\` BIGINT NOT NULL,
336
+ \`updated_at\` BIGINT NOT NULL,
337
+ \`batch_id\` VARCHAR(191) NULL,
338
+ \`progress\` DOUBLE NULL,
339
+
340
+ INDEX \`${V}_status_available_at_idx\`(\`status\`, \`available_at\`),
341
+ INDEX \`${V}_status_lease_expires_at_idx\`(\`status\`, \`lease_expires_at\`),
342
+ INDEX \`${V}_batch_id_idx\`(\`batch_id\`),
343
+ PRIMARY KEY (\`id\`)
344
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let Y=z==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',Z=z==="sqlite"?"":`,
345
+
346
+ CONSTRAINT "${V}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${V}" (
347
+ ${Y}
348
+ "name" TEXT NOT NULL,
349
+ "payload" TEXT NOT NULL,
350
+ "status" TEXT NOT NULL,
351
+ "attempts" INTEGER NOT NULL DEFAULT 0,
352
+ "available_at" BIGINT NOT NULL,
353
+ "claimed_at" BIGINT,
354
+ "lease_expires_at" BIGINT,
355
+ "last_error" TEXT,
356
+ "created_at" BIGINT NOT NULL,
357
+ "updated_at" BIGINT NOT NULL,
358
+ "batch_id" TEXT,
359
+ "progress" ${z==="sqlite"?"REAL":"DOUBLE PRECISION"}${Z}
360
+ )`,`CREATE INDEX IF NOT EXISTS "${V}_status_available_at_idx" ON "${V}"("status", "available_at")`,`CREATE INDEX IF NOT EXISTS "${V}_status_lease_expires_at_idx" ON "${V}"("status", "lease_expires_at")`,`CREATE INDEX IF NOT EXISTS "${V}_batch_id_idx" ON "${V}"("batch_id")`]}function f0(z,V){if(z==="mysql"||z==="mariadb")return[`ALTER TABLE \`${V}\` ADD COLUMN \`batch_id\` VARCHAR(191) NULL,
361
+ ADD COLUMN \`progress\` DOUBLE NULL,
362
+ ADD INDEX \`${V}_batch_id_idx\`(\`batch_id\`)`];let Y=z==="sqlite"?"REAL":"DOUBLE PRECISION";if(z==="sqlite")return[`ALTER TABLE "${V}" ADD COLUMN "batch_id" TEXT`,`ALTER TABLE "${V}" ADD COLUMN "progress" ${Y}`,`CREATE INDEX IF NOT EXISTS "${V}_batch_id_idx" ON "${V}"("batch_id")`];return[`ALTER TABLE "${V}" ADD COLUMN IF NOT EXISTS "batch_id" TEXT,
363
+ ADD COLUMN IF NOT EXISTS "progress" ${Y}`,`CREATE INDEX IF NOT EXISTS "${V}_batch_id_idx" ON "${V}"("batch_id")`]}function q0(z,V){if(z==="mysql"||z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${V}\` (
364
+ \`id\` VARCHAR(191) NOT NULL,
365
+ \`name\` VARCHAR(191) NULL,
366
+ \`total\` INTEGER NOT NULL,
367
+ \`pending\` INTEGER NOT NULL,
368
+ \`succeeded\` INTEGER NOT NULL DEFAULT 0,
369
+ \`failed\` INTEGER NOT NULL DEFAULT 0,
370
+ \`cancelled\` INTEGER NOT NULL DEFAULT 0,
371
+ \`failed_job_ids\` LONGTEXT NOT NULL,
372
+ \`options\` LONGTEXT NOT NULL,
373
+ \`cancelled_at\` BIGINT NULL,
374
+ \`finished_at\` BIGINT NULL,
375
+ \`created_at\` BIGINT NOT NULL,
376
+ \`updated_at\` BIGINT NOT NULL,
377
+
378
+ PRIMARY KEY (\`id\`)
379
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let Y=z==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',Z=z==="sqlite"?"":`,
380
+
381
+ CONSTRAINT "${V}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${V}" (
382
+ ${Y}
383
+ "name" TEXT,
384
+ "total" INTEGER NOT NULL,
385
+ "pending" INTEGER NOT NULL,
386
+ "succeeded" INTEGER NOT NULL DEFAULT 0,
387
+ "failed" INTEGER NOT NULL DEFAULT 0,
388
+ "cancelled" INTEGER NOT NULL DEFAULT 0,
389
+ "failed_job_ids" TEXT NOT NULL,
390
+ "options" TEXT NOT NULL,
391
+ "cancelled_at" BIGINT,
392
+ "finished_at" BIGINT,
393
+ "created_at" BIGINT NOT NULL,
394
+ "updated_at" BIGINT NOT NULL${Z}
395
+ )`]}function A0(z){let V=JSON.parse(z.options),Y=(Z)=>Z==null?null:Number(Z);return{id:String(z.id),name:z.name==null?null:String(z.name),total:Number(z.total),pending:Number(z.pending),succeeded:Number(z.succeeded),failed:Number(z.failed),cancelled:Number(z.cancelled),failedJobIds:JSON.parse(z.failed_job_ids),cancelledAt:Y(z.cancelled_at),finishedAt:Y(z.finished_at),createdAt:Number(z.created_at),allowFailures:V.allowFailures===!0,callbacks:V.callbacks??{}}}function m0(z){return JSON.stringify({allowFailures:z.allowFailures,callbacks:z.callbacks})}function _0(z){let V=String(z?.message??z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test(V)}async function e(z,V){try{return await z}catch(Y){if(!_0(Y))throw Y;throw Error(`Job batches need the "${V}" table and the batch_id and progress columns of the jobs table, and the database says one is missing. Add the GemiJobBatch model and the two GemiJob fields from the docs (docs/jobs-and-queues.md#batches) and migrate, or call the driver's createTable().`,{cause:Y})}}import{AsyncResource as c0}from"async_hooks";import{isMainThread as l0}from"worker_threads";function Nz(z){return z}function C0(){return{jobs:[],jobsDir:"app/jobs",workflows:[],workflowsDir:"app/workflows",concurrency:1,driver:"memory",visibilityTimeout:300000,pollInterval:1000,unknownJobGrace:3600000,locks:"auto"}}var b0=86400000;class V0{queue;workflows=new Map;steps=new Map;constructor(z){this.queue=z}async create(z){if(this.workflows.has(z.id))throw Error(`A workflow with the id ${z.id} already exists.`);this.prune(b0);let V=Date.now();this.workflows.set(z.id,{...z,status:"running",currentStep:null,progress:0,result:null,error:null,wakeAt:null,lockedBy:null,lockedUntil:null,retick:!1,createdAt:V,updatedAt:V}),this.steps.set(z.id,new Map),this.tick(z.id,0)}async find(z,V={}){let Y=this.workflows.get(z);if(!Y)return null;return{workflow:{...Y},steps:V.steps===!1?[]:this.stepsOf(z)}}async acquire(z,V,Y){let Z=this.workflows.get(z);if(!Z)return{kind:"missing"};let $=Date.now();if(Z.lockedBy!==null&&!w(Z.lockedBy,V)&&(Z.lockedUntil??0)>$)return Z.retick=!0,{kind:"busy"};return Z.lockedBy=V,Z.lockedUntil=$+Y,Z.retick=!1,{kind:"acquired",workflow:{...Z},steps:this.stepsOf(z)}}async renew(z,V,Y){let Z=this.workflows.get(z);if(!Z||Z.lockedBy!==V)return!1;return Z.lockedUntil=Date.now()+Y,!0}async update(z,V,Y){let Z=this.workflows.get(z);if(!Z)return;if(V.owner!==void 0&&Z.lockedBy!==V.owner)throw new R(z);let $=this.steps.get(z),X=V.key===void 0?void 0:$.get(V.key),H=Date.now(),G=Y({workflow:{...Z},step:X?{...X}:null,steps:V.allSteps?this.stepsOf(z):[],now:H});if(G.step){let Q=$.get(G.step.key);$.set(G.step.key,{...G.step,createdAt:Q?.createdAt??H,updatedAt:H})}if(G.batch)this.queue.enqueueBatch(G.batch);for(let Q of G.cancelBatches??[])this.queue.cancelBatch(Q);if(G.workflow)Object.assign(Z,G.workflow);if(Z.updatedAt=H,G.tick)this.tick(z,G.tick.delayMs);if(G.unlock){if(Z.lockedBy=null,Z.lockedUntil=null,Z.retick)Z.retick=!1,this.tick(z,0)}return G.result}async prune(z){let V=Date.now()-z,Y=0;for(let[Z,$]of this.workflows)if(["completed","failed","cancelled"].includes($.status)&&$.updatedAt<=V)this.workflows.delete(Z),this.steps.delete(Z),Y++;return Y}stepsOf(z){return[...this.steps.get(z)?.values()??[]].map((V)=>({...V}))}tick(z,V){this.queue.enqueue({name:I,args:JSON.stringify([z]),delayMs:Math.max(0,Math.round(V))})}}var u0=86400000;class i{entries=new Map;batches=new Map;workflows;listeners=new Set;timer;timerAt=1/0;seq=0;get waiting(){let z=0;for(let V of this.entries.values())if(!V.leased)z++;return z}get leased(){return this.entries.size-this.waiting}async enqueue(z){let V=this.add(z);return this.changed(),V}add({name:z,args:V,delayMs:Y=0,id:Z=crypto.randomUUID()},$){let X=Date.now();return this.entries.set(Z,{job:{id:Z,name:z,args:V,attempt:0,createdAt:X,...$===void 0?{}:{batchId:$}},until:X+Math.max(0,Y),leased:!1,seq:this.seq++,progress:0}),Z}async enqueueBatch(z){this.recordBatch(z)}recordBatch(z){let V=Date.now();this.forgetFinishedBatches(V);let Y=d({...z,total:z.args.length,now:V});for(let X of z.args)this.add({name:z.job,args:X},z.id);let{record:Z,calls:$}=x(Y,Y,V);this.batches.set(z.id,Z);for(let X of $)this.add(X);this.changed()}async findBatch(z,V={}){let Y=this.batches.get(z);if(!Y)return null;if(V.progress===!1||Y.pending===0)return W(Y);let Z=0;for(let $ of this.entries.values())if($.job.batchId===z)Z+=$.progress;return W(Y,Z)}async cancelBatch(z){return this.cancelBatchNow(z)}cancelBatchNow(z){let V=this.batches.get(z);if(!V||V.finishedAt!==null||V.cancelledAt!==null)return!1;let Y=Date.now(),Z=M(V,Y,this.cancelWaiting(z));return this.save(V,Z,Y),this.changed(),!0}workflowStore(){return this.workflows??=new V0({enqueue:(z)=>{this.add(z),this.changed()},enqueueBatch:(z)=>this.recordBatch(z),cancelBatch:(z)=>void this.cancelBatchNow(z)}),this.workflows}async reportProgress(z,V){let Y=this.current(z);if(Y)Y.progress=E(V)}async claim(z,V){let Y=Date.now(),Z=[...this.entries.values()].filter(($)=>$.until<=Y).sort(($,X)=>$.until-X.until||$.seq-X.seq).slice(0,Math.max(0,z));for(let $ of Z)$.job={...$.job,attempt:$.job.attempt+1},$.leased=!0,$.until=Y+V.visibilityTimeoutMs;if(Z.length>0)this.schedule();return Z.map(($)=>({...$.job}))}async complete(z){let V=this.current(z);if(!V)return;this.entries.delete(z.id),this.count(V,"succeeded"),this.schedule()}async fail(z,V){let Y=this.current(z);if(!Y)return;let Z=Y.job.batchId===void 0?void 0:this.batches.get(Y.job.batchId),$=V.cancelled===!0||V.retryInMs!==null&&Z?.cancelledAt!=null;if(V.retryInMs===null||$){this.entries.delete(z.id),this.count(Y,$?"cancelled":"failed"),this.schedule();return}Y.leased=!1,Y.until=Date.now()+Math.max(0,V.retryInMs),Y.seq=this.seq++,Y.progress=0,this.changed()}async release(z,V){let Y=this.current(z);if(!Y)return;Y.job={...Y.job,attempt:Y.job.attempt-1},Y.leased=!1,Y.until=Date.now()+Math.max(0,V.retryInMs),Y.seq=this.seq++,this.changed()}async heartbeat(z,V){let Y=Date.now()+V.visibilityTimeoutMs;for(let Z of z){let $=this.current(Z);if($)$.until=Y}this.schedule()}count(z,V){let Y=z.job.batchId;if(Y===void 0)return;let Z=this.batches.get(Y);if(!Z)return;let $=Date.now(),X=c(Z,V,z.job.id);if(l(Z,X))X=M(X,$,this.cancelWaiting(Y));this.save(Z,X,$),this.changed()}save(z,V,Y){let{record:Z,calls:$}=x(z,V,Y);this.batches.set(Z.id,Z);for(let X of $)this.add(X)}cancelWaiting(z){let V=0;for(let[Y,Z]of this.entries)if(Z.job.batchId===z&&!Z.leased)this.entries.delete(Y),V++;return V}forgetFinishedBatches(z){for(let[V,Y]of this.batches)if(Y.finishedAt!==null&&z-Y.finishedAt>u0)this.batches.delete(V)}subscribe(z){return this.listeners.add(z),()=>void this.listeners.delete(z)}current(z){let V=this.entries.get(z.id);if(!V||!V.leased||V.job.attempt!==z.attempt)return;return V}changed(){this.schedule();let z=Date.now();for(let V of this.entries.values())if(V.until<=z){this.wake();return}}wake(){for(let z of[...this.listeners])z()}schedule(){let z=Date.now(),V=1/0;for(let Y of this.entries.values())if(Y.until>z&&Y.until<V)V=Y.until;if(V===this.timerAt)return;if(clearTimeout(this.timer),this.timer=void 0,this.timerAt=V,V===1/0)return;this.timer=setTimeout(()=>{this.timer=void 0,this.timerAt=1/0,this.changed()},V-z),this.timer.unref?.()}}function s(z,V){let Y=Array.isArray(z)?z[Math.min(V,z.length)-1]:z;return Math.max(0,Y??0)}var k0={ms:1,s:1000,m:60000,h:3600000,d:86400000,w:604800000};function n(z){if(typeof z==="number"){if(!Number.isFinite(z)||z<0)throw TypeError(`A duration is 0 or more milliseconds; got ${z}.`);return Math.round(z)}let V=/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w)\s*$/.exec(String(z));if(!V)throw TypeError(`"${String(z)}" is not a duration. Use milliseconds, or a number and one of ms, s, m, h, d, w ("30s", "7d").`);return Math.round(Number(V[1])*k0[V[2]])}class I0 extends Error{step;batch;constructor(z,V,Y){super(V);this.step=z;this.batch=Y;this.name="StepFailedError"}}class Y0 extends Error{step;constructor(z){super(`No signal "${z}" arrived before its timeout.`);this.step=z;this.name="WaitTimeoutError"}}class E0 extends Error{constructor(z,V){super(`Step "${z}" took longer than its timeout of ${V}ms.`);this.name="StepTimeoutError"}}class O0 extends Error{constructor(z){super(`Workflow ${z} was cancelled.`);this.name="WorkflowCancelledError"}}class g extends Error{constructor(){super("The workflow is suspended until a step can continue. Rethrow this error if you catch it.");this.name="WorkflowSuspended"}}var D0=Symbol("done");class Z0{tick;workflowId;steps;seen=new Set;pending=new Set;suspension;lost=!1;cancelled=!1;current=null;constructor(z){this.tick=z;this.workflowId=z.workflowId,this.steps=new Map(z.steps.map((V)=>[V.key,V]))}run(z,V,Y={}){return this.track(z,()=>this.runStep(z,V,Y))}sleep(z,V){let Y=n(V);return this.track(z,()=>this.sleepStep(z,Y))}waitFor(z,V={}){let Y=V.timeout===void 0?void 0:n(V.timeout);return this.track(z,()=>this.waitStep(z,Y))}batch(z,V,Y,Z={}){return this.track(z,()=>this.batchStep(z,V,Y,Z))}async progress(z){let V=E(z);this.assertRunning();let Y=this.write(void 0,()=>({result:void 0,workflow:{progress:V}}));this.remember(Y),await Y}async settled(){while(this.pending.size>0)await Promise.allSettled(this.pending)}track(z,V){if(typeof z!=="string"||z.length===0||z.length>191)throw TypeError(`A step key is a string of 1 to 191 characters; got ${JSON.stringify(z)}.`);if(this.seen.has(z))throw Error(`Two steps of workflow ${this.workflowId} use the key "${z}". Each step needs a key of its own, or the second would return the first one's result.`);this.seen.add(z),this.assertRunning();let Y=V();return this.remember(Y),Y}remember(z){this.pending.add(z);let V=()=>void this.pending.delete(z);z.then(V,V)}assertRunning(){if(this.lost)throw new R(this.workflowId);if(this.suspension)throw new g}suspend(z,V){if(!this.suspension)this.suspension={status:z,wakes:[]};if(V!=null)this.suspension.wakes.push(V);throw new g}async write(z,V){let Y;try{Y=await this.tick.store.update(this.tick.workflowId,{owner:this.tick.owner,...z===void 0?{}:{key:z}},(Z)=>{if(Z.workflow.status==="cancelling"&&!this.tick.cancelling)return{result:D0};let $=V(Z);return{...$,result:{value:$.result}}})}catch(Z){if(Z instanceof R)this.lost=!0;throw Z}if(Y===void 0)throw this.lost=!0,new R(this.tick.workflowId);if(Y===D0)this.cancelled=!0,this.suspend("waiting");return Y.value}record(z,V,Y){let Z={workflowId:this.tick.workflowId,key:z,status:"running",attempt:0,output:null,error:null,batchId:null,wakeAt:null,startedAt:null,finishedAt:null,createdAt:0,updatedAt:0,...V,...Y};return this.steps.set(z,Z),Z}mismatch(z,V,Y){throw Error(`Step "${z}" of workflow ${this.tick.workflowId} was recorded as a ${V} step, and is now used as ${Y}. A key belongs to one step; rename one of them.`)}async runStep(z,V,Y){let Z=Math.max(1,Math.floor(Y.attempts??3)),$=Y.timeout===void 0?void 0:n(Y.timeout),X=this.steps.get(z);if(X?.status==="completed")return _(X.output);if(X?.status==="failed")throw j(z,X);if(X?.status==="retrying"&&X.wakeAt!==null&&X.wakeAt>Date.now())this.current=z,this.suspend("sleeping",X.wakeAt);for(;;){let H=await this.write(z,({workflow:J,step:P,now:N})=>{if(P?.status==="completed")return{result:{kind:"done",output:P.output}};if(P?.status==="failed")return{result:{kind:"failed",step:P}};if(P&&P.status!=="running"&&P.status!=="retrying")this.mismatch(z,P.status,"step.run");if(P?.status==="retrying"&&P.wakeAt!==null&&P.wakeAt>N)return{result:{kind:"wait",wakeAt:P.wakeAt}};let D=(P?.attempt??0)+1;if(D>Z){let G0=this.record(z,P,{status:"failed",error:`Attempt ${D-1} of ${Z} never finished, most likely because the process running it exited.`+(P?.error?` The last error was: ${P.error}`:""),finishedAt:N,wakeAt:null});return{result:{kind:"failed",step:G0},step:G0}}let u=this.record(z,P,{status:"running",attempt:D,startedAt:N,finishedAt:null,wakeAt:null});return{result:{kind:"run",attempt:D},step:u,workflow:J.status==="cancelling"?{currentStep:z}:{currentStep:z,status:"running"}}});if(this.current=z,H.kind==="done")return _(H.output);if(H.kind==="failed")throw j(z,H.step);if(H.kind==="wait")this.suspend("sleeping",H.wakeAt);let G=H.attempt,Q,B,K=!0;try{Q=await this.execute(z,V,G,$)}catch(J){B=J}if(this.cancelled)throw new g;let A=null;if(B===void 0)try{A=m(Q,`The result of step "${z}"`)}catch(J){B=J,K=!1}if(B===void 0)return await this.write(z,({step:J,now:P})=>({result:void 0,step:this.record(z,J,{status:"completed",output:A,error:null,wakeAt:null,finishedAt:P})})),_(A);let F=a(B);if(K&&G<Z){let J=s(Y.backoff??0,G),P=await this.write(z,({step:N,now:D})=>{let u=J>0?D+J:null;return{result:u,step:this.record(z,N,{status:"retrying",error:F,wakeAt:u})}});if(P!==null)this.suspend("sleeping",P);continue}let U=await this.write(z,({step:J,now:P})=>{let N=this.record(z,J,{status:"failed",error:F,wakeAt:null,finishedAt:P});return{result:N,step:N}});throw j(z,U)}}async execute(z,V,Y,Z){let $=new AbortController,X={idempotencyKey:`${this.tick.workflowId}:${z}`,attempt:Y,signal:$.signal},H=Promise.resolve().then(()=>V(X)),G,Q,B=new Promise((K,A)=>{let F=(U)=>{$.abort(U),A(U)};if(Z!==void 0)G=setTimeout(()=>F(new E0(z,Z)),Z);if(!this.tick.cancelling)Q=setInterval(()=>{this.tick.store.find(this.tick.workflowId,{steps:!1}).then((U)=>{if(U?.workflow.status!=="cancelling"||$.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};F(new O0(this.tick.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs),Q.unref?.()});try{return await Promise.race([H,B])}finally{clearTimeout(G),clearInterval(Q),H.catch(()=>{}),B.catch(()=>{})}}async sleepStep(z,V){let Y=this.steps.get(z);if(Y?.status==="completed")return;if(this.current=z,Y?.status==="sleeping"&&Y.wakeAt!==null&&Y.wakeAt>Date.now())this.suspend("sleeping",Y.wakeAt);let Z=await this.write(z,({step:$,now:X})=>{if($?.status==="completed")return{result:null};if($&&$.status!=="sleeping")this.mismatch(z,$.status,"step.sleep");let H=$?.wakeAt??X+V;if(H<=X)return{result:null,step:this.record(z,$,{status:"completed",wakeAt:H,startedAt:$?.startedAt??X,finishedAt:X})};if($)return{result:H};return{result:H,step:this.record(z,null,{status:"sleeping",wakeAt:H,startedAt:X}),workflow:{currentStep:z}}});if(Z!==null)this.suspend("sleeping",Z)}async waitStep(z,V){let Y=this.steps.get(z);if(Y?.status==="completed")return _(Y.output);if(Y?.status==="timed_out")throw new Y0(z);if(this.current=z,Y?.status==="waiting"&&(Y.wakeAt===null||Y.wakeAt>Date.now()))this.suspend("waiting",Y.wakeAt);let Z=await this.write(z,({step:$,now:X})=>{if($?.status==="completed")return{result:{kind:"value",output:$.output}};if($?.status==="timed_out")return{result:{kind:"timeout"}};if($?.status==="signalled")return{result:{kind:"value",output:$.output},step:this.record(z,$,{status:"completed",wakeAt:null,startedAt:$.startedAt??X,finishedAt:X})};if($&&$.status!=="waiting")this.mismatch(z,$.status,"step.waitFor");if($){if($.wakeAt!==null&&$.wakeAt<=X)return{result:{kind:"timeout"},step:this.record(z,$,{status:"timed_out",finishedAt:X})};return{result:{kind:"wait",wakeAt:$.wakeAt}}}let H=V===void 0?null:X+V;return{result:{kind:"wait",wakeAt:H},step:this.record(z,null,{status:"waiting",wakeAt:H,startedAt:X}),workflow:{currentStep:z}}});if(Z.kind==="value")return _(Z.output);if(Z.kind==="timeout")throw new Y0(z);this.suspend("waiting",Z.wakeAt)}async batchStep(z,V,Y,Z){let $=Z.allowFailures===!0,X=this.steps.get(z);if(X?.status==="completed")return _(X.output);if(X?.status==="failed")throw j(z,X);if(X&&X.status!=="batching")this.mismatch(z,X.status,"step.batch");if(this.current=z,!X){let A=this.tick.buildBatch(V,Y,{name:Z.name??`workflow:${this.tick.workflowId}:${z}`,allowFailures:$});if(X=await this.write(z,({step:F,now:U})=>{if(F)return{result:F};let J=this.record(z,null,{status:"batching",batchId:A.id,startedAt:U});return{result:J,step:J,batch:A,workflow:{currentStep:z}}}),this.tick.scheduled(),X.status==="completed")return _(X.output);if(X.status==="failed")throw j(z,X)}let H=X.batchId===null?null:await this.tick.findBatch(X.batchId);if(H&&H.finishedAt===null)this.suspend("waiting");let G=H!==null&&H.cancelledAt===null&&(H.failed===0||$),Q=H===null?null:JSON.stringify(H),B=G?null:H===null?`The batch of step "${z}" (${X.batchId}) no longer exists.`:`The batch of step "${z}" failed: ${H.failed} failed and ${H.cancelled} cancelled of ${H.total}.`,K=await this.write(z,({step:A,now:F})=>{let U=this.record(z,A,{status:G?"completed":"failed",output:Q,error:B,finishedAt:F});return{result:U,step:U}});if(!G)throw j(z,K);return H}}function j(z,V){let Y=V.batchId!==null&&V.output!==null?JSON.parse(V.output):void 0;return new I0(z,Y?V.error??`Step "${z}" failed.`:`Step "${z}" failed: ${V.error??"unknown error"}`,Y)}function m(z,V){if(z===void 0)return null;let Y=JSON.stringify(z);if(Y===void 0)throw TypeError(`${V} cannot be stored: JSON has no form for it.`);let Z=Buffer.byteLength(Y,"utf8");if(Z>t)throw RangeError(`${V} is ${Z} bytes as JSON, over the ${t}-byte limit. Store it elsewhere and return its id.`);return Y}function _(z){return z===null?void 0:JSON.parse(z)}function a(z){return z instanceof Error?z.message:String(z)}var r=["completed","failed","cancelled"],p0=1000;class $0{queue;registry={};storeInstance;tickClass;reportedNames=new Set;constructor(z){this.queue=z}get workflows(){return this.registry}use(z){this.registry={};for(let V of z){if(V.name==="unset"||!V.name){console.error("A workflow class has no `static name`, so it was not registered. Add one.");continue}if(this.registry[V.name]){console.error(`Two workflows are named "${V.name}" \u2014 the first is registered `+"and this one is not. A workflow's name is its key in storage. Rename one.");continue}this.registry[V.name]=V}}get tickJob(){return this.tickClass??=w0(this),this.tickClass}get store(){if(!this.storeInstance){let z=this.queue.driver.workflowStore?.();if(!z||!this.queue.driver.enqueueBatch)throw Error("This queue's driver does not support workflows. The memory and database drivers do.");this.storeInstance=z}return this.storeInstance}start(z,V){if(z.name==="unset"||!z.name)throw Error("Cannot start a workflow with no name");let Y=this.store,Z={id:Bun.randomUUIDv7(),name:z.name,args:m(V,`The arguments of ${z.name}`)??"[]"},$=()=>this.queue.claimSoon(),X=Y.joinsTransaction?.()===!0;if(!X){if(C(()=>Y.create(Z).then($,(B)=>{console.error(`[gemi] The queue could not record the workflow ${z.name}, which was held until its transaction committed. The transaction stays committed; the workflow did not start.`,B)})))return Promise.resolve(Z.id)}let H=Y.create(Z),G=X&&C($);return H.then(()=>{if(!G)$();return Z.id})}async signal(z,V,Y){if(typeof V!=="string"||V.length===0||V.length>191)throw TypeError("A signal key is a string of 1 to 191 characters.");let Z=m(Y,`The payload of signal "${V}"`),$=await this.store.update(z,{key:V},({workflow:X,step:H,now:G})=>{if(r.includes(X.status)||X.status==="cancelling")return{result:!1};if(!H)return{result:!0,step:{workflowId:z,key:V,status:"signalled",attempt:0,output:Z,error:null,batchId:null,wakeAt:null,startedAt:null,finishedAt:G,createdAt:G,updatedAt:G}};if(H.status!=="waiting")return{result:!1};return{result:!0,step:{...H,status:"signalled",output:Z,wakeAt:H.wakeAt,finishedAt:G},tick:{delayMs:0}}});if($)this.queue.claimSoon();return $===!0}async cancel(z){let V=await this.store.update(z,{allSteps:!0},({workflow:Y,steps:Z})=>{if(r.includes(Y.status)||Y.status==="cancelling")return{result:!1};return{result:!0,workflow:{status:"cancelling"},cancelBatches:Z.filter(($)=>$.status==="batching"&&$.batchId!==null).map(($)=>$.batchId),tick:{delayMs:0}}});if(V)this.queue.claimSoon();return V===!0}async find(z){let V=await this.store.find(z);if(!V)return null;let{workflow:Y,steps:Z}=V,$=[];try{$=JSON.parse(Y.args)}catch{}return{id:Y.id,name:Y.name,status:Y.status,args:$,currentStep:Y.currentStep,progress:Y.progress,result:d0(Y.result),error:Y.error,steps:await Promise.all(Z.map(async(X)=>{let H={key:X.key,status:X.status,attempt:X.attempt,error:X.error,batchId:X.batchId,wakeAt:X.wakeAt,startedAt:X.startedAt,finishedAt:X.finishedAt};if(X.batchId===null)return H;let G=await this.queue.driver.findBatch?.(X.batchId);return G?{...H,progress:G.progress}:H})),createdAt:Y.createdAt,updatedAt:Y.updatedAt}}async tick(z,V){let Y=this.store,Z=V.$claimed,$=Z?`${Z.id}:${Z.attempt}`:`${crypto.randomUUID()}:1`,X=Math.max(1,this.queue.config.visibilityTimeout),H=await Y.acquire(z,$,X);if(H.kind!=="acquired")return;let{workflow:G}=H,Q=(J={})=>Y.update(z,{owner:$},()=>({...J,result:void 0,unlock:!0})).then(()=>this.queue.claimSoon()).catch((P)=>{if(!(P instanceof R))throw P});if(r.includes(G.status))return Q();let B=this.registry[G.name];if(!B)return this.unknown(G,V,Q);let K;try{K=JSON.parse(G.args)}catch(J){return Q({workflow:{status:"failed",error:`The arguments are not JSON: ${a(J)}`}})}let A=setInterval(()=>{Y.renew(z,$,X).catch((J)=>{console.error(`[gemi] Could not extend the hold on workflow ${z}.`,J)})},Math.max(1,Math.floor(X/3)));A.unref?.();let F=G.status==="cancelling",U=new Z0({workflowId:z,owner:$,store:Y,steps:H.steps,cancelling:F,findBatch:(J)=>this.queue.driver.findBatch?.(J,{progress:!1})??Promise.resolve(null),buildBatch:(J,P,N)=>this.queue.buildBatch(J,P.map((D)=>JSON.stringify(D)),{name:N.name,allowFailures:N.allowFailures,finally:{name:I,args:[z]}}),scheduled:()=>this.queue.claimSoon(),cancelCheckMs:p0});try{let J;try{let P=new B,N=await(F?P.onCancel(U,...K):P.run(U,...K));J=U.suspension?{kind:"suspended"}:{kind:"completed",result:F?null:m(N,`The result of ${G.name}`)}}catch(P){if(J=U.suspension||P instanceof g?{kind:"suspended"}:{kind:"failed",error:a(P)},P instanceof R)U.lost=!0}if(await U.settled(),U.lost)return;if(J.kind==="completed"&&U.suspension)J={kind:"suspended"};await Y.update(z,{owner:$},({workflow:P,now:N})=>this.finish(P,J,U,F,N)),this.queue.claimSoon()}catch(J){if(J instanceof R)return;throw J}finally{clearInterval(A)}}finish(z,V,Y,Z,$){let X={result:void 0,unlock:!0};if(z.status==="cancelling"&&!Z)return{...X,tick:{delayMs:0}};if(V.kind==="completed")return{...X,workflow:Z?{status:"cancelled",currentStep:null,wakeAt:null}:{status:"completed",result:V.result,progress:1,currentStep:null,wakeAt:null,error:null}};if(V.kind==="failed")return{...X,workflow:{status:Z?"cancelled":"failed",error:V.error,wakeAt:null}};let H=Y.suspension??{status:"waiting",wakes:[]},G={...X,workflow:{status:Z?"cancelling":H.status,currentStep:Y.current??z.currentStep}};if(H.wakes.length>0){let Q=Math.min(...H.wakes);if(!(z.wakeAt!==null&&z.wakeAt>$&&z.wakeAt<=Q))G.tick={delayMs:Math.max(0,Q-$)},G.workflow.wakeAt=Q}return G}async unknown(z,V,Y){let Z=Date.now()-z.createdAt;if(this.queue.durable&&Z<this.queue.config.unknownJobGrace){if(!this.reportedNames.has(z.name))this.reportedNames.add(z.name),console.error(`Left workflow "${z.name}" for another replica: nothing is registered here under that name.`);await Y(),V.release(Math.round(this.queue.config.pollInterval*(1+Math.random())));return}console.error(`Failed workflow ${z.id}: nothing is registered under the name "${z.name}". If the class exists, it was not discovered: check that it is under the queue slice's workflowsDir (app/workflows by default), or list it in app/config/queue.ts.`),await Y({workflow:{status:"failed",error:`No workflow is registered under the name "${z.name}".`}})}tickDeadLettered(z,V){console.error(`[gemi] The tick of workflow ${z} was dead-lettered.`,V),this.store.update(z,{},({workflow:Y})=>r.includes(Y.status)?{result:void 0}:{result:void 0,workflow:{status:"failed",error:`Its tick job was dead-lettered: ${V.message}`},unlock:!0}).catch(()=>{})}}function w0(z){return class extends S{static name=I;maxAttempts=20;backoff=[1000,5000,15000,30000,60000];async run(Y){await z.tick(Y,this)}onDeadletter(Y,Z){z.tickDeadLettered(Z,Y)}}}function d0(z){try{return _(z)}catch{return z}}function i0(){let z=process.env.APP_DIR,V=process.env.ROOT_DIR,Y=Bun.env.NODE_ENV==="production"?`${V}/dist/server/bootstrap.mjs`:`${z}/bootstrap.ts`,Z=new File([`
396
+ import { app } from "${Y}"
397
+ self.onmessage = async (event) => {
398
+ const clone = app.clone()
399
+ let result = null;
400
+ let error = null;
401
+ try {
402
+ result = await clone.dispatchJob(event.data.jobName, event.data.args)
403
+ } catch (err) {
404
+ error = err
405
+ }
406
+ clone.destroy()
407
+ if(error) {
408
+ self.postMessage({error});
409
+ } else {
410
+ self.postMessage({result});
411
+ }
412
+ };
413
+ `],"worker.ts"),$=URL.createObjectURL(Z);return new Worker($)}async function s0(z,V){let Y=i0();return Y.postMessage({jobName:z,args:V}),await new Promise((Z,$)=>{Y.onmessage=(X)=>{let H=X.data;if("error"in H)$(H.error);else Z(H.result)}})}var n0=new c0("gemi.queue"),a0=60000;class h{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;lockManager;workflowRuntime;constructor(z={},V={}){if(this.config=S0(C0(),z),this.application=V.application,this.driver=zz(this.config.driver,this.application),this.useJobs(this.config.jobs),this.config.workflows.length>0)this.useWorkflows(this.config.workflows)}useJobs(z){this.config.jobs=z,this.jobs={};for(let V of z)this.claim(V);this.registerTickJob()}useWorkflows(z){this.config.workflows=z,this.workflows.use(z),this.registerTickJob()}get registeredWorkflows(){return[...this.config.workflows]}get workflows(){return this.workflowRuntime??=new $0(this),this.workflowRuntime}registerTickJob(){if(!this.workflowRuntime||Object.keys(this.workflowRuntime.workflows).length===0)return;let z=this.workflowRuntime.tickJob;if(this.jobs[z.name]&&this.jobs[z.name]!==z){console.error(`A queued job is named "${z.name}", which the workflow runtime uses. Workflows will not run until it is renamed.`);return}this.jobs[z.name]=z}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,V){if(this.jobs[z])return new this.jobs[z]().run(JSON.parse(V))}push(z,V,Y={}){let Z=this.uniqueKey(z,V);if(Z)return this.pushUnique(z,V,Z,Y);let $=this.driver.joinsTransaction?.()===!0;if(!$){let X=Bun.randomUUIDv7();if(C(()=>this.record(z,V,{id:X,reportFailure:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X)}return this.record(z,V,{reportFailure:Y.reportFailure,joins:$})}pushBatch(z,V,Y={}){let Z=this.buildBatch(z,V,Y),$={id:Z.id,total:V.length},X=this.driver.joinsTransaction?.()===!0;if(!X){if(C(()=>this.recordBatch(Z,{committed:!0}).then(()=>{},()=>{})))return Promise.resolve($)}return this.recordBatch(Z,{joins:X}).then(()=>$)}buildBatch(z,V,Y={}){if(!this.driver.enqueueBatch)throw Error("This queue's driver does not support batches. The memory and database drivers do.");if(new z().worker)throw Error(`${z.name} is a worker job, and a worker job cannot be dispatched in a batch: its thread has no way to report progress or reach the batch.`);if(z.prototype.uniqueId!==S.prototype.uniqueId)throw Error(`${z.name} is unique (it defines uniqueId), and a unique job cannot be dispatched in a batch: a duplicate would resolve to a job outside the batch, and the batch would wait for it forever.`);let $={};for(let X of["then","catch","finally"]){let H=Y[X];if(H===void 0)continue;if(typeof H?.name!=="string"||!Array.isArray(H.args))throw Error(`The batch's ${X} callback is not a job call. Build it with SomeJob.with(...args).`);$[X]={name:H.name,args:H.args}}return{id:Bun.randomUUIDv7(),name:Y.name??null,job:z.name,args:V,allowFailures:Y.allowFailures===!0,callbacks:$}}recordBatch(z,V){let Y=this.driver.enqueueBatch(z);this.startIfIdle();let Z=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),$=V.joins===!0&&C(Z);return Y.then(()=>$||Z(),(X)=>{if(!V.committed)return;console.error(`[gemi] The queue driver could not record a batch of ${z.job}, which was held until its transaction committed. The transaction stays committed; the batch's jobs did not run and will not be retried.`,X)}),Y}async findBatch(z){if(!this.driver.findBatch)throw Error("This queue's driver does not support batches.");return this.driver.findBatch(z)}async cancelBatch(z){if(!this.driver.cancelBatch)throw Error("This queue's driver does not support batches.");let V=await this.driver.cancelBatch(z);if(V)this.claimSoon();return V}get locks(){return this.lockManager??=new T0(this.resolveLockStore()),this.lockManager}resolveLockStore(){let z=this.config.locks;if(z==="auto"){let V=this.driver.lockStore?.();if(V)return V;if(this.durable)console.warn('[gemi] The queue driver keeps no locks, so unique jobs, withoutOverlapping and onOneServer only hold within this process. Set the queue slice\'s `locks` to "database" or a LockStore.');return new p}if(z==="memory")return new p;if(z==="database"||typeof z==="function"){if(!this.application&&(z==="database"||z.length>0))throw Error("The queue's locks need the application they belong to, and this QueueManager was built without one. Pass { application }.");if(z==="database")return new y(this.application.make(H0));return z(this.application)}if(typeof z==="string")throw Error(`Unknown queue locks "${z}". The queue slice's locks is "auto", "memory", "database", a LockStore, or a function returning one.`);return z}uniqueKey(z,V){if(z.prototype.uniqueId===S.prototype.uniqueId)return;let Y=new z,Z=Y.uniqueId(...JSON.parse(V));if(Z===void 0||Z===null||Z==="")return;return{key:L0(z.name,Z),ttl:Math.max(1,Y.uniqueFor)}}pushUnique(z,V,Y,Z){let $=Bun.randomUUIDv7();if(C(()=>this.recordUnique(z,V,Y,$,{report:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve($);return this.recordUnique(z,V,Y,$,{report:Z.reportFailure!==!1,committed:!1})}recordUnique(z,V,Y,Z,$){let X=this.locks.store,H=(async()=>{for(let G=0;G<5;G++){if(await X.acquire(Y.key,Z,Y.ttl)!==null)try{return await this.record(z,V,{id:Z,reportFailure:!1})}catch(B){throw await X.release(Y.key,Z).catch(()=>{}),B}let Q=await X.holder(Y.key);if(Q)return Q.owner}throw Error(`The unique key "${Y.key}" kept changing hands, so ${z.name} was not queued.`)})();return H.catch((G)=>{if(!$.report)return;console.error(`[gemi] The queue could not record the unique job ${z.name}`+($.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."),G)}),H}async releaseUnique(z,V,Y){if(z.uniqueId===S.prototype.uniqueId)return;try{let Z=z.uniqueId(...V);if(Z===void 0||Z===null||Z==="")return;await this.locks.store.release(L0(Y.name,Z),Y.id)}catch(Z){console.error(`[gemi] Could not free the unique key of ${Y.name} (${Y.id}); it frees itself after uniqueFor.`,Z)}}record(z,V,Y){let Z=this.driver.enqueue({name:z.name,args:V,...Y.id===void 0?{}:{id:Y.id}});this.startIfIdle();let $=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),X=Y.joins===!0&&C($);return Z.then(()=>X||$(),(H)=>{if(Y.reportFailure===!1)return;console.error(`[gemi] The queue driver could not record ${z.name}`+(Y.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."),H)}),Z}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 V=await this.driver.retryDead(z);if(V)this.claimSoon();return V}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()&&!r0())globalThis.__gemiDevQueue=this;if(this.unsubscribe=this.driver.subscribe?.(()=>this.wake()),this.looping)return this.wake();n0.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 V,Y=new Promise(($)=>{if(z!==1/0)V=setTimeout($,z)}),Z=(async()=>{await this.claiming?.catch(()=>{}),await Promise.allSettled([...this.inFlight.values()].map(($)=>$.done))})();return await Promise.race([Z,Y]),clearTimeout(V),{unfinished:[...this.inFlight.values()].map(($)=>({...$.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&&M0()?0:this.config.concurrency-this.inFlight.size;if(z>0){this.woken=!1;let V=this.driver.claim(z,{...this.lease(),registered:{names:Object.keys(this.jobs),graceMs:this.config.unknownJobGrace}});this.claiming=V;let Y=[];try{Y=await V,this.claimFailures=0}catch(Z){this.claimFailures++,console.error(`The queue could not claim jobs from its driver; it will try again in ${this.retryDelay()}ms.`,Z)}finally{this.claiming=void 0}for(let Z of Y)this.execute(Z);if(Y.length===z)continue;if(this.woken&&this.inFlight.size<this.config.concurrency)continue}await this.sleep()}}sleep(){return new Promise((z)=>{let V,Y=this.claimFailures>0?this.retryDelay():this.driver.subscribe?void 0:this.config.pollInterval;if(Y!==void 0)V=setTimeout(()=>this.wake(),Y),V.unref?.();this.resume=()=>{clearTimeout(V),z()}})}retryDelay(){let z=Math.min(Math.max(0,this.claimFailures-1),30);return Math.min(this.config.pollInterval*2**z,a0)}wake(){this.woken=!0;let z=this.resume;this.resume=void 0,z?.()}get durable(){return!(this.driver instanceof i)}mayClaimHere(){return!this.application||t0()}lease(){return{visibilityTimeoutMs:this.config.visibilityTimeout}}execute(z){let V=`${z.id}:${z.attempt}`,Y=()=>this.run(z),Z=(this.application?W0.run(this.application,Y):Y()).catch(($)=>{console.error(`The queue could not record the outcome of ${z.name}.`,$)}).finally(()=>{this.inFlight.delete(V),this.wake()});this.inFlight.set(V,{job:z,done:Z}),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 V=[...this.inFlight.values()].map((Y)=>Y.job);z.heartbeat(V,this.lease()).catch((Y)=>{console.error("The queue could not extend its job leases.",Y)})},Math.max(1,Math.floor(this.config.visibilityTimeout/3))),this.heartbeatTimer.unref?.()}async run(z){let V=this.jobs[z.name];if(!V){let B=Date.now()-z.createdAt;if(this.durable&&B<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 Y;try{Y=new V}catch(B){console.error(`Dropped a queued ${z.name}: it could not be constructed.`,B),await this.driver.fail(z,{error:`The job could not be constructed: ${String(B)}`,retryInMs:null});return}let Z;try{Z=JSON.parse(z.args)}catch(B){console.error(`Dropped a queued ${z.name}: its arguments are not JSON.`,B),await this.driver.fail(z,{error:`The arguments are not JSON: ${String(B)}`,retryInMs:null});return}if(z.attempt>Math.max(1,Y.maxAttempts)){let B=Error(`${z.name} was claimed for attempt ${z.attempt} of ${Y.maxAttempts}: an earlier attempt never finished, most likely because the process running it exited. Dead-lettered without running it again.`);X0(`${z.name}.onDeadletter`,()=>Y.onDeadletter(B,...Z)),await this.driver.fail(z,{error:B.message,retryInMs:null}),await this.releaseUnique(Y,Z,z);return}if(Y.$claimed={...z},z.batchId!==void 0){if((await this.driver.findBatch?.(z.batchId,{progress:!1}))?.cancelledAt!=null){await this.driver.fail(z,{error:"Its batch was cancelled before it ran.",retryInMs:null,cancelled:!0});return}let K=this.batchHandle(z);Y.batch=K.batch,Y.$progress=K.progress}let $=await this.admit(Y,Z,z);if(!$)return;let X,H;try{H=await(Y.worker?s0(z.name,z.args):Y.run(...Z))}catch(B){X=B}finally{await $.done()}let G=Y.$outcome;if(X===void 0&&G?.kind==="release"){await this.driver.release(z,{retryInMs:Math.max(0,G.delayMs)});return}if(X===void 0&&G?.kind==="fail")X=G.error;let Q=G?.kind==="fail"?G.retry:!0;if(X===void 0)try{Y.onSuccess(H,...Z)}catch(B){X=B}if(X!==void 0){let B=String(X?.stack??X);if(X0(`${z.name}.onFail`,()=>Y.onFail(X,...Z)),!Q||z.attempt>=Y.maxAttempts)X0(`${z.name}.onDeadletter`,()=>Y.onDeadletter(X,...Z)),await this.driver.fail(z,{error:B,retryInMs:null}),await this.releaseUnique(Y,Z,z);else await this.driver.fail(z,{error:B,retryInMs:s(Y.backoff,z.attempt)});return}await this.driver.complete(z),await this.releaseUnique(Y,Z,z)}batchHandle(z){let V=z.batchId,Y=this.driver;return{batch:{id:V,cancelled:async()=>(await Y.findBatch?.(V,{progress:!1}))?.cancelledAt!=null},progress:(Z)=>Y.reportProgress?.(z,Z)??Promise.resolve()}}async admit(z,V,Y){let Z=z.concurrency(...V),$=[z.throttle(...V)??[]].flat();if(!Z&&$.length===0)return{done:async()=>{}};let X=this.locks,H;if(Z&&Z.limit>0){let Q=this.config.visibilityTimeout;for(let B=0;B<Z.limit&&!H;B++)H=await X.acquire(`gemi:concurrency:${Z.key}:${B}`,{ttl:Q,renew:!0})??void 0;if(!H){await this.driver.release(Y,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}}let G=[];for(let Q of $){let B=`gemi:throttle:${Q.key}`,K=await X.store.hit(B,Q.limit,Q.window);if(!K.allowed){await Promise.all(G.map((A)=>X.store.refund(A))),await H?.release(),await this.driver.release(Y,{retryInMs:Math.max(1,K.resetInMs)});return}G.push(B)}return{done:async()=>{await H?.release().catch((Q)=>{console.error(`[gemi] Could not free a concurrency slot of ${Y.name}.`,Q)})}}}}function L0(z,V){return`gemi:job:${z}:${String(V)}`}function X0(z,V){try{V()}catch(Y){console.error(`${z} threw; the job's claim was ended anyway.`,Y)}}function r0(){return Bun.env.NODE_ENV==="production"}function t0(){if(!l0)return!1;if(e0())return!0;return process.env.ROOT_DIR!==void 0&&!o0()}function o0(z=process.env){return(z.GEMI_QUEUE_CLAIM??"").trim().toLowerCase()==="off"}var x0=Symbol.for("gemi.queue.worker");function tz(z=!0){globalThis[x0]=z}function e0(){return globalThis[x0]===!0}function zz(z,V){if(z==="memory")return new i;if(z==="database"||typeof z==="function"){if(!V&&(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 z0(V.make(H0));return z(V)}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}class S{static name="unset";worker=!1;maxAttempts=3;backoff=0;uniqueId(...z){return}uniqueFor=3600000;throttle(...z){return}concurrency(...z){return}release(z=0){this.$outcome={kind:"release",delayMs:z}}fail(z,V={}){this.$outcome={kind:"fail",error:z instanceof Error?z:Error(String(z)),retry:V.retry??!0}}batch=void 0;async progress(z){let V=E(z);await this.$progress?.(V)}$progress;$claimed;$outcome;run(...z){}onFail(z,...V){}onSuccess(z,...V){}onDeadletter(z,...V){}static dispatch(...z){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return b(h).push(this,JSON.stringify(z))}static dispatchBatch(z,V={}){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return b(h).pushBatch(this,z.map((Y)=>JSON.stringify(Y)),V)}static with(...z){if(this.name==="unset")throw Error("Cannot use a job with no name as a callback");return JSON.stringify(z),{name:this.name,args:z}}static findBatch(z){return b(h).findBatch(z)}static cancelBatch(z){return b(h).cancelBatch(z)}}
414
+ export{p as Bc,y as Cc,o as Dc,F0 as Ec,z0 as Fc,S as Gc,Nz as Hc,C0 as Ic,V0 as Jc,i as Kc,I0 as Lc,Y0 as Mc,E0 as Nc,O0 as Oc,Z0 as Pc,$0 as Qc,h as Rc,t0 as Sc,o0 as Tc,tz as Uc,e0 as Vc};
415
+
416
+ //# debugId=C7F8EB97FE1A446664756E2164756E21