gemi 0.237.3 → 0.239.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 (206) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +2 -2
  3. package/dist/ai/testing/index.js +3 -3
  4. package/dist/ai/testing/index.js.map +3 -3
  5. package/dist/ai/testing/scriptedProvider.d.ts +10 -4
  6. package/dist/ai/testing/scriptedProvider.d.ts.map +1 -1
  7. package/dist/app/index.js +1 -1
  8. package/dist/bun/plugin.js +1 -1
  9. package/dist/bun/preload.js +1 -1
  10. package/dist/{chunk-psdcmh65.js → chunk-0wa8ztk5.js} +8 -8
  11. package/dist/{chunk-psdcmh65.js.map → chunk-0wa8ztk5.js.map} +3 -3
  12. package/dist/{chunk-34a5b9xt.js → chunk-13eq76tw.js} +2 -2
  13. package/dist/{chunk-34a5b9xt.js.map → chunk-13eq76tw.js.map} +1 -1
  14. package/dist/{chunk-hk37x8mp.js → chunk-1kjyhseb.js} +1 -1
  15. package/dist/{chunk-s3fpkpdh.js → chunk-1wfwqgm5.js} +2 -2
  16. package/dist/{chunk-s3fpkpdh.js.map → chunk-1wfwqgm5.js.map} +1 -1
  17. package/dist/{chunk-8kp4rkd3.js → chunk-342ydn4n.js} +2 -2
  18. package/dist/{chunk-8kp4rkd3.js.map → chunk-342ydn4n.js.map} +1 -1
  19. package/dist/{chunk-ajyfp09w.js → chunk-387fpg2k.js} +2 -2
  20. package/dist/{chunk-ajyfp09w.js.map → chunk-387fpg2k.js.map} +1 -1
  21. package/dist/{chunk-xe76d4v6.js → chunk-3ady4k66.js} +2 -2
  22. package/dist/{chunk-4rs6w1gp.js.map → chunk-3ady4k66.js.map} +1 -1
  23. package/dist/{chunk-97t5t8jp.js → chunk-3crknzwp.js} +3 -3
  24. package/dist/{chunk-97t5t8jp.js.map → chunk-3crknzwp.js.map} +1 -1
  25. package/dist/{chunk-gbgwtaqq.js → chunk-3kgp6xka.js} +1 -1
  26. package/dist/{chunk-wj0q7tyn.js → chunk-3mq0wmq7.js} +3 -3
  27. package/dist/{chunk-wj0q7tyn.js.map → chunk-3mq0wmq7.js.map} +1 -1
  28. package/dist/{chunk-mhvg8nnb.js → chunk-3qmhe96e.js} +2 -2
  29. package/dist/{chunk-mhvg8nnb.js.map → chunk-3qmhe96e.js.map} +1 -1
  30. package/dist/{chunk-xm0fb17q.js → chunk-3rm4v7ht.js} +3 -3
  31. package/dist/{chunk-xm0fb17q.js.map → chunk-3rm4v7ht.js.map} +1 -1
  32. package/dist/{chunk-358krc4n.js → chunk-4mysb5ej.js} +2 -2
  33. package/dist/{chunk-358krc4n.js.map → chunk-4mysb5ej.js.map} +1 -1
  34. package/dist/{chunk-8adbpxpm.js → chunk-4sv5vkab.js} +2 -2
  35. package/dist/{chunk-8adbpxpm.js.map → chunk-4sv5vkab.js.map} +1 -1
  36. package/dist/{chunk-prvncxxf.js → chunk-4wj4bwvc.js} +3 -3
  37. package/dist/{chunk-prvncxxf.js.map → chunk-4wj4bwvc.js.map} +1 -1
  38. package/dist/{chunk-5na9khtz.js → chunk-51mz612v.js} +2 -2
  39. package/dist/{chunk-5na9khtz.js.map → chunk-51mz612v.js.map} +1 -1
  40. package/dist/{chunk-wt80ekv9.js → chunk-6gek696n.js} +92 -92
  41. package/dist/{chunk-wt80ekv9.js.map → chunk-6gek696n.js.map} +4 -4
  42. package/dist/{chunk-h1a4febx.js → chunk-7axcthef.js} +2 -2
  43. package/dist/{chunk-h1a4febx.js.map → chunk-7axcthef.js.map} +1 -1
  44. package/dist/{chunk-dh1wbntq.js → chunk-7fh7cfjh.js} +2 -2
  45. package/dist/{chunk-dh1wbntq.js.map → chunk-7fh7cfjh.js.map} +1 -1
  46. package/dist/{chunk-ea5fv4h9.js → chunk-7sxbq483.js} +2 -2
  47. package/dist/{chunk-ea5fv4h9.js.map → chunk-7sxbq483.js.map} +1 -1
  48. package/dist/{chunk-4wdc4q33.js → chunk-7ycjs0xn.js} +2 -2
  49. package/dist/{chunk-4wdc4q33.js.map → chunk-7ycjs0xn.js.map} +1 -1
  50. package/dist/{chunk-ygfwbh8p.js → chunk-8e14zcdc.js} +2 -2
  51. package/dist/{chunk-ygfwbh8p.js.map → chunk-8e14zcdc.js.map} +1 -1
  52. package/dist/{chunk-szyr67g7.js → chunk-8wvh099n.js} +2 -2
  53. package/dist/{chunk-szyr67g7.js.map → chunk-8wvh099n.js.map} +1 -1
  54. package/dist/{chunk-fcbtgekt.js → chunk-92zmwb33.js} +2 -2
  55. package/dist/{chunk-fcbtgekt.js.map → chunk-92zmwb33.js.map} +1 -1
  56. package/dist/{chunk-pe4f30nw.js → chunk-9fgyanab.js} +2 -2
  57. package/dist/{chunk-pe4f30nw.js.map → chunk-9fgyanab.js.map} +1 -1
  58. package/dist/{chunk-wskms8nf.js → chunk-a8q7ds6w.js} +1 -1
  59. package/dist/chunk-aczp96k5.js +13 -0
  60. package/dist/chunk-aczp96k5.js.map +16 -0
  61. package/dist/{chunk-7qhqqf0q.js → chunk-agpty0p6.js} +2 -2
  62. package/dist/{chunk-7qhqqf0q.js.map → chunk-agpty0p6.js.map} +1 -1
  63. package/dist/{chunk-nxap8bmy.js → chunk-bvgcv0jx.js} +2 -2
  64. package/dist/{chunk-nxap8bmy.js.map → chunk-bvgcv0jx.js.map} +1 -1
  65. package/dist/chunk-by0ydsqs.js +5 -0
  66. package/dist/{chunk-cwkf46bk.js.map → chunk-by0ydsqs.js.map} +1 -1
  67. package/dist/{chunk-4rs6w1gp.js → chunk-c7hbdsjv.js} +2 -2
  68. package/dist/{chunk-xe76d4v6.js.map → chunk-c7hbdsjv.js.map} +1 -1
  69. package/dist/chunk-ccymw1ed.js +9 -0
  70. package/dist/chunk-ccymw1ed.js.map +10 -0
  71. package/dist/{chunk-9wf36729.js → chunk-cjwjrk12.js} +1 -1
  72. package/dist/{chunk-ca1qwsjj.js → chunk-e4adgvd6.js} +2 -2
  73. package/dist/{chunk-ca1qwsjj.js.map → chunk-e4adgvd6.js.map} +1 -1
  74. package/dist/{chunk-xr8mcx1y.js → chunk-etj63p4p.js} +2 -2
  75. package/dist/{chunk-xr8mcx1y.js.map → chunk-etj63p4p.js.map} +1 -1
  76. package/dist/{chunk-engdyem1.js → chunk-fec4qnr3.js} +2 -2
  77. package/dist/{chunk-engdyem1.js.map → chunk-fec4qnr3.js.map} +1 -1
  78. package/dist/{chunk-2fw9pm64.js → chunk-feh44g4f.js} +2 -2
  79. package/dist/{chunk-2fw9pm64.js.map → chunk-feh44g4f.js.map} +1 -1
  80. package/dist/{chunk-kgpqz8te.js → chunk-ff8rtz9h.js} +2 -2
  81. package/dist/{chunk-kgpqz8te.js.map → chunk-ff8rtz9h.js.map} +1 -1
  82. package/dist/{chunk-bxby9c62.js → chunk-g9q39z7t.js} +2 -2
  83. package/dist/{chunk-bxby9c62.js.map → chunk-g9q39z7t.js.map} +1 -1
  84. package/dist/{chunk-692nx054.js → chunk-gs8fvb6a.js} +2 -2
  85. package/dist/{chunk-692nx054.js.map → chunk-gs8fvb6a.js.map} +1 -1
  86. package/dist/{chunk-ycwv9n7m.js → chunk-gxre6wnc.js} +1 -1
  87. package/dist/{chunk-pb7n7vaq.js → chunk-gykwq8py.js} +1 -1
  88. package/dist/{chunk-h2cvg5r5.js → chunk-j3zz8046.js} +2 -2
  89. package/dist/{chunk-h2cvg5r5.js.map → chunk-j3zz8046.js.map} +1 -1
  90. package/dist/{chunk-y73xy0zy.js → chunk-kabkxq5q.js} +2 -2
  91. package/dist/{chunk-y73xy0zy.js.map → chunk-kabkxq5q.js.map} +1 -1
  92. package/dist/{chunk-dt8bxq4c.js → chunk-kgbgj7v4.js} +2 -2
  93. package/dist/{chunk-dt8bxq4c.js.map → chunk-kgbgj7v4.js.map} +1 -1
  94. package/dist/{chunk-zz0k1na4.js → chunk-m0n0ddd2.js} +1 -1
  95. package/dist/{chunk-41bpne77.js → chunk-mmc5bbf4.js} +2 -2
  96. package/dist/{chunk-41bpne77.js.map → chunk-mmc5bbf4.js.map} +1 -1
  97. package/dist/{chunk-1etmnz40.js → chunk-p0dgpm5r.js} +2 -2
  98. package/dist/{chunk-1etmnz40.js.map → chunk-p0dgpm5r.js.map} +1 -1
  99. package/dist/{chunk-dnqmvmnp.js → chunk-pkew0k7c.js} +2 -2
  100. package/dist/{chunk-dnqmvmnp.js.map → chunk-pkew0k7c.js.map} +1 -1
  101. package/dist/{chunk-y89vn9da.js → chunk-q8pr18w6.js} +4 -4
  102. package/dist/{chunk-y89vn9da.js.map → chunk-q8pr18w6.js.map} +1 -1
  103. package/dist/{chunk-d2jafhaf.js → chunk-qb8pjdez.js} +4 -4
  104. package/dist/{chunk-d2jafhaf.js.map → chunk-qb8pjdez.js.map} +1 -1
  105. package/dist/{chunk-hgwtg5zp.js → chunk-qkfd84hx.js} +2 -2
  106. package/dist/{chunk-hgwtg5zp.js.map → chunk-qkfd84hx.js.map} +1 -1
  107. package/dist/{chunk-mykr2v6g.js → chunk-rc86ewq1.js} +3 -3
  108. package/dist/{chunk-mykr2v6g.js.map → chunk-rc86ewq1.js.map} +1 -1
  109. package/dist/{chunk-88c8ck33.js → chunk-re13gf4s.js} +3 -3
  110. package/dist/{chunk-88c8ck33.js.map → chunk-re13gf4s.js.map} +1 -1
  111. package/dist/{chunk-80kga3p1.js → chunk-rpwvwsq9.js} +1 -1
  112. package/dist/{chunk-9779ngzq.js → chunk-rreb2k19.js} +2 -2
  113. package/dist/{chunk-9779ngzq.js.map → chunk-rreb2k19.js.map} +1 -1
  114. package/dist/{chunk-7ytazpjd.js → chunk-samm4h7d.js} +1 -1
  115. package/dist/{chunk-cvg01wc0.js → chunk-sx2gadhs.js} +2 -2
  116. package/dist/{chunk-cvg01wc0.js.map → chunk-sx2gadhs.js.map} +1 -1
  117. package/dist/{chunk-vf9jtq9h.js → chunk-t495wyhh.js} +2 -2
  118. package/dist/{chunk-vf9jtq9h.js.map → chunk-t495wyhh.js.map} +1 -1
  119. package/dist/{chunk-f0bz1q3t.js → chunk-tvb68dqg.js} +1 -1
  120. package/dist/{chunk-4pjv77s5.js → chunk-vk1x3rsw.js} +2 -2
  121. package/dist/{chunk-4pjv77s5.js.map → chunk-vk1x3rsw.js.map} +1 -1
  122. package/dist/{chunk-mn5xxg4q.js → chunk-vq1q8mgm.js} +2 -2
  123. package/dist/{chunk-mn5xxg4q.js.map → chunk-vq1q8mgm.js.map} +1 -1
  124. package/dist/{chunk-49kkapvr.js → chunk-vqmy8jfr.js} +2 -2
  125. package/dist/{chunk-49kkapvr.js.map → chunk-vqmy8jfr.js.map} +1 -1
  126. package/dist/{chunk-wzng3k56.js → chunk-vvq18rrr.js} +2 -2
  127. package/dist/{chunk-wzng3k56.js.map → chunk-vvq18rrr.js.map} +1 -1
  128. package/dist/{chunk-vtf7tkef.js → chunk-wgb26e02.js} +2 -2
  129. package/dist/{chunk-vtf7tkef.js.map → chunk-wgb26e02.js.map} +1 -1
  130. package/dist/{chunk-g7exgg3k.js → chunk-wjjxqw9b.js} +2 -2
  131. package/dist/{chunk-g7exgg3k.js.map → chunk-wjjxqw9b.js.map} +1 -1
  132. package/dist/{chunk-q1grt110.js → chunk-wkw8afk0.js} +2 -2
  133. package/dist/{chunk-q1grt110.js.map → chunk-wkw8afk0.js.map} +1 -1
  134. package/dist/{chunk-kbz5s9wb.js → chunk-x68jra5n.js} +2 -2
  135. package/dist/{chunk-kbz5s9wb.js.map → chunk-x68jra5n.js.map} +1 -1
  136. package/dist/{chunk-p7ae0rnf.js → chunk-z0jf5kzx.js} +2 -2
  137. package/dist/{chunk-p7ae0rnf.js.map → chunk-z0jf5kzx.js.map} +1 -1
  138. package/dist/{chunk-cckfxk08.js → chunk-z6gwn4xf.js} +2 -2
  139. package/dist/{chunk-cckfxk08.js.map → chunk-z6gwn4xf.js.map} +1 -1
  140. package/dist/{chunk-j5r7vm8a.js → chunk-zsmwmg8x.js} +2 -2
  141. package/dist/{chunk-j5r7vm8a.js.map → chunk-zsmwmg8x.js.map} +1 -1
  142. package/dist/config/index.js +1 -1
  143. package/dist/console/run.js +2 -2
  144. package/dist/console/run.js.map +1 -1
  145. package/dist/container/index.js +2 -2
  146. package/dist/container/index.js.map +1 -1
  147. package/dist/database/Connection.d.ts +7 -0
  148. package/dist/database/Connection.d.ts.map +1 -1
  149. package/dist/database/config.d.ts +16 -0
  150. package/dist/database/config.d.ts.map +1 -1
  151. package/dist/database/index.js +2 -2
  152. package/dist/database/index.js.map +1 -1
  153. package/dist/database/sqliteClient.d.ts +42 -0
  154. package/dist/database/sqliteClient.d.ts.map +1 -0
  155. package/dist/database/sqliteQueue.d.ts +67 -0
  156. package/dist/database/sqliteQueue.d.ts.map +1 -0
  157. package/dist/email/index.js +2 -2
  158. package/dist/email/index.js.map +1 -1
  159. package/dist/facades/index.js +1 -1
  160. package/dist/foundation/index.js +2 -2
  161. package/dist/foundation/index.js.map +1 -1
  162. package/dist/http/index.js +1 -1
  163. package/dist/i18n/dictionaryRuntime.js +2 -2
  164. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  165. package/dist/i18n/index.js +2 -2
  166. package/dist/i18n/index.js.map +1 -1
  167. package/dist/kernel/index.js +2 -2
  168. package/dist/kernel/index.js.map +1 -1
  169. package/dist/orm/context.d.ts +3 -61
  170. package/dist/orm/context.d.ts.map +1 -1
  171. package/dist/orm/index.js +2 -2
  172. package/dist/orm/index.js.map +1 -1
  173. package/dist/probe/index.js +2 -2
  174. package/dist/probe/index.js.map +1 -1
  175. package/dist/server/index.js +2 -2
  176. package/dist/server/index.js.map +1 -1
  177. package/dist/services/change-feed/DatabaseChangeFeedDriver.d.ts +0 -1
  178. package/dist/services/change-feed/DatabaseChangeFeedDriver.d.ts.map +1 -1
  179. package/dist/services/index.js +2 -2
  180. package/dist/services/index.js.map +1 -1
  181. package/dist/services/lock/DatabaseLockStore.d.ts +6 -1
  182. package/dist/services/lock/DatabaseLockStore.d.ts.map +1 -1
  183. package/dist/services/queue/DatabaseQueueDriver.d.ts +6 -1
  184. package/dist/services/queue/DatabaseQueueDriver.d.ts.map +1 -1
  185. package/dist/services/queue/work.js +2 -2
  186. package/dist/services/queue/work.js.map +1 -1
  187. package/dist/stats/route-table.js +1 -1
  188. package/dist/support/index.js +2 -2
  189. package/dist/support/index.js.map +1 -1
  190. package/dist/vitest/index.js +1 -1
  191. package/package.json +1 -1
  192. package/dist/chunk-2as2xfem.js +0 -5
  193. package/dist/chunk-2as2xfem.js.map +0 -14
  194. package/dist/chunk-cwkf46bk.js +0 -5
  195. package/dist/chunk-mxqrmjha.js +0 -13
  196. package/dist/chunk-mxqrmjha.js.map +0 -10
  197. /package/dist/{chunk-hk37x8mp.js.map → chunk-1kjyhseb.js.map} +0 -0
  198. /package/dist/{chunk-gbgwtaqq.js.map → chunk-3kgp6xka.js.map} +0 -0
  199. /package/dist/{chunk-wskms8nf.js.map → chunk-a8q7ds6w.js.map} +0 -0
  200. /package/dist/{chunk-9wf36729.js.map → chunk-cjwjrk12.js.map} +0 -0
  201. /package/dist/{chunk-ycwv9n7m.js.map → chunk-gxre6wnc.js.map} +0 -0
  202. /package/dist/{chunk-pb7n7vaq.js.map → chunk-gykwq8py.js.map} +0 -0
  203. /package/dist/{chunk-zz0k1na4.js.map → chunk-m0n0ddd2.js.map} +0 -0
  204. /package/dist/{chunk-80kga3p1.js.map → chunk-rpwvwsq9.js.map} +0 -0
  205. /package/dist/{chunk-7ytazpjd.js.map → chunk-samm4h7d.js.map} +0 -0
  206. /package/dist/{chunk-f0bz1q3t.js.map → chunk-tvb68dqg.js.map} +0 -0
@@ -1,12 +1,12 @@
1
1
  // @bun
2
- import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as Z1}from"./chunk-6wv3k8ap.js";import{Cl as v0,Dl as SZ,ml as fZ,nl as bZ,ol as TZ,ql as o,rl as tZ,tl as O0}from"./chunk-mxqrmjha.js";import{Wl as DZ}from"./chunk-2as2xfem.js";import{rm as eZ,um as B0}from"./chunk-wj0q7tyn.js";import{Dm as w0}from"./chunk-49kkapvr.js";class C0{table;sql;dialect;connection;busyTimeout;configured;constructor(Z,$={}){let V=$.table??"gemi_locks";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(V))throw Error(`The lock table name "${V}" is not a plain identifier. Use letters, digits and underscores.`);this.table=V,this.sql=Z.sql,this.dialect=Z.dialect,this.connection=Z.name,this.busyTimeout=$.busyTimeout??1000}async createTable(){await this.configure();for(let Z of H1(this.dialect,this.table))await this.sql.unsafe(Z)}async acquire(Z,$,V){await this.configure();let z=this.sql,X=this.now(z);if(await this.seed(z,Z),this.mysql){let G=await z`
2
+ import{Vk as r,Wk as h0,Yk as z1,il as i0}from"./chunk-0wa8ztk5.js";import{kl as V1}from"./chunk-6wv3k8ap.js";import{Cl as g0,ml as qZ,nl as mZ,ol as MZ,ql as o,rl as eZ,tl as O0}from"./chunk-ccymw1ed.js";import{Pl as IZ,Ql as v0,Rl as x0,Yl as LZ}from"./chunk-aczp96k5.js";import{tm as $1,wm as Q0}from"./chunk-3mq0wmq7.js";import{Fm as l0}from"./chunk-vqmy8jfr.js";class C0{table;sql;dialect;connection;busyTimeout;configured;constructor(Z,$={}){let V=$.table??"gemi_locks";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(V))throw Error(`The lock table name "${V}" is not a plain identifier. Use letters, digits and underscores.`);this.table=V,this.sql=Z.sql,this.dialect=Z.dialect,this.connection=Z.name,this.busyTimeout=$.busyTimeout??1000,x0(Z.sql,$.busyTimeout)}async createTable(){await this.configure();for(let Z of P1(this.dialect,this.table))await this.sql.unsafe(Z)}async acquire(Z,$,V){await this.configure();let z=this.sql,X=this.now(z);if(await this.seed(z,Z),this.mysql){let G=await z`
3
3
  UPDATE ${this.name(z)}
4
4
  SET owner = ${$}, token = token + 1, expires_at = ${X} + ${this.ms(z,V)},
5
5
  updated_at = ${X}
6
6
  WHERE name = ${Z} AND expires_at <= ${X}
7
- `;if(e(G)===0)return null;let[B]=await z`
7
+ `;if(e(G)===0)return null;let[Q]=await z`
8
8
  SELECT token FROM ${this.name(z)} WHERE name = ${Z} AND owner = ${$}
9
- `;return B?Number(B.token):null}let Y=await z`
9
+ `;return Q?Number(Q.token):null}let Y=await z`
10
10
  UPDATE ${this.name(z)}
11
11
  SET owner = ${$}, token = token + 1, expires_at = ${X} + ${this.ms(z,V)},
12
12
  updated_at = ${X}
@@ -30,34 +30,34 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
30
30
  UPDATE ${this.name(V)}
31
31
  SET token = ${this.int(V,$)}, updated_at = ${this.now(V)}
32
32
  WHERE name = ${Z} AND token < ${this.int(V,$)}
33
- `;return e(z)>0}async fence(Z,$,V,z){await this.configure();let X=async(G)=>{let B=this.now(G),H;if(this.dialect==="sqlite"){let Q=await G`
34
- UPDATE ${this.name(G)} SET updated_at = ${B}
35
- WHERE name = ${Z} AND owner = ${$} AND token = ${V} AND expires_at > ${B}
36
- `;H=e(Q)>0}else H=(await G`
33
+ `;return e(z)>0}async fence(Z,$,V,z){await this.configure();let X=async(G)=>{let Q=this.now(G),B;if(this.dialect==="sqlite"){let H=await G`
34
+ UPDATE ${this.name(G)} SET updated_at = ${Q}
35
+ WHERE name = ${Z} AND owner = ${$} AND token = ${V} AND expires_at > ${Q}
36
+ `;B=e(H)>0}else B=(await G`
37
37
  SELECT 1 AS held FROM ${this.name(G)}
38
- WHERE name = ${Z} AND owner = ${$} AND token = ${V} AND expires_at > ${B}
38
+ WHERE name = ${Z} AND owner = ${$} AND token = ${V} AND expires_at > ${Q}
39
39
  FOR UPDATE
40
- `).length>0;if(!H)throw new x0(Z,V);return z()},Y=this.connection;if(Y===void 0){let G=async()=>await this.sql.begin((B)=>X(B));return this.dialect==="sqlite"?SZ(this.sql,G):G()}return v0(this.sql,(G)=>TZ(Y,()=>X(G)),{connection:Y,dialect:this.dialect})}async hit(Z,$,V,z=1){await this.configure();let X=this.sql,Y=this.now(X),G=this.ms(X,Math.max(1,V)),B=this.int(X,z),H=this.int(X,$),Q=this.name(X);if(!this.mysql){let J=await X`
41
- INSERT INTO ${Q} (name, owner, token, expires_at, updated_at)
42
- VALUES (${Z}, '', ${B}, ${Y} + ${G}, ${Y})
40
+ `).length>0;if(!B)throw new h0(Z,V);return z()},Y=this.connection;if(Y===void 0){let G=async()=>await this.sql.begin((Q)=>X(Q));return this.dialect==="sqlite"?IZ(this.sql,G):G()}return g0(this.sql,(G)=>MZ(Y,()=>X(G)),{connection:Y,dialect:this.dialect})}async hit(Z,$,V,z=1){await this.configure();let X=this.sql,Y=this.now(X),G=this.ms(X,Math.max(1,V)),Q=this.int(X,z),B=this.int(X,$),H=this.name(X);if(!this.mysql){let J=await X`
41
+ INSERT INTO ${H} (name, owner, token, expires_at, updated_at)
42
+ VALUES (${Z}, '', ${Q}, ${Y} + ${G}, ${Y})
43
43
  ON CONFLICT (name) DO UPDATE
44
- SET token = CASE WHEN ${Q}.expires_at <= ${Y} THEN ${B} ELSE ${Q}.token + ${B} END,
45
- expires_at = CASE WHEN ${Q}.expires_at <= ${Y} THEN ${Y} + ${G} ELSE ${Q}.expires_at END,
44
+ SET token = CASE WHEN ${H}.expires_at <= ${Y} THEN ${Q} ELSE ${H}.token + ${Q} END,
45
+ expires_at = CASE WHEN ${H}.expires_at <= ${Y} THEN ${Y} + ${G} ELSE ${H}.expires_at END,
46
46
  updated_at = ${Y}
47
- WHERE ${Q}.expires_at <= ${Y} OR ${Q}.token + ${B} <= ${H}
47
+ WHERE ${H}.expires_at <= ${Y} OR ${H}.token + ${Q} <= ${B}
48
48
  RETURNING token, expires_at - ${Y} AS reset
49
- `;if(J[0])return s0(!0,J[0]);return s0(!1,await this.window(X,Z))}for(let J=0;;J++){await this.seed(X,Z);let F=await X`
50
- UPDATE ${Q}
51
- SET token = CASE WHEN expires_at <= ${Y} THEN ${B} ELSE token + ${B} END,
49
+ `;if(J[0])return r0(!0,J[0]);return r0(!1,await this.window(X,Z))}for(let J=0;;J++){await this.seed(X,Z);let F=await X`
50
+ UPDATE ${H}
51
+ SET token = CASE WHEN expires_at <= ${Y} THEN ${Q} ELSE token + ${Q} END,
52
52
  expires_at = CASE WHEN expires_at <= ${Y} THEN ${Y} + ${G} ELSE expires_at END,
53
53
  updated_at = ${Y}
54
- WHERE name = ${Z} AND (expires_at <= ${Y} OR token + ${B} <= ${H})
55
- `,U=e(F)>0,A=await this.window(X,Z);if(U||A||J>0)return s0(U,A)}}async pruneWindows(Z,$=1000){if(Z==="")throw Error("pruneWindows needs a prefix: it must never reach lock rows.");await this.configure();let V=this.sql,z=this.now(V),X=this.name(V),Y=V.unsafe(String(Math.max(1,Math.floor($)))),G=V.unsafe(String(Z.length)),B=this.mysql?V`CAST(substr(name, 1, ${G}) AS BINARY) = CAST(${Z} AS BINARY) AND expires_at <= ${z}`:V`substr(name, 1, ${G}) = ${Z} AND expires_at <= ${z}`,H=this.mysql?await V`DELETE FROM ${X} WHERE ${B} LIMIT ${Y}`:await V`
54
+ WHERE name = ${Z} AND (expires_at <= ${Y} OR token + ${Q} <= ${B})
55
+ `,U=e(F)>0,A=await this.window(X,Z);if(U||A||J>0)return r0(U,A)}}async pruneWindows(Z,$=1000){if(Z==="")throw Error("pruneWindows needs a prefix: it must never reach lock rows.");await this.configure();let V=this.sql,z=this.now(V),X=this.name(V),Y=V.unsafe(String(Math.max(1,Math.floor($)))),G=V.unsafe(String(Z.length)),Q=this.mysql?V`CAST(substr(name, 1, ${G}) AS BINARY) = CAST(${Z} AS BINARY) AND expires_at <= ${z}`:V`substr(name, 1, ${G}) = ${Z} AND expires_at <= ${z}`,B=this.mysql?await V`DELETE FROM ${X} WHERE ${Q} LIMIT ${Y}`:await V`
56
56
  DELETE FROM ${X}
57
- WHERE name IN (SELECT name FROM ${X} WHERE ${B} LIMIT ${Y})
57
+ WHERE name IN (SELECT name FROM ${X} WHERE ${Q} LIMIT ${Y})
58
58
  -- Again here: a hit may have restarted a window since the select.
59
59
  AND expires_at <= ${z}
60
- `;return e(H)}async window(Z,$){let[V]=await Z`
60
+ `;return e(B)}async window(Z,$){let[V]=await Z`
61
61
  SELECT token, expires_at - ${this.now(Z)} AS reset FROM ${this.name(Z)} WHERE name = ${$}
62
62
  `;return V}async refund(Z){await this.configure();let $=this.sql,V=this.now($);await $`
63
63
  UPDATE ${this.name($)} SET token = token - 1, updated_at = ${V}
@@ -72,7 +72,7 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
72
72
  INSERT INTO ${this.name(Z)} (name, owner, token, expires_at, updated_at)
73
73
  VALUES (${$}, '', 0, 0, ${V})
74
74
  ON CONFLICT (name) DO NOTHING
75
- `}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,$){return this.int(Z,Math.max(0,Math.round($)))}int(Z,$){let V=Math.round($);return this.mysql?Z`CAST(${V} AS SIGNED)`:Z`CAST(${V} AS BIGINT)`}}function s0(Z,$){return{allowed:Z,resetInMs:Math.max(0,Number($?.reset??0)),count:Number($?.token??0)}}function e(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function H1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
75
+ `}get mysql(){return this.dialect==="mysql"||this.dialect==="mariadb"}configure(){if(this.dialect!=="sqlite"||this.busyTimeout===0||v0(this.sql))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,$){return this.int(Z,Math.max(0,Math.round($)))}int(Z,$){let V=Math.round($);return this.mysql?Z`CAST(${V} AS SIGNED)`:Z`CAST(${V} AS BIGINT)`}}function r0(Z,$){return{allowed:Z,resetInMs:Math.max(0,Number($?.reset??0)),count:Number($?.token??0)}}function e(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function P1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
76
76
  \`name\` VARCHAR(191) NOT NULL,
77
77
  \`owner\` VARCHAR(191) NOT NULL,
78
78
  \`token\` BIGINT NOT NULL DEFAULT 0,
@@ -88,13 +88,13 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
88
88
  "token" BIGINT NOT NULL DEFAULT 0,
89
89
  "expires_at" BIGINT NOT NULL,
90
90
  "updated_at" BIGINT NOT NULL${z}
91
- )`]}class g0{entries=new Map;counters=new Map;async acquire(Z,$,V){let z=Date.now(),X=this.entries.get(Z);if(X&&(X.expiresAt>z||X.fences>0))return null;let Y=(X?.token??0)+1;return this.entries.set(Z,{owner:$,token:Y,expiresAt:z+Math.max(0,V),fences:0}),Y}async extend(Z,$,V,z){let X=this.current(Z,$,V);if(!X)return!1;return X.expiresAt=Date.now()+Math.max(0,z),!0}async release(Z,$,V){let z=this.current(Z,$,V);if(!z)return!1;return z.owner="",z.expiresAt=0,!0}async holder(Z){let $=this.entries.get(Z);if(!$||$.expiresAt<=Date.now())return null;return{owner:$.owner,token:$.token}}async held(Z,$,V){return this.current(Z,$,V)!==void 0}async advance(Z,$){if((this.counters.get(Z)??-1/0)>=$)return!1;return this.counters.set(Z,$),!0}async fence(Z,$,V,z){let X=this.current(Z,$,V);if(!X)throw new x0(Z,V);X.fences++;try{return await z()}finally{X.fences--}}windows=new Map;async hit(Z,$,V,z=1){let X=Date.now(),Y=this.windows.get(Z);if(!Y||Y.endsAt<=X)Y={count:0,endsAt:X+Math.max(1,V)},this.windows.set(Z,Y);if(Y.count+z>$)return{allowed:!1,resetInMs:Y.endsAt-X,count:Y.count};return Y.count+=z,{allowed:!0,resetInMs:Y.endsAt-X,count:Y.count}}async pruneWindows(Z,$=1000){if(Z==="")throw Error("pruneWindows needs a prefix: it must never reach lock rows.");let V=Date.now(),z=0;for(let[X,Y]of this.windows){if(z>=$)break;if(X.startsWith(Z)&&Y.endsAt<=V)this.windows.delete(X),z++}return z}async refund(Z){let $=this.windows.get(Z);if($&&$.endsAt>Date.now()&&$.count>0)$.count--}current(Z,$,V){let z=this.entries.get(Z);if(!z||z.owner!==$||z.expiresAt<=Date.now())return;if(V!==void 0&&z.token!==V)return;return z}}var m="gemi.WorkflowTick",n0=262144;function h0(Z,$){let V=(z)=>z.slice(0,z.lastIndexOf(":"));return V(Z)===V($)}class b 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 J1=["completed","failed","cancelled"];class r0{db;table;stepTable;itemTable;sourceTable;constructor(Z,$){this.db=Z;this.table=$.table,this.stepTable=$.stepTable,this.itemTable=$.itemTable,this.sourceTable=$.sourceTable;let V=Z.connection;if(Z.dialect!=="sqlite"&&V!==void 0)this.transaction=(z)=>v0(Z.sql,()=>z(),{connection:V})}transaction;joinsTransaction(){return this.db.transaction()!==void 0}create(Z){let $=this.db.transaction(),V=$?this.insertWorkflow($,Z):this.db.atomically((z)=>this.insertWorkflow(z,Z));if($)O0(V);return V}async insertWorkflow(Z,$){await this.db.configure();let V=this.db.now(Z);await P0(Z`
91
+ )`]}class y0{entries=new Map;counters=new Map;async acquire(Z,$,V){let z=Date.now(),X=this.entries.get(Z);if(X&&(X.expiresAt>z||X.fences>0))return null;let Y=(X?.token??0)+1;return this.entries.set(Z,{owner:$,token:Y,expiresAt:z+Math.max(0,V),fences:0}),Y}async extend(Z,$,V,z){let X=this.current(Z,$,V);if(!X)return!1;return X.expiresAt=Date.now()+Math.max(0,z),!0}async release(Z,$,V){let z=this.current(Z,$,V);if(!z)return!1;return z.owner="",z.expiresAt=0,!0}async holder(Z){let $=this.entries.get(Z);if(!$||$.expiresAt<=Date.now())return null;return{owner:$.owner,token:$.token}}async held(Z,$,V){return this.current(Z,$,V)!==void 0}async advance(Z,$){if((this.counters.get(Z)??-1/0)>=$)return!1;return this.counters.set(Z,$),!0}async fence(Z,$,V,z){let X=this.current(Z,$,V);if(!X)throw new h0(Z,V);X.fences++;try{return await z()}finally{X.fences--}}windows=new Map;async hit(Z,$,V,z=1){let X=Date.now(),Y=this.windows.get(Z);if(!Y||Y.endsAt<=X)Y={count:0,endsAt:X+Math.max(1,V)},this.windows.set(Z,Y);if(Y.count+z>$)return{allowed:!1,resetInMs:Y.endsAt-X,count:Y.count};return Y.count+=z,{allowed:!0,resetInMs:Y.endsAt-X,count:Y.count}}async pruneWindows(Z,$=1000){if(Z==="")throw Error("pruneWindows needs a prefix: it must never reach lock rows.");let V=Date.now(),z=0;for(let[X,Y]of this.windows){if(z>=$)break;if(X.startsWith(Z)&&Y.endsAt<=V)this.windows.delete(X),z++}return z}async refund(Z){let $=this.windows.get(Z);if($&&$.endsAt>Date.now()&&$.count>0)$.count--}current(Z,$,V){let z=this.entries.get(Z);if(!z||z.owner!==$||z.expiresAt<=Date.now())return;if(V!==void 0&&z.token!==V)return;return z}}var m="gemi.WorkflowTick",t0=262144;function f0(Z,$){let V=(z)=>z.slice(0,z.lastIndexOf(":"));return V(Z)===V($)}class b 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 K1=["completed","failed","cancelled"];class o0{db;table;stepTable;itemTable;sourceTable;constructor(Z,$){this.db=Z;this.table=$.table,this.stepTable=$.stepTable,this.itemTable=$.itemTable,this.sourceTable=$.sourceTable;let V=Z.connection;if(Z.dialect!=="sqlite"&&V!==void 0)this.transaction=(z)=>g0(Z.sql,()=>z(),{connection:V})}transaction;joinsTransaction(){return this.db.transaction()!==void 0}create(Z){let $=this.db.transaction(),V=$?this.insertWorkflow($,Z):this.db.atomically((z)=>this.insertWorkflow(z,Z));if($)O0(V);return V}async insertWorkflow(Z,$){await this.db.configure();let V=this.db.now(Z);await P0(Z`
92
92
  INSERT INTO ${this.workflows(Z)}
93
93
  (id, name, args, status, progress, retick, created_at, updated_at)
94
94
  VALUES
95
95
  (${$.id}, ${$.name}, ${$.args}, 'running',
96
96
  ${this.db.fraction(Z,0)}, 0, ${V}, ${V})
97
- `,this.table),await this.db.insertJob(Z,{name:m,args:JSON.stringify([$.id])})}async find(Z,$={}){await this.db.configure();let V=this.db.sql,[z]=await P0(V`SELECT * FROM ${this.workflows(V)} WHERE id = ${Z}`,this.table);if(!z)return null;return{workflow:IZ(z),steps:$.steps===!1?[]:await this.stepsOf(V,Z)}}acquire(Z,$,V){return this.db.atomically(async(z)=>{let X=await this.lock(z,Z);if(!X)return{kind:"missing"};let Y=await this.db.clock(z);if(X.lockedBy!==null&&!h0(X.lockedBy,$)&&(X.lockedUntil??0)>Y)return await z`UPDATE ${this.workflows(z)} SET retick = 1 WHERE id = ${Z}`,{kind:"busy"};let G=Y+Math.max(0,Math.round(V));return await z`
97
+ `,this.table),await this.db.insertJob(Z,{name:m,args:JSON.stringify([$.id])})}async find(Z,$={}){await this.db.configure();let V=this.db.sql,[z]=await P0(V`SELECT * FROM ${this.workflows(V)} WHERE id = ${Z}`,this.table);if(!z)return null;return{workflow:jZ(z),steps:$.steps===!1?[]:await this.stepsOf(V,Z)}}acquire(Z,$,V){return this.db.atomically(async(z)=>{let X=await this.lock(z,Z);if(!X)return{kind:"missing"};let Y=await this.db.clock(z);if(X.lockedBy!==null&&!f0(X.lockedBy,$)&&(X.lockedUntil??0)>Y)return await z`UPDATE ${this.workflows(z)} SET retick = 1 WHERE id = ${Z}`,{kind:"busy"};let G=Y+Math.max(0,Math.round(V));return await z`
98
98
  UPDATE ${this.workflows(z)}
99
99
  SET locked_by = ${$}, locked_until = ${this.db.ms(z,G)}, retick = 0
100
100
  WHERE id = ${Z}
@@ -102,7 +102,7 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
102
102
  UPDATE ${this.workflows(z)}
103
103
  SET locked_until = ${this.db.now(z)} + ${this.db.ms(z,V)}
104
104
  WHERE id = ${Z} AND locked_by = ${$}
105
- `;return y0(X)>0}update(Z,$,V){let z=async(Y)=>{let G=await this.lock(Y,Z);if(!G)return;if($.owner!==void 0&&G.lockedBy!==$.owner)throw new b(Z);let B=$.key===void 0?null:await this.stepOf(Y,Z,$.key),H=$.allSteps?await this.stepsOf(Y,Z):[],Q=$.items===void 0?[]:await this.itemsOf(Y,Z,$.items,["running","retrying"],-1,null),J=V({workflow:G,step:B,steps:H,items:Q,now:Date.now()});if(J.step){let P=J.step.key===$.key?B!==null:await this.stepOf(Y,Z,J.step.key)!==null;await this.writeStep(Y,J.step,P)}if(J.items)await this.writeItems(Y,Z,J.items);if(J.batch)await this.db.insertBatch(Y,J.batch);for(let P of J.cancelBatches??[])await this.db.cancelBatch(Y,P);let F={...G,...J.workflow},U=J.unlock===!0,A=Y`
105
+ `;return b0(X)>0}update(Z,$,V){let z=async(Y)=>{let G=await this.lock(Y,Z);if(!G)return;if($.owner!==void 0&&G.lockedBy!==$.owner)throw new b(Z);let Q=$.key===void 0?null:await this.stepOf(Y,Z,$.key),B=$.allSteps?await this.stepsOf(Y,Z):[],H=$.items===void 0?[]:await this.itemsOf(Y,Z,$.items,["running","retrying"],-1,null),J=V({workflow:G,step:Q,steps:B,items:H,now:Date.now()});if(J.step){let P=J.step.key===$.key?Q!==null:await this.stepOf(Y,Z,J.step.key)!==null;await this.writeStep(Y,J.step,P)}if(J.items)await this.writeItems(Y,Z,J.items);if(J.batch)await this.db.insertBatch(Y,J.batch);for(let P of J.cancelBatches??[])await this.db.cancelBatch(Y,P);let F={...G,...J.workflow},U=J.unlock===!0,A=Y`
106
106
  status = ${F.status}, current_step = ${F.currentStep},
107
107
  progress = ${this.db.fraction(Y,F.progress)}, result = ${F.result},
108
108
  error = ${F.error}, wake_at = ${this.db.timeOrNull(Y,F.wakeAt)},
@@ -118,7 +118,7 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
118
118
  )
119
119
  `;let Y=await V`
120
120
  DELETE FROM ${this.workflows(V)} WHERE ${z} AND updated_at <= ${X}
121
- `;return y0(Y)});try{let V=this.db.sql;await V`
121
+ `;return b0(Y)});try{let V=this.db.sql;await V`
122
122
  DELETE FROM ${this.items(V)}
123
123
  WHERE NOT EXISTS (
124
124
  SELECT 1 FROM ${this.workflows(V)} w WHERE w.id = ${this.items(V)}.workflow_id
@@ -128,39 +128,39 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
128
128
  WHERE workflow_id IS NOT NULL AND NOT EXISTS (
129
129
  SELECT 1 FROM ${this.workflows(V)} w WHERE w.id = ${this.sources(V)}.workflow_id
130
130
  )
131
- `}catch(V){if(!W0(V))throw V}return $}async writeSource(Z,$,V){if(V.length===0)return;await this.db.configure();let z=this.db.sql;for(let X=0;X<V.length;X+=500){let Y=this.db.now(z),G=V.slice(X,X+500).map((B)=>z`(${Z}, ${B.index}, ${$}, ${B.payload}, ${Y})`);await b0(z`
131
+ `}catch(V){if(!W0(V))throw V}return $}async writeSource(Z,$,V){if(V.length===0)return;await this.db.configure();let z=this.db.sql;for(let X=0;X<V.length;X+=500){let Y=this.db.now(z),G=V.slice(X,X+500).map((Q)=>z`(${Z}, ${Q.index}, ${$}, ${Q.payload}, ${Y})`);await m0(z`
132
132
  INSERT INTO ${this.sources(z)} (source_id, idx, workflow_id, payload, created_at)
133
- VALUES ${G.reduce((B,H)=>z`${B}, ${H}`)}
134
- `,this.sourceTable)}}async readSource(Z,$,V){await this.db.configure();let z=this.db.sql;return(await b0(z`
133
+ VALUES ${G.reduce((Q,B)=>z`${Q}, ${B}`)}
134
+ `,this.sourceTable)}}async readSource(Z,$,V){await this.db.configure();let z=this.db.sql;return(await m0(z`
135
135
  SELECT idx, payload FROM ${this.sources(z)}
136
136
  WHERE source_id = ${Z} AND idx >= ${$} AND idx < ${V}
137
137
  ORDER BY idx
138
- `,this.sourceTable)).map((Y)=>({index:Number(Y.idx),payload:String(Y.payload)}))}async deleteSource(Z){await this.db.configure();let $=this.db.sql,V=await b0($`DELETE FROM ${this.sources($)} WHERE source_id = ${Z}`,this.sourceTable);return y0(V)}async pruneSources(Z){await this.db.configure();let $=this.db.sql,V=await b0($`
138
+ `,this.sourceTable)).map((Y)=>({index:Number(Y.idx),payload:String(Y.payload)}))}async deleteSource(Z){await this.db.configure();let $=this.db.sql,V=await m0($`DELETE FROM ${this.sources($)} WHERE source_id = ${Z}`,this.sourceTable);return b0(V)}async pruneSources(Z){await this.db.configure();let $=this.db.sql,V=await m0($`
139
139
  DELETE FROM ${this.sources($)}
140
140
  WHERE workflow_id IS NULL
141
141
  AND created_at <= ${this.db.now($)} - ${this.db.ms($,Z)}
142
- `,this.sourceTable);return y0(V)}endedClause(Z){return Z`status IN (${J1.map(($)=>Z`${$}`).reduce(($,V)=>Z`${$}, ${V}`)})`}async writeItems(Z,$,V){let z=this.db,X=V.step,Y=V.delete??[];for(let B=0;B<Y.length;B+=500){let H=Y.slice(B,B+500).map((Q)=>Z`${Q}`);await f0(Z`
142
+ `,this.sourceTable);return b0(V)}endedClause(Z){return Z`status IN (${K1.map(($)=>Z`${$}`).reduce(($,V)=>Z`${$}, ${V}`)})`}async writeItems(Z,$,V){let z=this.db,X=V.step,Y=V.delete??[];for(let Q=0;Q<Y.length;Q+=500){let B=Y.slice(Q,Q+500).map((H)=>Z`${H}`);await q0(Z`
143
143
  DELETE FROM ${this.items(Z)}
144
144
  WHERE workflow_id = ${$} AND step_key = ${X}
145
- AND idx IN (${H.reduce((Q,J)=>Z`${Q}, ${J}`)})
146
- `,this.itemTable)}let G=V.insert??[];for(let B=0;B<G.length;B+=200){let H=z.now(Z),Q=G.slice(B,B+200).map((J)=>Z`(
145
+ AND idx IN (${B.reduce((H,J)=>Z`${H}, ${J}`)})
146
+ `,this.itemTable)}let G=V.insert??[];for(let Q=0;Q<G.length;Q+=200){let B=z.now(Z),H=G.slice(Q,Q+200).map((J)=>Z`(
147
147
  ${$}, ${X}, ${J.index}, ${J.key}, ${J.status}, ${J.attempt},
148
148
  ${J.error}, ${J.output}, ${z.timeOrNull(Z,J.wakeAt)},
149
- ${z.timeOrNull(Z,J.startedAt)}, ${z.timeOrNull(Z,J.finishedAt)}, ${H}, ${H}
150
- )`);await f0(Z`
149
+ ${z.timeOrNull(Z,J.startedAt)}, ${z.timeOrNull(Z,J.finishedAt)}, ${B}, ${B}
150
+ )`);await q0(Z`
151
151
  INSERT INTO ${this.items(Z)}
152
152
  (workflow_id, step_key, idx, item_key, status, attempt, error, output, wake_at,
153
153
  started_at, finished_at, created_at, updated_at)
154
- VALUES ${Q.reduce((J,F)=>Z`${J}, ${F}`)}
155
- `,this.itemTable)}for(let B of V.update??[])await f0(Z`
154
+ VALUES ${H.reduce((J,F)=>Z`${J}, ${F}`)}
155
+ `,this.itemTable)}for(let Q of V.update??[])await q0(Z`
156
156
  UPDATE ${this.items(Z)}
157
- SET item_key = ${B.key}, status = ${B.status}, attempt = ${B.attempt},
158
- error = ${B.error}, output = ${B.output},
159
- wake_at = ${z.timeOrNull(Z,B.wakeAt)},
160
- started_at = ${z.timeOrNull(Z,B.startedAt)},
161
- finished_at = ${z.timeOrNull(Z,B.finishedAt)}, updated_at = ${z.now(Z)}
162
- WHERE workflow_id = ${$} AND step_key = ${X} AND idx = ${B.index}
163
- `,this.itemTable)}async itemsOf(Z,$,V,z,X,Y){let G=z.map((H)=>Z`${H}`).reduce((H,Q)=>Z`${H}, ${Q}`);return(await f0(Y===null?Z`
157
+ SET item_key = ${Q.key}, status = ${Q.status}, attempt = ${Q.attempt},
158
+ error = ${Q.error}, output = ${Q.output},
159
+ wake_at = ${z.timeOrNull(Z,Q.wakeAt)},
160
+ started_at = ${z.timeOrNull(Z,Q.startedAt)},
161
+ finished_at = ${z.timeOrNull(Z,Q.finishedAt)}, updated_at = ${z.now(Z)}
162
+ WHERE workflow_id = ${$} AND step_key = ${X} AND idx = ${Q.index}
163
+ `,this.itemTable)}async itemsOf(Z,$,V,z,X,Y){let G=z.map((B)=>Z`${B}`).reduce((B,H)=>Z`${B}, ${H}`);return(await q0(Y===null?Z`
164
164
  SELECT * FROM ${this.items(Z)}
165
165
  WHERE workflow_id = ${$} AND step_key = ${V}
166
166
  AND status IN (${G}) AND idx > ${X}
@@ -170,7 +170,7 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
170
170
  WHERE workflow_id = ${$} AND step_key = ${V}
171
171
  AND status IN (${G}) AND idx > ${X}
172
172
  ORDER BY idx LIMIT ${Y}
173
- `,this.itemTable)).map(P1)}async writeStep(Z,$,V){let z=this.db,X=this.keyColumn(Z);if(V){await Z`
173
+ `,this.itemTable)).map(F1)}async writeStep(Z,$,V){let z=this.db,X=this.keyColumn(Z);if(V){await Z`
174
174
  UPDATE ${this.steps(Z)}
175
175
  SET status = ${$.status}, attempt = ${$.attempt}, output = ${$.output},
176
176
  error = ${$.error}, batch_id = ${$.batchId},
@@ -186,10 +186,10 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
186
186
  (${$.workflowId}, ${$.key}, ${$.status}, ${$.attempt}, ${$.output},
187
187
  ${$.error}, ${$.batchId}, ${z.timeOrNull(Z,$.wakeAt)},
188
188
  ${z.timeOrNull(Z,$.startedAt)}, ${z.timeOrNull(Z,$.finishedAt)}, ${Y}, ${Y})
189
- `}async lock(Z,$){let V;if(this.db.dialect==="sqlite")await P0(Z`UPDATE ${this.workflows(Z)} SET updated_at = updated_at WHERE id = ${$}`,this.table),V=await Z`SELECT * FROM ${this.workflows(Z)} WHERE id = ${$}`;else V=await P0(Z`SELECT * FROM ${this.workflows(Z)} WHERE id = ${$} FOR UPDATE`,this.table);return V[0]?IZ(V[0]):void 0}async stepOf(Z,$,V){let[z]=await P0(Z`SELECT * FROM ${this.steps(Z)} WHERE workflow_id = ${$} AND ${this.keyColumn(Z)} = ${V}`,this.stepTable);return z?MZ(z):null}async stepsOf(Z,$){return(await P0(Z`
189
+ `}async lock(Z,$){let V;if(this.db.dialect==="sqlite")await P0(Z`UPDATE ${this.workflows(Z)} SET updated_at = updated_at WHERE id = ${$}`,this.table),V=await Z`SELECT * FROM ${this.workflows(Z)} WHERE id = ${$}`;else V=await P0(Z`SELECT * FROM ${this.workflows(Z)} WHERE id = ${$} FOR UPDATE`,this.table);return V[0]?jZ(V[0]):void 0}async stepOf(Z,$,V){let[z]=await P0(Z`SELECT * FROM ${this.steps(Z)} WHERE workflow_id = ${$} AND ${this.keyColumn(Z)} = ${V}`,this.stepTable);return z?vZ(z):null}async stepsOf(Z,$){return(await P0(Z`
190
190
  SELECT * FROM ${this.steps(Z)} WHERE workflow_id = ${$}
191
191
  ORDER BY created_at, ${this.keyColumn(Z)}
192
- `,this.stepTable)).map(MZ)}workflows(Z){return Z.unsafe(this.db.quoted(this.table))}steps(Z){return Z.unsafe(this.db.quoted(this.stepTable))}items(Z){return Z.unsafe(this.db.quoted(this.itemTable))}sources(Z){return Z.unsafe(this.db.quoted(this.sourceTable))}keyColumn(Z){return Z.unsafe(this.db.quoted("key"))}}function Z0(Z){return Z==null?null:Number(Z)}function w(Z){return Z==null?null:String(Z)}function IZ(Z){return{id:String(Z.id),name:String(Z.name),args:String(Z.args),status:String(Z.status),currentStep:w(Z.current_step),progress:Number(Z.progress??0),result:w(Z.result),error:w(Z.error),wakeAt:Z0(Z.wake_at),lockedBy:w(Z.locked_by),lockedUntil:Z0(Z.locked_until),retick:Number(Z.retick??0)!==0,createdAt:Number(Z.created_at),updatedAt:Number(Z.updated_at)}}function MZ(Z){return{workflowId:String(Z.workflow_id),key:String(Z.key),status:String(Z.status),attempt:Number(Z.attempt??0),output:w(Z.output),error:w(Z.error),batchId:w(Z.batch_id),wakeAt:Z0(Z.wake_at),startedAt:Z0(Z.started_at),finishedAt:Z0(Z.finished_at),createdAt:Number(Z.created_at),updatedAt:Number(Z.updated_at)}}function P1(Z){return{workflowId:String(Z.workflow_id),step:String(Z.step_key),index:Number(Z.idx),key:w(Z.item_key),status:String(Z.status),attempt:Number(Z.attempt??0),error:w(Z.error),output:w(Z.output),wakeAt:Z0(Z.wake_at),startedAt:Z0(Z.started_at),finishedAt:Z0(Z.finished_at),createdAt:Number(Z.created_at),updatedAt:Number(Z.updated_at)}}function y0(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function W0(Z){let $=String(Z?.message??Z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test($)}async function P0(Z,$){try{return await Z}catch(V){if(!W0(V))throw V;throw Error(`Workflows need the "${$}" 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:V})}}async function f0(Z,$){try{return await Z}catch(V){if(!W0(V))throw V;throw Error(`step.each needs the "${$}" table, and the database says it is missing. Add the GemiWorkflowItem model from the docs (docs/workflows.md#the-workflow-tables) and migrate, or call the queue driver's createTable().`,{cause:V})}}async function b0(Z,$){try{return await Z}catch(V){if(!W0(V))throw V;throw Error(`Item sources need the "${$}" table, and the database says it is missing. Add the GemiWorkflowSource model from the docs (docs/workflows.md#the-workflow-tables) and migrate, or call the queue driver's createTable().`,{cause:V})}}function jZ(Z,$,V){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
192
+ `,this.stepTable)).map(vZ)}workflows(Z){return Z.unsafe(this.db.quoted(this.table))}steps(Z){return Z.unsafe(this.db.quoted(this.stepTable))}items(Z){return Z.unsafe(this.db.quoted(this.itemTable))}sources(Z){return Z.unsafe(this.db.quoted(this.sourceTable))}keyColumn(Z){return Z.unsafe(this.db.quoted("key"))}}function Z0(Z){return Z==null?null:Number(Z)}function c(Z){return Z==null?null:String(Z)}function jZ(Z){return{id:String(Z.id),name:String(Z.name),args:String(Z.args),status:String(Z.status),currentStep:c(Z.current_step),progress:Number(Z.progress??0),result:c(Z.result),error:c(Z.error),wakeAt:Z0(Z.wake_at),lockedBy:c(Z.locked_by),lockedUntil:Z0(Z.locked_until),retick:Number(Z.retick??0)!==0,createdAt:Number(Z.created_at),updatedAt:Number(Z.updated_at)}}function vZ(Z){return{workflowId:String(Z.workflow_id),key:String(Z.key),status:String(Z.status),attempt:Number(Z.attempt??0),output:c(Z.output),error:c(Z.error),batchId:c(Z.batch_id),wakeAt:Z0(Z.wake_at),startedAt:Z0(Z.started_at),finishedAt:Z0(Z.finished_at),createdAt:Number(Z.created_at),updatedAt:Number(Z.updated_at)}}function F1(Z){return{workflowId:String(Z.workflow_id),step:String(Z.step_key),index:Number(Z.idx),key:c(Z.item_key),status:String(Z.status),attempt:Number(Z.attempt??0),error:c(Z.error),output:c(Z.output),wakeAt:Z0(Z.wake_at),startedAt:Z0(Z.started_at),finishedAt:Z0(Z.finished_at),createdAt:Number(Z.created_at),updatedAt:Number(Z.updated_at)}}function b0(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function W0(Z){let $=String(Z?.message??Z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test($)}async function P0(Z,$){try{return await Z}catch(V){if(!W0(V))throw V;throw Error(`Workflows need the "${$}" 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:V})}}async function q0(Z,$){try{return await Z}catch(V){if(!W0(V))throw V;throw Error(`step.each needs the "${$}" table, and the database says it is missing. Add the GemiWorkflowItem model from the docs (docs/workflows.md#the-workflow-tables) and migrate, or call the queue driver's createTable().`,{cause:V})}}async function m0(Z,$){try{return await Z}catch(V){if(!W0(V))throw V;throw Error(`Item sources need the "${$}" table, and the database says it is missing. Add the GemiWorkflowSource model from the docs (docs/workflows.md#the-workflow-tables) and migrate, or call the queue driver's createTable().`,{cause:V})}}function xZ(Z,$,V){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
193
193
  \`id\` VARCHAR(191) NOT NULL,
194
194
  \`name\` VARCHAR(191) NOT NULL,
195
195
  \`args\` LONGTEXT NOT NULL,
@@ -254,7 +254,7 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
254
254
  "updated_at" BIGINT NOT NULL,
255
255
 
256
256
  ${z?'PRIMARY KEY ("workflow_id", "key")':`CONSTRAINT "${V}_pkey" PRIMARY KEY ("workflow_id","key")`}
257
- )`,`CREATE INDEX IF NOT EXISTS "${$}_status_idx" ON "${$}"("status")`]}function vZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
257
+ )`,`CREATE INDEX IF NOT EXISTS "${$}_status_idx" ON "${$}"("status")`]}function gZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
258
258
  \`workflow_id\` VARCHAR(191) NOT NULL,
259
259
  \`step_key\` VARCHAR(191) NOT NULL,
260
260
  \`idx\` INTEGER NOT NULL,
@@ -286,7 +286,7 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
286
286
  "updated_at" BIGINT NOT NULL,
287
287
 
288
288
  ${Z==="sqlite"?'PRIMARY KEY ("workflow_id", "step_key", "idx")':`CONSTRAINT "${$}_pkey" PRIMARY KEY ("workflow_id","step_key","idx")`}
289
- )`]}function xZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
289
+ )`]}function hZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
290
290
  \`source_id\` VARCHAR(191) NOT NULL,
291
291
  \`idx\` INTEGER NOT NULL,
292
292
  \`workflow_id\` VARCHAR(191) NULL,
@@ -303,7 +303,7 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
303
303
  "created_at" BIGINT NOT NULL,
304
304
 
305
305
  ${Z==="sqlite"?'PRIMARY KEY ("source_id", "idx")':`CONSTRAINT "${$}_pkey" PRIMARY KEY ("source_id","idx")`}
306
- )`,`CREATE INDEX IF NOT EXISTS "${$}_workflow_id_idx" ON "${$}"("workflow_id")`]}function q0(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 m0(Z,$,V){if(Z.pending<=0)return Z;let z={...Z,pending:Z.pending-1};if($==="succeeded")z.succeeded++;else if($==="cancelled")z.cancelled++;else z.failed++,z.failedJobIds=[...Z.failedJobIds,V];return z}function k0(Z,$){return!$.allowFailures&&$.cancelledAt===null&&$.finishedAt===null&&$.failed>Z.failed}function K0(Z,$,V){let z=Math.min(Math.max(0,V),Z.pending);return{...Z,cancelledAt:Z.cancelledAt??$,pending:Z.pending-z,cancelled:Z.cancelled+z}}function F0(Z,$,V){let z=$,X=[],Y=$.callbacks,G=Z.failed===0&&Z.cancelledAt===null,B=$.failed===0&&$.cancelledAt===null;if(G&&!B&&Y.catch)X.push(Y.catch);if($.pending===0&&$.finishedAt===null){if(z={...$,finishedAt:V},$.cancelledAt===null&&($.failed===0||$.allowFailures)&&Y.then)X.push(Y.then);if(Y.finally)X.push(Y.finally)}let H=G0(z);return{record:z,calls:X.map((Q)=>({name:Q.name,args:JSON.stringify([...Q.args,H])}))}}function G0(Z,$=0){let{allowFailures:V,callbacks:z,...X}=Z,Y=Z.total-Z.pending,G=Z.total===0?1:Math.min(1,Math.max(0,(Y+Math.max(0,$))/Z.total));return{...X,failedJobIds:[...Z.failedJobIds],progress:G}}function i(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{SQL:K1}=globalThis.Bun;class t0{db;statements;own;ownTail=Promise.resolve();constructor(Z,$){this.db=Z;this.statements=N1(Z.dialect,$)}async acquire(Z){return this.step(async($)=>{let V=[...new Set(Z.slots.map((Y)=>Y.key))].sort();for(let Y of V){let{limit:G}=Z.slots.find((B)=>B.key===Y);await $("lockGate",{key:Y,limit:G})}let[z]=await $("placeOf",{holder:Z.holder}),X=z?.queued_at==null?Number((await $("clock",{}))[0].now):Number(z.queued_at);for(let{key:Y,limit:G}of Z.slots){await this.prune($,Y);let[B]=await $("ticket",{key:Y,holder:Z.holder});if(!B)await $("insertWaiting",{key:Y,holder:Z.holder,job:Z.job.id,workflow:Z.workflowId??null,queued:X});else if(String(B.job_id)!==Z.job.id)await $("pointAt",{key:Y,holder:Z.holder,job:Z.job.id});let H=B?Number(B.queued_at):X,Q=async()=>await this.count($,"countHolders",{key:Y})+await this.count($,"countAhead",{key:Y,queued:H,holder:Z.holder,cap:Math.max(1,G)})<G,J=B?.state==="holding";if(!J&&await Q())J=!0;if(!J)await this.wake($,Y,G,Z.holder),J=await Q();if(J&&B?.state!=="holding")await $("hold",{key:Y,holder:Z.holder});if(J){await this.wake($,Y,G,Z.holder);continue}let U=await this.count($,"countAhead",{key:Y,queued:H,holder:Z.holder,cap:Math.max(1,G)})<Math.max(1,G)?Z.recheckMs.near:Z.recheckMs.far;return await $("park",{id:Z.job.id,attempt:Z.job.attempt,ms:Math.max(0,Math.round(U))}),!1}return!0})}async release(Z){await this.step(async($)=>{let V=await $("keysOf",{holder:Z}),z=[...new Set(V.map((X)=>String(X.slot_key)))].sort();for(let X of z)await $("touchGate",{key:X});for(let X of z){await $("deleteTicket",{key:X,holder:Z}),await this.prune($,X);let[Y]=await $("gate",{key:X});await this.wake($,X,Number(Y?.slot_limit??0),Z)}})}async prune(Z,$){if(await Z("pruneJobHolders",{key:$}),(await Z("hasWorkflowHolders",{key:$})).length>0)await Z("pruneWorkflowHolders",{key:$})}async wake(Z,$,V,z){let X=V-await this.count(Z,"countHolders",{key:$});while(X>0){let Y=await Z("nextWaiters",{key:$,except:z,n:X+8});if(Y.length===0)return;let G=0;for(let B of Y){if(X<=0)return;let H=String(B.holder),Q=B.job_id==null?null:String(B.job_id),J=B.workflow_id==null?null:String(B.workflow_id);if(J!==null){let[A]=await Z("workflowStatus",{id:J});if(!A||U1.includes(String(A.status))){await Z("deleteTicket",{key:$,holder:H}),G++;continue}}if(Q!==null)await Z("wakeJob",{id:Q});let[F]=Q===null?[]:await Z("jobStatus",{id:Q});if(!(F!==void 0&&F1.includes(String(F.status)))){if(J===null){await Z("deleteTicket",{key:$,holder:H}),G++;continue}let A=await this.db.insertJob(Z.q,{name:m,args:JSON.stringify([J])});await Z("pointAt",{key:$,holder:H,job:A})}X--}if(G===0)return}}async count(Z,$,V){let[z]=await Z($,V);return Number(z?.n??0)}async step(Z){await this.db.configure();for(let $=0;;$++)try{return await this.transaction((V)=>Z(this.runner(V)))}catch(V){if($>=4||!A1(V))throw D1(V,this.statements.table);await new Promise((z)=>setTimeout(z,10+Math.random()*40*($+1)))}}async transaction(Z){let $=this.ownClient();if($){let X=this.ownTail.then(()=>$.begin((Y)=>Z(Y)));return this.ownTail=X.catch(()=>{}),X}if(this.db.dialect!=="mysql"&&this.db.dialect!=="mariadb")return this.db.atomically(Z);let V=await this.db.sql.reserve(),[z]=await V`SELECT @@transaction_isolation AS level`;await V`SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED`;try{return await V.begin((X)=>Z(X))}finally{let X=z?.level?.replaceAll("-"," ");if(X&&/^[A-Z ]+$/.test(X))await V.unsafe(`SET SESSION TRANSACTION ISOLATION LEVEL ${X}`);V.release()}}ownClient(){if(this.own)return this.own;if(this.db.dialect!=="postgres"||!R1())return;let Z=this.db.sql.options;if(Z?.adapter!=="postgres")return;return this.own=new K1({...Z,max:1,idleTimeout:5}),this.own}runner(Z){let $=async(V,z)=>{let[X,Y]=this.statements.compile(V,z);return await Z.unsafe(X,Y)};return $.q=Z,$}}var F1=["pending","claimed"],U1=["completed","failed","cancelled","paused"];function gZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
306
+ )`,`CREATE INDEX IF NOT EXISTS "${$}_workflow_id_idx" ON "${$}"("workflow_id")`]}function k0(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 u0(Z,$,V){if(Z.pending<=0)return Z;let z={...Z,pending:Z.pending-1};if($==="succeeded")z.succeeded++;else if($==="cancelled")z.cancelled++;else z.failed++,z.failedJobIds=[...Z.failedJobIds,V];return z}function p0(Z,$){return!$.allowFailures&&$.cancelledAt===null&&$.finishedAt===null&&$.failed>Z.failed}function K0(Z,$,V){let z=Math.min(Math.max(0,V),Z.pending);return{...Z,cancelledAt:Z.cancelledAt??$,pending:Z.pending-z,cancelled:Z.cancelled+z}}function F0(Z,$,V){let z=$,X=[],Y=$.callbacks,G=Z.failed===0&&Z.cancelledAt===null,Q=$.failed===0&&$.cancelledAt===null;if(G&&!Q&&Y.catch)X.push(Y.catch);if($.pending===0&&$.finishedAt===null){if(z={...$,finishedAt:V},$.cancelledAt===null&&($.failed===0||$.allowFailures)&&Y.then)X.push(Y.then);if(Y.finally)X.push(Y.finally)}let B=G0(z);return{record:z,calls:X.map((H)=>({name:H.name,args:JSON.stringify([...H.args,B])}))}}function G0(Z,$=0){let{allowFailures:V,callbacks:z,...X}=Z,Y=Z.total-Z.pending,G=Z.total===0?1:Math.min(1,Math.max(0,(Y+Math.max(0,$))/Z.total));return{...X,failedJobIds:[...Z.failedJobIds],progress:G}}function i(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{SQL:U1}=globalThis.Bun;class e0{db;statements;own;ownTail=Promise.resolve();constructor(Z,$){this.db=Z;this.statements=A1(Z.dialect,$)}async acquire(Z){return this.step(async($)=>{let V=[...new Set(Z.slots.map((Y)=>Y.key))].sort();for(let Y of V){let{limit:G}=Z.slots.find((Q)=>Q.key===Y);await $("lockGate",{key:Y,limit:G})}let[z]=await $("placeOf",{holder:Z.holder}),X=z?.queued_at==null?Number((await $("clock",{}))[0].now):Number(z.queued_at);for(let{key:Y,limit:G}of Z.slots){await this.prune($,Y);let[Q]=await $("ticket",{key:Y,holder:Z.holder});if(!Q)await $("insertWaiting",{key:Y,holder:Z.holder,job:Z.job.id,workflow:Z.workflowId??null,queued:X});else if(String(Q.job_id)!==Z.job.id)await $("pointAt",{key:Y,holder:Z.holder,job:Z.job.id});let B=Q?Number(Q.queued_at):X,H=async()=>await this.count($,"countHolders",{key:Y})+await this.count($,"countAhead",{key:Y,queued:B,holder:Z.holder,cap:Math.max(1,G)})<G,J=Q?.state==="holding";if(!J&&await H())J=!0;if(!J)await this.wake($,Y,G,Z.holder),J=await H();if(J&&Q?.state!=="holding")await $("hold",{key:Y,holder:Z.holder});if(J){await this.wake($,Y,G,Z.holder);continue}let U=await this.count($,"countAhead",{key:Y,queued:B,holder:Z.holder,cap:Math.max(1,G)})<Math.max(1,G)?Z.recheckMs.near:Z.recheckMs.far;return await $("park",{id:Z.job.id,attempt:Z.job.attempt,ms:Math.max(0,Math.round(U))}),!1}return!0})}async release(Z){await this.step(async($)=>{let V=await $("keysOf",{holder:Z}),z=[...new Set(V.map((X)=>String(X.slot_key)))].sort();for(let X of z)await $("touchGate",{key:X});for(let X of z){await $("deleteTicket",{key:X,holder:Z}),await this.prune($,X);let[Y]=await $("gate",{key:X});await this.wake($,X,Number(Y?.slot_limit??0),Z)}})}async prune(Z,$){if(await Z("pruneJobHolders",{key:$}),(await Z("hasWorkflowHolders",{key:$})).length>0)await Z("pruneWorkflowHolders",{key:$})}async wake(Z,$,V,z){let X=V-await this.count(Z,"countHolders",{key:$});while(X>0){let Y=await Z("nextWaiters",{key:$,except:z,n:X+8});if(Y.length===0)return;let G=0;for(let Q of Y){if(X<=0)return;let B=String(Q.holder),H=Q.job_id==null?null:String(Q.job_id),J=Q.workflow_id==null?null:String(Q.workflow_id);if(J!==null){let[A]=await Z("workflowStatus",{id:J});if(!A||R1.includes(String(A.status))){await Z("deleteTicket",{key:$,holder:B}),G++;continue}}if(H!==null)await Z("wakeJob",{id:H});let[F]=H===null?[]:await Z("jobStatus",{id:H});if(!(F!==void 0&&N1.includes(String(F.status)))){if(J===null){await Z("deleteTicket",{key:$,holder:B}),G++;continue}let A=await this.db.insertJob(Z.q,{name:m,args:JSON.stringify([J])});await Z("pointAt",{key:$,holder:B,job:A})}X--}if(G===0)return}}async count(Z,$,V){let[z]=await Z($,V);return Number(z?.n??0)}async step(Z){await this.db.configure();for(let $=0;;$++)try{return await this.transaction((V)=>Z(this.runner(V)))}catch(V){if($>=4||!_1(V))throw L1(V,this.statements.table);await new Promise((z)=>setTimeout(z,10+Math.random()*40*($+1)))}}async transaction(Z){let $=this.ownClient();if($){let X=this.ownTail.then(()=>$.begin((Y)=>Z(Y)));return this.ownTail=X.catch(()=>{}),X}if(this.db.dialect!=="mysql"&&this.db.dialect!=="mariadb")return this.db.atomically(Z);let V=await this.db.sql.reserve(),[z]=await V`SELECT @@transaction_isolation AS level`;await V`SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED`;try{return await V.begin((X)=>Z(X))}finally{let X=z?.level?.replaceAll("-"," ");if(X&&/^[A-Z ]+$/.test(X))await V.unsafe(`SET SESSION TRANSACTION ISOLATION LEVEL ${X}`);V.release()}}ownClient(){if(this.own)return this.own;if(this.db.dialect!=="postgres"||!D1())return;let Z=this.db.sql.options;if(Z?.adapter!=="postgres")return;return this.own=new U1({...Z,max:1,idleTimeout:5}),this.own}runner(Z){let $=async(V,z)=>{let[X,Y]=this.statements.compile(V,z);return await Z.unsafe(X,Y)};return $.q=Z,$}}var N1=["pending","claimed"],R1=["completed","failed","cancelled","paused"];function yZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
307
307
  \`slot_key\` VARCHAR(191) NOT NULL,
308
308
  \`holder\` VARCHAR(191) NOT NULL,
309
309
  \`job_id\` VARCHAR(191) NULL,
@@ -327,18 +327,18 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
327
327
  "slot_limit" INTEGER NOT NULL DEFAULT 0,
328
328
  "queued_at" BIGINT NOT NULL,
329
329
  "updated_at" BIGINT NOT NULL${V}
330
- )`,`CREATE INDEX IF NOT EXISTS "${$}_slot_key_state_queued_at_holder_idx" ON "${$}"("slot_key", "state", "queued_at", "holder")`,`CREATE INDEX IF NOT EXISTS "${$}_holder_idx" ON "${$}"("holder")`]}function N1(Z,$){let V=Z==="mysql"||Z==="mariadb",z=(U)=>V?`\`${U}\``:`"${U}"`,X=z($.slots),Y=z($.jobs),G=z($.workflows),B=Z==="postgres"?"floor(extract(epoch from statement_timestamp()) * 1000)::bigint":V?"(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)":"CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)",H=(U)=>V?`CAST({${U}} AS SIGNED)`:`CAST({${U}} AS BIGINT)`,Q=(U)=>V?`ON DUPLICATE KEY UPDATE ${U.replace(/excluded\.(\w+)/g,"VALUES($1)")}`:`ON CONFLICT (slot_key, holder) DO UPDATE SET ${U}`,J={clock:`SELECT ${B} AS now`,lockGate:`INSERT INTO ${X} (slot_key, holder, state, slot_limit, queued_at, updated_at)
331
- VALUES ({key}, '', 'gate', ${H("limit")}, ${B}, ${B})
332
- ${Q("slot_limit = excluded.slot_limit, updated_at = excluded.updated_at")}`,touchGate:`INSERT INTO ${X} (slot_key, holder, state, slot_limit, queued_at, updated_at)
333
- VALUES ({key}, '', 'gate', 0, ${B}, ${B})
334
- ${Q("updated_at = excluded.updated_at")}`,gate:`SELECT slot_limit FROM ${X} WHERE slot_key = {key} AND holder = ''`,placeOf:`SELECT MIN(queued_at) AS queued_at FROM ${X} WHERE holder = {holder}`,ticket:`SELECT state, queued_at, job_id FROM ${X} WHERE slot_key = {key} AND holder = {holder}`,insertWaiting:`INSERT INTO ${X}
330
+ )`,`CREATE INDEX IF NOT EXISTS "${$}_slot_key_state_queued_at_holder_idx" ON "${$}"("slot_key", "state", "queued_at", "holder")`,`CREATE INDEX IF NOT EXISTS "${$}_holder_idx" ON "${$}"("holder")`]}function A1(Z,$){let V=Z==="mysql"||Z==="mariadb",z=(U)=>V?`\`${U}\``:`"${U}"`,X=z($.slots),Y=z($.jobs),G=z($.workflows),Q=Z==="postgres"?"floor(extract(epoch from statement_timestamp()) * 1000)::bigint":V?"(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)":"CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)",B=(U)=>V?`CAST({${U}} AS SIGNED)`:`CAST({${U}} AS BIGINT)`,H=(U)=>V?`ON DUPLICATE KEY UPDATE ${U.replace(/excluded\.(\w+)/g,"VALUES($1)")}`:`ON CONFLICT (slot_key, holder) DO UPDATE SET ${U}`,J={clock:`SELECT ${Q} AS now`,lockGate:`INSERT INTO ${X} (slot_key, holder, state, slot_limit, queued_at, updated_at)
331
+ VALUES ({key}, '', 'gate', ${B("limit")}, ${Q}, ${Q})
332
+ ${H("slot_limit = excluded.slot_limit, updated_at = excluded.updated_at")}`,touchGate:`INSERT INTO ${X} (slot_key, holder, state, slot_limit, queued_at, updated_at)
333
+ VALUES ({key}, '', 'gate', 0, ${Q}, ${Q})
334
+ ${H("updated_at = excluded.updated_at")}`,gate:`SELECT slot_limit FROM ${X} WHERE slot_key = {key} AND holder = ''`,placeOf:`SELECT MIN(queued_at) AS queued_at FROM ${X} WHERE holder = {holder}`,ticket:`SELECT state, queued_at, job_id FROM ${X} WHERE slot_key = {key} AND holder = {holder}`,insertWaiting:`INSERT INTO ${X}
335
335
  (slot_key, holder, job_id, workflow_id, state, slot_limit, queued_at, updated_at)
336
- VALUES ({key}, {holder}, {job}, {workflow}, 'waiting', 0, ${H("queued")}, ${B})`,pointAt:`UPDATE ${X} SET job_id = {job}, updated_at = ${B}
337
- WHERE slot_key = {key} AND holder = {holder}`,hold:`UPDATE ${X} SET state = 'holding', updated_at = ${B}
336
+ VALUES ({key}, {holder}, {job}, {workflow}, 'waiting', 0, ${B("queued")}, ${Q})`,pointAt:`UPDATE ${X} SET job_id = {job}, updated_at = ${Q}
337
+ WHERE slot_key = {key} AND holder = {holder}`,hold:`UPDATE ${X} SET state = 'holding', updated_at = ${Q}
338
338
  WHERE slot_key = {key} AND holder = {holder}`,deleteTicket:`DELETE FROM ${X} WHERE slot_key = {key} AND holder = {holder}`,keysOf:`SELECT slot_key FROM ${X} WHERE holder = {holder}`,countHolders:`SELECT COUNT(*) AS n FROM ${X} WHERE slot_key = {key} AND state = 'holding'`,countAhead:`SELECT COUNT(*) AS n FROM (
339
339
  SELECT holder FROM ${X}
340
340
  WHERE slot_key = {key} AND state = 'waiting'
341
- AND (queued_at < ${H("queued")} OR (queued_at = ${H("queued")} AND holder < {holder}))
341
+ AND (queued_at < ${B("queued")} OR (queued_at = ${B("queued")} AND holder < {holder}))
342
342
  LIMIT {cap}
343
343
  ) ahead`,nextWaiters:`SELECT holder, job_id, workflow_id FROM ${X}
344
344
  WHERE slot_key = {key} AND state = 'waiting' AND holder <> {except}
@@ -355,16 +355,16 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
355
355
  SELECT 1 FROM ${G}
356
356
  WHERE ${G}.id = ${X}.workflow_id
357
357
  AND ${G}.status NOT IN ('completed', 'failed', 'cancelled', 'paused')
358
- )`,wakeJob:`UPDATE ${Y} SET available_at = ${B}, updated_at = ${B}
359
- WHERE id = {id} AND status = 'pending' AND available_at > ${B}`,jobStatus:`SELECT status FROM ${Y} WHERE id = {id}`,workflowStatus:`SELECT status FROM ${G} WHERE id = {id}`,park:`UPDATE ${Y}
360
- SET status = 'pending', attempts = attempts - 1, available_at = ${B} + ${H("ms")},
361
- lease_expires_at = NULL, updated_at = ${B}
362
- WHERE id = {id} AND status = 'claimed' AND attempts = ${H("attempt")}`},F=new Map;return{table:$.slots,texts:J,compile(U,A){let N=F.get(U);if(!N){let P=[];N={text:J[U].replace(/\{([a-z]+)\}/g,(D,T)=>{if(Z==="postgres"){let _=P.indexOf(T);if(_===-1)_=P.push(T)-1;return`$${_+1}`}return P.push(T),"?"}),names:P},F.set(U,N)}return[N.text,N.names.map((P)=>{if(!(P in A))throw Error(`The slot statement ${U} needs {${P}}.`);return A[P]})]}}}function R1(){let[Z=0,$=0]=Bun.version.split(".").map(Number);return Z<1||Z===1&&$<4}function A1(Z){let $=Z;return $?.errno===1213||$?.code==="40P01"||/deadlock|try restarting transaction/i.test(String($?.message??""))}function D1(Z,$){let V=String(Z?.message??Z);if(!/does not exist|doesn't exist|no such table/i.test(V)||!V.includes($))return Z;return Error(`Concurrency limits on the database driver need the "${$}" table, and the database says it is missing. Add the GemiJobSlot model from the docs (docs/jobs-and-queues.md#concurrency-limits--concurrency) and migrate, or call the driver's createTable().`,{cause:Z})}var hZ=200,_1="Its batch was cancelled before it ran.";class e0{table;batchTable;workflowTable;workflowStepTable;workflowItemTable;workflowSourceTable;slotTable;workflows;slotLines;sql;dialect;connection;busyTimeout;configured;sqliteTail=Promise.resolve();constructor(Z,$={}){let V=$.table??"gemi_jobs",z=$.batchTable??(V==="gemi_jobs"?"gemi_job_batches":`${V}_batches`),X=V==="gemi_jobs",Y=$.workflowTable??(X?"gemi_workflows":`${V}_workflows`),G=$.workflowStepTable??(X?"gemi_workflow_steps":`${V}_workflow_steps`),B=$.workflowItemTable??(X?"gemi_workflow_items":`${V}_workflow_items`),H=$.workflowSourceTable??(X?"gemi_workflow_sources":`${V}_workflow_sources`),Q=$.slotTable??(X?"gemi_job_slots":`${V}_slots`);for(let F of[V,Q,z,Y,G,B,H])if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(F))throw Error(`The queue table name "${F}" is not a plain identifier. Use letters, digits and underscores.`);let J=$.busyTimeout??1000;if(!Number.isInteger(J)||J<0)throw Error(`The queue's busyTimeout must be a whole number of milliseconds, 0 or more; got ${J}.`);this.table=V,this.batchTable=z,this.workflowTable=Y,this.workflowStepTable=G,this.workflowItemTable=B,this.workflowSourceTable=H,this.slotTable=Q,this.sql=Z.sql,this.dialect=Z.dialect,this.connection=Z.name,this.busyTimeout=J}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,...$]=L1(this.dialect,this.table);if(await this.sql.unsafe(Z),!await this.hasBatchColumns())for(let V of C1(this.dialect,this.table))await this.sql.unsafe(V);for(let V of $)await this.sql.unsafe(V);for(let V of W1(this.dialect,this.batchTable))await this.sql.unsafe(V);for(let V of jZ(this.dialect,this.workflowTable,this.workflowStepTable))await this.sql.unsafe(V);for(let V of vZ(this.dialect,this.workflowItemTable))await this.sql.unsafe(V);for(let V of xZ(this.dialect,this.workflowSourceTable))await this.sql.unsafe(V);for(let V of gZ(this.dialect,this.slotTable))await this.sql.unsafe(V)}async hasBatchColumns(){try{return await this.sql.unsafe(`SELECT batch_id, progress FROM ${this.quoted(this.table)} WHERE 1 = 0`),!0}catch(Z){if(qZ(Z))return!1;throw Z}}enqueue(Z){let $=this.transaction(),V=this.insert($??this.sql,Z);if($)O0(V);return V}async insert(Z,{name:$,args:V,delayMs:z=0,id:X=Bun.randomUUIDv7()}){await this.configure();let Y=this.now(Z);return await Z`
358
+ )`,wakeJob:`UPDATE ${Y} SET available_at = ${Q}, updated_at = ${Q}
359
+ WHERE id = {id} AND status = 'pending' AND available_at > ${Q}`,jobStatus:`SELECT status FROM ${Y} WHERE id = {id}`,workflowStatus:`SELECT status FROM ${G} WHERE id = {id}`,park:`UPDATE ${Y}
360
+ SET status = 'pending', attempts = attempts - 1, available_at = ${Q} + ${B("ms")},
361
+ lease_expires_at = NULL, updated_at = ${Q}
362
+ WHERE id = {id} AND status = 'claimed' AND attempts = ${B("attempt")}`},F=new Map;return{table:$.slots,texts:J,compile(U,A){let N=F.get(U);if(!N){let P=[];N={text:J[U].replace(/\{([a-z]+)\}/g,(D,T)=>{if(Z==="postgres"){let _=P.indexOf(T);if(_===-1)_=P.push(T)-1;return`$${_+1}`}return P.push(T),"?"}),names:P},F.set(U,N)}return[N.text,N.names.map((P)=>{if(!(P in A))throw Error(`The slot statement ${U} needs {${P}}.`);return A[P]})]}}}function D1(){let[Z=0,$=0]=Bun.version.split(".").map(Number);return Z<1||Z===1&&$<4}function _1(Z){let $=Z;return $?.errno===1213||$?.code==="40P01"||/deadlock|try restarting transaction/i.test(String($?.message??""))}function L1(Z,$){let V=String(Z?.message??Z);if(!/does not exist|doesn't exist|no such table/i.test(V)||!V.includes($))return Z;return Error(`Concurrency limits on the database driver need the "${$}" table, and the database says it is missing. Add the GemiJobSlot model from the docs (docs/jobs-and-queues.md#concurrency-limits--concurrency) and migrate, or call the driver's createTable().`,{cause:Z})}var fZ=200,C1="Its batch was cancelled before it ran.";class $Z{table;batchTable;workflowTable;workflowStepTable;workflowItemTable;workflowSourceTable;slotTable;workflows;slotLines;sql;dialect;connection;busyTimeout;configured;sqliteTail=Promise.resolve();constructor(Z,$={}){let V=$.table??"gemi_jobs",z=$.batchTable??(V==="gemi_jobs"?"gemi_job_batches":`${V}_batches`),X=V==="gemi_jobs",Y=$.workflowTable??(X?"gemi_workflows":`${V}_workflows`),G=$.workflowStepTable??(X?"gemi_workflow_steps":`${V}_workflow_steps`),Q=$.workflowItemTable??(X?"gemi_workflow_items":`${V}_workflow_items`),B=$.workflowSourceTable??(X?"gemi_workflow_sources":`${V}_workflow_sources`),H=$.slotTable??(X?"gemi_job_slots":`${V}_slots`);for(let F of[V,H,z,Y,G,Q,B])if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(F))throw Error(`The queue table name "${F}" is not a plain identifier. Use letters, digits and underscores.`);let J=$.busyTimeout??1000;if(!Number.isInteger(J)||J<0)throw Error(`The queue's busyTimeout must be a whole number of milliseconds, 0 or more; got ${J}.`);this.table=V,this.batchTable=z,this.workflowTable=Y,this.workflowStepTable=G,this.workflowItemTable=Q,this.workflowSourceTable=B,this.slotTable=H,this.sql=Z.sql,this.dialect=Z.dialect,this.connection=Z.name,this.busyTimeout=J,x0(Z.sql,$.busyTimeout)}configure(){if(this.dialect!=="sqlite"||this.busyTimeout===0||v0(this.sql))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,...$]=W1(this.dialect,this.table);if(await this.sql.unsafe(Z),!await this.hasBatchColumns())for(let V of O1(this.dialect,this.table))await this.sql.unsafe(V);for(let V of $)await this.sql.unsafe(V);for(let V of E1(this.dialect,this.batchTable))await this.sql.unsafe(V);for(let V of xZ(this.dialect,this.workflowTable,this.workflowStepTable))await this.sql.unsafe(V);for(let V of gZ(this.dialect,this.workflowItemTable))await this.sql.unsafe(V);for(let V of hZ(this.dialect,this.workflowSourceTable))await this.sql.unsafe(V);for(let V of yZ(this.dialect,this.slotTable))await this.sql.unsafe(V)}async hasBatchColumns(){try{return await this.sql.unsafe(`SELECT batch_id, progress FROM ${this.quoted(this.table)} WHERE 1 = 0`),!0}catch(Z){if(kZ(Z))return!1;throw Z}}enqueue(Z){let $=this.transaction(),V=this.insert($??this.sql,Z);if($)O0(V);return V}async insert(Z,{name:$,args:V,delayMs:z=0,id:X=Bun.randomUUIDv7()}){await this.configure();let Y=this.now(Z);return await Z`
363
363
  INSERT INTO ${this.name(Z)}
364
364
  (id, name, payload, status, attempts, available_at, created_at, updated_at)
365
365
  VALUES
366
366
  (${X}, ${$}, ${V}, 'pending', 0, ${Y} + ${this.ms(Z,z)}, ${Y}, ${Y})
367
- `,X}lockStore(){return new C0({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=fZ();if(Z===void 0||bZ()!==this.connection)return;return Z}async claim(Z,$){let V=Math.max(0,Math.floor(Z));if(V===0)return[];return await this.configure(),(this.dialect==="mysql"||this.dialect==="mariadb"?await this.claimLocking(V,$):await this.claimUpdating(V,$)).map((X)=>({order:Number(X.available_at),job:{id:String(X.id),name:String(X.name),args:String(X.payload),attempt:Number(X.attempts),createdAt:Number(X.created_at),...X.batch_id==null?{}:{batchId:String(X.batch_id)}}})).sort((X,Y)=>X.order-Y.order||(X.job.id<Y.job.id?-1:1)).map(({job:X})=>X)}async complete(Z){if(Z.batchId!==void 0)return this.endBatchJob(Z,"succeeded");await this.configure();let $=this.sql;await $`
367
+ `,X}lockStore(){return new C0({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=qZ();if(Z===void 0||mZ()!==this.connection)return;return Z}async claim(Z,$){let V=Math.max(0,Math.floor(Z));if(V===0)return[];return await this.configure(),(this.dialect==="mysql"||this.dialect==="mariadb"?await this.claimLocking(V,$):await this.claimUpdating(V,$)).map((X)=>({order:Number(X.available_at),job:{id:String(X.id),name:String(X.name),args:String(X.payload),attempt:Number(X.attempts),createdAt:Number(X.created_at),...X.batch_id==null?{}:{batchId:String(X.batch_id)}}})).sort((X,Y)=>X.order-Y.order||(X.job.id<Y.job.id?-1:1)).map(({job:X})=>X)}async complete(Z){if(Z.batchId!==void 0)return this.endBatchJob(Z,"succeeded");await this.configure();let $=this.sql;await $`
368
368
  DELETE FROM ${this.name($)}
369
369
  WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
370
370
  `}async fail(Z,$){if(Z.batchId!==void 0)return this.endBatchJob(Z,"failed",$);await this.configure();let V=this.sql,z=this.now(V);if($.retryInMs===null){await V`
@@ -398,41 +398,41 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
398
398
  `;return U0(X)>0}async prune(Z){await this.configure();let $=this.sql,V=await $`
399
399
  DELETE FROM ${this.name($)}
400
400
  WHERE status = 'dead' AND updated_at <= ${this.now($)} - ${this.ms($,Z)}
401
- `;return U0(V)}enqueueBatch(Z){let $=this.transaction(),V=$?this.insertBatch($,Z):this.atomically((z)=>this.insertBatch(z,Z));if($)O0(V);return V}async insertBatch(Z,$){await this.configure();let V=await this.clock(Z),z=q0({...$,total:$.args.length,now:V}),{record:X,calls:Y}=F0(z,z,V);await o0(Z`
401
+ `;return U0(V)}enqueueBatch(Z){let $=this.transaction(),V=$?this.insertBatch($,Z):this.atomically((z)=>this.insertBatch(z,Z));if($)O0(V);return V}async insertBatch(Z,$){await this.configure();let V=await this.clock(Z),z=k0({...$,total:$.args.length,now:V}),{record:X,calls:Y}=F0(z,z,V);await ZZ(Z`
402
402
  INSERT INTO ${this.batches(Z)}
403
403
  (id, name, total, pending, succeeded, failed, cancelled, failed_job_ids, options,
404
404
  cancelled_at, finished_at, created_at, updated_at)
405
405
  VALUES
406
406
  (${X.id}, ${X.name}, ${X.total}, ${X.pending}, 0, 0, 0,
407
- '[]', ${O1(X)}, NULL, ${this.timeOrNull(Z,X.finishedAt)},
407
+ '[]', ${T1(X)}, NULL, ${this.timeOrNull(Z,X.finishedAt)},
408
408
  ${this.ms(Z,V)}, ${this.ms(Z,V)})
409
- `,this.batchTable);let G=this.ms(Z,V);for(let B=0;B<$.args.length;B+=hZ){let H=$.args.slice(B,B+hZ).map((Q)=>Z`(${Bun.randomUUIDv7()}, ${$.job}, ${Q}, 'pending', 0, ${G}, ${G}, ${G}, ${$.id}, 0)`).reduce((Q,J)=>Z`${Q}, ${J}`);await o0(Z`
409
+ `,this.batchTable);let G=this.ms(Z,V);for(let Q=0;Q<$.args.length;Q+=fZ){let B=$.args.slice(Q,Q+fZ).map((H)=>Z`(${Bun.randomUUIDv7()}, ${$.job}, ${H}, 'pending', 0, ${G}, ${G}, ${G}, ${$.id}, 0)`).reduce((H,J)=>Z`${H}, ${J}`);await ZZ(Z`
410
410
  INSERT INTO ${this.name(Z)}
411
411
  (id, name, payload, status, attempts, available_at, created_at, updated_at, batch_id, progress)
412
- VALUES ${H}
413
- `,this.table)}for(let B of Y)await this.insert(Z,B)}async findBatch(Z,$={}){await this.configure();let V=this.sql,[z]=await o0(V`SELECT * FROM ${this.batches(V)} WHERE id = ${Z}`,this.batchTable);if(!z)return null;let X=yZ(z);if($.progress===!1||X.pending===0)return G0(X);let[Y]=await V`
412
+ VALUES ${B}
413
+ `,this.table)}for(let Q of Y)await this.insert(Z,Q)}async findBatch(Z,$={}){await this.configure();let V=this.sql,[z]=await ZZ(V`SELECT * FROM ${this.batches(V)} WHERE id = ${Z}`,this.batchTable);if(!z)return null;let X=bZ(z);if($.progress===!1||X.pending===0)return G0(X);let[Y]=await V`
414
414
  SELECT COALESCE(SUM(progress), 0) AS running FROM ${this.name(V)}
415
415
  WHERE batch_id = ${Z} AND status IN ('pending', 'claimed')
416
- `;return G0(X,Number(Y?.running??0))}async cancelBatch(Z){return this.atomically(($)=>this.cancelBatchOn($,Z))}async cancelBatchOn(Z,$){let V=await this.lockBatch(Z,$);if(!V||V.finishedAt!==null||V.cancelledAt!==null)return!1;let z=await this.clock(Z),X=K0(V,z,await this.cancelWaiting(Z,$));return await this.saveBatch(Z,V,X,z),!0}workflowStore(){return this.workflows??=new r0({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,$)=>this.ms(Z,$),timeOrNull:(Z,$)=>this.timeOrNull(Z,$),fraction:(Z,$)=>this.fraction(Z,$),clock:(Z)=>this.clock(Z),insertJob:(Z,$)=>this.insert(Z,$),insertBatch:(Z,$)=>this.insertBatch(Z,$),cancelBatch:(Z,$)=>this.cancelBatchOn(Z,$),quoted:(Z)=>this.quoted(Z)},{table:this.workflowTable,stepTable:this.workflowStepTable,itemTable:this.workflowItemTable,sourceTable:this.workflowSourceTable}),this.workflows}acquireSlots(Z){return this.slots().acquire(Z)}releaseSlots(Z){return this.slots().release(Z)}slots(){return this.slotLines??=new t0({sql:this.sql,dialect:this.dialect,configure:()=>this.configure(),atomically:(Z)=>this.atomically(Z),insertJob:(Z,$)=>this.insert(Z,$)},{slots:this.slotTable,jobs:this.table,workflows:this.workflowTable}),this.slotLines}async reportProgress(Z,$){let V=i($);await this.configure();let z=this.sql;await z`
416
+ `;return G0(X,Number(Y?.running??0))}async cancelBatch(Z){return this.atomically(($)=>this.cancelBatchOn($,Z))}async cancelBatchOn(Z,$){let V=await this.lockBatch(Z,$);if(!V||V.finishedAt!==null||V.cancelledAt!==null)return!1;let z=await this.clock(Z),X=K0(V,z,await this.cancelWaiting(Z,$));return await this.saveBatch(Z,V,X,z),!0}workflowStore(){return this.workflows??=new o0({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,$)=>this.ms(Z,$),timeOrNull:(Z,$)=>this.timeOrNull(Z,$),fraction:(Z,$)=>this.fraction(Z,$),clock:(Z)=>this.clock(Z),insertJob:(Z,$)=>this.insert(Z,$),insertBatch:(Z,$)=>this.insertBatch(Z,$),cancelBatch:(Z,$)=>this.cancelBatchOn(Z,$),quoted:(Z)=>this.quoted(Z)},{table:this.workflowTable,stepTable:this.workflowStepTable,itemTable:this.workflowItemTable,sourceTable:this.workflowSourceTable}),this.workflows}acquireSlots(Z){return this.slots().acquire(Z)}releaseSlots(Z){return this.slots().release(Z)}slots(){return this.slotLines??=new e0({sql:this.sql,dialect:this.dialect,configure:()=>this.configure(),atomically:(Z)=>this.atomically(Z),insertJob:(Z,$)=>this.insert(Z,$)},{slots:this.slotTable,jobs:this.table,workflows:this.workflowTable}),this.slotLines}async reportProgress(Z,$){let V=i($);await this.configure();let z=this.sql;await z`
417
417
  UPDATE ${this.name(z)} SET progress = ${this.fraction(z,V)}
418
418
  WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
419
419
  `}async pruneBatches(Z){await this.configure();let $=this.sql,V=await $`
420
420
  DELETE FROM ${this.batches($)}
421
421
  WHERE finished_at IS NOT NULL AND finished_at <= ${this.now($)} - ${this.ms($,Z)}
422
- `;return U0(V)}endBatchJob(Z,$,V){let z=Z.batchId;return this.atomically(async(X)=>{let Y=await this.lockBatch(X,z),G=X`id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}`,B=this.now(X);if($==="succeeded"){let J=await X`DELETE FROM ${this.name(X)} WHERE ${G}`;if(U0(J)===0||!Y)return;return this.count(X,Y,"succeeded",Z.id)}let H=V.cancelled===!0||V.retryInMs!==null&&Y!==void 0&&Y.cancelledAt!==null;if(V.retryInMs!==null&&!H){await X`
422
+ `;return U0(V)}endBatchJob(Z,$,V){let z=Z.batchId;return this.atomically(async(X)=>{let Y=await this.lockBatch(X,z),G=X`id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}`,Q=this.now(X);if($==="succeeded"){let J=await X`DELETE FROM ${this.name(X)} WHERE ${G}`;if(U0(J)===0||!Y)return;return this.count(X,Y,"succeeded",Z.id)}let B=V.cancelled===!0||V.retryInMs!==null&&Y!==void 0&&Y.cancelledAt!==null;if(V.retryInMs!==null&&!B){await X`
423
423
  UPDATE ${this.name(X)}
424
- SET status = 'pending', available_at = ${B} + ${this.ms(X,V.retryInMs)},
424
+ SET status = 'pending', available_at = ${Q} + ${this.ms(X,V.retryInMs)},
425
425
  lease_expires_at = NULL, last_error = ${V.error}, progress = 0,
426
- updated_at = ${B}
426
+ updated_at = ${Q}
427
427
  WHERE ${G}
428
- `;return}let Q=await X`
428
+ `;return}let H=await X`
429
429
  UPDATE ${this.name(X)}
430
430
  SET status = 'dead', lease_expires_at = NULL, last_error = ${V.error},
431
- updated_at = ${B}
431
+ updated_at = ${Q}
432
432
  WHERE ${G}
433
- `;if(U0(Q)===0||!Y)return;return this.count(X,Y,H?"cancelled":"failed",Z.id)})}async count(Z,$,V,z){let X=await this.clock(Z),Y=m0($,V,z);if(k0($,Y))Y=K0(Y,X,await this.cancelWaiting(Z,$.id));await this.saveBatch(Z,$,Y,X)}async cancelWaiting(Z,$){let V=this.now(Z),z=await Z`
433
+ `;if(U0(H)===0||!Y)return;return this.count(X,Y,B?"cancelled":"failed",Z.id)})}async count(Z,$,V,z){let X=await this.clock(Z),Y=u0($,V,z);if(p0($,Y))Y=K0(Y,X,await this.cancelWaiting(Z,$.id));await this.saveBatch(Z,$,Y,X)}async cancelWaiting(Z,$){let V=this.now(Z),z=await Z`
434
434
  UPDATE ${this.name(Z)}
435
- SET status = 'dead', last_error = ${_1}, updated_at = ${V}
435
+ SET status = 'dead', last_error = ${C1}, updated_at = ${V}
436
436
  WHERE batch_id = ${$} AND status = 'pending'
437
437
  `;return U0(z)}async saveBatch(Z,$,V,z){let{record:X,calls:Y}=F0($,V,z);await Z`
438
438
  UPDATE ${this.batches(Z)}
@@ -441,7 +441,7 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
441
441
  cancelled_at = ${this.timeOrNull(Z,X.cancelledAt)},
442
442
  finished_at = ${this.timeOrNull(Z,X.finishedAt)}, updated_at = ${this.ms(Z,z)}
443
443
  WHERE id = ${X.id}
444
- `;for(let G of Y)await this.insert(Z,G)}async lockBatch(Z,$){let V;if(this.dialect==="sqlite")await Z`UPDATE ${this.batches(Z)} SET updated_at = updated_at WHERE id = ${$}`,V=await Z`SELECT * FROM ${this.batches(Z)} WHERE id = ${$}`;else V=await Z`SELECT * FROM ${this.batches(Z)} WHERE id = ${$} FOR UPDATE`;return V[0]?yZ(V[0]):void 0}atomically(Z){let $=async()=>{await this.configure();for(let z=0;;z++)try{return await this.sql.begin((X)=>Z(X))}catch(X){if(this.dialect!=="sqlite"||z>=50||!/within a transaction/i.test(String(X?.message??X)))throw X;await new Promise((Y)=>setTimeout(Y,20))}};if(this.dialect!=="sqlite")return $();let V=this.sqliteTail.then($,$);return this.sqliteTail=V.catch(()=>{}),V}async clock(Z){let[$]=await Z`SELECT ${this.now(Z)} AS now`;return Number($.now)}timeOrNull(Z,$){return $===null?Z`NULL`:this.ms(Z,$)}fraction(Z,$){return this.dialect==="postgres"?Z`CAST(${$} AS DOUBLE PRECISION)`:Z`${$}`}async claimUpdating(Z,$){let V=this.sql,z=this.now(V),X=this.ms(V,$.visibilityTimeoutMs),Y=this.name(V);if(this.dialect==="postgres")return await V`
444
+ `;for(let G of Y)await this.insert(Z,G)}async lockBatch(Z,$){let V;if(this.dialect==="sqlite")await Z`UPDATE ${this.batches(Z)} SET updated_at = updated_at WHERE id = ${$}`,V=await Z`SELECT * FROM ${this.batches(Z)} WHERE id = ${$}`;else V=await Z`SELECT * FROM ${this.batches(Z)} WHERE id = ${$} FOR UPDATE`;return V[0]?bZ(V[0]):void 0}atomically(Z){let $=async()=>{await this.configure();for(let z=0;;z++)try{return await this.sql.begin((X)=>Z(X))}catch(X){if(this.dialect!=="sqlite"||z>=50||!/within a transaction/i.test(String(X?.message??X)))throw X;await new Promise((Y)=>setTimeout(Y,20))}};if(this.dialect!=="sqlite")return $();let V=this.sqliteTail.then($,$);return this.sqliteTail=V.catch(()=>{}),V}async clock(Z){let[$]=await Z`SELECT ${this.now(Z)} AS now`;return Number($.now)}timeOrNull(Z,$){return $===null?Z`NULL`:this.ms(Z,$)}fraction(Z,$){return this.dialect==="postgres"?Z`CAST(${$} AS DOUBLE PRECISION)`:Z`${$}`}async claimUpdating(Z,$){let V=this.sql,z=this.now(V),X=this.ms(V,$.visibilityTimeoutMs),Y=this.name(V);if(this.dialect==="postgres")return await V`
445
445
  WITH next AS (
446
446
  SELECT id FROM ${Y}
447
447
  WHERE ${this.claimable(V,$)}
@@ -475,25 +475,25 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
475
475
  ORDER BY available_at, id
476
476
  LIMIT ${$}
477
477
  FOR UPDATE SKIP LOCKED
478
- `;if(G.length<$){let B=await z`
478
+ `;if(G.length<$){let Q=await z`
479
479
  SELECT ${Y} FROM ${X}
480
480
  WHERE status = 'claimed' AND lease_expires_at <= ${this.now(z)}
481
481
  AND ${this.runnable(z,V,"lease_expires_at")}
482
482
  ORDER BY lease_expires_at, id
483
483
  LIMIT ${$-G.length}
484
484
  FOR UPDATE SKIP LOCKED
485
- `;G.push(...B)}for(let B of G){let H=this.now(z);await z`
485
+ `;G.push(...Q)}for(let Q of G){let B=this.now(z);await z`
486
486
  UPDATE ${X}
487
- SET status = 'claimed', attempts = attempts + 1, claimed_at = ${H},
488
- lease_expires_at = ${H} + ${this.ms(z,V.visibilityTimeoutMs)},
489
- updated_at = ${H}
490
- WHERE id = ${B.id}
491
- `}return G.map((B)=>({...B,attempts:Number(B.attempts)+1}))})}claimable(Z,$){let V=this.now(Z);return Z`(
487
+ SET status = 'claimed', attempts = attempts + 1, claimed_at = ${B},
488
+ lease_expires_at = ${B} + ${this.ms(z,V.visibilityTimeoutMs)},
489
+ updated_at = ${B}
490
+ WHERE id = ${Q.id}
491
+ `}return G.map((Q)=>({...Q,attempts:Number(Q.attempts)+1}))})}claimable(Z,$){let V=this.now(Z);return Z`(
492
492
  (status = 'pending' AND available_at <= ${V}
493
493
  AND ${this.runnable(Z,$,"available_at")})
494
494
  OR (status = 'claimed' AND lease_expires_at <= ${V}
495
495
  AND ${this.runnable(Z,$,"lease_expires_at")})
496
- )`}runnable(Z,$,V){let z=$.registered;if(!z)return Z`1 = 1`;let X=z.names.length?Z`name IN (${z.names.map((G)=>Z`${G}`).reduce((G,B)=>Z`${G}, ${B}`)})`:Z`1 = 0`;if(!Number.isFinite(z.graceMs))return X;let Y=Z.unsafe(V);return Z`(${X} OR ${Y} <= ${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,$){let V=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?Z`CAST(${V} AS SIGNED)`:Z`CAST(${V} AS BIGINT)`}}function U0(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function L1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
496
+ )`}runnable(Z,$,V){let z=$.registered;if(!z)return Z`1 = 1`;let X=z.names.length?Z`name IN (${z.names.map((G)=>Z`${G}`).reduce((G,Q)=>Z`${G}, ${Q}`)})`:Z`1 = 0`;if(!Number.isFinite(z.graceMs))return X;let Y=Z.unsafe(V);return Z`(${X} OR ${Y} <= ${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,$){let V=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?Z`CAST(${V} AS SIGNED)`:Z`CAST(${V} AS BIGINT)`}}function U0(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function W1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
497
497
  \`id\` VARCHAR(191) NOT NULL,
498
498
  \`name\` VARCHAR(191) NOT NULL,
499
499
  \`payload\` LONGTEXT NOT NULL,
@@ -528,10 +528,10 @@ import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-psdcmh65.js";import{kl as
528
528
  "updated_at" BIGINT NOT NULL,
529
529
  "batch_id" TEXT,
530
530
  "progress" ${Z==="sqlite"?"REAL":"DOUBLE PRECISION"}${z}
531
- )`,`CREATE INDEX IF NOT EXISTS "${$}_status_available_at_idx" ON "${$}"("status", "available_at")`,`CREATE INDEX IF NOT EXISTS "${$}_status_lease_expires_at_idx" ON "${$}"("status", "lease_expires_at")`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`]}function C1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`ALTER TABLE \`${$}\` ADD COLUMN \`batch_id\` VARCHAR(191) NULL,
531
+ )`,`CREATE INDEX IF NOT EXISTS "${$}_status_available_at_idx" ON "${$}"("status", "available_at")`,`CREATE INDEX IF NOT EXISTS "${$}_status_lease_expires_at_idx" ON "${$}"("status", "lease_expires_at")`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`]}function O1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`ALTER TABLE \`${$}\` ADD COLUMN \`batch_id\` VARCHAR(191) NULL,
532
532
  ADD COLUMN \`progress\` DOUBLE NULL,
533
533
  ADD INDEX \`${$}_batch_id_idx\`(\`batch_id\`)`];let V=Z==="sqlite"?"REAL":"DOUBLE PRECISION";if(Z==="sqlite")return[`ALTER TABLE "${$}" ADD COLUMN "batch_id" TEXT`,`ALTER TABLE "${$}" ADD COLUMN "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`];return[`ALTER TABLE "${$}" ADD COLUMN IF NOT EXISTS "batch_id" TEXT,
534
- ADD COLUMN IF NOT EXISTS "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`]}function W1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
534
+ ADD COLUMN IF NOT EXISTS "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`]}function E1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
535
535
  \`id\` VARCHAR(191) NOT NULL,
536
536
  \`name\` VARCHAR(191) NULL,
537
537
  \`total\` INTEGER NOT NULL,
@@ -563,7 +563,7 @@ ADD COLUMN IF NOT EXISTS "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batc
563
563
  "finished_at" BIGINT,
564
564
  "created_at" BIGINT NOT NULL,
565
565
  "updated_at" BIGINT NOT NULL${z}
566
- )`]}function yZ(Z){let $=JSON.parse(Z.options),V=(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:V(Z.cancelled_at),finishedAt:V(Z.finished_at),createdAt:Number(Z.created_at),allowFailures:$.allowFailures===!0,callbacks:$.callbacks??{}}}function O1(Z){return JSON.stringify({allowFailures:Z.allowFailures,callbacks:Z.callbacks})}function qZ(Z){let $=String(Z?.message??Z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test($)}async function o0(Z,$){try{return await Z}catch(V){if(!qZ(V))throw V;throw Error(`Job batches need the "${$}" 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:V})}}function E3(Z){return Z}function mZ(){return{jobs:[],jobsDir:"app/jobs",workflows:[],workflowsDir:"app/workflows",concurrency:1,driver:"memory",visibilityTimeout:300000,pollInterval:1000,unknownJobGrace:3600000,locks:"auto"}}var E1=86400000;class ZZ{queue;workflows=new Map;steps=new Map;items=new Map;sources=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(E1);let $=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:$,updatedAt:$}),this.steps.set(Z.id,new Map),this.tick(Z.id,0)}async find(Z,$={}){let V=this.workflows.get(Z);if(!V)return null;return{workflow:{...V},steps:$.steps===!1?[]:this.stepsOf(Z)}}async acquire(Z,$,V){let z=this.workflows.get(Z);if(!z)return{kind:"missing"};let X=Date.now();if(z.lockedBy!==null&&!h0(z.lockedBy,$)&&(z.lockedUntil??0)>X)return z.retick=!0,{kind:"busy"};return z.lockedBy=$,z.lockedUntil=X+V,z.retick=!1,{kind:"acquired",workflow:{...z},steps:this.stepsOf(Z)}}async renew(Z,$,V){let z=this.workflows.get(Z);if(!z||z.lockedBy!==$)return!1;return z.lockedUntil=Date.now()+V,!0}statusOf(Z){return this.workflows.get(Z)?.status}async update(Z,$,V){let z=this.workflows.get(Z);if(!z)return;if($.owner!==void 0&&z.lockedBy!==$.owner)throw new b(Z);let X=this.steps.get(Z),Y=$.key===void 0?void 0:X.get($.key),G=Date.now(),B=V({workflow:{...z},step:Y?{...Y}:null,steps:$.allSteps?this.stepsOf(Z):[],items:$.items===void 0?[]:this.itemsOf(Z,$.items,["running","retrying"],-1,1/0),now:G});if(B.step){let H=X.get(B.step.key);X.set(B.step.key,{...B.step,createdAt:H?.createdAt??G,updatedAt:G})}if(B.items){let H=this.rowsOf(Z,B.items.step);for(let Q of B.items.delete??[])H.all.delete(Q),H.open.delete(Q);for(let Q of[...B.items.insert??[],...B.items.update??[]]){let J=H.all.get(Q.index);if(H.all.set(Q.index,{...Q,step:B.items.step,createdAt:J?.createdAt??G,updatedAt:G}),Q.status==="running"||Q.status==="retrying")H.open.add(Q.index);else H.open.delete(Q.index)}}if(B.batch)this.queue.enqueueBatch(B.batch);for(let H of B.cancelBatches??[])this.queue.cancelBatch(H);if(B.workflow)Object.assign(z,B.workflow);if(z.updatedAt=G,B.tick)this.tick(Z,B.tick.delayMs);if(B.unlock){if(z.lockedBy=null,z.lockedUntil=null,z.retick)z.retick=!1,this.tick(Z,0)}return B.result}async prune(Z){let $=Date.now()-Z,V=0;for(let[z,X]of this.workflows)if(["completed","failed","cancelled"].includes(X.status)&&X.updatedAt<=$){this.workflows.delete(z),this.steps.delete(z),this.items.delete(z);for(let[G,B]of this.sources)if(B.workflowId===z)this.sources.delete(G);V++}return V}async writeSource(Z,$,V){let z=this.sources.get(Z);if(!z)z={workflowId:$,createdAt:Date.now(),rows:new Map},this.sources.set(Z,z);for(let X of V){if(z.rows.has(X.index))throw Error(`Item source "${Z}" already has an item at index ${X.index}.`);z.rows.set(X.index,X.payload)}}async readSource(Z,$,V){let z=this.sources.get(Z)?.rows,X=[];if(!z)return X;for(let Y=Math.max(0,$);Y<V;Y++){let G=z.get(Y);if(G!==void 0)X.push({index:Y,payload:G})}return X}async deleteSource(Z){let $=this.sources.get(Z)?.rows.size??0;return this.sources.delete(Z),$}async pruneSources(Z){let $=Date.now()-Z,V=0;for(let[z,X]of this.sources)if(X.workflowId===null&&X.createdAt<=$)V+=X.rows.size,this.sources.delete(z);return V}async listItems(Z,$,V){return this.itemsOf(Z,$,V.statuses,V.after??-1,V.limit)}itemsOf(Z,$,V,z,X){let Y=this.items.get(Z)?.get($);if(!Y)return[];let B=V.every((Q)=>Q==="running"||Q==="retrying")?[...Y.open]:[...Y.all.keys()],H=[];for(let Q of B.sort((J,F)=>J-F)){if(Q<=z)continue;let J=Y.all.get(Q);if(!V.includes(J.status))continue;if(H.push({...J}),H.length>=X)break}return H}rowsOf(Z,$){let V=this.items.get(Z);if(!V)this.items.set(Z,V=new Map);let z=V.get($);if(!z)V.set($,z={all:new Map,open:new Set});return z}stepsOf(Z){return[...this.steps.get(Z)?.values()??[]].map(($)=>({...$}))}tick(Z,$){this.queue.enqueue({name:m,args:JSON.stringify([Z]),delayMs:Math.max(0,Math.round($))})}}function $Z(Z){return`workflow:${Z}`}var kZ=191;function u0(Z,$){if(Z===void 0||Z===null)return[];let V=Array.isArray(Z)?Z:[Z],z=new Set,X=[];for(let Y of V){if(Y===void 0||Y===null)continue;let{key:G,limit:B}=Y??{};if(typeof G!=="string"||G.length===0||G.length>kZ)throw TypeError(`${$}.concurrency returned a key that is not a string of 1 to ${kZ} characters: ${JSON.stringify(G)}.`);if(typeof B!=="number"||!Number.isInteger(B)||B<0)throw TypeError(`${$}.concurrency returned the limit ${String(B)} for "${G}"; a limit is a whole number, 0 or more.`);if(z.has(G))throw TypeError(`${$}.concurrency returned the key "${G}" twice.`);z.add(G),X.push({key:G,limit:B})}return X}class VZ{host;lines=new Map;keysOf=new Map;order=0;constructor(Z){this.host=Z}line(Z){let $=this.lines.get(Z),V=$?this.sorted($):[];return{holding:V.filter((z)=>z.state==="holding").map((z)=>z.holder),waiting:V.filter((z)=>z.state==="waiting").map((z)=>z.holder)}}acquire(Z){let $;for(let V of this.keysOf.get(Z.holder)??[]){let z=this.lines.get(V)?.tickets.get(Z.holder);if(z&&($===void 0||z.order<$))$=z.order}$??=this.order++;for(let{key:V,limit:z}of Z.slots){let X=this.lines.get(V)??{key:V,limit:z,tickets:new Map};this.lines.set(V,X),X.limit=z,this.prune(X);let Y=X.tickets.get(Z.holder);if(!Y){Y={holder:Z.holder,state:"waiting",order:$,jobId:Z.job.id,workflowId:Z.workflowId},X.tickets.set(Z.holder,Y);let H=this.keysOf.get(Z.holder)??new Set;H.add(V),this.keysOf.set(Z.holder,H)}Y.jobId=Z.job.id;let G=()=>this.holders(X)+this.ahead(X,Y)<z;if(Y.state==="waiting"&&!G())this.wake(X,Z.holder);if(Y.state==="waiting"&&G())Y.state="holding";if(Y.state==="holding"){this.wake(X,Z.holder);continue}let B=this.ahead(X,Y)<Math.max(1,z);return this.host.park(Z.job,B?Z.recheckMs.near:Z.recheckMs.far),!1}return!0}release(Z){let $=this.keysOf.get(Z);if(!$)return;this.keysOf.delete(Z);for(let V of $){let z=this.lines.get(V);if(!z)continue;if(z.tickets.delete(Z),this.prune(z),this.wake(z,Z),z.tickets.size===0)this.lines.delete(V)}}sorted(Z){return[...Z.tickets.values()].sort(($,V)=>$.order-V.order||($.holder<V.holder?-1:$.holder>V.holder?1:0))}holders(Z){let $=0;for(let V of Z.tickets.values())if(V.state==="holding")$++;return $}ahead(Z,$){let V=0;for(let z of Z.tickets.values()){if(z.state!=="waiting"||z===$)continue;if(z.order<$.order||z.order===$.order&&z.holder<$.holder)V++}return V}alive(Z){return Z.workflowId!==void 0?this.host.workflowAlive(Z.workflowId):this.host.jobAlive(Z.jobId)}prune(Z){for(let $ of Z.tickets.values())if($.state==="holding"&&!this.alive($))this.forget(Z,$)}wake(Z,$){let V=Z.limit-this.holders(Z);for(let z of this.sorted(Z)){if(V<=0)return;if(z.state!=="waiting"||z.holder===$)continue;if(!this.alive(z)){this.forget(Z,z);continue}if(!this.host.wake(z.jobId)){if(z.workflowId===void 0){this.forget(Z,z);continue}z.jobId=this.host.tick(z.workflowId)}V--}}forget(Z,$){Z.tickets.delete($.holder);let V=this.keysOf.get($.holder);if(V?.delete(Z.key),V?.size===0)this.keysOf.delete($.holder)}}var T1=86400000;class p0{entries=new Map;batches=new Map;workflows;slots=new VZ({jobAlive:(Z)=>this.entries.has(Z),workflowAlive:(Z)=>{let $=this.workflows?.statusOf(Z);return $!==void 0&&$!=="completed"&&$!=="failed"&&$!=="cancelled"&&$!=="paused"},park:(Z,$)=>{let V=this.current(Z);if(!V)return;V.job={...V.job,attempt:V.job.attempt-1},V.leased=!1,V.until=Date.now()+Math.max(0,$),this.changed()},wake:(Z)=>{let $=this.entries.get(Z);if(!$)return!1;if(!$.leased&&$.until>Date.now())$.until=Date.now(),this.changed();return!0},tick:(Z)=>{let $=this.add({name:m,args:JSON.stringify([Z])});return this.changed(),$}});listeners=new Set;timer;timerAt=1/0;seq=0;get waiting(){let Z=0;for(let $ of this.entries.values())if(!$.leased)Z++;return Z}get leased(){return this.entries.size-this.waiting}async enqueue(Z){let $=this.add(Z);return this.changed(),$}add({name:Z,args:$,delayMs:V=0,id:z=crypto.randomUUID()},X){let Y=Date.now();return this.entries.set(z,{job:{id:z,name:Z,args:$,attempt:0,createdAt:Y,...X===void 0?{}:{batchId:X}},until:Y+Math.max(0,V),leased:!1,seq:this.seq++,progress:0}),z}async enqueueBatch(Z){this.recordBatch(Z)}recordBatch(Z){let $=Date.now();this.forgetFinishedBatches($);let V=q0({...Z,total:Z.args.length,now:$});for(let Y of Z.args)this.add({name:Z.job,args:Y},Z.id);let{record:z,calls:X}=F0(V,V,$);this.batches.set(Z.id,z);for(let Y of X)this.add(Y);this.changed()}async findBatch(Z,$={}){let V=this.batches.get(Z);if(!V)return null;if($.progress===!1||V.pending===0)return G0(V);let z=0;for(let X of this.entries.values())if(X.job.batchId===Z)z+=X.progress;return G0(V,z)}async cancelBatch(Z){return this.cancelBatchNow(Z)}cancelBatchNow(Z){let $=this.batches.get(Z);if(!$||$.finishedAt!==null||$.cancelledAt!==null)return!1;let V=Date.now(),z=K0($,V,this.cancelWaiting(Z));return this.save($,z,V),this.changed(),!0}workflowStore(){return this.workflows??=new ZZ({enqueue:(Z)=>{this.add(Z),this.changed()},enqueueBatch:(Z)=>this.recordBatch(Z),cancelBatch:(Z)=>void this.cancelBatchNow(Z)}),this.workflows}async acquireSlots(Z){return this.slots.acquire(Z)}async releaseSlots(Z){this.slots.release(Z)}async reportProgress(Z,$){let V=this.current(Z);if(V)V.progress=i($)}async claim(Z,$){let V=Date.now(),z=[...this.entries.values()].filter((X)=>X.until<=V).sort((X,Y)=>X.until-Y.until||X.seq-Y.seq).slice(0,Math.max(0,Z));for(let X of z)X.job={...X.job,attempt:X.job.attempt+1},X.leased=!0,X.until=V+$.visibilityTimeoutMs;if(z.length>0)this.schedule();return z.map((X)=>({...X.job}))}async complete(Z){let $=this.current(Z);if(!$)return;this.entries.delete(Z.id),this.count($,"succeeded"),this.schedule()}async fail(Z,$){let V=this.current(Z);if(!V)return;let z=V.job.batchId===void 0?void 0:this.batches.get(V.job.batchId),X=$.cancelled===!0||$.retryInMs!==null&&z?.cancelledAt!=null;if($.retryInMs===null||X){this.entries.delete(Z.id),this.count(V,X?"cancelled":"failed"),this.schedule();return}V.leased=!1,V.until=Date.now()+Math.max(0,$.retryInMs),V.seq=this.seq++,V.progress=0,this.changed()}async release(Z,$){let V=this.current(Z);if(!V)return;V.job={...V.job,attempt:V.job.attempt-1},V.leased=!1,V.until=Date.now()+Math.max(0,$.retryInMs),V.seq=this.seq++,this.changed()}async heartbeat(Z,$){let V=Date.now()+$.visibilityTimeoutMs;for(let z of Z){let X=this.current(z);if(X)X.until=V}this.schedule()}count(Z,$){let V=Z.job.batchId;if(V===void 0)return;let z=this.batches.get(V);if(!z)return;let X=Date.now(),Y=m0(z,$,Z.job.id);if(k0(z,Y))Y=K0(Y,X,this.cancelWaiting(V));this.save(z,Y,X),this.changed()}save(Z,$,V){let{record:z,calls:X}=F0(Z,$,V);this.batches.set(z.id,z);for(let Y of X)this.add(Y)}cancelWaiting(Z){let $=0;for(let[V,z]of this.entries)if(z.job.batchId===Z&&!z.leased)this.entries.delete(V),$++;return $}forgetFinishedBatches(Z){for(let[$,V]of this.batches)if(V.finishedAt!==null&&Z-V.finishedAt>T1)this.batches.delete($)}subscribe(Z){return this.listeners.add(Z),()=>void this.listeners.delete(Z)}current(Z){let $=this.entries.get(Z.id);if(!$||!$.leased||$.job.attempt!==Z.attempt)return;return $}changed(){this.schedule();let Z=Date.now();for(let $ of this.entries.values())if($.until<=Z){this.wake();return}}wake(){for(let Z of[...this.listeners])Z()}schedule(){let Z=Date.now(),$=1/0;for(let V of this.entries.values())if(V.until>Z&&V.until<$)$=V.until;if($===this.timerAt)return;if(clearTimeout(this.timer),this.timer=void 0,this.timerAt=$,$===1/0)return;this.timer=setTimeout(()=>{this.timer=void 0,this.timerAt=1/0,this.changed()},$-Z),this.timer.unref?.()}}import{AsyncResource as d1}from"async_hooks";import{existsSync as l1}from"fs";import{isMainThread as a1}from"worker_threads";class Q0{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,$={}){this.$outcome={kind:"fail",error:Z instanceof Error?Z:Error(String(Z)),retry:$.retry??!0}}batch=void 0;async progress(Z){let $=i(Z);await this.$progress?.($)}$progress;$claimed;$outcome;run(...Z){}onFail(Z,...$){}onSuccess(Z,...$){}onDeadletter(Z,...$){}static dispatch(...Z){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return B0($0).push(this,JSON.stringify(Z))}static dispatchBatch(Z,$={}){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return B0($0).pushBatch(this,Z.map((V)=>JSON.stringify(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 B0($0).findBatch(Z)}static cancelBatch(Z){return B0($0).cancelBatch(Z)}}function E0(Z,$){let V=Array.isArray(Z)?Z[Math.min($,Z.length)-1]:Z;return Math.max(0,V??0)}class YZ extends Error{step;batch;summary;constructor(Z,$,V,z){super($);this.step=Z;this.batch=V;this.summary=z;this.name="StepFailedError"}}class GZ extends Error{step;constructor(Z){super(`No signal "${Z}" arrived before its timeout.`);this.step=Z;this.name="WaitTimeoutError"}}class BZ extends Error{constructor(Z,$){super(`Step "${Z}" took longer than its timeout of ${$}ms.`);this.name="StepTimeoutError"}}class QZ extends Error{constructor(Z){super(`Workflow ${Z} was cancelled.`);this.name="WorkflowCancelledError"}}class t extends Error{constructor(){super("The workflow is suspended until a step can continue. Rethrow this error if you catch it.");this.name="WorkflowSuspended"}}var uZ=Symbol("done"),pZ=Symbol("paused");class FZ{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(($)=>[$.key,$]))}run(Z,$,V={}){return this.track(Z,()=>this.runStep(Z,$,V))}sleep(Z,$){let V=r($);return this.track(Z,()=>this.sleepStep(Z,V))}waitFor(Z,$={}){let V=$.timeout===void 0?void 0:r($.timeout);return this.track(Z,()=>this.waitStep(Z,V))}batch(Z,$,V,z={}){return this.track(Z,()=>this.batchStep(Z,$,V,z))}each(Z,$,V){return this.track(Z,()=>this.eachStep(Z,$,V))}source(Z,$,V={}){let z=`${this.workflowId}:${Z}`;return this.run(Z,async()=>KZ(this.tick.store,z,await $(),this.workflowId),V)}async progress(Z){let $=i(Z);this.assertRunning();let V=this.write(void 0,()=>({result:void 0,workflow:{progress:$}}));this.remember(V),await V}async settled(){while(this.pending.size>0)await Promise.allSettled(this.pending)}track(Z,$){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 V=$();return this.remember(V),V}remember(Z){this.pending.add(Z);let $=()=>void this.pending.delete(Z);Z.then($,$)}assertRunning(){if(this.lost)throw new b(this.workflowId);if(this.suspension)throw new t}suspend(Z,$){if(!this.suspension)this.suspension={status:Z,wakes:[]};if($!=null)this.suspension.wakes.push($);throw new t}async write(Z,$,V={}){let z;try{z=await this.tick.store.update(this.tick.workflowId,{owner:this.tick.owner,...Z===void 0?{}:{key:Z},...V.items&&Z!==void 0?{items:Z}:{},...V.joinTransaction?{joinTransaction:!0}:{}},(X)=>{if(X.workflow.status==="cancelling"&&!this.tick.cancelling)return{result:uZ};if(V.start&&X.workflow.status==="paused"&&!this.tick.cancelling)return{result:pZ};let Y=$(X);return{...Y,result:{value:Y.result}}})}catch(X){if(X instanceof b)this.lost=!0;throw X}if(z===void 0)throw this.lost=!0,new b(this.tick.workflowId);if(z===uZ)this.cancelled=!0,this.suspend("waiting");if(z===pZ)this.suspend("paused");return z.value}record(Z,$,V){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};return this.steps.set(Z,z),z}mismatch(Z,$,V){throw Error(`Step "${Z}" of workflow ${this.tick.workflowId} was recorded as a ${$} step, and is now used as ${V}. A key belongs to one step; rename one of them.`)}async runStep(Z,$,V){let z=Math.max(1,Math.floor(V.attempts??3)),X=V.timeout===void 0?void 0:r(V.timeout),Y=this.steps.get(Z);if(Y?.status==="completed")return n(Y.output);if(Y?.status==="failed")throw s(Z,Y);if(Y?.status==="retrying"&&Y.wakeAt!==null&&Y.wakeAt>Date.now())this.current=Z,this.suspend("sleeping",Y.wakeAt);for(;;){let G=await this.write(Z,({workflow:N,step:P,now:W})=>{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>W)return{result:{kind:"wait",wakeAt:P.wakeAt}};let D=(P?.attempt??0)+1;if(D>z){let _=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:W,wakeAt:null});return{result:{kind:"failed",step:_},step:_}}let T=this.record(Z,P,{status:"running",attempt:D,startedAt:W,finishedAt:null,wakeAt:null});return{result:{kind:"run",attempt:D},step:T,workflow:N.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{start:!0});if(this.current=Z,G.kind==="done")return n(G.output);if(G.kind==="failed")throw s(Z,G.step);if(G.kind==="wait")this.suspend("sleeping",G.wakeAt);let B=G.attempt,H,Q,J=!0;try{H=await this.execute(Z,$,B,X)}catch(N){Q=N}if(this.cancelled)throw new t;let F=null;if(Q===void 0)try{F=S0(H,`The result of step "${Z}"`)}catch(N){Q=N,J=!1}if(Q===void 0)return await this.write(Z,({step:N,now:P})=>({result:void 0,step:this.record(Z,N,{status:"completed",output:F,error:null,wakeAt:null,finishedAt:P})})),n(F);let U=N0(Q);if(J&&B<z){let N=E0(V.backoff??0,B),P=await this.write(Z,({step:W,now:D})=>{let T=N>0?D+N:null;return{result:T,step:this.record(Z,W,{status:"retrying",error:U,wakeAt:T})}});if(P!==null)this.suspend("sleeping",P);continue}let A=await this.write(Z,({step:N,now:P})=>{let W=this.record(Z,N,{status:"failed",error:U,wakeAt:null,finishedAt:P});return{result:W,step:W}});throw s(Z,A)}}async execute(Z,$,V,z){let X=new AbortController,Y={idempotencyKey:`${this.tick.workflowId}:${Z}`,attempt:V,signal:X.signal},G=Promise.resolve().then(()=>$(Y)),B,H,Q=new Promise((J,F)=>{let U=(A)=>{X.abort(A),F(A)};if(z!==void 0)B=setTimeout(()=>U(new BZ(Z,z)),z);if(!this.tick.cancelling)H=setInterval(()=>{this.tick.store.find(this.tick.workflowId,{steps:!1}).then((A)=>{if(A?.workflow.status!=="cancelling"||X.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};U(new QZ(this.tick.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs),H.unref?.()});try{return await Promise.race([G,Q])}finally{clearTimeout(B),clearInterval(H),G.catch(()=>{}),Q.catch(()=>{})}}async sleepStep(Z,$){let V=this.steps.get(Z);if(V?.status==="completed")return;if(this.current=Z,V?.status==="sleeping"&&V.wakeAt!==null&&V.wakeAt>Date.now())this.suspend("sleeping",V.wakeAt);let z=await this.write(Z,({step:X,now:Y})=>{if(X?.status==="completed")return{result:null};if(X&&X.status!=="sleeping")this.mismatch(Z,X.status,"step.sleep");let G=X?.wakeAt??Y+$;if(G<=Y)return{result:null,step:this.record(Z,X,{status:"completed",wakeAt:G,startedAt:X?.startedAt??Y,finishedAt:Y})};if(X)return{result:G};return{result:G,step:this.record(Z,null,{status:"sleeping",wakeAt:G,startedAt:Y}),workflow:{currentStep:Z}}});if(z!==null)this.suspend("sleeping",z)}async waitStep(Z,$){let V=this.steps.get(Z);if(V?.status==="completed")return n(V.output);if(V?.status==="timed_out")throw new GZ(Z);if(this.current=Z,V?.status==="waiting"&&(V.wakeAt===null||V.wakeAt>Date.now()))this.suspend("waiting",V.wakeAt);let z=await this.write(Z,({step:X,now:Y})=>{if(X?.status==="completed")return{result:{kind:"value",output:X.output}};if(X?.status==="timed_out")return{result:{kind:"timeout"}};if(X?.status==="signalled")return{result:{kind:"value",output:X.output},step:this.record(Z,X,{status:"completed",wakeAt:null,startedAt:X.startedAt??Y,finishedAt:Y})};if(X&&X.status!=="waiting")this.mismatch(Z,X.status,"step.waitFor");if(X){if(X.wakeAt!==null&&X.wakeAt<=Y)return{result:{kind:"timeout"},step:this.record(Z,X,{status:"timed_out",finishedAt:Y})};return{result:{kind:"wait",wakeAt:X.wakeAt}}}let G=$===void 0?null:Y+$;return{result:{kind:"wait",wakeAt:G},step:this.record(Z,null,{status:"waiting",wakeAt:G,startedAt:Y}),workflow:{currentStep:Z}}});if(z.kind==="value")return n(z.output);if(z.kind==="timeout")throw new GZ(Z);this.suspend("waiting",z.wakeAt)}async eachStep(Z,$,V){let z=$.source,X=z?z.count:$.count;if(!z&&typeof $.item!=="function")throw TypeError(`step.each "${Z}" needs either { count, item } or { source }.`);if(!Number.isSafeInteger(X)||X<0||X>cZ)throw TypeError(`step.each "${Z}" needs a count that is a whole number from 0 to ${cZ}; got ${String(X)}.`);let Y=Math.max(1,Math.floor($.concurrency??1)),G=Math.max(1,Math.floor($.attempts??3)),B=$.timeout===void 0?void 0:r($.timeout),H=$.tickBudget===void 0?S1:r($.tickBudget),Q=$.progress!==!1,J=$.chunk!==void 0,F=J?Math.max(1,Math.floor($.chunk)):1,U=[$.throttle??[]].flat().map((K)=>({name:`gemi:throttle:${K.key}`,limit:Math.max(0,Math.floor(K.limit)),windowMs:r(K.window)})),A=j1($.maxFailures),N=this.tick.store,P=$.transaction===!0&&N.transaction?(K)=>N.transaction(K):void 0;if($.transaction===!0&&!P)f1();let W=z?nZ(N,z,Math.max(M1,Y*F*4)):$.item;if(!N.listItems)throw Error("This queue's workflow store does not support step.each. The memory and database drivers do.");if(U.length>0&&!this.tick.throttle)throw Error(`step.each "${Z}" has a throttle, and this queue has no lock store.`);let D=this.steps.get(Z);if(D?.status==="completed")return PZ(D.output);if(D?.status==="failed")throw s(Z,D);if(D&&D.status!=="iterating")this.mismatch(Z,D.status,"step.each");if(this.current=Z,this.tick.durable===!1)y1();let T=await this.write(Z,({workflow:K,step:R,items:L,now:O})=>{if(R?.status==="completed")return{result:{kind:"done",output:R.output}};if(R?.status==="failed")return{result:{kind:"failed",step:R}};if(R&&R.status!=="iterating")this.mismatch(Z,R.status,"step.each");let x=R?c0(R.output):v1(X);return{result:{kind:"go",state:x,open:L},...R?{}:{step:this.record(Z,null,{status:"iterating",output:XZ(x),startedAt:O})},workflow:K.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{items:!0,start:!0});if(T.kind==="done")return PZ(T.output);if(T.kind==="failed")throw s(Z,T.step);let _=T.state;if(_.count!==X)b1(this.workflowId,Z,_.count,X);let D0=_.count,d=new Map(T.open.map((K)=>[K.index,K])),k=[],_0=new Map,a0=new Map,_Z=Date.now()+H,H0=0,M0=!1,V0=null,p=new AbortController,LZ=setInterval(()=>{N.find(this.workflowId,{steps:!1}).then((K)=>{if(K?.workflow.status==="paused")M0=!0;if(K?.workflow.status!=="cancelling"||p.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};p.abort(new QZ(this.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs);LZ.unref?.(),V0=A(_);let CZ=(K,R)=>{let L={...K};for(let O of R)if(O.counter)L[O.counter]++;return L},WZ=(K)=>{let R=K.succeeded+K.skipped+K.failed;return Q?{workflow:{progress:D0===0?1:i(R/D0)}}:{}},OZ=(K)=>{if(_={count:_.count,next:Math.max(_.next,K.next),succeeded:Math.max(_.succeeded,K.succeeded),skipped:Math.max(_.skipped,K.skipped),failed:Math.max(_.failed,K.failed)},!V0)V0=A(_);if(V0&&!p.signal.aborted)p.abort(new t)},X1=async(K)=>{let R=K.map(()=>null),L=new Map,O=new AbortController,x=()=>O.abort(p.signal.reason);p.signal.addEventListener("abort",x,{once:!0});let u,z0=K.length===1?`${Z}[${K[0].index}]`:`${Z}[${K[0].index}..${K.at(-1).index}]`,L0=new Promise((C,S)=>{if(O.signal.addEventListener("abort",()=>S(O.signal.reason),{once:!0}),B!==void 0)u=setTimeout(()=>O.abort(new BZ(z0,B)),B)}),y=(C)=>{throw new JZ(Math.max(0,Math.floor(Number(C)||0)))},X0=(C)=>K.map((S,q)=>{let l=L.get(q);if(!l)return{index:S.index,row:null,counter:"succeeded"};return{index:S.index,row:dZ(S,R[q],l.reason,l.data,C),counter:"skipped"}}),Y0=null,g=(async()=>{let C=await Promise.all(K.map((M)=>W(M.index)));K.forEach((M,v)=>{R[v]=g1($.key?$.key(C[v],M.index):M.index)});let S=(M)=>`${this.workflowId}:${Z}:${R[M]}`,q=Math.max(...K.map((M)=>M.attempt)),l=async()=>{if(J){let M={idempotencyKey:S(0),attempt:q,signal:O.signal,items:K.map((v,f)=>({index:v.index,key:R[f],idempotencyKey:S(f)})),skip:(v,f,I)=>{if(!Number.isInteger(v)||v<0||v>=K.length)throw RangeError(`ctx.skip: no item at position ${v} of this chunk.`);L.set(v,{reason:String(f),data:I})},release:y};await V(C,M)}else{let M={idempotencyKey:S(0),attempt:q,signal:O.signal,index:K[0].index,key:R[0],skip:(v,f)=>{throw new HZ(v,f)},release:y};await V(C[0],M)}};if(!P)return l();await P(async()=>{if(await l(),O.signal.aborted)throw O.signal.reason;let M=X0(Date.now()),v=await this.write(Z,({step:f})=>{let I={step:Z,insert:[],update:[],delete:[]};for(let J0 of M)if(J0.row===null)I.delete.push(J0.index);else I.update.push(J0.row);let a=CZ(f?c0(f.output):_,M);return{result:a,step:this.record(Z,f,{status:"iterating",output:XZ(a)}),items:I,...WZ(a)}},{joinTransaction:!0});Y0=M.map((f)=>({...f,recorded:!0})),OZ(v)})})(),j,E=!1;try{await Promise.race([g,L0])}catch(C){E=!0,j=C}finally{clearTimeout(u),p.signal.removeEventListener("abort",x),g.catch(()=>{}),L0.catch(()=>{})}if(Y0){k.push(...Y0);return}if(p.signal.aborted||this.cancelled||this.lost)return;let h=Date.now();if(!E){k.push(...X0(h));return}if(j instanceof HZ){k.push({index:K[0].index,row:dZ(K[0],R[0],j.reason,j.data,h),counter:"skipped"});return}if(j instanceof JZ){H0=Math.max(H0,h+j.delayMs),K.forEach((C,S)=>{k.push({index:C.index,row:{...C,key:R[S],status:"retrying",attempt:Math.max(0,C.attempt-1),wakeAt:h+j.delayMs},counter:null})});return}let c=T0(N0(j),2000);K.forEach((C,S)=>{if(C.attempt<G){let q=E0($.backoff??0,C.attempt);k.push({index:C.index,row:{...C,key:R[S],status:"retrying",error:c,wakeAt:h+q},counter:null});return}k.push({index:C.index,row:{...C,key:R[S],status:"failed",error:c,wakeAt:null,finishedAt:h},counter:"failed"})})},Y1=async(K)=>{if(U.length===0||K===0)return K;let R=this.tick.throttle;for(let L=0;L<K;L++){let O=[];for(let x of U){let u=await R.hit(x.name,x.limit,x.windowMs);if(!u.allowed)return await Promise.all(O.map((z0)=>R.refund(z0))),H0=Math.max(H0,Date.now()+Math.max(1,u.resetInMs)),L;O.push(x.name)}}return K},G1=async(K)=>{if(U.length===0)return;for(let R=0;R<K;R++)for(let L of U)await this.tick.throttle.refund(L.name)};try{for(;;){let K=Date.now(),R=K>=_Z||w0()||this.cancelled||M0||V0!==null,L=[],O=0;if(!R&&K>=H0){let y=(Y-_0.size)*F,X0=new Set(k.map((j)=>j.index));for(let j of[...d.values()].sort((E,h)=>E.index-h.index)){if(L.length>=y)break;if(a0.has(j.index)||X0.has(j.index))continue;if(j.status==="running"||(j.wakeAt??0)<=K)L.push(j)}let Y0=Y*F+wZ-d.size;O=Math.max(0,Math.min(y-L.length,D0-_.next,Y0));let g=await Y1(L.length+O);if(g<L.length)L=L.slice(0,g),O=0;else O=g-L.length}if(k.length>0||L.length>0||O>0){let y=k.splice(0,k.length),X0=y.filter((E)=>!E.recorded),Y0=L.length+O,g=await this.write(Z,({workflow:E,step:h,now:c})=>{let C=CZ(h?c0(h.output):_,X0),S={step:Z,insert:[],update:[],delete:[]},q=[],l=[];for(let I of X0)if(I.row===null)S.delete.push(I.index);else S.update.push(I.row);let M=E.status==="paused"&&!this.tick.cancelling;for(let I of M?[]:L){if(I.attempt+1>G){let J0={...I,status:"failed",error:T0(`Attempt ${I.attempt} of ${G} never finished, most likely because the process running it exited.`+(I.error?` The last error was: ${I.error}`:""),2000),wakeAt:null,finishedAt:c};C.failed++,S.update.push(J0),l.push(J0);continue}let a={...I,status:"running",attempt:I.attempt+1,wakeAt:null,startedAt:c};S.update.push(a),q.push(a)}let v=M?0:O,f=q.length;for(let I=0;I<v;I++){let a=x1(this.workflowId,Z,C.next+I,c);S.insert.push(a),q.push(a)}return C.next+=v,{result:{next:C,started:q,closed:l,reruns:f,paused:M},step:this.record(Z,h,{status:"iterating",output:XZ(C)}),items:S,...WZ(C)}});if(OZ(g.next),g.paused)M0=!0;await G1(Y0-g.started.length);for(let E of y)if(E.row?.status==="retrying")d.set(E.index,E.row);else d.delete(E.index);for(let E of g.closed)d.delete(E.index);for(let E of g.started)d.set(E.index,E);let j=[...lZ(g.started.slice(0,g.reruns),F),...lZ(g.started.slice(g.reruns),F)];for(let E of j){let h=E[0].index;for(let c of E)a0.set(c.index,h);_0.set(h,X1(E).finally(()=>{_0.delete(h);for(let c of E)a0.delete(c.index)}))}}if(_0.size>0){await Promise.race(_0.values());continue}if(k.length>0)continue;if(this.cancelled)throw new t;if(V0)break;if(_.next>=D0&&d.size===0)break;if(M0)this.suspend("paused");if(R)this.suspend("running",Date.now());let x=Date.now(),u=1/0;if(_.next<D0&&d.size<Y*F+wZ)u=x;for(let y of d.values())if(y.status==="running")u=x;else if(y.status==="retrying")u=Math.min(u,y.wakeAt??0);let z0=Math.max(u,H0);if(z0<=x)continue;let L0=z0-x;if(L0<=Math.min(I1,_Z-x)){await new Promise((y)=>setTimeout(y,Math.max(0,L0)));continue}this.suspend("sleeping",z0)}}finally{if(clearInterval(LZ),!p.signal.aborted)p.abort(new t)}let EZ=await N.listItems(this.workflowId,Z,{statuses:["failed","skipped"],limit:zZ+1}),i0={...UZ(_),problems:EZ.slice(0,zZ).map(NZ),moreProblems:EZ.length>zZ},B1=JSON.stringify({$each:_,problems:i0.problems,moreProblems:i0.moreProblems}),j0=V0,Q1=await this.write(Z,({step:K,now:R})=>{let L=this.record(Z,K,{status:j0?"failed":"completed",output:B1,error:j0,finishedAt:R});return{result:L,step:L,...Q&&!j0?{workflow:{progress:1}}:{}}});if(j0)throw s(Z,Q1);return i0}async batchStep(Z,$,V,z){let X=z.allowFailures===!0,Y=this.steps.get(Z);if(Y?.status==="completed")return n(Y.output);if(Y?.status==="failed")throw s(Z,Y);if(Y&&Y.status!=="batching")this.mismatch(Z,Y.status,"step.batch");if(this.current=Z,!Y){let F=this.tick.buildBatch($,V,{name:z.name??`workflow:${this.tick.workflowId}:${Z}`,allowFailures:X});if(Y=await this.write(Z,({step:U,now:A})=>{if(U)return{result:U};let N=this.record(Z,null,{status:"batching",batchId:F.id,startedAt:A});return{result:N,step:N,batch:F,workflow:{currentStep:Z}}},{start:!0}),this.tick.scheduled(),Y.status==="completed")return n(Y.output);if(Y.status==="failed")throw s(Z,Y)}let G=Y.batchId===null?null:await this.tick.findBatch(Y.batchId);if(G&&G.finishedAt===null)this.suspend("waiting");let B=G!==null&&G.cancelledAt===null&&(G.failed===0||X),H=G===null?null:JSON.stringify(G),Q=B?null:G===null?`The batch of step "${Z}" (${Y.batchId}) no longer exists.`:`The batch of step "${Z}" failed: ${G.failed} failed and ${G.cancelled} cancelled of ${G.total}.`,J=await this.write(Z,({step:F,now:U})=>{let A=this.record(Z,F,{status:B?"completed":"failed",output:H,error:Q,finishedAt:U});return{result:A,step:A}});if(!B)throw s(Z,J);return G}}function s(Z,$){if($.output?.startsWith('{"$each"'))return new YZ(Z,`Step "${Z}" failed: ${$.error??"unknown error"}`,void 0,PZ($.output));let V=$.batchId!==null&&$.output!==null?JSON.parse($.output):void 0;return new YZ(Z,V?$.error??`Step "${Z}" failed.`:`Step "${Z}" failed: ${$.error??"unknown error"}`,V)}function S0(Z,$){if(Z===void 0)return null;let V=JSON.stringify(Z);if(V===void 0)throw TypeError(`${$} cannot be stored: JSON has no form for it.`);let z=Buffer.byteLength(V,"utf8");if(z>n0)throw RangeError(`${$} is ${z} bytes as JSON, over the ${n0}-byte limit. Store it elsewhere and return its id.`);return V}function n(Z){return Z===null?void 0:JSON.parse(Z)}function N0(Z){return Z instanceof Error?Z.message:String(Z)}var cZ=2147483647,S1=30000,wZ=100,I1=1000,M1=64,zZ=100;class HZ extends Error{reason;data;constructor(Z,$){super(`Skipped: ${Z}`);this.reason=Z;this.data=$;this.name="ItemSkipped"}}class JZ extends Error{delayMs;constructor(Z){super(`Released for ${Z}ms`);this.delayMs=Z;this.name="ItemReleased"}}function dZ(Z,$,V,z,X){let Y=null,G=T0(String(V));try{Y=h1(z)}catch(B){G=T0(`${G} (${N0(B)})`)}return{...Z,key:$,status:"skipped",error:G,output:Y,wakeAt:null,finishedAt:X}}function lZ(Z,$){let V=[];for(let z=0;z<Z.length;z+=$)V.push(Z.slice(z,z+$));return V}function j1(Z){if(Z===void 0)return()=>null;if(typeof Z==="number"){let z=Math.max(0,Math.floor(Z));return(X)=>X.failed>z?`${X.failed} items failed, more than maxFailures (${z}).`:null}let $=Math.min(1,Math.max(0,Z.ratio)),V=Math.max(1,Math.floor(Z.after??20));return(z)=>{let X=z.succeeded+z.skipped+z.failed;if(X<V||z.failed/X<=$)return null;return`${z.failed} of ${X} items failed, more than maxFailures allows (a ratio of ${$}).`}}function v1(Z){return{count:Z,next:0,succeeded:0,skipped:0,failed:0}}function XZ(Z){return JSON.stringify({$each:Z})}function c0(Z){let $=Z===null?null:JSON.parse(Z);if(!$?.$each)throw Error("A step.each step has no state.");return $.$each}function rZ(Z){if(Z===null||!Z.startsWith('{"$each"'))return null;try{return UZ(c0(Z))}catch{return null}}function UZ(Z){return{total:Z.count,done:Z.succeeded+Z.skipped+Z.failed,succeeded:Z.succeeded,skipped:Z.skipped,failed:Z.failed}}function PZ(Z){let $=JSON.parse(Z??"null");return{...UZ($.$each),problems:$.problems??[],moreProblems:$.moreProblems===!0}}function NZ(Z){let $={index:Z.index,key:Z.key,status:Z.status==="skipped"?"skipped":"failed",reason:T0(Z.error??""),attempt:Z.attempt};if(Z.output!==null)$.data=JSON.parse(Z.output);return $}function x1(Z,$,V,z){return{workflowId:Z,step:$,index:V,key:null,status:"running",attempt:1,error:null,output:null,wakeAt:null,startedAt:z,finishedAt:null,createdAt:z,updatedAt:z}}function g1(Z){let $=typeof Z==="number"&&Number.isFinite(Z)?String(Z):Z;if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError(`An item key is a string of 1 to 191 characters, or a number; got ${JSON.stringify(Z)}.`);return $}function T0(Z,$=500){return Z.length<=$?Z:`${Z.slice(0,$-1)}\u2026`}function h1(Z){if(Z===void 0)return null;let $=JSON.stringify(Z);if($===void 0)throw TypeError("its data has no JSON form, so it was not kept");if(Buffer.byteLength($,"utf8")>1024)throw RangeError("its data is over 1 KB as JSON, so it was not kept");return $}var aZ=!1;function y1(){if(aZ||Bun.env.NODE_ENV!=="production")return;aZ=!0,console.warn("[gemi] step.each is running on a queue whose driver keeps nothing across restarts (the memory driver), so a deploy or a crash loses the workflow and the rest of its list. Use the database driver for work that must finish.")}var iZ=!1;function f1(){if(iZ)return;iZ=!0,console.warn("[gemi] step.each with transaction: true runs its items without a transaction: this queue's workflow store cannot record an item in the app's transaction (only the database driver on Postgres or MySQL can). Items are at least once.")}var sZ=new Set;function b1(Z,$,V,z){let X=`${Z}:${$}`;if(sZ.has(X))return;sZ.add(X),console.warn(`[gemi] step.each "${$}" of workflow ${Z} was started with a count of ${V} and is now given ${z}. It goes on with ${V}: the count is fixed when the step first runs.`)}function d0(Z){return Z==="completed"||Z==="failed"||Z==="cancelled"}var R0=["completed","failed","cancelled"],q1=1000,m1=250,k1=30000;class RZ{queue;registry={};storeInstance;ownFeed;publishing=new Map;published=new Map;tickClass;reportedNames=new Set;constructor(Z){this.queue=Z}get workflows(){return this.registry}use(Z){this.registry={};for(let $ of Z){if($.name==="unset"||!$.name){console.error("A workflow class has no `static name`, so it was not registered. Add one.");continue}if(this.registry[$.name]){console.error(`Two workflows are named "${$.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[$.name]=$}}get tickJob(){return this.tickClass??=u1(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=this.publishingStore(Z)}return this.storeInstance}get feed(){let Z=this.queue.boundApplication;if(Z?.bound(l0))return Z.make(l0);return this.ownFeed??=new l0,this.ownFeed}channel(Z){return`gemi:workflow:${Z}`}async update(Z){let $=await this.find(Z);if(!$)return null;let{args:V,result:z,...X}=$;return X}stream(Z,$,V={}){return this.feed.stream(Z,this.channel($),V)}cursor(Z){return this.feed.cursor(this.channel(Z))}async*subscribe(Z,$={}){let V=this.feed.subscribe(this.channel(Z),{signal:$.signal});try{await V.ready();let z=await this.update(Z);if(!z)return;if(yield z,d0(z.status))return;let X=V[Symbol.asyncIterator](),Y=X.next();for(;;){let G=await w1(Y,k1),B;if(G==="timeout")B=await this.update(Z);else{if(G.done)return;Y=X.next(),B=c1(G.value,Z)??await this.update(Z)}if(!B||B.updatedAt<z.updatedAt)continue;if(JSON.stringify(B)===JSON.stringify(z))continue;if(z=B,yield z,d0(z.status))return}}finally{V.close()}}publishingStore(Z){let $=(z)=>void tZ(()=>this.schedulePublish(z)),V={create:(z)=>Z.create(z).then((X)=>{return $(z.id),X}),find:(z,X)=>Z.find(z,X),acquire:(z,X,Y)=>Z.acquire(z,X,Y),renew:(z,X,Y)=>Z.renew(z,X,Y),update:(z,X,Y)=>Z.update(z,X,Y).then((G)=>{return $(z),G})};if(Z.joinsTransaction)V.joinsTransaction=()=>Z.joinsTransaction();if(Z.transaction)V.transaction=(z)=>Z.transaction(z);if(Z.listItems)V.listItems=(...z)=>Z.listItems(...z);if(Z.prune)V.prune=(z)=>Z.prune(z);if(Z.writeSource)V.writeSource=(...z)=>Z.writeSource(...z),V.readSource=(...z)=>Z.readSource(...z),V.deleteSource=(...z)=>Z.deleteSource(...z),V.pruneSources=(...z)=>Z.pruneSources(...z);return V}schedulePublish(Z){if(this.publishing.has(Z))return;let $=Math.max(0,(this.published.get(Z)??0)+m1-Date.now()),V=setTimeout(()=>{this.publishing.delete(Z),this.published.set(Z,Date.now()),this.publish(Z)},$);V.unref?.(),this.publishing.set(Z,V)}async publish(Z){try{let $=await this.update(Z);if(!$)return;if(d0($.status))this.published.delete(Z);await this.feed.publish(this.channel(Z),$)}catch($){console.error(`[gemi] Workflow ${Z}: could not publish its change.`,$)}}async close(){for(let Z of this.publishing.values())clearTimeout(Z);this.publishing.clear(),await this.ownFeed?.close(),this.ownFeed=void 0}start(Z,$){if(Z.name==="unset"||!Z.name)throw Error("Cannot start a workflow with no name");let V=this.store,z={id:Bun.randomUUIDv7(),name:Z.name,args:S0($,`The arguments of ${Z.name}`)??"[]"},X=()=>this.queue.claimSoon(),Y=V.joinsTransaction?.()===!0;if(!Y){if(o(()=>V.create(z).then(X,(Q)=>{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.`,Q)})))return Promise.resolve(z.id)}let G=V.create(z),B=Y&&o(X);return G.then(()=>{if(!B)X();return z.id})}async signal(Z,$,V){if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError("A signal key is a string of 1 to 191 characters.");let z=S0(V,`The payload of signal "${$}"`),X=await this.store.update(Z,{key:$},({workflow:Y,step:G,now:B})=>{if(R0.includes(Y.status)||Y.status==="cancelling")return{result:!1};if(!G)return{result:!0,step:{workflowId:Z,key:$,status:"signalled",attempt:0,output:z,error:null,batchId:null,wakeAt:null,startedAt:null,finishedAt:B,createdAt:B,updatedAt:B}};if(G.status!=="waiting")return{result:!1};return{result:!0,step:{...G,status:"signalled",output:z,wakeAt:G.wakeAt,finishedAt:B},tick:{delayMs:0}}});if(X)this.queue.claimSoon();return X===!0}async cancel(Z){let $=await this.store.update(Z,{allSteps:!0},({workflow:V,steps:z})=>{if(R0.includes(V.status)||V.status==="cancelling")return{result:!1};return{result:!0,workflow:{status:"cancelling"},cancelBatches:z.filter((X)=>X.status==="batching"&&X.batchId!==null).map((X)=>X.batchId),tick:{delayMs:0}}});if($)this.queue.claimSoon();return $===!0}async pause(Z){let $=await this.store.update(Z,{},({workflow:V})=>{if(R0.includes(V.status)||V.status==="cancelling"||V.status==="paused")return{result:!1};return{result:!0,workflow:{status:"paused"}}});if($===!0)this.releaseSlotsOf(Z);return $===!0}async resume(Z){let $=await this.store.update(Z,{},({workflow:V})=>{if(V.status!=="paused")return{result:!1};return{result:!0,workflow:{status:"running",wakeAt:null},tick:{delayMs:0}}});if($)this.queue.claimSoon();return $===!0}async find(Z){let $=await this.store.find(Z);if(!$)return null;let{workflow:V,steps:z}=$,X=[];try{X=JSON.parse(V.args)}catch{}return{id:V.id,name:V.name,status:V.status,args:X,currentStep:V.currentStep,progress:V.progress,result:p1(V.result),error:V.error,steps:await Promise.all(z.map(async(Y)=>{let G={key:Y.key,status:Y.status,attempt:Y.attempt,error:Y.error,batchId:Y.batchId,wakeAt:Y.wakeAt,startedAt:Y.startedAt,finishedAt:Y.finishedAt},B=rZ(Y.output);if(B)return{...G,items:B,progress:B.total===0?1:B.done/B.total};if(Y.batchId===null)return G;let H=await this.queue.driver.findBatch?.(Y.batchId);return H?{...G,progress:H.progress}:G})),createdAt:V.createdAt,updatedAt:V.updatedAt}}async items(Z,$,V={}){let z=this.store;if(!z.listItems)return[];let X=Math.max(1,Math.min(1000,Math.floor(V.limit??100)));return(await z.listItems(Z,$,{statuses:V.status?[V.status]:["failed","skipped"],...V.after===void 0?{}:{after:V.after},limit:X})).map(NZ)}async tick(Z,$){let V=this.store,z=$.$claimed,X=z?`${z.id}:${z.attempt}`:`${crypto.randomUUID()}:1`,Y=Math.max(1,this.queue.config.visibilityTimeout),G=await V.acquire(Z,X,Y);if(G.kind!=="acquired")return;let{workflow:B}=G,H=(P={})=>V.update(Z,{owner:X},()=>({...P,result:void 0,unlock:!0})).then(()=>this.queue.claimSoon()).catch((W)=>{if(!(W instanceof b))throw W});if(R0.includes(B.status)||B.status==="paused"){await H(),await this.releaseSlotsOf(Z,B);return}let Q=this.registry[B.name];if(!Q)return this.unknown(B,$,H);let J;try{J=JSON.parse(B.args)}catch(P){return H({workflow:{status:"failed",error:`The arguments are not JSON: ${N0(P)}`}})}let F=B.status==="cancelling",U;try{U=await this.limitsOf(Q,J)}catch(P){throw await H(),P}if(U.length>0&&!F&&z){let P=this.queue.driver;if(!P.acquireSlots||!P.releaseSlots)return H({workflow:{status:"failed",error:`${B.name} declares concurrency, and this queue's driver has no concurrency slots. The memory and database drivers do.`}});if(!await P.acquireSlots({holder:$Z(Z),workflowId:Z,job:z,slots:U,recheckMs:this.queue.slotRecheck()}))return $.$outcome={kind:"parked"},H()}let A=setInterval(()=>{V.renew(Z,X,Y).catch((P)=>{console.error(`[gemi] Could not extend the hold on workflow ${Z}.`,P)})},Math.max(1,Math.floor(Y/3)));A.unref?.();let N=new FZ({workflowId:Z,owner:X,store:V,steps:G.steps,cancelling:F,findBatch:(P)=>this.queue.driver.findBatch?.(P,{progress:!1})??Promise.resolve(null),buildBatch:(P,W,D)=>this.queue.buildBatch(P,W.map((T)=>JSON.stringify(T)),{name:D.name,allowFailures:D.allowFailures,finally:{name:m,args:[Z]}}),scheduled:()=>this.queue.claimSoon(),cancelCheckMs:q1,durable:this.queue.durable,throttle:{hit:(P,W,D)=>this.queue.locks.store.hit(P,W,D),refund:(P)=>this.queue.locks.store.refund(P)}});try{let P;try{let D=new Q,T=await(F?D.onCancel(N,...J):D.run(N,...J));P=N.suspension?{kind:"suspended"}:{kind:"completed",result:F?null:S0(T,`The result of ${B.name}`)}}catch(D){if(P=N.suspension||D instanceof t?{kind:"suspended"}:{kind:"failed",error:N0(D)},D instanceof b)N.lost=!0}if(await N.settled(),N.lost)return;if(P.kind==="completed"&&N.suspension)P={kind:"suspended"};let W;if(await V.update(Z,{owner:X},({workflow:D,now:T})=>{let _=this.finish(D,P,N,F,T);return W=_.workflow?.status??D.status,_}),this.queue.claimSoon(),U.length>0&&W!==void 0&&(R0.includes(W)||W==="paused"))await this.releaseSlots(Z)}catch(P){if(P instanceof b)return;throw P}finally{clearInterval(A)}}finish(Z,$,V,z,X){let Y={result:void 0,unlock:!0};if(Z.status==="cancelling"&&!z)return{...Y,tick:{delayMs:0}};if($.kind==="completed")return{...Y,workflow:z?{status:"cancelled",currentStep:null,wakeAt:null}:{status:"completed",result:$.result,progress:1,currentStep:null,wakeAt:null,error:null}};if($.kind==="failed")return{...Y,workflow:{status:z?"cancelled":"failed",error:$.error,wakeAt:null}};let G=V.suspension??{status:"waiting",wakes:[]};if(!z&&(Z.status==="paused"||G.status==="paused"))return Z.status==="paused"?{...Y,workflow:{currentStep:V.current??Z.currentStep}}:{...Y,workflow:{status:"running"},tick:{delayMs:0}};let B={...Y,workflow:{status:z?"cancelling":G.status,currentStep:V.current??Z.currentStep}};if(G.wakes.length>0){let H=Math.min(...G.wakes);if(!(Z.wakeAt!==null&&Z.wakeAt>X&&Z.wakeAt<=H))B.tick={delayMs:Math.max(0,H-X)},B.workflow.wakeAt=H}return B}async limitsOf(Z,$){let V=new Z;if(typeof V.concurrency!=="function")return[];return u0(await V.concurrency(...$),Z.name)}async releaseSlots(Z){try{await this.queue.driver.releaseSlots?.($Z(Z))}catch($){console.error(`[gemi] Could not free the concurrency slots of workflow ${Z}.`,$)}}async releaseSlotsOf(Z,$){try{let V=$??(await this.store.find(Z,{steps:!1}))?.workflow,z=V&&this.registry[V.name];if(!V||!z)return;if((await this.limitsOf(z,JSON.parse(V.args))).length>0)await this.releaseSlots(Z)}catch(V){console.error(`[gemi] Could not free the concurrency slots of workflow ${Z}.`,V)}}async unknown(Z,$,V){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 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 V({workflow:{status:"failed",error:`No workflow is registered under the name "${Z.name}".`}})}tickDeadLettered(Z,$){console.error(`[gemi] The tick of workflow ${Z} was dead-lettered.`,$),this.store.update(Z,{},({workflow:V})=>R0.includes(V.status)?{result:void 0}:{result:void 0,workflow:{status:"failed",error:`Its tick job was dead-lettered: ${$.message}`},unlock:!0}).then(()=>this.releaseSlotsOf(Z)).catch(()=>{})}}function u1(Z){return class extends Q0{static name=m;maxAttempts=20;backoff=[1000,5000,15000,30000,60000];async run(V){await Z.tick(V,this)}onDeadletter(V,z){Z.tickDeadLettered(z,V)}}}function p1(Z){try{return n(Z)}catch{return Z}}function c1(Z,$){if(Z.type!=="change")return null;let V=Z.data;if(!V||typeof V!=="object"||V.id!==$||typeof V.updatedAt!=="number")return null;return V}async function w1(Z,$){let V,z=new Promise((X)=>{V=setTimeout(()=>X("timeout"),$)});try{return await Promise.race([Z,z])}finally{clearTimeout(V)}}var __dirname="/home/runner/work/gemi/gemi/packages/gemi/services/queue";function i1(Z=process.env){let $=Z.ROOT_DIR??process.cwd(),V=Z.APP_DIR??`${$}/app`,z=Z.NODE_ENV==="production"?`${$}/dist/server/bootstrap.mjs`:`${V}/bootstrap.ts`,X;try{X=Bun.resolveSync("gemi/app",$)}catch{X=Bun.resolveSync("gemi/app",__dirname)}return{bootstrap:l1(z)?z:void 0,kernel:`${V}/kernel/Kernel.ts`,app:X}}function s1(){let Z=i1(),$=Z.bootstrap?`const { app } = await import(${JSON.stringify(Z.bootstrap)});`:`const { App } = await import(${JSON.stringify(Z.app)});
566
+ )`]}function bZ(Z){let $=JSON.parse(Z.options),V=(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:V(Z.cancelled_at),finishedAt:V(Z.finished_at),createdAt:Number(Z.created_at),allowFailures:$.allowFailures===!0,callbacks:$.callbacks??{}}}function T1(Z){return JSON.stringify({allowFailures:Z.allowFailures,callbacks:Z.callbacks})}function kZ(Z){let $=String(Z?.message??Z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test($)}async function ZZ(Z,$){try{return await Z}catch(V){if(!kZ(V))throw V;throw Error(`Job batches need the "${$}" 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:V})}}function M3(Z){return Z}function uZ(){return{jobs:[],jobsDir:"app/jobs",workflows:[],workflowsDir:"app/workflows",concurrency:1,driver:"memory",visibilityTimeout:300000,pollInterval:1000,unknownJobGrace:3600000,locks:"auto"}}var S1=86400000;class VZ{queue;workflows=new Map;steps=new Map;items=new Map;sources=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(S1);let $=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:$,updatedAt:$}),this.steps.set(Z.id,new Map),this.tick(Z.id,0)}async find(Z,$={}){let V=this.workflows.get(Z);if(!V)return null;return{workflow:{...V},steps:$.steps===!1?[]:this.stepsOf(Z)}}async acquire(Z,$,V){let z=this.workflows.get(Z);if(!z)return{kind:"missing"};let X=Date.now();if(z.lockedBy!==null&&!f0(z.lockedBy,$)&&(z.lockedUntil??0)>X)return z.retick=!0,{kind:"busy"};return z.lockedBy=$,z.lockedUntil=X+V,z.retick=!1,{kind:"acquired",workflow:{...z},steps:this.stepsOf(Z)}}async renew(Z,$,V){let z=this.workflows.get(Z);if(!z||z.lockedBy!==$)return!1;return z.lockedUntil=Date.now()+V,!0}statusOf(Z){return this.workflows.get(Z)?.status}async update(Z,$,V){let z=this.workflows.get(Z);if(!z)return;if($.owner!==void 0&&z.lockedBy!==$.owner)throw new b(Z);let X=this.steps.get(Z),Y=$.key===void 0?void 0:X.get($.key),G=Date.now(),Q=V({workflow:{...z},step:Y?{...Y}:null,steps:$.allSteps?this.stepsOf(Z):[],items:$.items===void 0?[]:this.itemsOf(Z,$.items,["running","retrying"],-1,1/0),now:G});if(Q.step){let B=X.get(Q.step.key);X.set(Q.step.key,{...Q.step,createdAt:B?.createdAt??G,updatedAt:G})}if(Q.items){let B=this.rowsOf(Z,Q.items.step);for(let H of Q.items.delete??[])B.all.delete(H),B.open.delete(H);for(let H of[...Q.items.insert??[],...Q.items.update??[]]){let J=B.all.get(H.index);if(B.all.set(H.index,{...H,step:Q.items.step,createdAt:J?.createdAt??G,updatedAt:G}),H.status==="running"||H.status==="retrying")B.open.add(H.index);else B.open.delete(H.index)}}if(Q.batch)this.queue.enqueueBatch(Q.batch);for(let B of Q.cancelBatches??[])this.queue.cancelBatch(B);if(Q.workflow)Object.assign(z,Q.workflow);if(z.updatedAt=G,Q.tick)this.tick(Z,Q.tick.delayMs);if(Q.unlock){if(z.lockedBy=null,z.lockedUntil=null,z.retick)z.retick=!1,this.tick(Z,0)}return Q.result}async prune(Z){let $=Date.now()-Z,V=0;for(let[z,X]of this.workflows)if(["completed","failed","cancelled"].includes(X.status)&&X.updatedAt<=$){this.workflows.delete(z),this.steps.delete(z),this.items.delete(z);for(let[G,Q]of this.sources)if(Q.workflowId===z)this.sources.delete(G);V++}return V}async writeSource(Z,$,V){let z=this.sources.get(Z);if(!z)z={workflowId:$,createdAt:Date.now(),rows:new Map},this.sources.set(Z,z);for(let X of V){if(z.rows.has(X.index))throw Error(`Item source "${Z}" already has an item at index ${X.index}.`);z.rows.set(X.index,X.payload)}}async readSource(Z,$,V){let z=this.sources.get(Z)?.rows,X=[];if(!z)return X;for(let Y=Math.max(0,$);Y<V;Y++){let G=z.get(Y);if(G!==void 0)X.push({index:Y,payload:G})}return X}async deleteSource(Z){let $=this.sources.get(Z)?.rows.size??0;return this.sources.delete(Z),$}async pruneSources(Z){let $=Date.now()-Z,V=0;for(let[z,X]of this.sources)if(X.workflowId===null&&X.createdAt<=$)V+=X.rows.size,this.sources.delete(z);return V}async listItems(Z,$,V){return this.itemsOf(Z,$,V.statuses,V.after??-1,V.limit)}itemsOf(Z,$,V,z,X){let Y=this.items.get(Z)?.get($);if(!Y)return[];let Q=V.every((H)=>H==="running"||H==="retrying")?[...Y.open]:[...Y.all.keys()],B=[];for(let H of Q.sort((J,F)=>J-F)){if(H<=z)continue;let J=Y.all.get(H);if(!V.includes(J.status))continue;if(B.push({...J}),B.length>=X)break}return B}rowsOf(Z,$){let V=this.items.get(Z);if(!V)this.items.set(Z,V=new Map);let z=V.get($);if(!z)V.set($,z={all:new Map,open:new Set});return z}stepsOf(Z){return[...this.steps.get(Z)?.values()??[]].map(($)=>({...$}))}tick(Z,$){this.queue.enqueue({name:m,args:JSON.stringify([Z]),delayMs:Math.max(0,Math.round($))})}}function zZ(Z){return`workflow:${Z}`}var pZ=191;function w0(Z,$){if(Z===void 0||Z===null)return[];let V=Array.isArray(Z)?Z:[Z],z=new Set,X=[];for(let Y of V){if(Y===void 0||Y===null)continue;let{key:G,limit:Q}=Y??{};if(typeof G!=="string"||G.length===0||G.length>pZ)throw TypeError(`${$}.concurrency returned a key that is not a string of 1 to ${pZ} characters: ${JSON.stringify(G)}.`);if(typeof Q!=="number"||!Number.isInteger(Q)||Q<0)throw TypeError(`${$}.concurrency returned the limit ${String(Q)} for "${G}"; a limit is a whole number, 0 or more.`);if(z.has(G))throw TypeError(`${$}.concurrency returned the key "${G}" twice.`);z.add(G),X.push({key:G,limit:Q})}return X}class XZ{host;lines=new Map;keysOf=new Map;order=0;constructor(Z){this.host=Z}line(Z){let $=this.lines.get(Z),V=$?this.sorted($):[];return{holding:V.filter((z)=>z.state==="holding").map((z)=>z.holder),waiting:V.filter((z)=>z.state==="waiting").map((z)=>z.holder)}}acquire(Z){let $;for(let V of this.keysOf.get(Z.holder)??[]){let z=this.lines.get(V)?.tickets.get(Z.holder);if(z&&($===void 0||z.order<$))$=z.order}$??=this.order++;for(let{key:V,limit:z}of Z.slots){let X=this.lines.get(V)??{key:V,limit:z,tickets:new Map};this.lines.set(V,X),X.limit=z,this.prune(X);let Y=X.tickets.get(Z.holder);if(!Y){Y={holder:Z.holder,state:"waiting",order:$,jobId:Z.job.id,workflowId:Z.workflowId},X.tickets.set(Z.holder,Y);let B=this.keysOf.get(Z.holder)??new Set;B.add(V),this.keysOf.set(Z.holder,B)}Y.jobId=Z.job.id;let G=()=>this.holders(X)+this.ahead(X,Y)<z;if(Y.state==="waiting"&&!G())this.wake(X,Z.holder);if(Y.state==="waiting"&&G())Y.state="holding";if(Y.state==="holding"){this.wake(X,Z.holder);continue}let Q=this.ahead(X,Y)<Math.max(1,z);return this.host.park(Z.job,Q?Z.recheckMs.near:Z.recheckMs.far),!1}return!0}release(Z){let $=this.keysOf.get(Z);if(!$)return;this.keysOf.delete(Z);for(let V of $){let z=this.lines.get(V);if(!z)continue;if(z.tickets.delete(Z),this.prune(z),this.wake(z,Z),z.tickets.size===0)this.lines.delete(V)}}sorted(Z){return[...Z.tickets.values()].sort(($,V)=>$.order-V.order||($.holder<V.holder?-1:$.holder>V.holder?1:0))}holders(Z){let $=0;for(let V of Z.tickets.values())if(V.state==="holding")$++;return $}ahead(Z,$){let V=0;for(let z of Z.tickets.values()){if(z.state!=="waiting"||z===$)continue;if(z.order<$.order||z.order===$.order&&z.holder<$.holder)V++}return V}alive(Z){return Z.workflowId!==void 0?this.host.workflowAlive(Z.workflowId):this.host.jobAlive(Z.jobId)}prune(Z){for(let $ of Z.tickets.values())if($.state==="holding"&&!this.alive($))this.forget(Z,$)}wake(Z,$){let V=Z.limit-this.holders(Z);for(let z of this.sorted(Z)){if(V<=0)return;if(z.state!=="waiting"||z.holder===$)continue;if(!this.alive(z)){this.forget(Z,z);continue}if(!this.host.wake(z.jobId)){if(z.workflowId===void 0){this.forget(Z,z);continue}z.jobId=this.host.tick(z.workflowId)}V--}}forget(Z,$){Z.tickets.delete($.holder);let V=this.keysOf.get($.holder);if(V?.delete(Z.key),V?.size===0)this.keysOf.delete($.holder)}}var I1=86400000;class c0{entries=new Map;batches=new Map;workflows;slots=new XZ({jobAlive:(Z)=>this.entries.has(Z),workflowAlive:(Z)=>{let $=this.workflows?.statusOf(Z);return $!==void 0&&$!=="completed"&&$!=="failed"&&$!=="cancelled"&&$!=="paused"},park:(Z,$)=>{let V=this.current(Z);if(!V)return;V.job={...V.job,attempt:V.job.attempt-1},V.leased=!1,V.until=Date.now()+Math.max(0,$),this.changed()},wake:(Z)=>{let $=this.entries.get(Z);if(!$)return!1;if(!$.leased&&$.until>Date.now())$.until=Date.now(),this.changed();return!0},tick:(Z)=>{let $=this.add({name:m,args:JSON.stringify([Z])});return this.changed(),$}});listeners=new Set;timer;timerAt=1/0;seq=0;get waiting(){let Z=0;for(let $ of this.entries.values())if(!$.leased)Z++;return Z}get leased(){return this.entries.size-this.waiting}async enqueue(Z){let $=this.add(Z);return this.changed(),$}add({name:Z,args:$,delayMs:V=0,id:z=crypto.randomUUID()},X){let Y=Date.now();return this.entries.set(z,{job:{id:z,name:Z,args:$,attempt:0,createdAt:Y,...X===void 0?{}:{batchId:X}},until:Y+Math.max(0,V),leased:!1,seq:this.seq++,progress:0}),z}async enqueueBatch(Z){this.recordBatch(Z)}recordBatch(Z){let $=Date.now();this.forgetFinishedBatches($);let V=k0({...Z,total:Z.args.length,now:$});for(let Y of Z.args)this.add({name:Z.job,args:Y},Z.id);let{record:z,calls:X}=F0(V,V,$);this.batches.set(Z.id,z);for(let Y of X)this.add(Y);this.changed()}async findBatch(Z,$={}){let V=this.batches.get(Z);if(!V)return null;if($.progress===!1||V.pending===0)return G0(V);let z=0;for(let X of this.entries.values())if(X.job.batchId===Z)z+=X.progress;return G0(V,z)}async cancelBatch(Z){return this.cancelBatchNow(Z)}cancelBatchNow(Z){let $=this.batches.get(Z);if(!$||$.finishedAt!==null||$.cancelledAt!==null)return!1;let V=Date.now(),z=K0($,V,this.cancelWaiting(Z));return this.save($,z,V),this.changed(),!0}workflowStore(){return this.workflows??=new VZ({enqueue:(Z)=>{this.add(Z),this.changed()},enqueueBatch:(Z)=>this.recordBatch(Z),cancelBatch:(Z)=>void this.cancelBatchNow(Z)}),this.workflows}async acquireSlots(Z){return this.slots.acquire(Z)}async releaseSlots(Z){this.slots.release(Z)}async reportProgress(Z,$){let V=this.current(Z);if(V)V.progress=i($)}async claim(Z,$){let V=Date.now(),z=[...this.entries.values()].filter((X)=>X.until<=V).sort((X,Y)=>X.until-Y.until||X.seq-Y.seq).slice(0,Math.max(0,Z));for(let X of z)X.job={...X.job,attempt:X.job.attempt+1},X.leased=!0,X.until=V+$.visibilityTimeoutMs;if(z.length>0)this.schedule();return z.map((X)=>({...X.job}))}async complete(Z){let $=this.current(Z);if(!$)return;this.entries.delete(Z.id),this.count($,"succeeded"),this.schedule()}async fail(Z,$){let V=this.current(Z);if(!V)return;let z=V.job.batchId===void 0?void 0:this.batches.get(V.job.batchId),X=$.cancelled===!0||$.retryInMs!==null&&z?.cancelledAt!=null;if($.retryInMs===null||X){this.entries.delete(Z.id),this.count(V,X?"cancelled":"failed"),this.schedule();return}V.leased=!1,V.until=Date.now()+Math.max(0,$.retryInMs),V.seq=this.seq++,V.progress=0,this.changed()}async release(Z,$){let V=this.current(Z);if(!V)return;V.job={...V.job,attempt:V.job.attempt-1},V.leased=!1,V.until=Date.now()+Math.max(0,$.retryInMs),V.seq=this.seq++,this.changed()}async heartbeat(Z,$){let V=Date.now()+$.visibilityTimeoutMs;for(let z of Z){let X=this.current(z);if(X)X.until=V}this.schedule()}count(Z,$){let V=Z.job.batchId;if(V===void 0)return;let z=this.batches.get(V);if(!z)return;let X=Date.now(),Y=u0(z,$,Z.job.id);if(p0(z,Y))Y=K0(Y,X,this.cancelWaiting(V));this.save(z,Y,X),this.changed()}save(Z,$,V){let{record:z,calls:X}=F0(Z,$,V);this.batches.set(z.id,z);for(let Y of X)this.add(Y)}cancelWaiting(Z){let $=0;for(let[V,z]of this.entries)if(z.job.batchId===Z&&!z.leased)this.entries.delete(V),$++;return $}forgetFinishedBatches(Z){for(let[$,V]of this.batches)if(V.finishedAt!==null&&Z-V.finishedAt>I1)this.batches.delete($)}subscribe(Z){return this.listeners.add(Z),()=>void this.listeners.delete(Z)}current(Z){let $=this.entries.get(Z.id);if(!$||!$.leased||$.job.attempt!==Z.attempt)return;return $}changed(){this.schedule();let Z=Date.now();for(let $ of this.entries.values())if($.until<=Z){this.wake();return}}wake(){for(let Z of[...this.listeners])Z()}schedule(){let Z=Date.now(),$=1/0;for(let V of this.entries.values())if(V.until>Z&&V.until<$)$=V.until;if($===this.timerAt)return;if(clearTimeout(this.timer),this.timer=void 0,this.timerAt=$,$===1/0)return;this.timer=setTimeout(()=>{this.timer=void 0,this.timerAt=1/0,this.changed()},$-Z),this.timer.unref?.()}}import{AsyncResource as a1}from"async_hooks";import{existsSync as i1}from"fs";import{isMainThread as s1}from"worker_threads";class H0{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,$={}){this.$outcome={kind:"fail",error:Z instanceof Error?Z:Error(String(Z)),retry:$.retry??!0}}batch=void 0;async progress(Z){let $=i(Z);await this.$progress?.($)}$progress;$claimed;$outcome;run(...Z){}onFail(Z,...$){}onSuccess(Z,...$){}onDeadletter(Z,...$){}static dispatch(...Z){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return Q0($0).push(this,JSON.stringify(Z))}static dispatchBatch(Z,$={}){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return Q0($0).pushBatch(this,Z.map((V)=>JSON.stringify(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 Q0($0).findBatch(Z)}static cancelBatch(Z){return Q0($0).cancelBatch(Z)}}function E0(Z,$){let V=Array.isArray(Z)?Z[Math.min($,Z.length)-1]:Z;return Math.max(0,V??0)}class QZ extends Error{step;batch;summary;constructor(Z,$,V,z){super($);this.step=Z;this.batch=V;this.summary=z;this.name="StepFailedError"}}class HZ extends Error{step;constructor(Z){super(`No signal "${Z}" arrived before its timeout.`);this.step=Z;this.name="WaitTimeoutError"}}class BZ extends Error{constructor(Z,$){super(`Step "${Z}" took longer than its timeout of ${$}ms.`);this.name="StepTimeoutError"}}class JZ extends Error{constructor(Z){super(`Workflow ${Z} was cancelled.`);this.name="WorkflowCancelledError"}}class t extends Error{constructor(){super("The workflow is suspended until a step can continue. Rethrow this error if you catch it.");this.name="WorkflowSuspended"}}var wZ=Symbol("done"),cZ=Symbol("paused");class NZ{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(($)=>[$.key,$]))}run(Z,$,V={}){return this.track(Z,()=>this.runStep(Z,$,V))}sleep(Z,$){let V=r($);return this.track(Z,()=>this.sleepStep(Z,V))}waitFor(Z,$={}){let V=$.timeout===void 0?void 0:r($.timeout);return this.track(Z,()=>this.waitStep(Z,V))}batch(Z,$,V,z={}){return this.track(Z,()=>this.batchStep(Z,$,V,z))}each(Z,$,V){return this.track(Z,()=>this.eachStep(Z,$,V))}source(Z,$,V={}){let z=`${this.workflowId}:${Z}`;return this.run(Z,async()=>UZ(this.tick.store,z,await $(),this.workflowId),V)}async progress(Z){let $=i(Z);this.assertRunning();let V=this.write(void 0,()=>({result:void 0,workflow:{progress:$}}));this.remember(V),await V}async settled(){while(this.pending.size>0)await Promise.allSettled(this.pending)}track(Z,$){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 V=$();return this.remember(V),V}remember(Z){this.pending.add(Z);let $=()=>void this.pending.delete(Z);Z.then($,$)}assertRunning(){if(this.lost)throw new b(this.workflowId);if(this.suspension)throw new t}suspend(Z,$){if(!this.suspension)this.suspension={status:Z,wakes:[]};if($!=null)this.suspension.wakes.push($);throw new t}async write(Z,$,V={}){let z;try{z=await this.tick.store.update(this.tick.workflowId,{owner:this.tick.owner,...Z===void 0?{}:{key:Z},...V.items&&Z!==void 0?{items:Z}:{},...V.joinTransaction?{joinTransaction:!0}:{}},(X)=>{if(X.workflow.status==="cancelling"&&!this.tick.cancelling)return{result:wZ};if(V.start&&X.workflow.status==="paused"&&!this.tick.cancelling)return{result:cZ};let Y=$(X);return{...Y,result:{value:Y.result}}})}catch(X){if(X instanceof b)this.lost=!0;throw X}if(z===void 0)throw this.lost=!0,new b(this.tick.workflowId);if(z===wZ)this.cancelled=!0,this.suspend("waiting");if(z===cZ)this.suspend("paused");return z.value}record(Z,$,V){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};return this.steps.set(Z,z),z}mismatch(Z,$,V){throw Error(`Step "${Z}" of workflow ${this.tick.workflowId} was recorded as a ${$} step, and is now used as ${V}. A key belongs to one step; rename one of them.`)}async runStep(Z,$,V){let z=Math.max(1,Math.floor(V.attempts??3)),X=V.timeout===void 0?void 0:r(V.timeout),Y=this.steps.get(Z);if(Y?.status==="completed")return n(Y.output);if(Y?.status==="failed")throw s(Z,Y);if(Y?.status==="retrying"&&Y.wakeAt!==null&&Y.wakeAt>Date.now())this.current=Z,this.suspend("sleeping",Y.wakeAt);for(;;){let G=await this.write(Z,({workflow:N,step:P,now:W})=>{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>W)return{result:{kind:"wait",wakeAt:P.wakeAt}};let D=(P?.attempt??0)+1;if(D>z){let _=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:W,wakeAt:null});return{result:{kind:"failed",step:_},step:_}}let T=this.record(Z,P,{status:"running",attempt:D,startedAt:W,finishedAt:null,wakeAt:null});return{result:{kind:"run",attempt:D},step:T,workflow:N.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{start:!0});if(this.current=Z,G.kind==="done")return n(G.output);if(G.kind==="failed")throw s(Z,G.step);if(G.kind==="wait")this.suspend("sleeping",G.wakeAt);let Q=G.attempt,B,H,J=!0;try{B=await this.execute(Z,$,Q,X)}catch(N){H=N}if(this.cancelled)throw new t;let F=null;if(H===void 0)try{F=S0(B,`The result of step "${Z}"`)}catch(N){H=N,J=!1}if(H===void 0)return await this.write(Z,({step:N,now:P})=>({result:void 0,step:this.record(Z,N,{status:"completed",output:F,error:null,wakeAt:null,finishedAt:P})})),n(F);let U=N0(H);if(J&&Q<z){let N=E0(V.backoff??0,Q),P=await this.write(Z,({step:W,now:D})=>{let T=N>0?D+N:null;return{result:T,step:this.record(Z,W,{status:"retrying",error:U,wakeAt:T})}});if(P!==null)this.suspend("sleeping",P);continue}let A=await this.write(Z,({step:N,now:P})=>{let W=this.record(Z,N,{status:"failed",error:U,wakeAt:null,finishedAt:P});return{result:W,step:W}});throw s(Z,A)}}async execute(Z,$,V,z){let X=new AbortController,Y={idempotencyKey:`${this.tick.workflowId}:${Z}`,attempt:V,signal:X.signal},G=Promise.resolve().then(()=>$(Y)),Q,B,H=new Promise((J,F)=>{let U=(A)=>{X.abort(A),F(A)};if(z!==void 0)Q=setTimeout(()=>U(new BZ(Z,z)),z);if(!this.tick.cancelling)B=setInterval(()=>{this.tick.store.find(this.tick.workflowId,{steps:!1}).then((A)=>{if(A?.workflow.status!=="cancelling"||X.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};U(new JZ(this.tick.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs),B.unref?.()});try{return await Promise.race([G,H])}finally{clearTimeout(Q),clearInterval(B),G.catch(()=>{}),H.catch(()=>{})}}async sleepStep(Z,$){let V=this.steps.get(Z);if(V?.status==="completed")return;if(this.current=Z,V?.status==="sleeping"&&V.wakeAt!==null&&V.wakeAt>Date.now())this.suspend("sleeping",V.wakeAt);let z=await this.write(Z,({step:X,now:Y})=>{if(X?.status==="completed")return{result:null};if(X&&X.status!=="sleeping")this.mismatch(Z,X.status,"step.sleep");let G=X?.wakeAt??Y+$;if(G<=Y)return{result:null,step:this.record(Z,X,{status:"completed",wakeAt:G,startedAt:X?.startedAt??Y,finishedAt:Y})};if(X)return{result:G};return{result:G,step:this.record(Z,null,{status:"sleeping",wakeAt:G,startedAt:Y}),workflow:{currentStep:Z}}});if(z!==null)this.suspend("sleeping",z)}async waitStep(Z,$){let V=this.steps.get(Z);if(V?.status==="completed")return n(V.output);if(V?.status==="timed_out")throw new HZ(Z);if(this.current=Z,V?.status==="waiting"&&(V.wakeAt===null||V.wakeAt>Date.now()))this.suspend("waiting",V.wakeAt);let z=await this.write(Z,({step:X,now:Y})=>{if(X?.status==="completed")return{result:{kind:"value",output:X.output}};if(X?.status==="timed_out")return{result:{kind:"timeout"}};if(X?.status==="signalled")return{result:{kind:"value",output:X.output},step:this.record(Z,X,{status:"completed",wakeAt:null,startedAt:X.startedAt??Y,finishedAt:Y})};if(X&&X.status!=="waiting")this.mismatch(Z,X.status,"step.waitFor");if(X){if(X.wakeAt!==null&&X.wakeAt<=Y)return{result:{kind:"timeout"},step:this.record(Z,X,{status:"timed_out",finishedAt:Y})};return{result:{kind:"wait",wakeAt:X.wakeAt}}}let G=$===void 0?null:Y+$;return{result:{kind:"wait",wakeAt:G},step:this.record(Z,null,{status:"waiting",wakeAt:G,startedAt:Y}),workflow:{currentStep:Z}}});if(z.kind==="value")return n(z.output);if(z.kind==="timeout")throw new HZ(Z);this.suspend("waiting",z.wakeAt)}async eachStep(Z,$,V){let z=$.source,X=z?z.count:$.count;if(!z&&typeof $.item!=="function")throw TypeError(`step.each "${Z}" needs either { count, item } or { source }.`);if(!Number.isSafeInteger(X)||X<0||X>dZ)throw TypeError(`step.each "${Z}" needs a count that is a whole number from 0 to ${dZ}; got ${String(X)}.`);let Y=Math.max(1,Math.floor($.concurrency??1)),G=Math.max(1,Math.floor($.attempts??3)),Q=$.timeout===void 0?void 0:r($.timeout),B=$.tickBudget===void 0?M1:r($.tickBudget),H=$.progress!==!1,J=$.chunk!==void 0,F=J?Math.max(1,Math.floor($.chunk)):1,U=[$.throttle??[]].flat().map((K)=>({name:`gemi:throttle:${K.key}`,limit:Math.max(0,Math.floor(K.limit)),windowMs:r(K.window)})),A=x1($.maxFailures),N=this.tick.store,P=$.transaction===!0&&N.transaction?(K)=>N.transaction(K):void 0;if($.transaction===!0&&!P)q1();let W=z?tZ(N,z,Math.max(v1,Y*F*4)):$.item;if(!N.listItems)throw Error("This queue's workflow store does not support step.each. The memory and database drivers do.");if(U.length>0&&!this.tick.throttle)throw Error(`step.each "${Z}" has a throttle, and this queue has no lock store.`);let D=this.steps.get(Z);if(D?.status==="completed")return FZ(D.output);if(D?.status==="failed")throw s(Z,D);if(D&&D.status!=="iterating")this.mismatch(Z,D.status,"step.each");if(this.current=Z,this.tick.durable===!1)b1();let T=await this.write(Z,({workflow:K,step:R,items:L,now:O})=>{if(R?.status==="completed")return{result:{kind:"done",output:R.output}};if(R?.status==="failed")return{result:{kind:"failed",step:R}};if(R&&R.status!=="iterating")this.mismatch(Z,R.status,"step.each");let x=R?d0(R.output):g1(X);return{result:{kind:"go",state:x,open:L},...R?{}:{step:this.record(Z,null,{status:"iterating",output:GZ(x),startedAt:O})},workflow:K.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{items:!0,start:!0});if(T.kind==="done")return FZ(T.output);if(T.kind==="failed")throw s(Z,T.step);let _=T.state;if(_.count!==X)m1(this.workflowId,Z,_.count,X);let D0=_.count,d=new Map(T.open.map((K)=>[K.index,K])),k=[],_0=new Map,s0=new Map,CZ=Date.now()+B,B0=0,M0=!1,V0=null,p=new AbortController,WZ=setInterval(()=>{N.find(this.workflowId,{steps:!1}).then((K)=>{if(K?.workflow.status==="paused")M0=!0;if(K?.workflow.status!=="cancelling"||p.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};p.abort(new JZ(this.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs);WZ.unref?.(),V0=A(_);let OZ=(K,R)=>{let L={...K};for(let O of R)if(O.counter)L[O.counter]++;return L},EZ=(K)=>{let R=K.succeeded+K.skipped+K.failed;return H?{workflow:{progress:D0===0?1:i(R/D0)}}:{}},TZ=(K)=>{if(_={count:_.count,next:Math.max(_.next,K.next),succeeded:Math.max(_.succeeded,K.succeeded),skipped:Math.max(_.skipped,K.skipped),failed:Math.max(_.failed,K.failed)},!V0)V0=A(_);if(V0&&!p.signal.aborted)p.abort(new t)},G1=async(K)=>{let R=K.map(()=>null),L=new Map,O=new AbortController,x=()=>O.abort(p.signal.reason);p.signal.addEventListener("abort",x,{once:!0});let u,z0=K.length===1?`${Z}[${K[0].index}]`:`${Z}[${K[0].index}..${K.at(-1).index}]`,L0=new Promise((C,S)=>{if(O.signal.addEventListener("abort",()=>S(O.signal.reason),{once:!0}),Q!==void 0)u=setTimeout(()=>O.abort(new BZ(z0,Q)),Q)}),y=(C)=>{throw new KZ(Math.max(0,Math.floor(Number(C)||0)))},X0=(C)=>K.map((S,q)=>{let l=L.get(q);if(!l)return{index:S.index,row:null,counter:"succeeded"};return{index:S.index,row:aZ(S,R[q],l.reason,l.data,C),counter:"skipped"}}),Y0=null,g=(async()=>{let C=await Promise.all(K.map((M)=>W(M.index)));K.forEach((M,v)=>{R[v]=y1($.key?$.key(C[v],M.index):M.index)});let S=(M)=>`${this.workflowId}:${Z}:${R[M]}`,q=Math.max(...K.map((M)=>M.attempt)),l=async()=>{if(J){let M={idempotencyKey:S(0),attempt:q,signal:O.signal,items:K.map((v,f)=>({index:v.index,key:R[f],idempotencyKey:S(f)})),skip:(v,f,I)=>{if(!Number.isInteger(v)||v<0||v>=K.length)throw RangeError(`ctx.skip: no item at position ${v} of this chunk.`);L.set(v,{reason:String(f),data:I})},release:y};await V(C,M)}else{let M={idempotencyKey:S(0),attempt:q,signal:O.signal,index:K[0].index,key:R[0],skip:(v,f)=>{throw new PZ(v,f)},release:y};await V(C[0],M)}};if(!P)return l();await P(async()=>{if(await l(),O.signal.aborted)throw O.signal.reason;let M=X0(Date.now()),v=await this.write(Z,({step:f})=>{let I={step:Z,insert:[],update:[],delete:[]};for(let J0 of M)if(J0.row===null)I.delete.push(J0.index);else I.update.push(J0.row);let a=OZ(f?d0(f.output):_,M);return{result:a,step:this.record(Z,f,{status:"iterating",output:GZ(a)}),items:I,...EZ(a)}},{joinTransaction:!0});Y0=M.map((f)=>({...f,recorded:!0})),TZ(v)})})(),j,E=!1;try{await Promise.race([g,L0])}catch(C){E=!0,j=C}finally{clearTimeout(u),p.signal.removeEventListener("abort",x),g.catch(()=>{}),L0.catch(()=>{})}if(Y0){k.push(...Y0);return}if(p.signal.aborted||this.cancelled||this.lost)return;let h=Date.now();if(!E){k.push(...X0(h));return}if(j instanceof PZ){k.push({index:K[0].index,row:aZ(K[0],R[0],j.reason,j.data,h),counter:"skipped"});return}if(j instanceof KZ){B0=Math.max(B0,h+j.delayMs),K.forEach((C,S)=>{k.push({index:C.index,row:{...C,key:R[S],status:"retrying",attempt:Math.max(0,C.attempt-1),wakeAt:h+j.delayMs},counter:null})});return}let w=T0(N0(j),2000);K.forEach((C,S)=>{if(C.attempt<G){let q=E0($.backoff??0,C.attempt);k.push({index:C.index,row:{...C,key:R[S],status:"retrying",error:w,wakeAt:h+q},counter:null});return}k.push({index:C.index,row:{...C,key:R[S],status:"failed",error:w,wakeAt:null,finishedAt:h},counter:"failed"})})},Q1=async(K)=>{if(U.length===0||K===0)return K;let R=this.tick.throttle;for(let L=0;L<K;L++){let O=[];for(let x of U){let u=await R.hit(x.name,x.limit,x.windowMs);if(!u.allowed)return await Promise.all(O.map((z0)=>R.refund(z0))),B0=Math.max(B0,Date.now()+Math.max(1,u.resetInMs)),L;O.push(x.name)}}return K},H1=async(K)=>{if(U.length===0)return;for(let R=0;R<K;R++)for(let L of U)await this.tick.throttle.refund(L.name)};try{for(;;){let K=Date.now(),R=K>=CZ||l0()||this.cancelled||M0||V0!==null,L=[],O=0;if(!R&&K>=B0){let y=(Y-_0.size)*F,X0=new Set(k.map((j)=>j.index));for(let j of[...d.values()].sort((E,h)=>E.index-h.index)){if(L.length>=y)break;if(s0.has(j.index)||X0.has(j.index))continue;if(j.status==="running"||(j.wakeAt??0)<=K)L.push(j)}let Y0=Y*F+lZ-d.size;O=Math.max(0,Math.min(y-L.length,D0-_.next,Y0));let g=await Q1(L.length+O);if(g<L.length)L=L.slice(0,g),O=0;else O=g-L.length}if(k.length>0||L.length>0||O>0){let y=k.splice(0,k.length),X0=y.filter((E)=>!E.recorded),Y0=L.length+O,g=await this.write(Z,({workflow:E,step:h,now:w})=>{let C=OZ(h?d0(h.output):_,X0),S={step:Z,insert:[],update:[],delete:[]},q=[],l=[];for(let I of X0)if(I.row===null)S.delete.push(I.index);else S.update.push(I.row);let M=E.status==="paused"&&!this.tick.cancelling;for(let I of M?[]:L){if(I.attempt+1>G){let J0={...I,status:"failed",error:T0(`Attempt ${I.attempt} of ${G} never finished, most likely because the process running it exited.`+(I.error?` The last error was: ${I.error}`:""),2000),wakeAt:null,finishedAt:w};C.failed++,S.update.push(J0),l.push(J0);continue}let a={...I,status:"running",attempt:I.attempt+1,wakeAt:null,startedAt:w};S.update.push(a),q.push(a)}let v=M?0:O,f=q.length;for(let I=0;I<v;I++){let a=h1(this.workflowId,Z,C.next+I,w);S.insert.push(a),q.push(a)}return C.next+=v,{result:{next:C,started:q,closed:l,reruns:f,paused:M},step:this.record(Z,h,{status:"iterating",output:GZ(C)}),items:S,...EZ(C)}});if(TZ(g.next),g.paused)M0=!0;await H1(Y0-g.started.length);for(let E of y)if(E.row?.status==="retrying")d.set(E.index,E.row);else d.delete(E.index);for(let E of g.closed)d.delete(E.index);for(let E of g.started)d.set(E.index,E);let j=[...iZ(g.started.slice(0,g.reruns),F),...iZ(g.started.slice(g.reruns),F)];for(let E of j){let h=E[0].index;for(let w of E)s0.set(w.index,h);_0.set(h,G1(E).finally(()=>{_0.delete(h);for(let w of E)s0.delete(w.index)}))}}if(_0.size>0){await Promise.race(_0.values());continue}if(k.length>0)continue;if(this.cancelled)throw new t;if(V0)break;if(_.next>=D0&&d.size===0)break;if(M0)this.suspend("paused");if(R)this.suspend("running",Date.now());let x=Date.now(),u=1/0;if(_.next<D0&&d.size<Y*F+lZ)u=x;for(let y of d.values())if(y.status==="running")u=x;else if(y.status==="retrying")u=Math.min(u,y.wakeAt??0);let z0=Math.max(u,B0);if(z0<=x)continue;let L0=z0-x;if(L0<=Math.min(j1,CZ-x)){await new Promise((y)=>setTimeout(y,Math.max(0,L0)));continue}this.suspend("sleeping",z0)}}finally{if(clearInterval(WZ),!p.signal.aborted)p.abort(new t)}let SZ=await N.listItems(this.workflowId,Z,{statuses:["failed","skipped"],limit:YZ+1}),n0={...RZ(_),problems:SZ.slice(0,YZ).map(AZ),moreProblems:SZ.length>YZ},B1=JSON.stringify({$each:_,problems:n0.problems,moreProblems:n0.moreProblems}),j0=V0,J1=await this.write(Z,({step:K,now:R})=>{let L=this.record(Z,K,{status:j0?"failed":"completed",output:B1,error:j0,finishedAt:R});return{result:L,step:L,...H&&!j0?{workflow:{progress:1}}:{}}});if(j0)throw s(Z,J1);return n0}async batchStep(Z,$,V,z){let X=z.allowFailures===!0,Y=this.steps.get(Z);if(Y?.status==="completed")return n(Y.output);if(Y?.status==="failed")throw s(Z,Y);if(Y&&Y.status!=="batching")this.mismatch(Z,Y.status,"step.batch");if(this.current=Z,!Y){let F=this.tick.buildBatch($,V,{name:z.name??`workflow:${this.tick.workflowId}:${Z}`,allowFailures:X});if(Y=await this.write(Z,({step:U,now:A})=>{if(U)return{result:U};let N=this.record(Z,null,{status:"batching",batchId:F.id,startedAt:A});return{result:N,step:N,batch:F,workflow:{currentStep:Z}}},{start:!0}),this.tick.scheduled(),Y.status==="completed")return n(Y.output);if(Y.status==="failed")throw s(Z,Y)}let G=Y.batchId===null?null:await this.tick.findBatch(Y.batchId);if(G&&G.finishedAt===null)this.suspend("waiting");let Q=G!==null&&G.cancelledAt===null&&(G.failed===0||X),B=G===null?null:JSON.stringify(G),H=Q?null:G===null?`The batch of step "${Z}" (${Y.batchId}) no longer exists.`:`The batch of step "${Z}" failed: ${G.failed} failed and ${G.cancelled} cancelled of ${G.total}.`,J=await this.write(Z,({step:F,now:U})=>{let A=this.record(Z,F,{status:Q?"completed":"failed",output:B,error:H,finishedAt:U});return{result:A,step:A}});if(!Q)throw s(Z,J);return G}}function s(Z,$){if($.output?.startsWith('{"$each"'))return new QZ(Z,`Step "${Z}" failed: ${$.error??"unknown error"}`,void 0,FZ($.output));let V=$.batchId!==null&&$.output!==null?JSON.parse($.output):void 0;return new QZ(Z,V?$.error??`Step "${Z}" failed.`:`Step "${Z}" failed: ${$.error??"unknown error"}`,V)}function S0(Z,$){if(Z===void 0)return null;let V=JSON.stringify(Z);if(V===void 0)throw TypeError(`${$} cannot be stored: JSON has no form for it.`);let z=Buffer.byteLength(V,"utf8");if(z>t0)throw RangeError(`${$} is ${z} bytes as JSON, over the ${t0}-byte limit. Store it elsewhere and return its id.`);return V}function n(Z){return Z===null?void 0:JSON.parse(Z)}function N0(Z){return Z instanceof Error?Z.message:String(Z)}var dZ=2147483647,M1=30000,lZ=100,j1=1000,v1=64,YZ=100;class PZ extends Error{reason;data;constructor(Z,$){super(`Skipped: ${Z}`);this.reason=Z;this.data=$;this.name="ItemSkipped"}}class KZ extends Error{delayMs;constructor(Z){super(`Released for ${Z}ms`);this.delayMs=Z;this.name="ItemReleased"}}function aZ(Z,$,V,z,X){let Y=null,G=T0(String(V));try{Y=f1(z)}catch(Q){G=T0(`${G} (${N0(Q)})`)}return{...Z,key:$,status:"skipped",error:G,output:Y,wakeAt:null,finishedAt:X}}function iZ(Z,$){let V=[];for(let z=0;z<Z.length;z+=$)V.push(Z.slice(z,z+$));return V}function x1(Z){if(Z===void 0)return()=>null;if(typeof Z==="number"){let z=Math.max(0,Math.floor(Z));return(X)=>X.failed>z?`${X.failed} items failed, more than maxFailures (${z}).`:null}let $=Math.min(1,Math.max(0,Z.ratio)),V=Math.max(1,Math.floor(Z.after??20));return(z)=>{let X=z.succeeded+z.skipped+z.failed;if(X<V||z.failed/X<=$)return null;return`${z.failed} of ${X} items failed, more than maxFailures allows (a ratio of ${$}).`}}function g1(Z){return{count:Z,next:0,succeeded:0,skipped:0,failed:0}}function GZ(Z){return JSON.stringify({$each:Z})}function d0(Z){let $=Z===null?null:JSON.parse(Z);if(!$?.$each)throw Error("A step.each step has no state.");return $.$each}function oZ(Z){if(Z===null||!Z.startsWith('{"$each"'))return null;try{return RZ(d0(Z))}catch{return null}}function RZ(Z){return{total:Z.count,done:Z.succeeded+Z.skipped+Z.failed,succeeded:Z.succeeded,skipped:Z.skipped,failed:Z.failed}}function FZ(Z){let $=JSON.parse(Z??"null");return{...RZ($.$each),problems:$.problems??[],moreProblems:$.moreProblems===!0}}function AZ(Z){let $={index:Z.index,key:Z.key,status:Z.status==="skipped"?"skipped":"failed",reason:T0(Z.error??""),attempt:Z.attempt};if(Z.output!==null)$.data=JSON.parse(Z.output);return $}function h1(Z,$,V,z){return{workflowId:Z,step:$,index:V,key:null,status:"running",attempt:1,error:null,output:null,wakeAt:null,startedAt:z,finishedAt:null,createdAt:z,updatedAt:z}}function y1(Z){let $=typeof Z==="number"&&Number.isFinite(Z)?String(Z):Z;if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError(`An item key is a string of 1 to 191 characters, or a number; got ${JSON.stringify(Z)}.`);return $}function T0(Z,$=500){return Z.length<=$?Z:`${Z.slice(0,$-1)}\u2026`}function f1(Z){if(Z===void 0)return null;let $=JSON.stringify(Z);if($===void 0)throw TypeError("its data has no JSON form, so it was not kept");if(Buffer.byteLength($,"utf8")>1024)throw RangeError("its data is over 1 KB as JSON, so it was not kept");return $}var sZ=!1;function b1(){if(sZ||Bun.env.NODE_ENV!=="production")return;sZ=!0,console.warn("[gemi] step.each is running on a queue whose driver keeps nothing across restarts (the memory driver), so a deploy or a crash loses the workflow and the rest of its list. Use the database driver for work that must finish.")}var nZ=!1;function q1(){if(nZ)return;nZ=!0,console.warn("[gemi] step.each with transaction: true runs its items without a transaction: this queue's workflow store cannot record an item in the app's transaction (only the database driver on Postgres or MySQL can). Items are at least once.")}var rZ=new Set;function m1(Z,$,V,z){let X=`${Z}:${$}`;if(rZ.has(X))return;rZ.add(X),console.warn(`[gemi] step.each "${$}" of workflow ${Z} was started with a count of ${V} and is now given ${z}. It goes on with ${V}: the count is fixed when the step first runs.`)}function a0(Z){return Z==="completed"||Z==="failed"||Z==="cancelled"}var R0=["completed","failed","cancelled"],k1=1000,u1=250,p1=30000;class DZ{queue;registry={};storeInstance;ownFeed;publishing=new Map;published=new Map;tickClass;reportedNames=new Set;constructor(Z){this.queue=Z}get workflows(){return this.registry}use(Z){this.registry={};for(let $ of Z){if($.name==="unset"||!$.name){console.error("A workflow class has no `static name`, so it was not registered. Add one.");continue}if(this.registry[$.name]){console.error(`Two workflows are named "${$.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[$.name]=$}}get tickJob(){return this.tickClass??=w1(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=this.publishingStore(Z)}return this.storeInstance}get feed(){let Z=this.queue.boundApplication;if(Z?.bound(i0))return Z.make(i0);return this.ownFeed??=new i0,this.ownFeed}channel(Z){return`gemi:workflow:${Z}`}async update(Z){let $=await this.find(Z);if(!$)return null;let{args:V,result:z,...X}=$;return X}stream(Z,$,V={}){return this.feed.stream(Z,this.channel($),V)}cursor(Z){return this.feed.cursor(this.channel(Z))}async*subscribe(Z,$={}){let V=this.feed.subscribe(this.channel(Z),{signal:$.signal});try{await V.ready();let z=await this.update(Z);if(!z)return;if(yield z,a0(z.status))return;let X=V[Symbol.asyncIterator](),Y=X.next();for(;;){let G=await l1(Y,p1),Q;if(G==="timeout")Q=await this.update(Z);else{if(G.done)return;Y=X.next(),Q=d1(G.value,Z)??await this.update(Z)}if(!Q||Q.updatedAt<z.updatedAt)continue;if(JSON.stringify(Q)===JSON.stringify(z))continue;if(z=Q,yield z,a0(z.status))return}}finally{V.close()}}publishingStore(Z){let $=(z)=>void eZ(()=>this.schedulePublish(z)),V={create:(z)=>Z.create(z).then((X)=>{return $(z.id),X}),find:(z,X)=>Z.find(z,X),acquire:(z,X,Y)=>Z.acquire(z,X,Y),renew:(z,X,Y)=>Z.renew(z,X,Y),update:(z,X,Y)=>Z.update(z,X,Y).then((G)=>{return $(z),G})};if(Z.joinsTransaction)V.joinsTransaction=()=>Z.joinsTransaction();if(Z.transaction)V.transaction=(z)=>Z.transaction(z);if(Z.listItems)V.listItems=(...z)=>Z.listItems(...z);if(Z.prune)V.prune=(z)=>Z.prune(z);if(Z.writeSource)V.writeSource=(...z)=>Z.writeSource(...z),V.readSource=(...z)=>Z.readSource(...z),V.deleteSource=(...z)=>Z.deleteSource(...z),V.pruneSources=(...z)=>Z.pruneSources(...z);return V}schedulePublish(Z){if(this.publishing.has(Z))return;let $=Math.max(0,(this.published.get(Z)??0)+u1-Date.now()),V=setTimeout(()=>{this.publishing.delete(Z),this.published.set(Z,Date.now()),this.publish(Z)},$);V.unref?.(),this.publishing.set(Z,V)}async publish(Z){try{let $=await this.update(Z);if(!$)return;if(a0($.status))this.published.delete(Z);await this.feed.publish(this.channel(Z),$)}catch($){console.error(`[gemi] Workflow ${Z}: could not publish its change.`,$)}}async close(){for(let Z of this.publishing.values())clearTimeout(Z);this.publishing.clear(),await this.ownFeed?.close(),this.ownFeed=void 0}start(Z,$){if(Z.name==="unset"||!Z.name)throw Error("Cannot start a workflow with no name");let V=this.store,z={id:Bun.randomUUIDv7(),name:Z.name,args:S0($,`The arguments of ${Z.name}`)??"[]"},X=()=>this.queue.claimSoon(),Y=V.joinsTransaction?.()===!0;if(!Y){if(o(()=>V.create(z).then(X,(H)=>{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.`,H)})))return Promise.resolve(z.id)}let G=V.create(z),Q=Y&&o(X);return G.then(()=>{if(!Q)X();return z.id})}async signal(Z,$,V){if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError("A signal key is a string of 1 to 191 characters.");let z=S0(V,`The payload of signal "${$}"`),X=await this.store.update(Z,{key:$},({workflow:Y,step:G,now:Q})=>{if(R0.includes(Y.status)||Y.status==="cancelling")return{result:!1};if(!G)return{result:!0,step:{workflowId:Z,key:$,status:"signalled",attempt:0,output:z,error:null,batchId:null,wakeAt:null,startedAt:null,finishedAt:Q,createdAt:Q,updatedAt:Q}};if(G.status!=="waiting")return{result:!1};return{result:!0,step:{...G,status:"signalled",output:z,wakeAt:G.wakeAt,finishedAt:Q},tick:{delayMs:0}}});if(X)this.queue.claimSoon();return X===!0}async cancel(Z){let $=await this.store.update(Z,{allSteps:!0},({workflow:V,steps:z})=>{if(R0.includes(V.status)||V.status==="cancelling")return{result:!1};return{result:!0,workflow:{status:"cancelling"},cancelBatches:z.filter((X)=>X.status==="batching"&&X.batchId!==null).map((X)=>X.batchId),tick:{delayMs:0}}});if($)this.queue.claimSoon();return $===!0}async pause(Z){let $=await this.store.update(Z,{},({workflow:V})=>{if(R0.includes(V.status)||V.status==="cancelling"||V.status==="paused")return{result:!1};return{result:!0,workflow:{status:"paused"}}});if($===!0)this.releaseSlotsOf(Z);return $===!0}async resume(Z){let $=await this.store.update(Z,{},({workflow:V})=>{if(V.status!=="paused")return{result:!1};return{result:!0,workflow:{status:"running",wakeAt:null},tick:{delayMs:0}}});if($)this.queue.claimSoon();return $===!0}async find(Z){let $=await this.store.find(Z);if(!$)return null;let{workflow:V,steps:z}=$,X=[];try{X=JSON.parse(V.args)}catch{}return{id:V.id,name:V.name,status:V.status,args:X,currentStep:V.currentStep,progress:V.progress,result:c1(V.result),error:V.error,steps:await Promise.all(z.map(async(Y)=>{let G={key:Y.key,status:Y.status,attempt:Y.attempt,error:Y.error,batchId:Y.batchId,wakeAt:Y.wakeAt,startedAt:Y.startedAt,finishedAt:Y.finishedAt},Q=oZ(Y.output);if(Q)return{...G,items:Q,progress:Q.total===0?1:Q.done/Q.total};if(Y.batchId===null)return G;let B=await this.queue.driver.findBatch?.(Y.batchId);return B?{...G,progress:B.progress}:G})),createdAt:V.createdAt,updatedAt:V.updatedAt}}async items(Z,$,V={}){let z=this.store;if(!z.listItems)return[];let X=Math.max(1,Math.min(1000,Math.floor(V.limit??100)));return(await z.listItems(Z,$,{statuses:V.status?[V.status]:["failed","skipped"],...V.after===void 0?{}:{after:V.after},limit:X})).map(AZ)}async tick(Z,$){let V=this.store,z=$.$claimed,X=z?`${z.id}:${z.attempt}`:`${crypto.randomUUID()}:1`,Y=Math.max(1,this.queue.config.visibilityTimeout),G=await V.acquire(Z,X,Y);if(G.kind!=="acquired")return;let{workflow:Q}=G,B=(P={})=>V.update(Z,{owner:X},()=>({...P,result:void 0,unlock:!0})).then(()=>this.queue.claimSoon()).catch((W)=>{if(!(W instanceof b))throw W});if(R0.includes(Q.status)||Q.status==="paused"){await B(),await this.releaseSlotsOf(Z,Q);return}let H=this.registry[Q.name];if(!H)return this.unknown(Q,$,B);let J;try{J=JSON.parse(Q.args)}catch(P){return B({workflow:{status:"failed",error:`The arguments are not JSON: ${N0(P)}`}})}let F=Q.status==="cancelling",U;try{U=await this.limitsOf(H,J)}catch(P){throw await B(),P}if(U.length>0&&!F&&z){let P=this.queue.driver;if(!P.acquireSlots||!P.releaseSlots)return B({workflow:{status:"failed",error:`${Q.name} declares concurrency, and this queue's driver has no concurrency slots. The memory and database drivers do.`}});if(!await P.acquireSlots({holder:zZ(Z),workflowId:Z,job:z,slots:U,recheckMs:this.queue.slotRecheck()}))return $.$outcome={kind:"parked"},B()}let A=setInterval(()=>{V.renew(Z,X,Y).catch((P)=>{console.error(`[gemi] Could not extend the hold on workflow ${Z}.`,P)})},Math.max(1,Math.floor(Y/3)));A.unref?.();let N=new NZ({workflowId:Z,owner:X,store:V,steps:G.steps,cancelling:F,findBatch:(P)=>this.queue.driver.findBatch?.(P,{progress:!1})??Promise.resolve(null),buildBatch:(P,W,D)=>this.queue.buildBatch(P,W.map((T)=>JSON.stringify(T)),{name:D.name,allowFailures:D.allowFailures,finally:{name:m,args:[Z]}}),scheduled:()=>this.queue.claimSoon(),cancelCheckMs:k1,durable:this.queue.durable,throttle:{hit:(P,W,D)=>this.queue.locks.store.hit(P,W,D),refund:(P)=>this.queue.locks.store.refund(P)}});try{let P;try{let D=new H,T=await(F?D.onCancel(N,...J):D.run(N,...J));P=N.suspension?{kind:"suspended"}:{kind:"completed",result:F?null:S0(T,`The result of ${Q.name}`)}}catch(D){if(P=N.suspension||D instanceof t?{kind:"suspended"}:{kind:"failed",error:N0(D)},D instanceof b)N.lost=!0}if(await N.settled(),N.lost)return;if(P.kind==="completed"&&N.suspension)P={kind:"suspended"};let W;if(await V.update(Z,{owner:X},({workflow:D,now:T})=>{let _=this.finish(D,P,N,F,T);return W=_.workflow?.status??D.status,_}),this.queue.claimSoon(),U.length>0&&W!==void 0&&(R0.includes(W)||W==="paused"))await this.releaseSlots(Z)}catch(P){if(P instanceof b)return;throw P}finally{clearInterval(A)}}finish(Z,$,V,z,X){let Y={result:void 0,unlock:!0};if(Z.status==="cancelling"&&!z)return{...Y,tick:{delayMs:0}};if($.kind==="completed")return{...Y,workflow:z?{status:"cancelled",currentStep:null,wakeAt:null}:{status:"completed",result:$.result,progress:1,currentStep:null,wakeAt:null,error:null}};if($.kind==="failed")return{...Y,workflow:{status:z?"cancelled":"failed",error:$.error,wakeAt:null}};let G=V.suspension??{status:"waiting",wakes:[]};if(!z&&(Z.status==="paused"||G.status==="paused"))return Z.status==="paused"?{...Y,workflow:{currentStep:V.current??Z.currentStep}}:{...Y,workflow:{status:"running"},tick:{delayMs:0}};let Q={...Y,workflow:{status:z?"cancelling":G.status,currentStep:V.current??Z.currentStep}};if(G.wakes.length>0){let B=Math.min(...G.wakes);if(!(Z.wakeAt!==null&&Z.wakeAt>X&&Z.wakeAt<=B))Q.tick={delayMs:Math.max(0,B-X)},Q.workflow.wakeAt=B}return Q}async limitsOf(Z,$){let V=new Z;if(typeof V.concurrency!=="function")return[];return w0(await V.concurrency(...$),Z.name)}async releaseSlots(Z){try{await this.queue.driver.releaseSlots?.(zZ(Z))}catch($){console.error(`[gemi] Could not free the concurrency slots of workflow ${Z}.`,$)}}async releaseSlotsOf(Z,$){try{let V=$??(await this.store.find(Z,{steps:!1}))?.workflow,z=V&&this.registry[V.name];if(!V||!z)return;if((await this.limitsOf(z,JSON.parse(V.args))).length>0)await this.releaseSlots(Z)}catch(V){console.error(`[gemi] Could not free the concurrency slots of workflow ${Z}.`,V)}}async unknown(Z,$,V){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 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 V({workflow:{status:"failed",error:`No workflow is registered under the name "${Z.name}".`}})}tickDeadLettered(Z,$){console.error(`[gemi] The tick of workflow ${Z} was dead-lettered.`,$),this.store.update(Z,{},({workflow:V})=>R0.includes(V.status)?{result:void 0}:{result:void 0,workflow:{status:"failed",error:`Its tick job was dead-lettered: ${$.message}`},unlock:!0}).then(()=>this.releaseSlotsOf(Z)).catch(()=>{})}}function w1(Z){return class extends H0{static name=m;maxAttempts=20;backoff=[1000,5000,15000,30000,60000];async run(V){await Z.tick(V,this)}onDeadletter(V,z){Z.tickDeadLettered(z,V)}}}function c1(Z){try{return n(Z)}catch{return Z}}function d1(Z,$){if(Z.type!=="change")return null;let V=Z.data;if(!V||typeof V!=="object"||V.id!==$||typeof V.updatedAt!=="number")return null;return V}async function l1(Z,$){let V,z=new Promise((X)=>{V=setTimeout(()=>X("timeout"),$)});try{return await Promise.race([Z,z])}finally{clearTimeout(V)}}var __dirname="/home/runner/work/gemi/gemi/packages/gemi/services/queue";function n1(Z=process.env){let $=Z.ROOT_DIR??process.cwd(),V=Z.APP_DIR??`${$}/app`,z=Z.NODE_ENV==="production"?`${$}/dist/server/bootstrap.mjs`:`${V}/bootstrap.ts`,X;try{X=Bun.resolveSync("gemi/app",$)}catch{X=Bun.resolveSync("gemi/app",__dirname)}return{bootstrap:i1(z)?z:void 0,kernel:`${V}/kernel/Kernel.ts`,app:X}}function r1(){let Z=n1(),$=Z.bootstrap?`const { app } = await import(${JSON.stringify(Z.bootstrap)});`:`const { App } = await import(${JSON.stringify(Z.app)});
567
567
  const { default: Kernel } = await import(${JSON.stringify(Z.kernel)});
568
568
  const app = new App({ kernel: Kernel });
569
569
  await app.waitForBoot();`,V=new File([`
@@ -585,7 +585,7 @@ ADD COLUMN IF NOT EXISTS "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batc
585
585
  }
586
586
  };
587
587
  self.postMessage({ ready: true });
588
- `],"worker.ts"),z=URL.createObjectURL(V);return new Worker(z)}async function n1(Z,$){let V=s1();try{return await new Promise((z,X)=>{V.onmessage=(Y)=>{let G=Y.data;if(G&&"ready"in G)V.postMessage({jobName:Z,args:$});else if("error"in G)X(G.error);else z(G.result)},V.onerror=(Y)=>{let G=Y.error??Y.message??Y;X(G instanceof Error?G:Error(`The worker thread for ${Z} failed: ${String(G)}`))},V.addEventListener("close",()=>{X(Error(`The worker thread for ${Z} exited before the job finished.`))})})}finally{V.terminate()}}var r1=new d1("gemi.queue"),t1=60000;class $0{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={},$={}){if(this.config=Z1(mZ(),Z),this.application=$.application,this.driver=V3(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 $ of Z)this.claim($);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 RZ(this),this.workflowRuntime}get boundApplication(){return this.application}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,$){let V=this.jobs[Z];if(!V)throw Error(`No job is registered under the name "${Z}" in this thread, so it did not run. The thread boots the application from app/kernel/Kernel.ts (or app/bootstrap.ts); check that the job is discovered there.`);return new V().run(...JSON.parse($))}push(Z,$,V={}){let z=this.uniqueKey(Z,$);if(z)return this.pushUnique(Z,$,z,V);let X=this.driver.joinsTransaction?.()===!0;if(!X){let Y=Bun.randomUUIDv7();if(o(()=>this.record(Z,$,{id:Y,reportFailure:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(Y)}return this.record(Z,$,{reportFailure:V.reportFailure,joins:X})}pushBatch(Z,$,V={}){let z=this.buildBatch(Z,$,V),X={id:z.id,total:$.length},Y=this.driver.joinsTransaction?.()===!0;if(!Y){if(o(()=>this.recordBatch(z,{committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X)}return this.recordBatch(z,{joins:Y}).then(()=>X)}buildBatch(Z,$,V={}){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!==Q0.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 X={};for(let Y of["then","catch","finally"]){let G=V[Y];if(G===void 0)continue;if(typeof G?.name!=="string"||!Array.isArray(G.args))throw Error(`The batch's ${Y} callback is not a job call. Build it with SomeJob.with(...args).`);X[Y]={name:G.name,args:G.args}}return{id:Bun.randomUUIDv7(),name:V.name??null,job:Z.name,args:$,allowFailures:V.allowFailures===!0,callbacks:X}}recordBatch(Z,$){let V=this.driver.enqueueBatch(Z);this.startIfIdle();let z=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),X=$.joins===!0&&o(z);return V.then(()=>X||z(),(Y)=>{if(!$.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.`,Y)}),V}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 $=await this.driver.cancelBatch(Z);if($)this.claimSoon();return $}get locks(){return this.lockManager??=new $1(this.resolveLockStore()),this.lockManager}resolveLockStore(){let Z=this.config.locks;if(Z==="auto"){let $=this.driver.lockStore?.();if($)return $;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 g0}if(Z==="memory")return new g0;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 C0(this.application.make(DZ));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,$){if(Z.prototype.uniqueId===Q0.prototype.uniqueId)return;let V=new Z,z=V.uniqueId(...JSON.parse($));if(z===void 0||z===null||z==="")return;return{key:oZ(Z.name,z),ttl:Math.max(1,V.uniqueFor)}}pushUnique(Z,$,V,z){let X=Bun.randomUUIDv7();if(o(()=>this.recordUnique(Z,$,V,X,{report:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X);return this.recordUnique(Z,$,V,X,{report:z.reportFailure!==!1,committed:!1})}recordUnique(Z,$,V,z,X){let Y=this.locks.store,G=(async()=>{for(let B=0;B<5;B++){if(await Y.acquire(V.key,z,V.ttl)!==null)try{return await this.record(Z,$,{id:z,reportFailure:!1})}catch(Q){throw await Y.release(V.key,z).catch(()=>{}),Q}let H=await Y.holder(V.key);if(H)return H.owner}throw Error(`The unique key "${V.key}" kept changing hands, so ${Z.name} was not queued.`)})();return G.catch((B)=>{if(!X.report)return;console.error(`[gemi] The queue could not record the unique job ${Z.name}`+(X.committed?", which was held until its transaction committed. The transaction stays committed; the job did not run and will not be retried.":", so it did not run and will not be retried."),B)}),G}async releaseUnique(Z,$,V){if(Z.uniqueId===Q0.prototype.uniqueId)return;try{let z=Z.uniqueId(...$);if(z===void 0||z===null||z==="")return;await this.locks.store.release(oZ(V.name,z),V.id)}catch(z){console.error(`[gemi] Could not free the unique key of ${V.name} (${V.id}); it frees itself after uniqueFor.`,z)}}record(Z,$,V){let z=this.driver.enqueue({name:Z.name,args:$,...V.id===void 0?{}:{id:V.id}});this.startIfIdle();let X=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),Y=V.joins===!0&&o(X);return z.then(()=>Y||X(),(G)=>{if(V.reportFailure===!1)return;console.error(`[gemi] The queue driver could not record ${Z.name}`+(V.committed?", which was held until its transaction committed. The transaction stays committed; the job did not run and will not be retried.":", so it did not run and will not be retried."),G)}),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 $=await this.driver.retryDead(Z);if($)this.claimSoon();return $}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()&&!o1())globalThis.__gemiDevQueue=this;if(this.unsubscribe=this.driver.subscribe?.(()=>this.wake()),this.looping)return this.wake();r1.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=new Promise((X)=>{if(Z!==1/0)$=setTimeout(X,Z)}),z=(async()=>{await this.claiming?.catch(()=>{}),await Promise.allSettled([...this.inFlight.values()].map((X)=>X.done))})();return await Promise.race([z,V]),clearTimeout($),{unfinished:[...this.inFlight.values()].map((X)=>({...X.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&&w0()?0:this.config.concurrency-this.inFlight.size;if(Z>0){this.woken=!1;let $=this.driver.claim(Z,{...this.lease(),registered:{names:Object.keys(this.jobs),graceMs:this.config.unknownJobGrace}});this.claiming=$;let V=[];try{V=await $,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 V)this.execute(z);if(V.length===Z)continue;if(this.woken&&this.inFlight.size<this.config.concurrency)continue}await this.sleep()}}sleep(){return new Promise((Z)=>{let $,V=this.claimFailures>0?this.retryDelay():this.driver.subscribe?void 0:this.config.pollInterval;if(V!==void 0)$=setTimeout(()=>this.wake(),V),$.unref?.();this.resume=()=>{clearTimeout($),Z()}})}retryDelay(){let Z=Math.min(Math.max(0,this.claimFailures-1),30);return Math.min(this.config.pollInterval*2**Z,t1)}wake(){this.woken=!0;let Z=this.resume;this.resume=void 0,Z?.()}get durable(){return!(this.driver instanceof p0)}mayClaimHere(){return!this.application||e1()}lease(){return{visibilityTimeoutMs:this.config.visibilityTimeout}}execute(Z){let $=`${Z.id}:${Z.attempt}`,V=()=>this.run(Z),z=(this.application?eZ.run(this.application,V):V()).catch((X)=>{console.error(`The queue could not record the outcome of ${Z.name}.`,X)}).finally(()=>{this.inFlight.delete($),this.wake()});this.inFlight.set($,{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 $=[...this.inFlight.values()].map((V)=>V.job);Z.heartbeat($,this.lease()).catch((V)=>{console.error("The queue could not extend its job leases.",V)})},Math.max(1,Math.floor(this.config.visibilityTimeout/3))),this.heartbeatTimer.unref?.()}async run(Z){let $=this.jobs[Z.name];if(!$){let Q=Date.now()-Z.createdAt;if(this.durable&&Q<this.config.unknownJobGrace){if(!this.releasedNames.has(Z.name))this.releasedNames.add(Z.name),console.error(`Left a queued "${Z.name}" for another replica: nothing is registered here under that name. It is dead-lettered if no replica has run it within unknownJobGrace (${this.config.unknownJobGrace}ms) of its dispatch.`);await this.driver.release(Z,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}console.error(`Dropped a queued job: nothing is registered under the name "${Z.name}". If the class exists, it was not `+"discovered \u2014 check that it is under the queue slice's jobsDir "+"(app/jobs by default), or list it in app/config/queue.ts."),await this.driver.fail(Z,{error:`No job is registered under the name "${Z.name}".`,retryInMs:null});return}let V;try{V=new $}catch(Q){console.error(`Dropped a queued ${Z.name}: it could not be constructed.`,Q),await this.driver.fail(Z,{error:`The job could not be constructed: ${String(Q)}`,retryInMs:null});return}let z;try{z=JSON.parse(Z.args)}catch(Q){console.error(`Dropped a queued ${Z.name}: its arguments are not JSON.`,Q),await this.driver.fail(Z,{error:`The arguments are not JSON: ${String(Q)}`,retryInMs:null});return}if(Z.attempt>Math.max(1,V.maxAttempts)){let Q=Error(`${Z.name} was claimed for attempt ${Z.attempt} of ${V.maxAttempts}: an earlier attempt never finished, most likely because the process running it exited. Dead-lettered without running it again.`);AZ(`${Z.name}.onDeadletter`,()=>V.onDeadletter(Q,...z)),await this.driver.fail(Z,{error:Q.message,retryInMs:null}),await this.releaseUnique(V,z,Z);return}if(V.$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 J=this.batchHandle(Z);V.batch=J.batch,V.$progress=J.progress}let X,Y;try{Y=await this.admit(V,z,Z)}catch(Q){X=Q}if(!Y&&X===void 0)return;let G;if(Y)try{G=await(V.worker?n1(Z.name,Z.args):V.run(...z))}catch(Q){X=Q}finally{await Y.done()}let B=V.$outcome;if(X===void 0&&B?.kind==="parked")return;if(X===void 0&&B?.kind==="release"){await this.driver.release(Z,{retryInMs:Math.max(0,B.delayMs)});return}if(X===void 0&&B?.kind==="fail")X=B.error;let H=B?.kind==="fail"?B.retry:!0;if(X===void 0)try{V.onSuccess(G,...z)}catch(Q){X=Q}if(X!==void 0){let Q=String(X?.stack??X);if(AZ(`${Z.name}.onFail`,()=>V.onFail(X,...z)),!H||Z.attempt>=V.maxAttempts)AZ(`${Z.name}.onDeadletter`,()=>V.onDeadletter(X,...z)),await this.driver.fail(Z,{error:Q,retryInMs:null}),await this.releaseUnique(V,z,Z);else await this.driver.fail(Z,{error:Q,retryInMs:E0(V.backoff,Z.attempt)});return}await this.driver.complete(Z),await this.releaseUnique(V,z,Z)}batchHandle(Z){let $=Z.batchId,V=this.driver;return{batch:{id:$,cancelled:async()=>(await V.findBatch?.($,{progress:!1}))?.cancelledAt!=null},progress:(z)=>V.reportProgress?.(Z,z)??Promise.resolve()}}async admit(Z,$,V){let z=u0(await Z.concurrency(...$),V.name),X=[Z.throttle(...$)??[]].flat();if(z.length===0&&X.length===0)return{done:async()=>{}};let Y=this.driver,G=async()=>{};if(z.length>0&&Y.acquireSlots&&Y.releaseSlots){if(!await Y.acquireSlots({holder:V.id,job:V,slots:z,recheckMs:this.slotRecheck()}))return;G=()=>Y.releaseSlots(V.id)}else if(z.length>0){let Q=await this.lockSlots(z);if(!Q){await Y.release(V,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}G=async()=>{await Promise.all(Q.map((J)=>J.release()))}}let B=this.locks,H=[];try{for(let Q of X){let J=`gemi:throttle:${Q.key}`,F=await B.store.hit(J,Q.limit,Q.window);if(!F.allowed){await Promise.all(H.map((U)=>B.store.refund(U))),await G(),await Y.release(V,{retryInMs:Math.max(1,F.resetInMs)});return}H.push(J)}}catch(Q){throw await G().catch(()=>{}),Q}return{done:async()=>{await G().catch((Q)=>{console.error(`[gemi] Could not free a concurrency slot of ${V.name}.`,Q)})}}}slotRecheck(){return{near:Math.max(1000,this.config.visibilityTimeout),far:3600000}}async lockSlots(Z){let $=this.config.visibilityTimeout,V=[];for(let{key:z,limit:X}of Z){let Y;for(let G=0;G<X&&!Y;G++)Y=await this.locks.acquire(`gemi:concurrency:${z}:${G}`,{ttl:$,renew:!0})??void 0;if(!Y){await Promise.all(V.map((G)=>G.release()));return}V.push(Y)}return V}}function oZ(Z,$){return`gemi:job:${Z}:${String($)}`}function AZ(Z,$){try{$()}catch(V){console.error(`${Z} threw; the job's claim was ended anyway.`,V)}}function o1(){return Bun.env.NODE_ENV==="production"}function e1(){if(!a1)return!1;if($3())return!0;return process.env.ROOT_DIR!==void 0&&!Z3()}function Z3(Z=process.env){return(Z.GEMI_QUEUE_CLAIM??"").trim().toLowerCase()==="off"}var V1=Symbol.for("gemi.queue.worker");function _6(Z=!0){globalThis[V1]=Z}function $3(){return globalThis[V1]===!0}function V3(Z,$){if(Z==="memory")return new p0;if(Z==="database"||typeof Z==="function"){if(!$&&(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 e0($.make(DZ));return Z($)}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}var z1=65536,z3=500;class X3{static write(Z,$){return KZ(I0(),Z,$,null)}static async read(Z,$){let[V]=await A0(I0()).readSource(Z,$,$+1);return V?JSON.parse(V.payload):void 0}static async readRange(Z,$,V){return(await A0(I0()).readSource(Z,$,V)).map((X)=>JSON.parse(X.payload))}static delete(Z){return A0(I0()).deleteSource(Z)}static prune(Z){return A0(I0()).pruneSources(r(Z))}}function I0(){return B0($0).workflows.store}function A0(Z){if(!Z.writeSource||!Z.readSource||!Z.deleteSource||!Z.pruneSources)throw Error("This queue's workflow store does not keep item sources. The memory and database drivers do.");return Z}async function KZ(Z,$,V,z){if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError(`An item source id is a string of 1 to 191 characters; got ${JSON.stringify($)}.`);A0(Z),await Z.deleteSource($);let X=0,Y=[];for await(let G of V){let B=JSON.stringify(G===void 0?null:G);if(B===void 0)throw TypeError(`Item ${X} of source "${$}" has no JSON form.`);let H=Buffer.byteLength(B,"utf8");if(H>z1)throw RangeError(`Item ${X} of source "${$}" is ${H} bytes as JSON, over the ${z1}-byte limit. Store it elsewhere and keep its id.`);if(Y.push({index:X++,payload:B}),Y.length>=z3)await Z.writeSource($,z,Y),Y=[]}return await Z.writeSource($,z,Y),{id:$,count:X}}function nZ(Z,$,V){A0(Z);let z=new Map,X=new Map,Y=0,G=(B,H)=>{let Q=`${B}:${H}`,J=X.get(Q);if(!J)J=Z.readSource($.id,B,H).then((F)=>{for(let U of F)z.set(U.index,U.payload);X.delete(Q)},(F)=>{throw X.delete(Q),F}),X.set(Q,J);return J};return async(B)=>{if(!z.has(B)){let Q=B-B%V,J=Math.min(Q+V,$.count);if(X.has(`${Q}:${J}`))await X.get(`${Q}:${J}`);else if(B>=Y)Y=Math.max(Y,J),await G(Q,J);if(!z.has(B))await G(B,B+1)}let H=z.get(B);if(z.delete(B),H===void 0)throw Error(`Item source "${$.id}" has no item at index ${B}.`);return JSON.parse(H)}}
589
- export{C0 as ye,g0 as ze,r0 as Ae,jZ as Be,e0 as Ce,E3 as De,mZ as Ee,ZZ as Fe,p0 as Ge,z1 as He,X3 as Ie,YZ as Je,GZ as Ke,BZ as Le,QZ as Me,FZ as Ne,d0 as Oe,RZ as Pe,$0 as Qe,e1 as Re,Z3 as Se,_6 as Te,$3 as Ue,Q0 as Ve};
588
+ `],"worker.ts"),z=URL.createObjectURL(V);return new Worker(z)}async function t1(Z,$){let V=r1();try{return await new Promise((z,X)=>{V.onmessage=(Y)=>{let G=Y.data;if(G&&"ready"in G)V.postMessage({jobName:Z,args:$});else if("error"in G)X(G.error);else z(G.result)},V.onerror=(Y)=>{let G=Y.error??Y.message??Y;X(G instanceof Error?G:Error(`The worker thread for ${Z} failed: ${String(G)}`))},V.addEventListener("close",()=>{X(Error(`The worker thread for ${Z} exited before the job finished.`))})})}finally{V.terminate()}}var o1=new a1("gemi.queue"),e1=60000;class $0{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={},$={}){if(this.config=V1(uZ(),Z),this.application=$.application,this.driver=X3(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 $ of Z)this.claim($);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 DZ(this),this.workflowRuntime}get boundApplication(){return this.application}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,$){let V=this.jobs[Z];if(!V)throw Error(`No job is registered under the name "${Z}" in this thread, so it did not run. The thread boots the application from app/kernel/Kernel.ts (or app/bootstrap.ts); check that the job is discovered there.`);return new V().run(...JSON.parse($))}push(Z,$,V={}){let z=this.uniqueKey(Z,$);if(z)return this.pushUnique(Z,$,z,V);let X=this.driver.joinsTransaction?.()===!0;if(!X){let Y=Bun.randomUUIDv7();if(o(()=>this.record(Z,$,{id:Y,reportFailure:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(Y)}return this.record(Z,$,{reportFailure:V.reportFailure,joins:X})}pushBatch(Z,$,V={}){let z=this.buildBatch(Z,$,V),X={id:z.id,total:$.length},Y=this.driver.joinsTransaction?.()===!0;if(!Y){if(o(()=>this.recordBatch(z,{committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X)}return this.recordBatch(z,{joins:Y}).then(()=>X)}buildBatch(Z,$,V={}){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!==H0.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 X={};for(let Y of["then","catch","finally"]){let G=V[Y];if(G===void 0)continue;if(typeof G?.name!=="string"||!Array.isArray(G.args))throw Error(`The batch's ${Y} callback is not a job call. Build it with SomeJob.with(...args).`);X[Y]={name:G.name,args:G.args}}return{id:Bun.randomUUIDv7(),name:V.name??null,job:Z.name,args:$,allowFailures:V.allowFailures===!0,callbacks:X}}recordBatch(Z,$){let V=this.driver.enqueueBatch(Z);this.startIfIdle();let z=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),X=$.joins===!0&&o(z);return V.then(()=>X||z(),(Y)=>{if(!$.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.`,Y)}),V}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 $=await this.driver.cancelBatch(Z);if($)this.claimSoon();return $}get locks(){return this.lockManager??=new z1(this.resolveLockStore()),this.lockManager}resolveLockStore(){let Z=this.config.locks;if(Z==="auto"){let $=this.driver.lockStore?.();if($)return $;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 y0}if(Z==="memory")return new y0;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 C0(this.application.make(LZ));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,$){if(Z.prototype.uniqueId===H0.prototype.uniqueId)return;let V=new Z,z=V.uniqueId(...JSON.parse($));if(z===void 0||z===null||z==="")return;return{key:Z1(Z.name,z),ttl:Math.max(1,V.uniqueFor)}}pushUnique(Z,$,V,z){let X=Bun.randomUUIDv7();if(o(()=>this.recordUnique(Z,$,V,X,{report:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X);return this.recordUnique(Z,$,V,X,{report:z.reportFailure!==!1,committed:!1})}recordUnique(Z,$,V,z,X){let Y=this.locks.store,G=(async()=>{for(let Q=0;Q<5;Q++){if(await Y.acquire(V.key,z,V.ttl)!==null)try{return await this.record(Z,$,{id:z,reportFailure:!1})}catch(H){throw await Y.release(V.key,z).catch(()=>{}),H}let B=await Y.holder(V.key);if(B)return B.owner}throw Error(`The unique key "${V.key}" kept changing hands, so ${Z.name} was not queued.`)})();return G.catch((Q)=>{if(!X.report)return;console.error(`[gemi] The queue could not record the unique job ${Z.name}`+(X.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."),Q)}),G}async releaseUnique(Z,$,V){if(Z.uniqueId===H0.prototype.uniqueId)return;try{let z=Z.uniqueId(...$);if(z===void 0||z===null||z==="")return;await this.locks.store.release(Z1(V.name,z),V.id)}catch(z){console.error(`[gemi] Could not free the unique key of ${V.name} (${V.id}); it frees itself after uniqueFor.`,z)}}record(Z,$,V){let z=this.driver.enqueue({name:Z.name,args:$,...V.id===void 0?{}:{id:V.id}});this.startIfIdle();let X=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),Y=V.joins===!0&&o(X);return z.then(()=>Y||X(),(G)=>{if(V.reportFailure===!1)return;console.error(`[gemi] The queue driver could not record ${Z.name}`+(V.committed?", which was held until its transaction committed. The transaction stays committed; the job did not run and will not be retried.":", so it did not run and will not be retried."),G)}),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 $=await this.driver.retryDead(Z);if($)this.claimSoon();return $}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()&&!Z3())globalThis.__gemiDevQueue=this;if(this.unsubscribe=this.driver.subscribe?.(()=>this.wake()),this.looping)return this.wake();o1.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=new Promise((X)=>{if(Z!==1/0)$=setTimeout(X,Z)}),z=(async()=>{await this.claiming?.catch(()=>{}),await Promise.allSettled([...this.inFlight.values()].map((X)=>X.done))})();return await Promise.race([z,V]),clearTimeout($),{unfinished:[...this.inFlight.values()].map((X)=>({...X.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&&l0()?0:this.config.concurrency-this.inFlight.size;if(Z>0){this.woken=!1;let $=this.driver.claim(Z,{...this.lease(),registered:{names:Object.keys(this.jobs),graceMs:this.config.unknownJobGrace}});this.claiming=$;let V=[];try{V=await $,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 V)this.execute(z);if(V.length===Z)continue;if(this.woken&&this.inFlight.size<this.config.concurrency)continue}await this.sleep()}}sleep(){return new Promise((Z)=>{let $,V=this.claimFailures>0?this.retryDelay():this.driver.subscribe?void 0:this.config.pollInterval;if(V!==void 0)$=setTimeout(()=>this.wake(),V),$.unref?.();this.resume=()=>{clearTimeout($),Z()}})}retryDelay(){let Z=Math.min(Math.max(0,this.claimFailures-1),30);return Math.min(this.config.pollInterval*2**Z,e1)}wake(){this.woken=!0;let Z=this.resume;this.resume=void 0,Z?.()}get durable(){return!(this.driver instanceof c0)}mayClaimHere(){return!this.application||$3()}lease(){return{visibilityTimeoutMs:this.config.visibilityTimeout}}execute(Z){let $=`${Z.id}:${Z.attempt}`,V=()=>this.run(Z),z=(this.application?$1.run(this.application,V):V()).catch((X)=>{console.error(`The queue could not record the outcome of ${Z.name}.`,X)}).finally(()=>{this.inFlight.delete($),this.wake()});this.inFlight.set($,{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 $=[...this.inFlight.values()].map((V)=>V.job);Z.heartbeat($,this.lease()).catch((V)=>{console.error("The queue could not extend its job leases.",V)})},Math.max(1,Math.floor(this.config.visibilityTimeout/3))),this.heartbeatTimer.unref?.()}async run(Z){let $=this.jobs[Z.name];if(!$){let H=Date.now()-Z.createdAt;if(this.durable&&H<this.config.unknownJobGrace){if(!this.releasedNames.has(Z.name))this.releasedNames.add(Z.name),console.error(`Left a queued "${Z.name}" for another replica: nothing is registered here under that name. It is dead-lettered if no replica has run it within unknownJobGrace (${this.config.unknownJobGrace}ms) of its dispatch.`);await this.driver.release(Z,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}console.error(`Dropped a queued job: nothing is registered under the name "${Z.name}". If the class exists, it was not `+"discovered \u2014 check that it is under the queue slice's jobsDir "+"(app/jobs by default), or list it in app/config/queue.ts."),await this.driver.fail(Z,{error:`No job is registered under the name "${Z.name}".`,retryInMs:null});return}let V;try{V=new $}catch(H){console.error(`Dropped a queued ${Z.name}: it could not be constructed.`,H),await this.driver.fail(Z,{error:`The job could not be constructed: ${String(H)}`,retryInMs:null});return}let z;try{z=JSON.parse(Z.args)}catch(H){console.error(`Dropped a queued ${Z.name}: its arguments are not JSON.`,H),await this.driver.fail(Z,{error:`The arguments are not JSON: ${String(H)}`,retryInMs:null});return}if(Z.attempt>Math.max(1,V.maxAttempts)){let H=Error(`${Z.name} was claimed for attempt ${Z.attempt} of ${V.maxAttempts}: an earlier attempt never finished, most likely because the process running it exited. Dead-lettered without running it again.`);_Z(`${Z.name}.onDeadletter`,()=>V.onDeadletter(H,...z)),await this.driver.fail(Z,{error:H.message,retryInMs:null}),await this.releaseUnique(V,z,Z);return}if(V.$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 J=this.batchHandle(Z);V.batch=J.batch,V.$progress=J.progress}let X,Y;try{Y=await this.admit(V,z,Z)}catch(H){X=H}if(!Y&&X===void 0)return;let G;if(Y)try{G=await(V.worker?t1(Z.name,Z.args):V.run(...z))}catch(H){X=H}finally{await Y.done()}let Q=V.$outcome;if(X===void 0&&Q?.kind==="parked")return;if(X===void 0&&Q?.kind==="release"){await this.driver.release(Z,{retryInMs:Math.max(0,Q.delayMs)});return}if(X===void 0&&Q?.kind==="fail")X=Q.error;let B=Q?.kind==="fail"?Q.retry:!0;if(X===void 0)try{V.onSuccess(G,...z)}catch(H){X=H}if(X!==void 0){let H=String(X?.stack??X);if(_Z(`${Z.name}.onFail`,()=>V.onFail(X,...z)),!B||Z.attempt>=V.maxAttempts)_Z(`${Z.name}.onDeadletter`,()=>V.onDeadletter(X,...z)),await this.driver.fail(Z,{error:H,retryInMs:null}),await this.releaseUnique(V,z,Z);else await this.driver.fail(Z,{error:H,retryInMs:E0(V.backoff,Z.attempt)});return}await this.driver.complete(Z),await this.releaseUnique(V,z,Z)}batchHandle(Z){let $=Z.batchId,V=this.driver;return{batch:{id:$,cancelled:async()=>(await V.findBatch?.($,{progress:!1}))?.cancelledAt!=null},progress:(z)=>V.reportProgress?.(Z,z)??Promise.resolve()}}async admit(Z,$,V){let z=w0(await Z.concurrency(...$),V.name),X=[Z.throttle(...$)??[]].flat();if(z.length===0&&X.length===0)return{done:async()=>{}};let Y=this.driver,G=async()=>{};if(z.length>0&&Y.acquireSlots&&Y.releaseSlots){if(!await Y.acquireSlots({holder:V.id,job:V,slots:z,recheckMs:this.slotRecheck()}))return;G=()=>Y.releaseSlots(V.id)}else if(z.length>0){let H=await this.lockSlots(z);if(!H){await Y.release(V,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}G=async()=>{await Promise.all(H.map((J)=>J.release()))}}let Q=this.locks,B=[];try{for(let H of X){let J=`gemi:throttle:${H.key}`,F=await Q.store.hit(J,H.limit,H.window);if(!F.allowed){await Promise.all(B.map((U)=>Q.store.refund(U))),await G(),await Y.release(V,{retryInMs:Math.max(1,F.resetInMs)});return}B.push(J)}}catch(H){throw await G().catch(()=>{}),H}return{done:async()=>{await G().catch((H)=>{console.error(`[gemi] Could not free a concurrency slot of ${V.name}.`,H)})}}}slotRecheck(){return{near:Math.max(1000,this.config.visibilityTimeout),far:3600000}}async lockSlots(Z){let $=this.config.visibilityTimeout,V=[];for(let{key:z,limit:X}of Z){let Y;for(let G=0;G<X&&!Y;G++)Y=await this.locks.acquire(`gemi:concurrency:${z}:${G}`,{ttl:$,renew:!0})??void 0;if(!Y){await Promise.all(V.map((G)=>G.release()));return}V.push(Y)}return V}}function Z1(Z,$){return`gemi:job:${Z}:${String($)}`}function _Z(Z,$){try{$()}catch(V){console.error(`${Z} threw; the job's claim was ended anyway.`,V)}}function Z3(){return Bun.env.NODE_ENV==="production"}function $3(){if(!s1)return!1;if(z3())return!0;return process.env.ROOT_DIR!==void 0&&!V3()}function V3(Z=process.env){return(Z.GEMI_QUEUE_CLAIM??"").trim().toLowerCase()==="off"}var X1=Symbol.for("gemi.queue.worker");function O6(Z=!0){globalThis[X1]=Z}function z3(){return globalThis[X1]===!0}function X3(Z,$){if(Z==="memory")return new c0;if(Z==="database"||typeof Z==="function"){if(!$&&(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 $Z($.make(LZ));return Z($)}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}var Y1=65536,Y3=500;class G3{static write(Z,$){return UZ(I0(),Z,$,null)}static async read(Z,$){let[V]=await A0(I0()).readSource(Z,$,$+1);return V?JSON.parse(V.payload):void 0}static async readRange(Z,$,V){return(await A0(I0()).readSource(Z,$,V)).map((X)=>JSON.parse(X.payload))}static delete(Z){return A0(I0()).deleteSource(Z)}static prune(Z){return A0(I0()).pruneSources(r(Z))}}function I0(){return Q0($0).workflows.store}function A0(Z){if(!Z.writeSource||!Z.readSource||!Z.deleteSource||!Z.pruneSources)throw Error("This queue's workflow store does not keep item sources. The memory and database drivers do.");return Z}async function UZ(Z,$,V,z){if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError(`An item source id is a string of 1 to 191 characters; got ${JSON.stringify($)}.`);A0(Z),await Z.deleteSource($);let X=0,Y=[];for await(let G of V){let Q=JSON.stringify(G===void 0?null:G);if(Q===void 0)throw TypeError(`Item ${X} of source "${$}" has no JSON form.`);let B=Buffer.byteLength(Q,"utf8");if(B>Y1)throw RangeError(`Item ${X} of source "${$}" is ${B} bytes as JSON, over the ${Y1}-byte limit. Store it elsewhere and keep its id.`);if(Y.push({index:X++,payload:Q}),Y.length>=Y3)await Z.writeSource($,z,Y),Y=[]}return await Z.writeSource($,z,Y),{id:$,count:X}}function tZ(Z,$,V){A0(Z);let z=new Map,X=new Map,Y=0,G=(Q,B)=>{let H=`${Q}:${B}`,J=X.get(H);if(!J)J=Z.readSource($.id,Q,B).then((F)=>{for(let U of F)z.set(U.index,U.payload);X.delete(H)},(F)=>{throw X.delete(H),F}),X.set(H,J);return J};return async(Q)=>{if(!z.has(Q)){let H=Q-Q%V,J=Math.min(H+V,$.count);if(X.has(`${H}:${J}`))await X.get(`${H}:${J}`);else if(Q>=Y)Y=Math.max(Y,J),await G(H,J);if(!z.has(Q))await G(Q,Q+1)}let B=z.get(Q);if(z.delete(Q),B===void 0)throw Error(`Item source "${$.id}" has no item at index ${Q}.`);return JSON.parse(B)}}
589
+ export{C0 as ye,y0 as ze,o0 as Ae,xZ as Be,$Z as Ce,M3 as De,uZ as Ee,VZ as Fe,c0 as Ge,Y1 as He,G3 as Ie,QZ as Je,HZ as Ke,BZ as Le,JZ as Me,NZ as Ne,a0 as Oe,DZ as Pe,$0 as Qe,$3 as Re,V3 as Se,O6 as Te,z3 as Ue,H0 as Ve};
590
590
 
591
- //# debugId=21BB7373F3EBE93A64756E2164756E21
591
+ //# debugId=FBAE63E9563D31C364756E2164756E21