bunqueue-client 0.1.8 → 0.2.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 (580) hide show
  1. package/CHANGELOG.md +162 -0
  2. package/LEGACY.md +460 -0
  3. package/README.md +204 -349
  4. package/dist/ack-batcher.js +7 -67
  5. package/dist/canonical-manifest.json +930 -0
  6. package/dist/chunk-b967v3w3.js +79 -0
  7. package/dist/chunk-fekm0ma6.js +110 -0
  8. package/dist/chunk-jxkszwqp.js +573 -0
  9. package/dist/embedded.js +16418 -0
  10. package/dist/frame.js +14 -57
  11. package/dist/index.d.ts +1 -27
  12. package/dist/index.js +10905 -16
  13. package/dist/legacy.d.ts +1 -0
  14. package/dist/legacy.js +2081 -0
  15. package/dist/{ack-batcher.d.ts → types/sdk/typescript/src/ack-batcher.d.ts} +3 -3
  16. package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/aging.d.ts +2 -2
  17. package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/batch.d.ts +2 -2
  18. package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/bunqueue-api.d.ts +5 -5
  19. package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/bunqueue.d.ts +13 -13
  20. package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/circuit-breaker.d.ts +2 -2
  21. package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/dedup-debounce.d.ts +2 -2
  22. package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/dlq-rate-limit.d.ts +2 -2
  23. package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/rate-gate.d.ts +1 -1
  24. package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/retry.d.ts +1 -1
  25. package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/triggers.d.ts +3 -3
  26. package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/ttl.d.ts +1 -1
  27. package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/types.d.ts +4 -4
  28. package/dist/types/sdk/typescript/src/canonical-transport/bun-sqlite-types.d.ts +21 -0
  29. package/dist/{connection-pool.d.ts → types/sdk/typescript/src/connection-pool.d.ts} +1 -1
  30. package/dist/{connection-types.d.ts → types/sdk/typescript/src/connection-types.d.ts} +1 -1
  31. package/dist/{connection.d.ts → types/sdk/typescript/src/connection.d.ts} +6 -19
  32. package/dist/{errors.d.ts → types/sdk/typescript/src/errors.d.ts} +3 -0
  33. package/dist/types/sdk/typescript/src/flow-commit.d.ts +5 -0
  34. package/dist/types/sdk/typescript/src/flow-plan-legacy.d.ts +13 -0
  35. package/dist/types/sdk/typescript/src/flow-plan.d.ts +29 -0
  36. package/dist/{flow-types.d.ts → types/sdk/typescript/src/flow-types.d.ts} +7 -4
  37. package/dist/{flow.d.ts → types/sdk/typescript/src/flow.d.ts} +6 -10
  38. package/dist/{frame.d.ts → types/sdk/typescript/src/frame.d.ts} +1 -1
  39. package/dist/types/sdk/typescript/src/index.d.ts +10 -0
  40. package/dist/{job.d.ts → types/sdk/typescript/src/job.d.ts} +4 -3
  41. package/dist/types/sdk/typescript/src/legacy.d.ts +27 -0
  42. package/dist/{observability.d.ts → types/sdk/typescript/src/observability.d.ts} +14 -0
  43. package/dist/{queue-admin.d.ts → types/sdk/typescript/src/queue-admin.d.ts} +3 -4
  44. package/dist/{queue-control.d.ts → types/sdk/typescript/src/queue-control.d.ts} +7 -6
  45. package/dist/{queue-query.d.ts → types/sdk/typescript/src/queue-query.d.ts} +3 -3
  46. package/dist/{queue.d.ts → types/sdk/typescript/src/queue.d.ts} +8 -8
  47. package/dist/{responses.d.ts → types/sdk/typescript/src/responses.d.ts} +2 -2
  48. package/dist/types/sdk/typescript/src/serialization.d.ts +10 -0
  49. package/dist/{socket-factory.d.ts → types/sdk/typescript/src/socket-factory.d.ts} +1 -1
  50. package/dist/types/sdk/typescript/src/terminal-outcome.d.ts +8 -0
  51. package/dist/{types.d.ts → types/sdk/typescript/src/types.d.ts} +5 -2
  52. package/dist/{worker-base.d.ts → types/sdk/typescript/src/worker-base.d.ts} +6 -6
  53. package/dist/types/sdk/typescript/src/worker-slot-signal.d.ts +6 -0
  54. package/dist/{worker-types.d.ts → types/sdk/typescript/src/worker-types.d.ts} +3 -3
  55. package/dist/{worker.d.ts → types/sdk/typescript/src/worker.d.ts} +3 -2
  56. package/dist/types/src/application/background/dlq.d.ts +2 -0
  57. package/dist/types/src/application/background/lifecycle.d.ts +4 -0
  58. package/dist/types/src/application/background/recovery/active.d.ts +5 -0
  59. package/dist/types/src/application/background/recovery/index.d.ts +2 -0
  60. package/dist/types/src/application/background/recovery/pending.d.ts +3 -0
  61. package/dist/types/src/application/background/recovery/restore.d.ts +5 -0
  62. package/dist/types/src/application/background/recovery/shared.d.ts +6 -0
  63. package/dist/types/src/application/background/timeouts.d.ts +25 -0
  64. package/dist/types/src/application/backgroundTasks.d.ts +7 -0
  65. package/dist/types/src/application/cleanupTasks.d.ts +10 -0
  66. package/dist/types/src/application/clientTracking.d.ts +44 -0
  67. package/dist/types/src/application/completedCleanup.d.ts +34 -0
  68. package/dist/types/src/application/completedRetry.d.ts +21 -0
  69. package/dist/types/src/application/contextFactory.d.ts +49 -0
  70. package/dist/types/src/application/dependencyCompletions.d.ts +63 -0
  71. package/dist/types/src/application/dependencyProcessor.d.ts +15 -0
  72. package/dist/types/src/application/dependencyResultTracker.d.ts +18 -0
  73. package/dist/types/src/application/dlqManager.d.ts +49 -0
  74. package/dist/types/src/application/dlqRetry.d.ts +12 -0
  75. package/dist/types/src/application/emptyQueueCleanup.d.ts +3 -0
  76. package/dist/types/src/application/eventsManager.d.ts +50 -0
  77. package/dist/types/src/application/flowFailureRecovery.d.ts +20 -0
  78. package/dist/types/src/application/flowParentBackpatch.d.ts +27 -0
  79. package/dist/types/src/application/jobLogsManager.d.ts +21 -0
  80. package/dist/types/src/application/latencyTracker.d.ts +39 -0
  81. package/dist/types/src/application/lockManager.d.ts +15 -0
  82. package/dist/types/src/application/lockOperations.d.ts +38 -0
  83. package/dist/types/src/application/metricsExporter.d.ts +27 -0
  84. package/dist/types/src/application/monitoringChecks.d.ts +36 -0
  85. package/dist/types/src/application/operations/ack/batch.d.ts +8 -0
  86. package/dist/types/src/application/operations/ack/completion.d.ts +3 -0
  87. package/dist/types/src/application/operations/ack/failure.d.ts +3 -0
  88. package/dist/types/src/application/operations/ack.d.ts +5 -0
  89. package/dist/types/src/application/operations/ackHelpers.d.ts +36 -0
  90. package/dist/types/src/application/operations/customId.d.ts +51 -0
  91. package/dist/types/src/application/operations/flowPush.d.ts +9 -0
  92. package/dist/types/src/application/operations/flowTopologyValidation.d.ts +3 -0
  93. package/dist/types/src/application/operations/flowValidation.d.ts +3 -0
  94. package/dist/types/src/application/operations/jobClaim.d.ts +17 -0
  95. package/dist/types/src/application/operations/jobManagement.d.ts +43 -0
  96. package/dist/types/src/application/operations/jobMoveOperations.d.ts +9 -0
  97. package/dist/types/src/application/operations/jobPromotion.d.ts +7 -0
  98. package/dist/types/src/application/operations/jobStateTransitions.d.ts +15 -0
  99. package/dist/types/src/application/operations/parentLink.d.ts +36 -0
  100. package/dist/types/src/application/operations/parentLinkInput.d.ts +8 -0
  101. package/dist/types/src/application/operations/pull.d.ts +20 -0
  102. package/dist/types/src/application/operations/pullFinalization.d.ts +6 -0
  103. package/dist/types/src/application/operations/pullStateTransition.d.ts +51 -0
  104. package/dist/types/src/application/operations/push.d.ts +13 -0
  105. package/dist/types/src/application/operations/pushAdmission.d.ts +36 -0
  106. package/dist/types/src/application/operations/pushBatch.d.ts +4 -0
  107. package/dist/types/src/application/operations/pushContext.d.ts +48 -0
  108. package/dist/types/src/application/operations/pushDeduplication.d.ts +42 -0
  109. package/dist/types/src/application/operations/pushInsert.d.ts +39 -0
  110. package/dist/types/src/application/operations/pushLocks.d.ts +15 -0
  111. package/dist/types/src/application/operations/query/collect.d.ts +12 -0
  112. package/dist/types/src/application/operations/query/jobLookup.d.ts +9 -0
  113. package/dist/types/src/application/operations/query/pagination.d.ts +8 -0
  114. package/dist/types/src/application/operations/query/state.d.ts +4 -0
  115. package/dist/types/src/application/operations/queryOperations.d.ts +5 -0
  116. package/dist/types/src/application/operations/queueControl.d.ts +50 -0
  117. package/dist/types/src/application/prometheusOperationalMetrics.d.ts +31 -0
  118. package/dist/types/src/application/queue-manager/ack.d.ts +23 -0
  119. package/dist/types/src/application/queue-manager/configuration.d.ts +27 -0
  120. package/dist/types/src/application/queue-manager/context.d.ts +5 -0
  121. package/dist/types/src/application/queue-manager/control.d.ts +20 -0
  122. package/dist/types/src/application/queue-manager/delivery.d.ts +33 -0
  123. package/dist/types/src/application/queue-manager/dependencies.d.ts +8 -0
  124. package/dist/types/src/application/queue-manager/dependency-runtime.d.ts +8 -0
  125. package/dist/types/src/application/queue-manager/flow-failures.d.ts +18 -0
  126. package/dist/types/src/application/queue-manager/flow-options.d.ts +8 -0
  127. package/dist/types/src/application/queue-manager/job-management.d.ts +17 -0
  128. package/dist/types/src/application/queue-manager/lifecycle.d.ts +4 -0
  129. package/dist/types/src/application/queue-manager/limits.d.ts +58 -0
  130. package/dist/types/src/application/queue-manager/locks.d.ts +21 -0
  131. package/dist/types/src/application/queue-manager/observability.d.ts +16 -0
  132. package/dist/types/src/application/queue-manager/queries.d.ts +24 -0
  133. package/dist/types/src/application/queue-manager/repeat.d.ts +4 -0
  134. package/dist/types/src/application/queue-manager/services.d.ts +19 -0
  135. package/dist/types/src/application/queue-manager/state.d.ts +96 -0
  136. package/dist/types/src/application/queue-manager/stats.d.ts +28 -0
  137. package/dist/types/src/application/queueManager.d.ts +5 -0
  138. package/dist/types/src/application/queueStatsAggregator.d.ts +23 -0
  139. package/dist/types/src/application/queueTelemetryJournal.d.ts +24 -0
  140. package/dist/types/src/application/repeatJobs.d.ts +7 -0
  141. package/dist/types/src/application/stallDetection.d.ts +10 -0
  142. package/dist/types/src/application/statsManager.d.ts +59 -0
  143. package/dist/types/src/application/taskErrorTracking.d.ts +22 -0
  144. package/dist/types/src/application/throughputTracker.d.ts +34 -0
  145. package/dist/types/src/application/types/ack.d.ts +136 -0
  146. package/dist/types/src/application/types/background.d.ts +18 -0
  147. package/dist/types/src/application/types/config.d.ts +41 -0
  148. package/dist/types/src/application/types/contextFactory.d.ts +87 -0
  149. package/dist/types/src/application/types/contexts.d.ts +114 -0
  150. package/dist/types/src/application/types/index.d.ts +7 -0
  151. package/dist/types/src/application/types/query.d.ts +23 -0
  152. package/dist/types/src/application/types/queueManager.d.ts +98 -0
  153. package/dist/types/src/application/webhookManager.d.ts +47 -0
  154. package/dist/types/src/application/workerManager.d.ts +61 -0
  155. package/dist/types/src/client/bunqueue/aging.d.ts +16 -0
  156. package/dist/types/src/client/bunqueue/batch.d.ts +16 -0
  157. package/dist/types/src/client/bunqueue/cancellation.d.ts +21 -0
  158. package/dist/types/src/client/bunqueue/circuitBreaker.d.ts +21 -0
  159. package/dist/types/src/client/bunqueue/dedupDebounce.d.ts +12 -0
  160. package/dist/types/src/client/bunqueue/dlqRateLimit.d.ts +26 -0
  161. package/dist/types/src/client/bunqueue/retry.d.ts +8 -0
  162. package/dist/types/src/client/bunqueue/runtime.d.ts +35 -0
  163. package/dist/types/src/client/bunqueue/triggers.d.ts +17 -0
  164. package/dist/types/src/client/bunqueue/ttl.d.ts +17 -0
  165. package/dist/types/src/client/bunqueue/types.d.ts +147 -0
  166. package/dist/types/src/client/bunqueue.d.ts +73 -0
  167. package/dist/types/src/client/dlqConversion.d.ts +5 -0
  168. package/dist/types/src/client/errors.d.ts +24 -0
  169. package/dist/types/src/client/events.d.ts +85 -0
  170. package/dist/types/src/client/flow.d.ts +70 -0
  171. package/dist/types/src/client/flowAtomic.d.ts +9 -0
  172. package/dist/types/src/client/flowJobCoreMethods.d.ts +28 -0
  173. package/dist/types/src/client/flowJobDependencies.d.ts +7 -0
  174. package/dist/types/src/client/flowJobFactory.d.ts +24 -0
  175. package/dist/types/src/client/flowJobMoveMethods.d.ts +16 -0
  176. package/dist/types/src/client/flowJobTypes.d.ts +29 -0
  177. package/dist/types/src/client/flowLegacyPlan.d.ts +16 -0
  178. package/dist/types/src/client/flowOptions.d.ts +10 -0
  179. package/dist/types/src/client/flowPlan.d.ts +16 -0
  180. package/dist/types/src/client/flowPush.d.ts +27 -0
  181. package/dist/types/src/client/flowReader.d.ts +10 -0
  182. package/dist/types/src/client/flowResults.d.ts +11 -0
  183. package/dist/types/src/client/flowTypes.d.ts +77 -0
  184. package/dist/types/src/client/forwarder.d.ts +74 -0
  185. package/dist/types/src/client/groupId.d.ts +1 -0
  186. package/dist/types/src/client/index.d.ts +46 -0
  187. package/dist/types/src/client/jobConversion.d.ts +10 -0
  188. package/dist/types/src/client/jobConversionHelpers.d.ts +28 -0
  189. package/dist/types/src/client/jobConversionTypes.d.ts +88 -0
  190. package/dist/types/src/client/jobDeduplication.d.ts +6 -0
  191. package/dist/types/src/client/jobHelpers.d.ts +31 -0
  192. package/dist/types/src/client/legacyConnectionOptions.d.ts +8 -0
  193. package/dist/types/src/client/manager.d.ts +15 -0
  194. package/dist/types/src/client/pro.d.ts +9 -0
  195. package/dist/types/src/client/queue/addBatcher.d.ts +59 -0
  196. package/dist/types/src/client/queue/bullmqCompat.d.ts +57 -0
  197. package/dist/types/src/client/queue/deduplication.d.ts +14 -0
  198. package/dist/types/src/client/queue/dlq.d.ts +61 -0
  199. package/dist/types/src/client/queue/dlqJobMethods.d.ts +9 -0
  200. package/dist/types/src/client/queue/dlqOps.d.ts +26 -0
  201. package/dist/types/src/client/queue/dlqStats.d.ts +3 -0
  202. package/dist/types/src/client/queue/failWire.d.ts +17 -0
  203. package/dist/types/src/client/queue/helpers.d.ts +19 -0
  204. package/dist/types/src/client/queue/job-proxy/dependencies.d.ts +9 -0
  205. package/dist/types/src/client/queue/job-proxy/reflection.d.ts +2 -0
  206. package/dist/types/src/client/queue/job-proxy/simple.d.ts +3 -0
  207. package/dist/types/src/client/queue/job-proxy/tcp.d.ts +4 -0
  208. package/dist/types/src/client/queue/jobMetadata.d.ts +10 -0
  209. package/dist/types/src/client/queue/jobMove.d.ts +32 -0
  210. package/dist/types/src/client/queue/jobProxy.d.ts +4 -0
  211. package/dist/types/src/client/queue/operations/add/bulk.d.ts +7 -0
  212. package/dist/types/src/client/queue/operations/add/payload.d.ts +25 -0
  213. package/dist/types/src/client/queue/operations/add/single.d.ts +3 -0
  214. package/dist/types/src/client/queue/operations/add.d.ts +2 -0
  215. package/dist/types/src/client/queue/operations/control.d.ts +42 -0
  216. package/dist/types/src/client/queue/operations/counts.d.ts +48 -0
  217. package/dist/types/src/client/queue/operations/groups.d.ts +24 -0
  218. package/dist/types/src/client/queue/operations/management.d.ts +51 -0
  219. package/dist/types/src/client/queue/operations/query.d.ts +50 -0
  220. package/dist/types/src/client/queue/operations/queryStates.d.ts +13 -0
  221. package/dist/types/src/client/queue/operations/queryTcpPages.d.ts +14 -0
  222. package/dist/types/src/client/queue/queue.d.ts +12 -0
  223. package/dist/types/src/client/queue/rateLimit.d.ts +46 -0
  224. package/dist/types/src/client/queue/runtime/compatibility.d.ts +13 -0
  225. package/dist/types/src/client/queue/runtime/configuration.d.ts +46 -0
  226. package/dist/types/src/client/queue/runtime/connection.d.ts +6 -0
  227. package/dist/types/src/client/queue/runtime/control.d.ts +41 -0
  228. package/dist/types/src/client/queue/runtime/queries.d.ts +66 -0
  229. package/dist/types/src/client/queue/runtime/scheduling.d.ts +33 -0
  230. package/dist/types/src/client/queue/runtime/state.d.ts +101 -0
  231. package/dist/types/src/client/queue/scheduler.d.ts +58 -0
  232. package/dist/types/src/client/queue/schedulerPagination.d.ts +7 -0
  233. package/dist/types/src/client/queue/stall.d.ts +20 -0
  234. package/dist/types/src/client/queue/types/add.d.ts +40 -0
  235. package/dist/types/src/client/queue/types/contexts.d.ts +33 -0
  236. package/dist/types/src/client/queue/types/index.d.ts +3 -0
  237. package/dist/types/src/client/queue/types/job.d.ts +50 -0
  238. package/dist/types/src/client/queue/types/runtime.d.ts +35 -0
  239. package/dist/types/src/client/queue/workers.d.ts +36 -0
  240. package/dist/types/src/client/queue-events/tcpSubscription.d.ts +23 -0
  241. package/dist/types/src/client/queue.d.ts +5 -0
  242. package/dist/types/src/client/queueGroup.d.ts +51 -0
  243. package/dist/types/src/client/resolveToken.d.ts +10 -0
  244. package/dist/types/src/client/sandboxed/index.d.ts +7 -0
  245. package/dist/types/src/client/sandboxed/queueOps.d.ts +24 -0
  246. package/dist/types/src/client/sandboxed/runtime/dispatch.d.ts +13 -0
  247. package/dist/types/src/client/sandboxed/runtime/lifecycle.d.ts +20 -0
  248. package/dist/types/src/client/sandboxed/runtime/log.d.ts +1 -0
  249. package/dist/types/src/client/sandboxed/runtime/pool.d.ts +11 -0
  250. package/dist/types/src/client/sandboxed/runtime/recovery.d.ts +11 -0
  251. package/dist/types/src/client/sandboxed/runtime/state.d.ts +39 -0
  252. package/dist/types/src/client/sandboxed/types/index.d.ts +2 -0
  253. package/dist/types/src/client/sandboxed/types/options.d.ts +27 -0
  254. package/dist/types/src/client/sandboxed/types/process.d.ts +39 -0
  255. package/dist/types/src/client/sandboxed/worker.d.ts +4 -0
  256. package/dist/types/src/client/sandboxed/wrapper.d.ts +12 -0
  257. package/dist/types/src/client/sandboxedWorker.d.ts +6 -0
  258. package/dist/types/src/client/tcp/client.d.ts +6 -0
  259. package/dist/types/src/client/tcp/commandQueue.d.ts +23 -0
  260. package/dist/types/src/client/tcp/connection.d.ts +4 -0
  261. package/dist/types/src/client/tcp/errors.d.ts +6 -0
  262. package/dist/types/src/client/tcp/health.d.ts +60 -0
  263. package/dist/types/src/client/tcp/index.d.ts +11 -0
  264. package/dist/types/src/client/tcp/reconnect.d.ts +47 -0
  265. package/dist/types/src/client/tcp/runtime/commands.d.ts +9 -0
  266. package/dist/types/src/client/tcp/runtime/connectivity.d.ts +13 -0
  267. package/dist/types/src/client/tcp/runtime/health.d.ts +14 -0
  268. package/dist/types/src/client/tcp/runtime/lifecycle.d.ts +8 -0
  269. package/dist/types/src/client/tcp/runtime/state.d.ts +50 -0
  270. package/dist/types/src/client/tcp/shared.d.ts +12 -0
  271. package/dist/types/src/client/tcp/transport.d.ts +18 -0
  272. package/dist/types/src/client/tcp/types/command.d.ts +9 -0
  273. package/dist/types/src/client/tcp/types/connection.d.ts +31 -0
  274. package/dist/types/src/client/tcp/types/index.d.ts +5 -0
  275. package/dist/types/src/client/tcp/types/socket.d.ts +8 -0
  276. package/dist/types/src/client/tcp/types/tls.d.ts +4 -0
  277. package/dist/types/src/client/tcp/types.d.ts +2 -0
  278. package/dist/types/src/client/tcpClient.d.ts +6 -0
  279. package/dist/types/src/client/tcpPool.d.ts +69 -0
  280. package/dist/types/src/client/types/connection.d.ts +30 -0
  281. package/dist/types/src/client/types/dlq.d.ts +45 -0
  282. package/dist/types/src/client/types/events.d.ts +54 -0
  283. package/dist/types/src/client/types/flow.d.ts +22 -0
  284. package/dist/types/src/client/types/index.d.ts +10 -0
  285. package/dist/types/src/client/types/job.d.ts +131 -0
  286. package/dist/types/src/client/types/metrics.d.ts +1 -0
  287. package/dist/types/src/client/types/options.d.ts +70 -0
  288. package/dist/types/src/client/types/worker.d.ts +54 -0
  289. package/dist/types/src/client/types.d.ts +2 -0
  290. package/dist/types/src/client/worker/ackBatcher.d.ts +55 -0
  291. package/dist/types/src/client/worker/ackFrontier.d.ts +21 -0
  292. package/dist/types/src/client/worker/ackOutcome.d.ts +8 -0
  293. package/dist/types/src/client/worker/batchExecution.d.ts +14 -0
  294. package/dist/types/src/client/worker/constants.d.ts +7 -0
  295. package/dist/types/src/client/worker/groupConcurrency.d.ts +49 -0
  296. package/dist/types/src/client/worker/handlers/completion.d.ts +29 -0
  297. package/dist/types/src/client/worker/handlers/dependencies.d.ts +11 -0
  298. package/dist/types/src/client/worker/handlers/mutations.d.ts +23 -0
  299. package/dist/types/src/client/worker/handlers/queries.d.ts +15 -0
  300. package/dist/types/src/client/worker/jobParser.d.ts +9 -0
  301. package/dist/types/src/client/worker/processor.d.ts +11 -0
  302. package/dist/types/src/client/worker/processorHandlers.d.ts +4 -0
  303. package/dist/types/src/client/worker/processorOutcome.d.ts +14 -0
  304. package/dist/types/src/client/worker/processorResult.d.ts +2 -0
  305. package/dist/types/src/client/worker/runtime/buffer.d.ts +8 -0
  306. package/dist/types/src/client/worker/runtime/control.d.ts +28 -0
  307. package/dist/types/src/client/worker/runtime/execution.d.ts +16 -0
  308. package/dist/types/src/client/worker/runtime/lifecycle.d.ts +7 -0
  309. package/dist/types/src/client/worker/runtime/manual.d.ts +10 -0
  310. package/dist/types/src/client/worker/runtime/options.d.ts +5 -0
  311. package/dist/types/src/client/worker/runtime/polling.d.ts +14 -0
  312. package/dist/types/src/client/worker/runtime/state.d.ts +121 -0
  313. package/dist/types/src/client/worker/types/index.d.ts +5 -0
  314. package/dist/types/src/client/worker/types/manual.d.ts +7 -0
  315. package/dist/types/src/client/worker/types/options.d.ts +26 -0
  316. package/dist/types/src/client/worker/types/outcome.d.ts +23 -0
  317. package/dist/types/src/client/worker/types/processor.d.ts +25 -0
  318. package/dist/types/src/client/worker/types/transport.d.ts +11 -0
  319. package/dist/types/src/client/worker/worker.d.ts +6 -0
  320. package/dist/types/src/client/worker/workerHeartbeat.d.ts +15 -0
  321. package/dist/types/src/client/worker/workerPull.d.ts +24 -0
  322. package/dist/types/src/client/worker/workerRateLimiter.d.ts +51 -0
  323. package/dist/types/src/client/worker.d.ts +6 -0
  324. package/dist/types/src/client/workflow/admission.d.ts +45 -0
  325. package/dist/types/src/client/workflow/clock.d.ts +60 -0
  326. package/dist/types/src/client/workflow/compensationChild.d.ts +33 -0
  327. package/dist/types/src/client/workflow/compensationClaim.d.ts +11 -0
  328. package/dist/types/src/client/workflow/compensationPass.d.ts +17 -0
  329. package/dist/types/src/client/workflow/compensationSupport.d.ts +24 -0
  330. package/dist/types/src/client/workflow/compensator.d.ts +34 -0
  331. package/dist/types/src/client/workflow/definitionGuard.d.ts +11 -0
  332. package/dist/types/src/client/workflow/emitter.d.ts +17 -0
  333. package/dist/types/src/client/workflow/engine.d.ts +66 -0
  334. package/dist/types/src/client/workflow/eventTypes.d.ts +44 -0
  335. package/dist/types/src/client/workflow/executionFence.d.ts +15 -0
  336. package/dist/types/src/client/workflow/executionTypes.d.ts +133 -0
  337. package/dist/types/src/client/workflow/executor.d.ts +52 -0
  338. package/dist/types/src/client/workflow/executorLifecycle.d.ts +19 -0
  339. package/dist/types/src/client/workflow/executorNodes.d.ts +18 -0
  340. package/dist/types/src/client/workflow/executorQueue.d.ts +9 -0
  341. package/dist/types/src/client/workflow/forEachRunner.d.ts +4 -0
  342. package/dist/types/src/client/workflow/identity.d.ts +48 -0
  343. package/dist/types/src/client/workflow/index.d.ts +23 -0
  344. package/dist/types/src/client/workflow/loops.d.ts +11 -0
  345. package/dist/types/src/client/workflow/mapRunner.d.ts +4 -0
  346. package/dist/types/src/client/workflow/recovery.d.ts +32 -0
  347. package/dist/types/src/client/workflow/rollbackControl.d.ts +37 -0
  348. package/dist/types/src/client/workflow/runner.d.ts +23 -0
  349. package/dist/types/src/client/workflow/runnerTiming.d.ts +14 -0
  350. package/dist/types/src/client/workflow/stepTypes.d.ts +171 -0
  351. package/dist/types/src/client/workflow/store.d.ts +83 -0
  352. package/dist/types/src/client/workflow/storeCodec.d.ts +7 -0
  353. package/dist/types/src/client/workflow/storeExecutionCodec.d.ts +11 -0
  354. package/dist/types/src/client/workflow/storeListing.d.ts +11 -0
  355. package/dist/types/src/client/workflow/storeMaintenance.d.ts +4 -0
  356. package/dist/types/src/client/workflow/storeSignals.d.ts +70 -0
  357. package/dist/types/src/client/workflow/subWorkflowRunner.d.ts +14 -0
  358. package/dist/types/src/client/workflow/types.d.ts +4 -0
  359. package/dist/types/src/client/workflow/unwindPlan.d.ts +87 -0
  360. package/dist/types/src/client/workflow/waitFor.d.ts +56 -0
  361. package/dist/types/src/client/workflow/workflow.d.ts +70 -0
  362. package/dist/types/src/client/workflow/workflowDecisions.d.ts +11 -0
  363. package/dist/types/src/client/workflow/workflowDefinition.d.ts +16 -0
  364. package/dist/types/src/client/workflow/workflowIntrospection.d.ts +5 -0
  365. package/dist/types/src/client/workflow/workflowValidation.d.ts +44 -0
  366. package/dist/types/src/config/index.d.ts +9 -0
  367. package/dist/types/src/config/loader.d.ts +7 -0
  368. package/dist/types/src/config/resolve.d.ts +59 -0
  369. package/dist/types/src/config/types.d.ts +88 -0
  370. package/dist/types/src/domain/job/constants.d.ts +12 -0
  371. package/dist/types/src/domain/job/create.d.ts +2 -0
  372. package/dist/types/src/domain/job/groupFifoOrder.d.ts +9 -0
  373. package/dist/types/src/domain/job/ids.d.ts +7 -0
  374. package/dist/types/src/domain/job/locks.d.ts +4 -0
  375. package/dist/types/src/domain/job/payload.d.ts +18 -0
  376. package/dist/types/src/domain/job/state.d.ts +8 -0
  377. package/dist/types/src/domain/job/terminal.d.ts +3 -0
  378. package/dist/types/src/domain/queue/dependencyTracker.d.ts +78 -0
  379. package/dist/types/src/domain/queue/dlqShard.d.ts +66 -0
  380. package/dist/types/src/domain/queue/groupLimiterManager.d.ts +30 -0
  381. package/dist/types/src/domain/queue/groupScheduler.d.ts +31 -0
  382. package/dist/types/src/domain/queue/groupSchedulerOrder.d.ts +6 -0
  383. package/dist/types/src/domain/queue/limiterManager.d.ts +68 -0
  384. package/dist/types/src/domain/queue/priorityQueue.d.ts +54 -0
  385. package/dist/types/src/domain/queue/priorityQueueOrder.d.ts +3 -0
  386. package/dist/types/src/domain/queue/shard/dependencies.d.ts +11 -0
  387. package/dist/types/src/domain/queue/shard/dlq.d.ts +26 -0
  388. package/dist/types/src/domain/queue/shard/keys.d.ts +19 -0
  389. package/dist/types/src/domain/queue/shard/lifecycle.d.ts +10 -0
  390. package/dist/types/src/domain/queue/shard/limits.d.ts +47 -0
  391. package/dist/types/src/domain/queue/shard/metrics.d.ts +32 -0
  392. package/dist/types/src/domain/queue/shard/state.d.ts +40 -0
  393. package/dist/types/src/domain/queue/shard.d.ts +7 -0
  394. package/dist/types/src/domain/queue/shardCounters.d.ts +35 -0
  395. package/dist/types/src/domain/queue/temporalIndex.d.ts +24 -0
  396. package/dist/types/src/domain/queue/temporalManager.d.ts +72 -0
  397. package/dist/types/src/domain/queue/uniqueKeyManager.d.ts +33 -0
  398. package/dist/types/src/domain/queue/waiterManager.d.ts +18 -0
  399. package/dist/types/src/domain/response/builders.d.ts +15 -0
  400. package/dist/types/src/domain/types/command.d.ts +2 -0
  401. package/dist/types/src/domain/types/commands/base.d.ts +5 -0
  402. package/dist/types/src/domain/types/commands/core.d.ts +110 -0
  403. package/dist/types/src/domain/types/commands/cron.d.ts +36 -0
  404. package/dist/types/src/domain/types/commands/dashboard.d.ts +13 -0
  405. package/dist/types/src/domain/types/commands/dlq.d.ts +44 -0
  406. package/dist/types/src/domain/types/commands/extended.d.ts +63 -0
  407. package/dist/types/src/domain/types/commands/index.d.ts +12 -0
  408. package/dist/types/src/domain/types/commands/limits.d.ts +108 -0
  409. package/dist/types/src/domain/types/commands/management.d.ts +73 -0
  410. package/dist/types/src/domain/types/commands/monitoring.d.ts +49 -0
  411. package/dist/types/src/domain/types/commands/protocol.d.ts +20 -0
  412. package/dist/types/src/domain/types/commands/query.d.ts +46 -0
  413. package/dist/types/src/domain/types/commands/union.d.ts +13 -0
  414. package/dist/types/src/domain/types/commands/workers.d.ts +39 -0
  415. package/dist/types/src/domain/types/cron.d.ts +91 -0
  416. package/dist/types/src/domain/types/deduplication.d.ts +43 -0
  417. package/dist/types/src/domain/types/dlq.d.ts +136 -0
  418. package/dist/types/src/domain/types/flow.d.ts +25 -0
  419. package/dist/types/src/domain/types/group.d.ts +26 -0
  420. package/dist/types/src/domain/types/job.d.ts +8 -0
  421. package/dist/types/src/domain/types/jobs/model.d.ts +153 -0
  422. package/dist/types/src/domain/types/metrics.d.ts +16 -0
  423. package/dist/types/src/domain/types/priorityQueue.d.ts +13 -0
  424. package/dist/types/src/domain/types/protocol.d.ts +5 -0
  425. package/dist/types/src/domain/types/queue.d.ts +110 -0
  426. package/dist/types/src/domain/types/response.d.ts +3 -0
  427. package/dist/types/src/domain/types/responses/model.d.ts +152 -0
  428. package/dist/types/src/domain/types/shard.d.ts +4 -0
  429. package/dist/types/src/domain/types/stall.d.ts +48 -0
  430. package/dist/types/src/domain/types/webhook.d.ts +42 -0
  431. package/dist/types/src/domain/types/worker.d.ts +40 -0
  432. package/dist/types/src/infrastructure/backup/backupTelemetry.d.ts +30 -0
  433. package/dist/types/src/infrastructure/backup/s3BackupConfig.d.ts +80 -0
  434. package/dist/types/src/infrastructure/cloud/types/config.d.ts +18 -0
  435. package/dist/types/src/infrastructure/cloud/types/event.d.ts +14 -0
  436. package/dist/types/src/infrastructure/cloud/types/snapshot.d.ts +52 -0
  437. package/dist/types/src/infrastructure/cloud/types/snapshotCore.d.ts +125 -0
  438. package/dist/types/src/infrastructure/cloud/types/snapshotJobs.d.ts +124 -0
  439. package/dist/types/src/infrastructure/cloud/types/snapshotTelemetry.d.ts +100 -0
  440. package/dist/types/src/infrastructure/cloud/types.d.ts +3 -0
  441. package/dist/types/src/infrastructure/persistence/batchInsert.d.ts +13 -0
  442. package/dist/types/src/infrastructure/persistence/completedJobCountSchema.d.ts +6 -0
  443. package/dist/types/src/infrastructure/persistence/dependencyCompletionSchema.d.ts +6 -0
  444. package/dist/types/src/infrastructure/persistence/dependencyCompletionStore.d.ts +40 -0
  445. package/dist/types/src/infrastructure/persistence/index.d.ts +5 -0
  446. package/dist/types/src/infrastructure/persistence/jobOptionsBlob.d.ts +19 -0
  447. package/dist/types/src/infrastructure/persistence/legacyNameMigration.d.ts +17 -0
  448. package/dist/types/src/infrastructure/persistence/migrationProgressSchema.d.ts +2 -0
  449. package/dist/types/src/infrastructure/persistence/migrations.d.ts +3 -0
  450. package/dist/types/src/infrastructure/persistence/schema.d.ts +8 -0
  451. package/dist/types/src/infrastructure/persistence/sqlite/admission.d.ts +9 -0
  452. package/dist/types/src/infrastructure/persistence/sqlite/completed.d.ts +17 -0
  453. package/dist/types/src/infrastructure/persistence/sqlite/control.d.ts +48 -0
  454. package/dist/types/src/infrastructure/persistence/sqlite/flows.d.ts +26 -0
  455. package/dist/types/src/infrastructure/persistence/sqlite/jobLifecycle.d.ts +17 -0
  456. package/dist/types/src/infrastructure/persistence/sqlite/jobs.d.ts +15 -0
  457. package/dist/types/src/infrastructure/persistence/sqlite/lifecycle.d.ts +6 -0
  458. package/dist/types/src/infrastructure/persistence/sqlite/mutations.d.ts +27 -0
  459. package/dist/types/src/infrastructure/persistence/sqlite/queries.d.ts +23 -0
  460. package/dist/types/src/infrastructure/persistence/sqlite/queueDeletionSql.d.ts +3 -0
  461. package/dist/types/src/infrastructure/persistence/sqlite/records.d.ts +24 -0
  462. package/dist/types/src/infrastructure/persistence/sqlite/state.d.ts +42 -0
  463. package/dist/types/src/infrastructure/persistence/sqlite/telemetry.d.ts +17 -0
  464. package/dist/types/src/infrastructure/persistence/sqlite/telemetryStore.d.ts +30 -0
  465. package/dist/types/src/infrastructure/persistence/sqlite/telemetryWrites.d.ts +47 -0
  466. package/dist/types/src/infrastructure/persistence/sqlite.d.ts +6 -0
  467. package/dist/types/src/infrastructure/persistence/sqliteBatch.d.ts +4 -0
  468. package/dist/types/src/infrastructure/persistence/sqliteMigration.d.ts +5 -0
  469. package/dist/types/src/infrastructure/persistence/sqliteSerializer.d.ts +50 -0
  470. package/dist/types/src/infrastructure/persistence/statements.d.ts +86 -0
  471. package/dist/types/src/infrastructure/persistence/types/admission.d.ts +8 -0
  472. package/dist/types/src/infrastructure/persistence/types/batch.d.ts +12 -0
  473. package/dist/types/src/infrastructure/persistence/types/sqlite.d.ts +27 -0
  474. package/dist/types/src/infrastructure/persistence/writeBuffer.d.ts +48 -0
  475. package/dist/types/src/infrastructure/persistence/writeBufferPending.d.ts +11 -0
  476. package/dist/types/src/infrastructure/scheduler/cron/execution.d.ts +12 -0
  477. package/dist/types/src/infrastructure/scheduler/cron/persisted.d.ts +5 -0
  478. package/dist/types/src/infrastructure/scheduler/cron/runtime.d.ts +31 -0
  479. package/dist/types/src/infrastructure/scheduler/cron/validation.d.ts +3 -0
  480. package/dist/types/src/infrastructure/scheduler/cronParser.d.ts +45 -0
  481. package/dist/types/src/infrastructure/scheduler/cronScheduler.d.ts +5 -0
  482. package/dist/types/src/infrastructure/scheduler/types/cronScheduler.d.ts +16 -0
  483. package/dist/types/src/infrastructure/server/protocol/commands.d.ts +8 -0
  484. package/dist/types/src/infrastructure/server/protocol/frameParser.d.ts +16 -0
  485. package/dist/types/src/infrastructure/server/protocol/lineBuffer.d.ts +6 -0
  486. package/dist/types/src/infrastructure/server/protocol/validation.d.ts +10 -0
  487. package/dist/types/src/infrastructure/server/protocol.d.ts +6 -0
  488. package/dist/types/src/infrastructure/server/socketWriteQueue.d.ts +66 -0
  489. package/dist/types/src/infrastructure/server/types/protocol.d.ts +4 -0
  490. package/dist/types/src/require-bun.d.ts +13 -0
  491. package/dist/types/src/shared/asyncLock.d.ts +13 -0
  492. package/dist/types/src/shared/boundedMap.d.ts +30 -0
  493. package/dist/types/src/shared/boundedSet.d.ts +26 -0
  494. package/dist/types/src/shared/hash.d.ts +30 -0
  495. package/dist/types/src/shared/histogram.d.ts +23 -0
  496. package/dist/types/src/shared/lock.d.ts +13 -0
  497. package/dist/types/src/shared/lockError.d.ts +3 -0
  498. package/dist/types/src/shared/lockTimeout.d.ts +2 -0
  499. package/dist/types/src/shared/logger.d.ts +48 -0
  500. package/dist/types/src/shared/lru.d.ts +9 -0
  501. package/dist/types/src/shared/lruMap.d.ts +42 -0
  502. package/dist/types/src/shared/lruSet.d.ts +36 -0
  503. package/dist/types/src/shared/minHeap.d.ts +43 -0
  504. package/dist/types/src/shared/msgpack.d.ts +3 -0
  505. package/dist/types/src/shared/pausedView.d.ts +19 -0
  506. package/dist/types/src/shared/rwLock.d.ts +22 -0
  507. package/dist/types/src/shared/serialization.d.ts +24 -0
  508. package/dist/types/src/shared/skipList.d.ts +97 -0
  509. package/dist/types/src/shared/skipListNodes.d.ts +6 -0
  510. package/dist/types/src/shared/storageHealth.d.ts +9 -0
  511. package/dist/types/src/shared/ttlMap.d.ts +81 -0
  512. package/dist/types/src/shared/types/lock.d.ts +7 -0
  513. package/dist/types/src/shared/types/skipList.d.ts +4 -0
  514. package/dist/types/src/shared/version.d.ts +4 -0
  515. package/dist/types/src/shared/webhookValidation.d.ts +6 -0
  516. package/package.json +27 -9
  517. package/src/ack-batcher.ts +8 -5
  518. package/src/bunqueue/bunqueue-api.ts +1 -1
  519. package/src/bunqueue/bunqueue.ts +2 -1
  520. package/src/canonical-transport/bun-sqlite-types.ts +22 -0
  521. package/src/canonical-transport/dlq.ts +12 -0
  522. package/src/canonical-transport/embedded.ts +55 -0
  523. package/src/canonical-transport/runtime.ts +49 -0
  524. package/src/canonical-transport/thread-worker.ts +83 -0
  525. package/src/canonical-transport/transport.ts +153 -0
  526. package/src/connection.ts +25 -30
  527. package/src/errors.ts +3 -0
  528. package/src/flow-commit.ts +45 -0
  529. package/src/flow-plan-legacy.ts +117 -0
  530. package/src/flow-plan.ts +209 -0
  531. package/src/flow-types.ts +4 -0
  532. package/src/flow.ts +31 -163
  533. package/src/frame.ts +5 -2
  534. package/src/index.ts +7 -75
  535. package/src/job.ts +43 -9
  536. package/src/legacy.ts +91 -0
  537. package/src/observability.ts +59 -1
  538. package/src/queue-admin.ts +5 -5
  539. package/src/queue-control.ts +12 -8
  540. package/src/queue.ts +10 -6
  541. package/src/serialization.ts +93 -0
  542. package/src/terminal-outcome.ts +58 -0
  543. package/src/types.ts +3 -6
  544. package/src/worker-base.ts +9 -6
  545. package/src/worker-slot-signal.ts +23 -0
  546. package/src/worker.ts +11 -5
  547. package/dist/backpressure.js +0 -39
  548. package/dist/bunqueue/aging.js +0 -53
  549. package/dist/bunqueue/batch.js +0 -60
  550. package/dist/bunqueue/bunqueue-api.js +0 -116
  551. package/dist/bunqueue/bunqueue.js +0 -194
  552. package/dist/bunqueue/cancellation.js +0 -48
  553. package/dist/bunqueue/circuit-breaker.js +0 -69
  554. package/dist/bunqueue/dedup-debounce.js +0 -37
  555. package/dist/bunqueue/dlq-rate-limit.js +0 -65
  556. package/dist/bunqueue/rate-gate.js +0 -61
  557. package/dist/bunqueue/retry.js +0 -56
  558. package/dist/bunqueue/triggers.js +0 -42
  559. package/dist/bunqueue/ttl.js +0 -31
  560. package/dist/bunqueue/types.js +0 -6
  561. package/dist/connection-pool.js +0 -60
  562. package/dist/connection-types.js +0 -2
  563. package/dist/connection.js +0 -281
  564. package/dist/errors.js +0 -25
  565. package/dist/flow-types.js +0 -2
  566. package/dist/flow.js +0 -212
  567. package/dist/job.js +0 -155
  568. package/dist/observability.js +0 -110
  569. package/dist/queue-admin.js +0 -158
  570. package/dist/queue-control.js +0 -105
  571. package/dist/queue-query.js +0 -187
  572. package/dist/queue.js +0 -92
  573. package/dist/responses.js +0 -10
  574. package/dist/socket-factory.js +0 -47
  575. package/dist/types.js +0 -50
  576. package/dist/worker-base.js +0 -159
  577. package/dist/worker-types.js +0 -5
  578. package/dist/worker.js +0 -211
  579. /package/dist/{backpressure.d.ts → types/sdk/typescript/src/backpressure.d.ts} +0 -0
  580. /package/dist/{bunqueue → types/sdk/typescript/src/bunqueue}/cancellation.d.ts +0 -0
package/dist/legacy.js ADDED
@@ -0,0 +1,2081 @@
1
+ import {
2
+ BunqueueError2,
3
+ ConnectionClosedError2,
4
+ CommandTimeoutError2,
5
+ CommandError2,
6
+ SerializationError2,
7
+ AuthError2,
8
+ UnrecoverableError2,
9
+ PROTOCOL_VERSION2,
10
+ MAX_FRAME_SIZE2,
11
+ compact2
12
+ } from "./chunk-b967v3w3.js";
13
+ import {
14
+ noopLogger2,
15
+ consoleLogger2,
16
+ Connection2,
17
+ ConnectionPool2
18
+ } from "./chunk-jxkszwqp.js";
19
+ import {
20
+ terminalOutcomeWasApplied,
21
+ AckBatcher2
22
+ } from "./chunk-fekm0ma6.js";
23
+
24
+ // src/job.ts
25
+ class Job {
26
+ raw;
27
+ token;
28
+ conn;
29
+ onProgress;
30
+ constructor(raw, connection, token, onProgress) {
31
+ this.raw = raw;
32
+ this.conn = connection;
33
+ this.token = token;
34
+ this.onProgress = onProgress;
35
+ }
36
+ get id() {
37
+ return String(this.raw.id);
38
+ }
39
+ get queue() {
40
+ return String(this.raw.queue);
41
+ }
42
+ get data() {
43
+ const data = this.raw.data;
44
+ if (this.topLevelName() !== undefined)
45
+ return data;
46
+ if (data && typeof data === "object" && !Array.isArray(data)) {
47
+ const record = data;
48
+ if (typeof record.name === "string") {
49
+ const { name: _legacyName, ...userData } = record;
50
+ return userData;
51
+ }
52
+ }
53
+ return data;
54
+ }
55
+ get name() {
56
+ const modern = this.topLevelName();
57
+ if (modern !== undefined)
58
+ return modern;
59
+ const data = this.raw.data;
60
+ if (data && typeof data === "object" && !Array.isArray(data) && "name" in data) {
61
+ const name = data.name;
62
+ return typeof name === "string" ? name : undefined;
63
+ }
64
+ return;
65
+ }
66
+ topLevelName() {
67
+ const name = this.raw.name;
68
+ return name === undefined || name === null ? undefined : String(name);
69
+ }
70
+ get priority() {
71
+ return Number(this.raw.priority ?? 0);
72
+ }
73
+ get attempts() {
74
+ return Number(this.raw.attempts ?? 0);
75
+ }
76
+ get maxAttempts() {
77
+ return Number(this.raw.maxAttempts ?? 0);
78
+ }
79
+ get createdAt() {
80
+ return this.raw.createdAt === undefined ? undefined : Number(this.raw.createdAt);
81
+ }
82
+ get timestamp() {
83
+ return this.createdAt ?? Date.now();
84
+ }
85
+ get startedAt() {
86
+ return this.raw.startedAt === undefined || this.raw.startedAt === null ? null : Number(this.raw.startedAt);
87
+ }
88
+ get completedAt() {
89
+ return this.raw.completedAt === undefined || this.raw.completedAt === null ? null : Number(this.raw.completedAt);
90
+ }
91
+ get customId() {
92
+ return this.raw.customId === undefined || this.raw.customId === null ? null : String(this.raw.customId);
93
+ }
94
+ get tags() {
95
+ return Array.isArray(this.raw.tags) ? this.raw.tags.map(String) : [];
96
+ }
97
+ get groupId() {
98
+ return this.raw.groupId === undefined || this.raw.groupId === null ? null : String(this.raw.groupId);
99
+ }
100
+ get parentId() {
101
+ return this.raw.parentId === undefined || this.raw.parentId === null ? null : String(this.raw.parentId);
102
+ }
103
+ get childrenIds() {
104
+ return Array.isArray(this.raw.childrenIds) ? this.raw.childrenIds.map(String) : [];
105
+ }
106
+ get dependsOn() {
107
+ return Array.isArray(this.raw.dependsOn) ? this.raw.dependsOn.map(String) : [];
108
+ }
109
+ get progress() {
110
+ return Number(this.raw.progress ?? 0);
111
+ }
112
+ get stacktrace() {
113
+ return Array.isArray(this.raw.stacktrace) ? this.raw.stacktrace.map(String) : null;
114
+ }
115
+ get state() {
116
+ return this.raw.state === undefined ? undefined : String(this.raw.state);
117
+ }
118
+ call(command) {
119
+ if (!this.conn)
120
+ return Promise.reject(new Error("Job is not bound to a connection"));
121
+ return this.conn.call(command);
122
+ }
123
+ async updateProgress(progress, message) {
124
+ await this.call({ cmd: "Progress", id: this.id, progress, message });
125
+ this.onProgress?.(this, progress);
126
+ }
127
+ async log(message, level) {
128
+ await this.call({ cmd: "AddLog", id: this.id, message, level });
129
+ }
130
+ async heartbeat() {
131
+ await this.call({ cmd: "JobHeartbeat", id: this.id, token: this.token });
132
+ }
133
+ async extendLock(durationMs) {
134
+ await this.call({ cmd: "ExtendLock", id: this.id, token: this.token, duration: durationMs });
135
+ }
136
+ async getState() {
137
+ const response = await this.call({ cmd: "GetState", id: this.id });
138
+ return String(response.state);
139
+ }
140
+ async getChildrenValues() {
141
+ const response = await this.call({ cmd: "GetChildrenValues", id: this.id });
142
+ const data = response.data ?? {};
143
+ return data.values ?? response.values ?? {};
144
+ }
145
+ async remove() {
146
+ await this.call({ cmd: "Cancel", id: this.id });
147
+ }
148
+ async discard() {
149
+ await this.call({
150
+ cmd: "Discard",
151
+ id: this.id,
152
+ ...this.token === undefined ? {} : { token: this.token }
153
+ });
154
+ }
155
+ async promote() {
156
+ await this.call({ cmd: "Promote", id: this.id });
157
+ }
158
+ async retry() {
159
+ await this.call({
160
+ cmd: "MoveToWait",
161
+ id: this.id,
162
+ ...this.token === undefined ? {} : { token: this.token }
163
+ });
164
+ }
165
+ async updateData(data) {
166
+ await this.call({ cmd: "Update", id: this.id, data });
167
+ }
168
+ async changePriority(opts) {
169
+ await this.call({
170
+ cmd: "ChangePriority",
171
+ id: this.id,
172
+ priority: opts.priority,
173
+ lifo: opts.lifo
174
+ });
175
+ }
176
+ async changeDelay(delayMs) {
177
+ await this.call({
178
+ cmd: "ChangeDelay",
179
+ id: this.id,
180
+ delay: delayMs,
181
+ ...this.token === undefined ? {} : { token: this.token }
182
+ });
183
+ }
184
+ async moveToDelayed(delayMs) {
185
+ await this.call({
186
+ cmd: "MoveToDelayed",
187
+ id: this.id,
188
+ delay: delayMs,
189
+ ...this.token === undefined ? {} : { token: this.token }
190
+ });
191
+ }
192
+ }
193
+
194
+ // src/types.ts
195
+ function wireJobOptions(opts = {}) {
196
+ return compact2({
197
+ priority: opts.priority,
198
+ delay: opts.delay,
199
+ maxAttempts: opts.attempts,
200
+ backoff: opts.backoff,
201
+ ttl: opts.ttl,
202
+ timeout: opts.timeout,
203
+ jobId: opts.jobId,
204
+ uniqueKey: opts.deduplication?.id,
205
+ dedup: opts.deduplication ? compact2({
206
+ ttl: opts.deduplication.ttl,
207
+ extend: opts.deduplication.extend,
208
+ replace: opts.deduplication.replace
209
+ }) : undefined,
210
+ dependsOn: opts.dependsOn,
211
+ parentId: opts.parentId,
212
+ childrenIds: opts.childrenIds,
213
+ tags: opts.tags,
214
+ groupId: opts.groupId,
215
+ lifo: opts.lifo,
216
+ removeOnComplete: typeof opts.removeOnComplete === "boolean" ? opts.removeOnComplete : undefined,
217
+ removeOnFail: typeof opts.removeOnFail === "boolean" ? opts.removeOnFail : undefined,
218
+ stallTimeout: opts.stallTimeout,
219
+ durable: opts.durable,
220
+ repeat: opts.repeat,
221
+ debounceId: opts.debounce?.id,
222
+ debounceTtl: opts.debounce?.ttl,
223
+ stackTraceLimit: opts.stackTraceLimit,
224
+ keepLogs: opts.keepLogs,
225
+ sizeLimit: opts.sizeLimit,
226
+ timestamp: opts.timestamp,
227
+ failParentOnFailure: opts.failParentOnFailure,
228
+ removeDependencyOnFailure: opts.removeDependencyOnFailure,
229
+ ignoreDependencyOnFailure: opts.ignoreDependencyOnFailure,
230
+ continueParentOnFailure: opts.continueParentOnFailure
231
+ });
232
+ }
233
+ function jobPayload(name, data) {
234
+ return { name, data };
235
+ }
236
+
237
+ // src/queue-admin.ts
238
+ var adminMethods = {
239
+ async getDlq(count) {
240
+ const response = await this.call(compact2({ cmd: "Dlq", queue: this.name, count }));
241
+ return response.jobs ?? response.data ?? [];
242
+ },
243
+ async retryDlq(jobId) {
244
+ const response = await this.call(compact2({ cmd: "RetryDlq", queue: this.name, jobId }));
245
+ return Number(response.count ?? 0);
246
+ },
247
+ async purgeDlq() {
248
+ const response = await this.call({ cmd: "PurgeDlq", queue: this.name });
249
+ return Number(response.count ?? 0);
250
+ },
251
+ async setDlqConfig(config) {
252
+ await this.call({ cmd: "SetDlqConfig", queue: this.name, config });
253
+ },
254
+ async getDlqConfig() {
255
+ const response = await this.call({ cmd: "GetDlqConfig", queue: this.name });
256
+ return response.config ?? response.data ?? {};
257
+ },
258
+ async setStallConfig(config) {
259
+ await this.call({ cmd: "SetStallConfig", queue: this.name, config });
260
+ },
261
+ async getStallConfig() {
262
+ const response = await this.call({ cmd: "GetStallConfig", queue: this.name });
263
+ return response.config ?? response.data ?? {};
264
+ },
265
+ async setGlobalRateLimit(max, duration) {
266
+ await this.call({ cmd: "RateLimit", queue: this.name, limit: max, duration });
267
+ },
268
+ async removeGlobalRateLimit() {
269
+ await this.call({ cmd: "RateLimitClear", queue: this.name });
270
+ },
271
+ async setGlobalConcurrency(concurrency) {
272
+ await this.call({ cmd: "SetConcurrency", queue: this.name, limit: concurrency });
273
+ },
274
+ async removeGlobalConcurrency() {
275
+ await this.call({ cmd: "ClearConcurrency", queue: this.name });
276
+ },
277
+ async upsertJobScheduler(schedulerId, repeat, template = {}) {
278
+ const dedup = template.opts?.deduplication;
279
+ await this.call(compact2({
280
+ cmd: "Cron",
281
+ name: schedulerId,
282
+ jobName: template.name ?? schedulerId,
283
+ queue: this.name,
284
+ data: "data" in template ? template.data : {},
285
+ schedule: repeat.pattern,
286
+ repeatEvery: repeat.every,
287
+ priority: template.opts?.priority,
288
+ timezone: repeat.tz,
289
+ immediately: repeat.immediately,
290
+ maxLimit: repeat.limit,
291
+ uniqueKey: dedup?.id,
292
+ dedup: dedup ? compact2({ ttl: dedup.ttl, extend: dedup.extend, replace: dedup.replace }) : undefined,
293
+ skipMissedOnRestart: repeat.skipMissedOnRestart,
294
+ skipIfNoWorker: repeat.skipIfNoWorker,
295
+ preventOverlap: repeat.preventOverlap,
296
+ jobOptions: template.opts ? wireJobOptions(template.opts) : undefined
297
+ }));
298
+ },
299
+ async removeJobScheduler(schedulerId) {
300
+ await this.call({ cmd: "CronDelete", name: schedulerId });
301
+ },
302
+ async getJobScheduler(schedulerId) {
303
+ try {
304
+ const response = await this.call({ cmd: "CronGet", name: schedulerId });
305
+ return response.cron ?? response.data ?? null;
306
+ } catch (err) {
307
+ if (err instanceof CommandError2 && /not found/i.test(err.message))
308
+ return null;
309
+ throw err;
310
+ }
311
+ },
312
+ async getJobSchedulers() {
313
+ const response = await this.call({ cmd: "CronList" });
314
+ const crons = response.crons ?? [];
315
+ return crons.filter((cron) => cron.queue === this.name);
316
+ },
317
+ async getJobSchedulersCount() {
318
+ return (await this.getJobSchedulers()).length;
319
+ },
320
+ addCron(name, schedule, data, opts) {
321
+ return this.upsertJobScheduler(name, { pattern: schedule }, { name, data, opts });
322
+ },
323
+ every(name, intervalMs, data, opts) {
324
+ return this.upsertJobScheduler(name, { every: intervalMs }, { name, data, opts });
325
+ },
326
+ async getWorkers() {
327
+ const response = await this.call({ cmd: "ListWorkers" });
328
+ const data = response.data ?? {};
329
+ return data.workers ?? response.workers ?? [];
330
+ },
331
+ async getWorkersCount() {
332
+ return (await this.getWorkers()).length;
333
+ },
334
+ async getStats() {
335
+ const response = await this.call({ cmd: "Stats" });
336
+ return response.stats ?? {};
337
+ },
338
+ async getMetrics() {
339
+ const response = await this.call({ cmd: "Metrics" });
340
+ return response.metrics ?? {};
341
+ },
342
+ async listQueues() {
343
+ const response = await this.call({ cmd: "ListQueues" });
344
+ const queues = response.queues ?? [];
345
+ return queues.map((q) => typeof q === "string" ? q : String(q.name));
346
+ },
347
+ async addWebhook(opts) {
348
+ const response = await this.call(compact2({
349
+ cmd: "AddWebhook",
350
+ url: opts.url,
351
+ events: opts.events,
352
+ queue: opts.queue ?? this.name,
353
+ secret: opts.secret
354
+ }));
355
+ const data = response.data ?? {};
356
+ return data.webhook ?? data;
357
+ },
358
+ async removeWebhook(webhookId) {
359
+ await this.call({ cmd: "RemoveWebhook", webhookId });
360
+ },
361
+ async listWebhooks() {
362
+ const response = await this.call({ cmd: "ListWebhooks" });
363
+ const data = response.data ?? {};
364
+ return data.webhooks ?? response.webhooks ?? [];
365
+ },
366
+ async setWebhookEnabled(webhookId, enabled) {
367
+ await this.call({ cmd: "SetWebhookEnabled", id: webhookId, enabled });
368
+ }
369
+ };
370
+
371
+ // src/worker-types.ts
372
+ var MAX_POLL_TIMEOUT_MS = 30000;
373
+ var MAX_STACK_LINES = 20;
374
+ var RECONNECT_BACKOFF_MS = [500, 1000, 2000, 5000];
375
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
376
+
377
+ // src/queue-control.ts
378
+ var controlMethods = {
379
+ async pause() {
380
+ await this.call({ cmd: "Pause", queue: this.name });
381
+ },
382
+ async resume() {
383
+ await this.call({ cmd: "Resume", queue: this.name });
384
+ },
385
+ async isPaused() {
386
+ return (await this.call({ cmd: "IsPaused", queue: this.name })).paused === true;
387
+ },
388
+ async drain() {
389
+ const response = await this.call({ cmd: "Drain", queue: this.name });
390
+ return response.count ?? 0;
391
+ },
392
+ async obliterate() {
393
+ await this.call({ cmd: "Obliterate", queue: this.name });
394
+ },
395
+ async clean(graceMs, limit, state) {
396
+ const response = await this.call(compact2({ cmd: "Clean", queue: this.name, grace: graceMs, limit, state }));
397
+ return response.count ?? 0;
398
+ },
399
+ async remove(id) {
400
+ await this.call({ cmd: "Cancel", id });
401
+ },
402
+ async discard(id) {
403
+ await this.call({ cmd: "Discard", id });
404
+ },
405
+ async promoteJob(id) {
406
+ await this.call({ cmd: "Promote", id });
407
+ },
408
+ async promoteJobs(opts = {}) {
409
+ const response = await this.call(compact2({ cmd: "PromoteJobs", queue: this.name, count: opts.count }));
410
+ return response.count ?? 0;
411
+ },
412
+ async retryJob(id) {
413
+ await this.call({ cmd: "MoveToWait", id });
414
+ },
415
+ async retryJobs(opts = {}) {
416
+ if (opts.state === "completed") {
417
+ await this.call({ cmd: "RetryCompleted", queue: this.name });
418
+ return;
419
+ }
420
+ await this.call(compact2({ cmd: "RetryDlq", queue: this.name, count: opts.count }));
421
+ },
422
+ async retryCompleted(id) {
423
+ await this.call(compact2({ cmd: "RetryCompleted", queue: this.name, id }));
424
+ },
425
+ async updateJobProgress(id, progress, message) {
426
+ await this.call(compact2({ cmd: "Progress", id, progress, message }));
427
+ },
428
+ async updateJobData(id, data) {
429
+ await this.call({ cmd: "Update", id, data });
430
+ },
431
+ async changeJobPriority(id, opts) {
432
+ await this.call({ cmd: "ChangePriority", id, priority: opts.priority, lifo: opts.lifo });
433
+ },
434
+ async changeJobDelay(id, delayMs, token) {
435
+ await this.call(compact2({ cmd: "ChangeDelay", id, delay: delayMs, token }));
436
+ },
437
+ async moveJobToWait(id, token) {
438
+ await this.call(compact2({ cmd: "MoveToWait", id, token }));
439
+ },
440
+ async moveJobToDelayed(id, delayMs, token) {
441
+ await this.call(compact2({ cmd: "MoveToDelayed", id, delay: delayMs, token }));
442
+ },
443
+ async extendJobLock(id, token, durationMs) {
444
+ await this.call({ cmd: "ExtendLock", id, token, duration: durationMs });
445
+ },
446
+ async moveJobToCompleted(id, returnValue, token) {
447
+ await this.call(compact2({ cmd: "ACK", id, result: returnValue, token }));
448
+ },
449
+ async moveJobToFailed(id, error, token) {
450
+ const err = typeof error === "string" ? undefined : error;
451
+ const message = err ? err.message || err.name : error;
452
+ const stack = err ? (err.stack ?? err.message).split(`
453
+ `).slice(0, MAX_STACK_LINES) : undefined;
454
+ await this.call(compact2({
455
+ cmd: "FAIL",
456
+ id,
457
+ error: message,
458
+ stack,
459
+ unrecoverable: err instanceof UnrecoverableError2 ? true : undefined,
460
+ token
461
+ }));
462
+ }
463
+ };
464
+
465
+ // src/queue-query.ts
466
+ function unwrapValues(response) {
467
+ const data = response.data ?? {};
468
+ return data.values ?? response.values ?? data ?? {};
469
+ }
470
+ var queryMethods = {
471
+ async getJob(id) {
472
+ try {
473
+ const response = await this.call({ cmd: "GetJob", id });
474
+ return response.job ? new Job(response.job, this.connection) : null;
475
+ } catch (err) {
476
+ if (err instanceof CommandError2 && /not found/i.test(err.message))
477
+ return null;
478
+ throw err;
479
+ }
480
+ },
481
+ async getJobByCustomId(customId) {
482
+ try {
483
+ const response = await this.call({ cmd: "GetJobByCustomId", customId });
484
+ return response.job ? new Job(response.job, this.connection) : null;
485
+ } catch (err) {
486
+ if (err instanceof CommandError2 && /not found/i.test(err.message))
487
+ return null;
488
+ throw err;
489
+ }
490
+ },
491
+ async getDeduplicationJobId(deduplicationId) {
492
+ const job = await this.getJobByCustomId(deduplicationId);
493
+ return job ? job.id : null;
494
+ },
495
+ async getJobs(opts = {}) {
496
+ const start = opts.start ?? 0;
497
+ const end = opts.end !== undefined && opts.end >= 0 ? opts.end : 1000;
498
+ const response = await this.call(compact2({
499
+ cmd: "GetJobs",
500
+ queue: this.name,
501
+ state: opts.state,
502
+ offset: start,
503
+ limit: end - start
504
+ }));
505
+ return (response.jobs ?? []).map((raw) => new Job(raw, this.connection));
506
+ },
507
+ getWaiting(start, end) {
508
+ return this.getJobs({ state: "waiting", start, end });
509
+ },
510
+ getDelayed(start, end) {
511
+ return this.getJobs({ state: "delayed", start, end });
512
+ },
513
+ getActive(start, end) {
514
+ return this.getJobs({ state: "active", start, end });
515
+ },
516
+ getCompleted(start, end) {
517
+ return this.getJobs({ state: "completed", start, end });
518
+ },
519
+ getFailed(start, end) {
520
+ return this.getJobs({ state: "failed", start, end });
521
+ },
522
+ getPrioritized(start, end) {
523
+ return this.getJobs({ state: "prioritized", start, end });
524
+ },
525
+ getWaitingChildren(start, end) {
526
+ return this.getJobs({ state: "waiting-children", start, end });
527
+ },
528
+ async getJobState(id) {
529
+ return (await this.call({ cmd: "GetState", id })).state;
530
+ },
531
+ async getResult(id) {
532
+ return (await this.call({ cmd: "GetResult", id })).result;
533
+ },
534
+ async getChildrenValues(id) {
535
+ return unwrapValues(await this.call({ cmd: "GetChildrenValues", id }));
536
+ },
537
+ async getFailedChildrenValues(id) {
538
+ return unwrapValues(await this.call({ cmd: "GetFailedChildrenValues", id }));
539
+ },
540
+ async getIgnoredChildrenFailures(id) {
541
+ return unwrapValues(await this.call({ cmd: "GetIgnoredChildrenFailures", id }));
542
+ },
543
+ async removeChildDependency(id) {
544
+ await this.call({ cmd: "RemoveChildDependency", id });
545
+ },
546
+ async removeUnprocessedChildren(id) {
547
+ await this.call({ cmd: "RemoveUnprocessedChildren", id });
548
+ },
549
+ async waitForJob(id, ttlMs = 30000) {
550
+ ttlMs = Math.min(Math.max(ttlMs, 0), 600000);
551
+ const response = await this.call({ cmd: "WaitJob", id, timeout: ttlMs }, ttlMs + 5000);
552
+ if (response.completed !== true) {
553
+ let state;
554
+ try {
555
+ state = await this.getJobState(id);
556
+ } catch {}
557
+ if (state === "failed")
558
+ throw new CommandError2(`job ${id} failed before completion`);
559
+ throw new CommandTimeoutError2(`waitUntilFinished timed out after ${ttlMs}ms`);
560
+ }
561
+ return response.result;
562
+ },
563
+ waitJobUntilFinished(id, _queueEvents, ttlMs) {
564
+ return this.waitForJob(id, ttlMs);
565
+ },
566
+ async getProgress(id) {
567
+ const response = await this.call({ cmd: "GetProgress", id });
568
+ return { progress: response.progress ?? 0, message: response.message ?? null };
569
+ },
570
+ async getJobCounts() {
571
+ return (await this.call({ cmd: "GetJobCounts", queue: this.name })).counts;
572
+ },
573
+ async getWaitingCount() {
574
+ return (await this.getJobCounts()).waiting;
575
+ },
576
+ async getActiveCount() {
577
+ return (await this.getJobCounts()).active;
578
+ },
579
+ async getCompletedCount() {
580
+ return (await this.getJobCounts()).completed;
581
+ },
582
+ async getFailedCount() {
583
+ return (await this.getJobCounts()).failed;
584
+ },
585
+ async getDelayedCount() {
586
+ return (await this.getJobCounts()).delayed;
587
+ },
588
+ async getPrioritizedCount() {
589
+ return (await this.getJobCounts()).prioritized;
590
+ },
591
+ async getWaitingChildrenCount() {
592
+ return (await this.getJobCounts())["waiting-children"];
593
+ },
594
+ async count() {
595
+ return (await this.call({ cmd: "Count", queue: this.name })).count ?? 0;
596
+ },
597
+ async getCountsPerPriority() {
598
+ const response = await this.call({ cmd: "GetCountsPerPriority", queue: this.name });
599
+ return response.counts ?? response.data ?? {};
600
+ },
601
+ async addJobLog(id, message, level) {
602
+ await this.call(compact2({ cmd: "AddLog", id, message, level }));
603
+ },
604
+ async getJobLogs(id, start, end) {
605
+ const response = await this.call(compact2({ cmd: "GetLogs", id, start, end }));
606
+ const data = response.data ?? {};
607
+ const logs = data.logs ?? response.logs ?? [];
608
+ return logs.map((row) => {
609
+ if (typeof row === "string")
610
+ return row;
611
+ const r = row;
612
+ return r.level ? `[${r.level}] ${r.message}` : String(r.message ?? row);
613
+ });
614
+ },
615
+ async clearJobLogs(id, keepLogs) {
616
+ await this.call(compact2({ cmd: "ClearLogs", id, keepLogs }));
617
+ }
618
+ };
619
+
620
+ // src/queue.ts
621
+ class Queue {
622
+ name;
623
+ connection;
624
+ ownsConnection;
625
+ constructor(name, opts = {}) {
626
+ this.name = name;
627
+ const connOptions = {
628
+ host: opts.host,
629
+ port: opts.port,
630
+ token: opts.token,
631
+ tls: opts.tls,
632
+ commandTimeoutMs: opts.commandTimeoutMs,
633
+ maxInFlight: opts.maxInFlight,
634
+ logger: opts.logger,
635
+ onTelemetry: opts.onTelemetry
636
+ };
637
+ this.connection = opts.connection ?? (opts.poolSize && opts.poolSize > 1 ? new ConnectionPool2(opts.poolSize, connOptions) : new Connection2(connOptions));
638
+ this.ownsConnection = opts.connection === undefined;
639
+ }
640
+ call(command, timeoutMs) {
641
+ return this.connection.call(command, timeoutMs);
642
+ }
643
+ async add(name, data, opts) {
644
+ const payload = jobPayload(name, data);
645
+ const response = await this.call({
646
+ cmd: "PUSH",
647
+ queue: this.name,
648
+ ...payload,
649
+ ...wireJobOptions(opts)
650
+ });
651
+ return new Job({ id: response.id, queue: this.name, ...payload }, this.connection);
652
+ }
653
+ async addBulk(jobs) {
654
+ const inputs = jobs.map((entry) => {
655
+ const opts = wireJobOptions(entry.opts);
656
+ if (opts.jobId !== undefined) {
657
+ opts.customId = opts.jobId;
658
+ delete opts.jobId;
659
+ }
660
+ return { ...jobPayload(entry.name, entry.data), ...opts };
661
+ });
662
+ const response = await this.call({ cmd: "PUSHB", queue: this.name, jobs: inputs });
663
+ const ids = response.ids ?? [];
664
+ return ids.map((id, i) => new Job({ id, queue: this.name, name: inputs[i].name, data: inputs[i].data }, this.connection));
665
+ }
666
+ ping() {
667
+ return this.connection.ping();
668
+ }
669
+ async waitUntilReady() {
670
+ await this.connection.connect();
671
+ }
672
+ close() {
673
+ if (this.ownsConnection)
674
+ this.connection.close();
675
+ }
676
+ async disconnect() {
677
+ this.close();
678
+ }
679
+ }
680
+ Object.assign(Queue.prototype, queryMethods, controlMethods, adminMethods);
681
+
682
+ // src/worker.ts
683
+ import { hostname as hostname2 } from "node:os";
684
+
685
+ // src/worker-base.ts
686
+ import { randomBytes } from "node:crypto";
687
+ import { EventEmitter } from "node:events";
688
+ import { hostname } from "node:os";
689
+ class WorkerBase extends EventEmitter {
690
+ queue;
691
+ concurrency;
692
+ batchSize;
693
+ pollTimeoutMs;
694
+ lockTtlMs;
695
+ heartbeatIntervalS;
696
+ workerId;
697
+ name;
698
+ connection;
699
+ active = new Map;
700
+ cancelledJobs = new Set;
701
+ stopped = false;
702
+ paused = false;
703
+ closedFlag = false;
704
+ running = false;
705
+ wasBusy = false;
706
+ processed = 0;
707
+ failedCount = 0;
708
+ readyPromise;
709
+ readyResolve = null;
710
+ readyFired = false;
711
+ loopPromise = null;
712
+ heartbeatTimer = null;
713
+ registeredGeneration = -1;
714
+ constructor(queue, opts = {}) {
715
+ super();
716
+ if ((opts.concurrency ?? 4) < 1)
717
+ throw new Error("concurrency must be >= 1");
718
+ this.queue = queue;
719
+ this.concurrency = opts.concurrency ?? 4;
720
+ const rawBatch = opts.batchSize ?? 10;
721
+ this.batchSize = Number.isFinite(rawBatch) ? Math.min(Math.max(1, rawBatch), 1000) : 10;
722
+ this.pollTimeoutMs = Math.min(opts.pollTimeoutMs ?? 5000, MAX_POLL_TIMEOUT_MS);
723
+ this.lockTtlMs = opts.lockTtlMs ?? 30000;
724
+ this.heartbeatIntervalS = opts.heartbeatIntervalS ?? 10;
725
+ this.workerId = `ts-${hostname()}-${process.pid}-${randomBytes(4).toString("hex")}`;
726
+ this.name = opts.name ?? this.workerId;
727
+ this.connection = new Connection2({
728
+ host: opts.host,
729
+ port: opts.port,
730
+ token: opts.token,
731
+ tls: opts.tls,
732
+ logger: opts.logger,
733
+ onTelemetry: opts.onTelemetry
734
+ });
735
+ this.readyPromise = new Promise((resolve) => {
736
+ this.readyResolve = resolve;
737
+ });
738
+ }
739
+ pause() {
740
+ this.paused = true;
741
+ }
742
+ resume() {
743
+ this.paused = false;
744
+ }
745
+ isRunning() {
746
+ return this.running && !this.closedFlag;
747
+ }
748
+ isPaused() {
749
+ return this.paused;
750
+ }
751
+ isClosed() {
752
+ return this.closedFlag;
753
+ }
754
+ async waitUntilReady() {
755
+ await this.readyPromise;
756
+ }
757
+ on(event, listener) {
758
+ if (event === "ready" && this.readyFired)
759
+ listener();
760
+ return super.on(event, listener);
761
+ }
762
+ once(event, listener) {
763
+ if (event === "ready" && this.readyFired) {
764
+ listener();
765
+ return this;
766
+ }
767
+ return super.once(event, listener);
768
+ }
769
+ off(event, listener) {
770
+ return super.off(event, listener);
771
+ }
772
+ cancelJob(jobId, reason) {
773
+ if (this.active.has(jobId)) {
774
+ this.cancelledJobs.add(jobId);
775
+ this.emit("cancelled", { jobId, reason: reason ?? "Job cancelled by worker" });
776
+ return true;
777
+ }
778
+ return false;
779
+ }
780
+ cancelAllJobs(reason) {
781
+ for (const jobId of this.active.keys()) {
782
+ this.cancelledJobs.add(jobId);
783
+ this.emit("cancelled", { jobId, reason: reason ?? "All jobs cancelled" });
784
+ }
785
+ }
786
+ isJobCancelled(jobId) {
787
+ return this.cancelledJobs.has(jobId);
788
+ }
789
+ async close(force = false) {
790
+ if (this.closedFlag)
791
+ return;
792
+ this.stopped = true;
793
+ if (this.loopPromise)
794
+ await this.loopPromise;
795
+ await this.beforeClose();
796
+ while (!force && this.active.size > 0)
797
+ await sleep(20);
798
+ if (this.heartbeatTimer) {
799
+ clearInterval(this.heartbeatTimer);
800
+ this.heartbeatTimer = null;
801
+ }
802
+ if (this.registeredGeneration >= 0) {
803
+ await this.safeCall({ cmd: "UnregisterWorker", workerId: this.workerId });
804
+ }
805
+ this.connection.close();
806
+ this.closedFlag = true;
807
+ this.running = false;
808
+ this.emit("closed");
809
+ }
810
+ async safeCall(command, outcome = () => true) {
811
+ try {
812
+ const response = await this.connection.call(command);
813
+ return outcome(response);
814
+ } catch (err) {
815
+ this.emit("error", err instanceof Error ? err : new Error(String(err)));
816
+ return false;
817
+ }
818
+ }
819
+ async beforeClose() {}
820
+ }
821
+
822
+ // src/worker-slot-signal.ts
823
+ class SlotSignal {
824
+ waiter = null;
825
+ wait(timeoutMs) {
826
+ return new Promise((resolve) => {
827
+ let settled = false;
828
+ const finish = () => {
829
+ if (settled)
830
+ return;
831
+ settled = true;
832
+ clearTimeout(timer);
833
+ if (this.waiter === finish)
834
+ this.waiter = null;
835
+ resolve();
836
+ };
837
+ const timer = setTimeout(finish, timeoutMs);
838
+ this.waiter = finish;
839
+ });
840
+ }
841
+ notify() {
842
+ this.waiter?.();
843
+ }
844
+ }
845
+
846
+ // src/worker.ts
847
+ class Worker extends WorkerBase {
848
+ processor;
849
+ ackBatcher;
850
+ slotSignal = new SlotSignal;
851
+ constructor(queue, processor, opts = {}) {
852
+ super(queue, opts);
853
+ this.processor = processor;
854
+ const ab = opts.ackBatch;
855
+ this.ackBatcher = ab?.enabled ? new AckBatcher2(this.connection, ab.maxSize ?? 50, ab.maxDelayMs ?? 5) : null;
856
+ if (opts.autorun !== false)
857
+ this.run();
858
+ }
859
+ async beforeClose() {
860
+ if (this.ackBatcher)
861
+ await this.ackBatcher.flush();
862
+ }
863
+ run() {
864
+ if (this.running || this.closedFlag)
865
+ return;
866
+ this.running = true;
867
+ this.loopPromise = this.loop().catch((err) => {
868
+ this.emit("error", err instanceof Error ? err : new Error(String(err)));
869
+ });
870
+ }
871
+ async loop() {
872
+ await this.register();
873
+ this.readyResolve?.();
874
+ this.readyFired = true;
875
+ this.emit("ready");
876
+ this.startHeartbeat();
877
+ let backoffIdx = 0;
878
+ while (!this.stopped) {
879
+ if (this.paused) {
880
+ await sleep(50);
881
+ continue;
882
+ }
883
+ try {
884
+ await this.pollOnce();
885
+ backoffIdx = 0;
886
+ } catch (err) {
887
+ this.emit("error", err instanceof Error ? err : new Error(String(err)));
888
+ if (err instanceof ConnectionClosedError2 || err instanceof CommandTimeoutError2) {
889
+ const delay = RECONNECT_BACKOFF_MS[Math.min(backoffIdx, RECONNECT_BACKOFF_MS.length - 1)];
890
+ backoffIdx += 1;
891
+ await sleep(delay);
892
+ } else {
893
+ await sleep(200);
894
+ }
895
+ }
896
+ }
897
+ }
898
+ async pollOnce() {
899
+ const free = this.concurrency - this.active.size;
900
+ if (free <= 0) {
901
+ await this.slotSignal.wait(20);
902
+ return;
903
+ }
904
+ if (this.connection.isConnected && this.connection.generation !== this.registeredGeneration) {
905
+ await this.register();
906
+ }
907
+ const response = await this.connection.call({
908
+ cmd: "PULLB",
909
+ queue: this.queue,
910
+ count: Math.min(free, this.batchSize),
911
+ timeout: this.pollTimeoutMs,
912
+ owner: this.workerId,
913
+ lockTtl: this.lockTtlMs
914
+ }, this.pollTimeoutMs + 1e4);
915
+ const jobs = response.jobs ?? [];
916
+ const tokens = response.tokens ?? [];
917
+ if (jobs.length === 0) {
918
+ if (this.wasBusy && this.active.size === 0) {
919
+ this.wasBusy = false;
920
+ this.emit("drained");
921
+ }
922
+ return;
923
+ }
924
+ this.wasBusy = true;
925
+ for (let i = 0;i < jobs.length; i++) {
926
+ const jobId = String(jobs[i].id);
927
+ this.active.set(jobId, tokens[i]);
928
+ this.runJob(jobs[i], tokens[i]);
929
+ }
930
+ }
931
+ async runJob(raw, token) {
932
+ const job = new Job(raw, this.connection, token, (j, p) => this.emit("progress", j, p));
933
+ this.emit("active", job);
934
+ try {
935
+ const result = await this.processor(job);
936
+ if (this.ackBatcher) {
937
+ this.ackBatcher.add({
938
+ id: job.id,
939
+ token,
940
+ result: result ?? undefined,
941
+ onSettled: (err, applied) => {
942
+ this.finishJob(job.id);
943
+ if (err) {
944
+ this.emit("error", err instanceof Error ? err : new Error(String(err)));
945
+ } else if (applied) {
946
+ this.processed += 1;
947
+ this.emit("completed", job, result);
948
+ }
949
+ }
950
+ });
951
+ return;
952
+ }
953
+ const acked = await this.safeCall(compact2({ cmd: "ACK", id: job.id, token, result: result ?? undefined }), (response) => terminalOutcomeWasApplied(response.data));
954
+ this.finishJob(job.id);
955
+ if (acked) {
956
+ this.processed += 1;
957
+ this.emit("completed", job, result);
958
+ }
959
+ } catch (err) {
960
+ const error = err instanceof Error ? err : new Error(String(err));
961
+ const stack = (error.stack ?? error.message).split(`
962
+ `).slice(0, MAX_STACK_LINES);
963
+ const failed = await this.safeCall(compact2({
964
+ cmd: "FAIL",
965
+ id: job.id,
966
+ token,
967
+ error: error.message || error.name,
968
+ stack,
969
+ unrecoverable: err instanceof UnrecoverableError2 ? true : undefined
970
+ }), (response) => terminalOutcomeWasApplied(response.data));
971
+ this.finishJob(job.id);
972
+ if (failed) {
973
+ this.failedCount += 1;
974
+ this.emit("failed", job, error);
975
+ }
976
+ }
977
+ }
978
+ finishJob(id) {
979
+ this.active.delete(id);
980
+ this.cancelledJobs.delete(id);
981
+ this.slotSignal.notify();
982
+ }
983
+ startHeartbeat() {
984
+ if (!(Number.isFinite(this.heartbeatIntervalS) && this.heartbeatIntervalS > 0))
985
+ return;
986
+ this.heartbeatTimer = setInterval(() => {
987
+ (async () => {
988
+ await this.safeCall({
989
+ cmd: "Heartbeat",
990
+ id: this.workerId,
991
+ activeJobs: this.active.size,
992
+ processed: this.processed,
993
+ failed: this.failedCount
994
+ });
995
+ if (this.active.size > 0) {
996
+ const ids = [...this.active.keys()];
997
+ const tokens = ids.map((id) => this.active.get(id));
998
+ await this.safeCall({ cmd: "JobHeartbeatB", ids, tokens });
999
+ }
1000
+ })();
1001
+ }, this.heartbeatIntervalS * 1000);
1002
+ this.heartbeatTimer.unref?.();
1003
+ }
1004
+ async register() {
1005
+ await this.safeCall({
1006
+ cmd: "RegisterWorker",
1007
+ name: this.name,
1008
+ queues: [this.queue],
1009
+ concurrency: this.concurrency,
1010
+ workerId: this.workerId,
1011
+ hostname: hostname2(),
1012
+ pid: process.pid,
1013
+ startedAt: Date.now()
1014
+ });
1015
+ this.registeredGeneration = this.connection.generation;
1016
+ }
1017
+ }
1018
+
1019
+ // src/bunqueue/aging.ts
1020
+ class PriorityAger {
1021
+ timer = null;
1022
+ config;
1023
+ queue;
1024
+ constructor(config, queue) {
1025
+ this.config = config;
1026
+ this.queue = queue;
1027
+ }
1028
+ start() {
1029
+ const interval = this.config.interval ?? 60000;
1030
+ this.timer = setInterval(() => {
1031
+ this.tick();
1032
+ }, interval);
1033
+ this.timer.unref?.();
1034
+ }
1035
+ async tick() {
1036
+ const minAge = this.config.minAge ?? 60000;
1037
+ const boost = this.config.boost ?? 1;
1038
+ const maxPriority = this.config.maxPriority ?? 100;
1039
+ const maxScan = this.config.maxScan ?? 100;
1040
+ const [waiting, prioritized] = await Promise.all([
1041
+ this.queue.getJobs({ state: "waiting", start: 0, end: maxScan }),
1042
+ this.queue.getJobs({ state: "prioritized", start: 0, end: maxScan })
1043
+ ]);
1044
+ const jobs = [...waiting, ...prioritized];
1045
+ const now = Date.now();
1046
+ for (const job of jobs) {
1047
+ const age = now - job.timestamp;
1048
+ if (age >= minAge && job.priority < maxPriority) {
1049
+ const newPriority = Math.min(job.priority + boost, maxPriority);
1050
+ try {
1051
+ await this.queue.changeJobPriority(job.id, { priority: newPriority });
1052
+ } catch {}
1053
+ }
1054
+ }
1055
+ }
1056
+ destroy() {
1057
+ if (this.timer) {
1058
+ clearInterval(this.timer);
1059
+ this.timer = null;
1060
+ }
1061
+ }
1062
+ }
1063
+
1064
+ // src/bunqueue/batch.ts
1065
+ class BatchAccumulator {
1066
+ buffer = [];
1067
+ timer = null;
1068
+ config;
1069
+ constructor(config) {
1070
+ this.config = config;
1071
+ }
1072
+ buildProcessor() {
1073
+ return (job) => {
1074
+ return new Promise((resolve, reject) => {
1075
+ this.buffer.push({ job, resolve, reject });
1076
+ if (this.buffer.length >= this.config.size) {
1077
+ this.flush();
1078
+ } else if (!this.timer) {
1079
+ const timeout = this.config.timeout ?? 5000;
1080
+ this.timer = setTimeout(() => {
1081
+ this.flush();
1082
+ }, timeout);
1083
+ }
1084
+ });
1085
+ };
1086
+ }
1087
+ flush() {
1088
+ if (this.timer) {
1089
+ clearTimeout(this.timer);
1090
+ this.timer = null;
1091
+ }
1092
+ const batch = this.buffer.splice(0);
1093
+ if (batch.length === 0)
1094
+ return;
1095
+ const jobs = batch.map((b) => b.job);
1096
+ this.config.processor(jobs).then((results) => {
1097
+ for (let i = 0;i < batch.length; i++) {
1098
+ batch[i].resolve(results[i] ?? undefined);
1099
+ }
1100
+ }, (err) => {
1101
+ const error = err instanceof Error ? err : new Error(String(err));
1102
+ for (const b of batch) {
1103
+ b.reject(error);
1104
+ }
1105
+ });
1106
+ }
1107
+ destroy() {
1108
+ if (this.timer) {
1109
+ clearTimeout(this.timer);
1110
+ this.timer = null;
1111
+ }
1112
+ if (this.buffer.length > 0) {
1113
+ this.flush();
1114
+ }
1115
+ }
1116
+ }
1117
+
1118
+ // src/bunqueue/bunqueue-api.ts
1119
+ var bunqueueApi = {
1120
+ async cron(id, pattern, data, opts) {
1121
+ await this.queue.upsertJobScheduler(id, { pattern, tz: opts?.timezone, limit: opts?.limit }, { name: id, data, opts: opts?.jobOpts });
1122
+ return this.queue.getJobScheduler(id);
1123
+ },
1124
+ async every(id, intervalMs, data, opts) {
1125
+ await this.queue.upsertJobScheduler(id, { every: intervalMs, limit: opts?.limit }, { name: id, data, opts: opts?.jobOpts });
1126
+ return this.queue.getJobScheduler(id);
1127
+ },
1128
+ removeCron(id) {
1129
+ return this.queue.removeJobScheduler(id);
1130
+ },
1131
+ listCrons() {
1132
+ return this.queue.getJobSchedulers();
1133
+ },
1134
+ cancel(jobId, gracePeriodMs = 0) {
1135
+ this.cancellation.cancel(jobId, gracePeriodMs);
1136
+ },
1137
+ isCancelled(jobId) {
1138
+ return this.cancellation.isCancelled(jobId);
1139
+ },
1140
+ getSignal(jobId) {
1141
+ return this.cancellation.getSignal(jobId);
1142
+ },
1143
+ getCircuitState() {
1144
+ return this.cb?.currentState ?? "closed";
1145
+ },
1146
+ resetCircuit() {
1147
+ this.cb?.reset();
1148
+ },
1149
+ trigger(rule) {
1150
+ this.triggerMgr.add(rule);
1151
+ return this;
1152
+ },
1153
+ setDefaultTtl(ttlMs) {
1154
+ this.ttlChecker?.setDefaultTtl(ttlMs);
1155
+ },
1156
+ setNameTtl(name, ttlMs) {
1157
+ this.ttlChecker?.setNameTtl(name, ttlMs);
1158
+ },
1159
+ setDlqConfig(config) {
1160
+ return this.dlqrl.setDlqConfig(config);
1161
+ },
1162
+ getDlqConfig() {
1163
+ return this.dlqrl.getDlqConfig();
1164
+ },
1165
+ getDlq(filter) {
1166
+ return this.dlqrl.getDlq(filter);
1167
+ },
1168
+ getDlqStats() {
1169
+ return this.dlqrl.getDlqStats();
1170
+ },
1171
+ retryDlq(id) {
1172
+ return this.dlqrl.retryDlq(id);
1173
+ },
1174
+ purgeDlq() {
1175
+ return this.dlqrl.purgeDlq();
1176
+ },
1177
+ setGlobalRateLimit(max, duration) {
1178
+ return this.dlqrl.setGlobalRateLimit(max, duration);
1179
+ },
1180
+ removeGlobalRateLimit() {
1181
+ return this.dlqrl.removeGlobalRateLimit();
1182
+ },
1183
+ on(event, listener) {
1184
+ this.worker.on(event, listener);
1185
+ return this;
1186
+ },
1187
+ once(event, listener) {
1188
+ this.worker.once(event, listener);
1189
+ return this;
1190
+ },
1191
+ off(event, listener) {
1192
+ this.worker.off(event, listener);
1193
+ return this;
1194
+ },
1195
+ pause() {
1196
+ this.queue.pause().catch(() => {});
1197
+ this.worker.pause();
1198
+ },
1199
+ resume() {
1200
+ this.queue.resume().catch(() => {});
1201
+ this.worker.resume();
1202
+ },
1203
+ async close(force = false) {
1204
+ this.ager?.destroy();
1205
+ this.cb?.destroy();
1206
+ this.batchAcc?.destroy();
1207
+ this.cancellation.destroyAll();
1208
+ await this.worker.close(force);
1209
+ this.queue.close();
1210
+ },
1211
+ isRunning() {
1212
+ return this.worker.isRunning();
1213
+ },
1214
+ isPaused() {
1215
+ return this.worker.isPaused();
1216
+ },
1217
+ isClosed() {
1218
+ return this.worker.isClosed();
1219
+ }
1220
+ };
1221
+
1222
+ // src/bunqueue/cancellation.ts
1223
+ class CancellationManager {
1224
+ controllers = new Map;
1225
+ register(jobId) {
1226
+ const ac = new AbortController;
1227
+ this.controllers.set(jobId, ac);
1228
+ return ac;
1229
+ }
1230
+ unregister(jobId) {
1231
+ this.controllers.delete(jobId);
1232
+ }
1233
+ cancel(jobId, gracePeriodMs = 0) {
1234
+ const ac = this.controllers.get(jobId);
1235
+ if (!ac)
1236
+ return;
1237
+ if (gracePeriodMs > 0) {
1238
+ setTimeout(() => {
1239
+ ac.abort();
1240
+ }, gracePeriodMs);
1241
+ } else {
1242
+ ac.abort();
1243
+ }
1244
+ }
1245
+ isCancelled(jobId) {
1246
+ const ac = this.controllers.get(jobId);
1247
+ return ac ? ac.signal.aborted : false;
1248
+ }
1249
+ getSignal(jobId) {
1250
+ return this.controllers.get(jobId)?.signal ?? null;
1251
+ }
1252
+ destroyAll() {
1253
+ for (const ac of this.controllers.values()) {
1254
+ ac.abort();
1255
+ }
1256
+ this.controllers.clear();
1257
+ }
1258
+ }
1259
+
1260
+ // src/bunqueue/circuit-breaker.ts
1261
+ class WorkerCircuitBreaker {
1262
+ state = "closed";
1263
+ failures = 0;
1264
+ timer = null;
1265
+ config;
1266
+ worker;
1267
+ constructor(config, worker) {
1268
+ this.config = config;
1269
+ this.worker = worker;
1270
+ }
1271
+ get currentState() {
1272
+ return this.state;
1273
+ }
1274
+ isOpen() {
1275
+ return this.state === "open";
1276
+ }
1277
+ onSuccess() {
1278
+ if (this.state === "half-open") {
1279
+ this.state = "closed";
1280
+ this.failures = 0;
1281
+ this.config.onClose?.();
1282
+ } else if (this.state === "closed") {
1283
+ this.failures = 0;
1284
+ }
1285
+ }
1286
+ onFailure() {
1287
+ this.failures++;
1288
+ const threshold = this.config.threshold ?? 5;
1289
+ if (this.state === "half-open" || this.failures >= threshold) {
1290
+ this.open();
1291
+ }
1292
+ }
1293
+ open() {
1294
+ this.state = "open";
1295
+ this.config.onOpen?.(this.failures);
1296
+ this.worker.pause();
1297
+ const resetTimeout = this.config.resetTimeout ?? 30000;
1298
+ if (this.timer)
1299
+ clearTimeout(this.timer);
1300
+ this.timer = setTimeout(() => {
1301
+ this.state = "half-open";
1302
+ this.config.onHalfOpen?.();
1303
+ this.worker.resume();
1304
+ }, resetTimeout);
1305
+ this.timer.unref?.();
1306
+ }
1307
+ reset() {
1308
+ this.state = "closed";
1309
+ this.failures = 0;
1310
+ if (this.timer) {
1311
+ clearTimeout(this.timer);
1312
+ this.timer = null;
1313
+ }
1314
+ if (this.worker.isPaused()) {
1315
+ this.worker.resume();
1316
+ }
1317
+ }
1318
+ destroy() {
1319
+ if (this.timer) {
1320
+ clearTimeout(this.timer);
1321
+ this.timer = null;
1322
+ }
1323
+ }
1324
+ }
1325
+
1326
+ // src/bunqueue/dedup-debounce.ts
1327
+ class DedupDebounceMerger {
1328
+ dedup;
1329
+ debounce;
1330
+ constructor(dedup, debounce) {
1331
+ this.dedup = dedup;
1332
+ this.debounce = debounce;
1333
+ }
1334
+ get active() {
1335
+ return this.dedup !== null || this.debounce !== null;
1336
+ }
1337
+ merge(name, opts, data) {
1338
+ if (!this.active)
1339
+ return opts;
1340
+ const merged = { ...opts };
1341
+ if (this.dedup && !merged.deduplication) {
1342
+ const dataKey = data !== undefined ? JSON.stringify(data) : "";
1343
+ merged.deduplication = {
1344
+ id: `${name}:${dataKey}`,
1345
+ ttl: this.dedup.ttl ?? 3600000,
1346
+ extend: this.dedup.extend,
1347
+ replace: this.dedup.replace
1348
+ };
1349
+ }
1350
+ if (this.debounce && !merged.debounce) {
1351
+ merged.debounce = {
1352
+ id: name,
1353
+ ttl: this.debounce.ttl
1354
+ };
1355
+ }
1356
+ return merged;
1357
+ }
1358
+ }
1359
+
1360
+ // src/bunqueue/dlq-rate-limit.ts
1361
+ function entryReason(entry) {
1362
+ return String(entry.reason ?? entry.entry?.reason ?? "unknown");
1363
+ }
1364
+ function entryName(entry) {
1365
+ const data = entry.data ?? entry.entry?.data;
1366
+ return data?.name === undefined ? undefined : String(data.name);
1367
+ }
1368
+
1369
+ class DlqRateLimitManager {
1370
+ queue;
1371
+ constructor(queue) {
1372
+ this.queue = queue;
1373
+ }
1374
+ async setDlqConfig(config) {
1375
+ await this.queue.setDlqConfig(config);
1376
+ }
1377
+ getDlqConfig() {
1378
+ return this.queue.getDlqConfig();
1379
+ }
1380
+ async getDlq(filter) {
1381
+ const entries = await this.queue.getDlq();
1382
+ if (!filter)
1383
+ return entries;
1384
+ return entries.filter((entry) => {
1385
+ if (filter.reason && entryReason(entry) !== filter.reason)
1386
+ return false;
1387
+ if (filter.jobName && entryName(entry) !== filter.jobName)
1388
+ return false;
1389
+ if (filter.since !== undefined) {
1390
+ const at = Number(entry.enteredAt ?? entry.failedAt ?? 0);
1391
+ if (at < filter.since)
1392
+ return false;
1393
+ }
1394
+ return true;
1395
+ });
1396
+ }
1397
+ async getDlqStats() {
1398
+ const entries = await this.queue.getDlq();
1399
+ const byReason = {};
1400
+ for (const entry of entries) {
1401
+ const reason = entryReason(entry);
1402
+ byReason[reason] = (byReason[reason] ?? 0) + 1;
1403
+ }
1404
+ return { total: entries.length, byReason };
1405
+ }
1406
+ retryDlq(id) {
1407
+ return this.queue.retryDlq(id);
1408
+ }
1409
+ purgeDlq() {
1410
+ return this.queue.purgeDlq();
1411
+ }
1412
+ async setGlobalRateLimit(max, duration) {
1413
+ await this.queue.setGlobalRateLimit(max, duration);
1414
+ }
1415
+ async removeGlobalRateLimit() {
1416
+ await this.queue.removeGlobalRateLimit();
1417
+ }
1418
+ }
1419
+
1420
+ // src/bunqueue/rate-gate.ts
1421
+ var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1422
+
1423
+ class RateGate {
1424
+ max;
1425
+ duration;
1426
+ groupKey;
1427
+ windows = new Map;
1428
+ constructor(options) {
1429
+ this.max = options.max;
1430
+ this.duration = options.duration;
1431
+ this.groupKey = options.groupKey;
1432
+ }
1433
+ groupFor(data) {
1434
+ if (!this.groupKey)
1435
+ return "";
1436
+ if (typeof data === "object" && data !== null) {
1437
+ const value = data[this.groupKey];
1438
+ if (value !== undefined && value !== null)
1439
+ return String(value);
1440
+ }
1441
+ return "";
1442
+ }
1443
+ async acquire(group) {
1444
+ for (;; ) {
1445
+ const now = Date.now();
1446
+ const window = this.windows.get(group) ?? [];
1447
+ const fresh = window.filter((t) => now - t < this.duration);
1448
+ if (fresh.length < this.max) {
1449
+ fresh.push(now);
1450
+ this.windows.set(group, fresh);
1451
+ return;
1452
+ }
1453
+ this.windows.set(group, fresh);
1454
+ const oldest = fresh[0];
1455
+ await sleep2(Math.max(oldest + this.duration - now, 10));
1456
+ }
1457
+ }
1458
+ prune() {
1459
+ const now = Date.now();
1460
+ for (const [group, window] of this.windows) {
1461
+ if (window.length === 0 || now - window[window.length - 1] >= this.duration) {
1462
+ this.windows.delete(group);
1463
+ }
1464
+ }
1465
+ }
1466
+ }
1467
+
1468
+ // src/bunqueue/retry.ts
1469
+ function calculateBackoff(strategy, attempt, baseDelay, error, config) {
1470
+ switch (strategy) {
1471
+ case "fixed":
1472
+ return baseDelay;
1473
+ case "exponential":
1474
+ return baseDelay * 2 ** (attempt - 1);
1475
+ case "jitter": {
1476
+ const exp = baseDelay * 2 ** (attempt - 1);
1477
+ return Math.floor(exp * (0.5 + Math.random()));
1478
+ }
1479
+ case "fibonacci": {
1480
+ let a = 1;
1481
+ let b = 1;
1482
+ for (let i = 0;i < attempt - 1; i++) {
1483
+ const next = a + b;
1484
+ a = b;
1485
+ b = next;
1486
+ }
1487
+ return baseDelay * b;
1488
+ }
1489
+ case "custom":
1490
+ if (config.customBackoff) {
1491
+ return config.customBackoff(attempt, error);
1492
+ }
1493
+ return baseDelay;
1494
+ default:
1495
+ return baseDelay;
1496
+ }
1497
+ }
1498
+ function executeWithRetry(fn, config) {
1499
+ const maxAttempts = config.maxAttempts ?? 3;
1500
+ const baseDelay = config.delay ?? 1000;
1501
+ const strategy = config.strategy ?? "exponential";
1502
+ const attempt = (n) => {
1503
+ return fn().catch((err) => {
1504
+ const error = err instanceof Error ? err : new Error(String(err));
1505
+ if (n >= maxAttempts)
1506
+ throw error;
1507
+ if (config.retryIf && !config.retryIf(error, n))
1508
+ throw error;
1509
+ const delay = calculateBackoff(strategy, n, baseDelay, error, config);
1510
+ return new Promise((resolve) => {
1511
+ setTimeout(() => {
1512
+ resolve(attempt(n + 1));
1513
+ }, delay);
1514
+ });
1515
+ });
1516
+ };
1517
+ return attempt(1);
1518
+ }
1519
+
1520
+ // src/bunqueue/triggers.ts
1521
+ class TriggerManager {
1522
+ rules = [];
1523
+ active = false;
1524
+ queue;
1525
+ worker;
1526
+ constructor(queue, worker) {
1527
+ this.queue = queue;
1528
+ this.worker = worker;
1529
+ }
1530
+ add(rule) {
1531
+ this.rules.push(rule);
1532
+ this.ensureActive();
1533
+ }
1534
+ ensureActive() {
1535
+ if (this.active)
1536
+ return;
1537
+ this.active = true;
1538
+ this.worker.on("completed", (job, result) => {
1539
+ this.fire("completed", job, result);
1540
+ });
1541
+ this.worker.on("failed", (job, error) => {
1542
+ this.fire("failed", job, error);
1543
+ });
1544
+ }
1545
+ fire(event, job, resultOrError) {
1546
+ for (const rule of this.rules) {
1547
+ if (rule.on !== job.name)
1548
+ continue;
1549
+ if ((rule.event ?? "completed") !== event)
1550
+ continue;
1551
+ if (rule.condition && !rule.condition(resultOrError, job))
1552
+ continue;
1553
+ const data = rule.data(resultOrError, job);
1554
+ this.queue.add(rule.create, data, rule.opts);
1555
+ }
1556
+ }
1557
+ }
1558
+
1559
+ // src/bunqueue/ttl.ts
1560
+ class TtlChecker {
1561
+ config;
1562
+ constructor(config) {
1563
+ this.config = config;
1564
+ }
1565
+ getTtl(jobName) {
1566
+ return this.config.perName?.[jobName] ?? this.config.defaultTtl ?? 0;
1567
+ }
1568
+ isExpired(jobName, jobTimestamp) {
1569
+ const ttl = this.getTtl(jobName);
1570
+ if (ttl <= 0)
1571
+ return false;
1572
+ return Date.now() - jobTimestamp > ttl;
1573
+ }
1574
+ setDefaultTtl(ttlMs) {
1575
+ this.config.defaultTtl = ttlMs;
1576
+ }
1577
+ setNameTtl(jobName, ttlMs) {
1578
+ this.config.perName ??= {};
1579
+ this.config.perName[jobName] = ttlMs;
1580
+ }
1581
+ }
1582
+
1583
+ // src/bunqueue/bunqueue.ts
1584
+ class Bunqueue {
1585
+ name;
1586
+ queue;
1587
+ worker;
1588
+ cancellation = new CancellationManager;
1589
+ cb;
1590
+ triggerMgr;
1591
+ ager;
1592
+ ttlChecker;
1593
+ batchAcc;
1594
+ dlqrl;
1595
+ middlewares = [];
1596
+ baseProcessor;
1597
+ retryConfig;
1598
+ merger;
1599
+ rateGate;
1600
+ defaultJobOptions;
1601
+ constructor(name, opts) {
1602
+ if (opts.embedded || opts.dataPath) {
1603
+ throw new Error('Bunqueue (bunqueue-client) is TCP-only: embedded mode requires the Bun runtime — use the official "bunqueue" package on Bun instead');
1604
+ }
1605
+ const modes = [opts.processor, opts.routes, opts.batch].filter(Boolean).length;
1606
+ if (modes === 0)
1607
+ throw new Error('Bunqueue requires "processor", "routes", or "batch"');
1608
+ if (modes > 1)
1609
+ throw new Error('Bunqueue: use only one of "processor", "routes", or "batch"');
1610
+ this.name = (opts.prefixKey ?? "") + name;
1611
+ this.retryConfig = opts.retry ?? null;
1612
+ this.ttlChecker = opts.ttl ? new TtlChecker(opts.ttl) : null;
1613
+ this.merger = new DedupDebounceMerger(opts.deduplication ?? null, opts.debounce ?? null);
1614
+ const limiter = opts.rateLimit ?? opts.limiter;
1615
+ this.rateGate = limiter ? new RateGate(limiter) : null;
1616
+ this.defaultJobOptions = this.buildDefaultJobOptions(opts);
1617
+ if (opts.batch) {
1618
+ this.batchAcc = new BatchAccumulator(opts.batch);
1619
+ this.baseProcessor = this.batchAcc.buildProcessor();
1620
+ } else {
1621
+ this.batchAcc = null;
1622
+ this.baseProcessor = opts.routes ? this.buildRouteProcessor(opts.routes) : opts.processor;
1623
+ }
1624
+ const wrappedProcessor = (job) => this.processJob(job);
1625
+ const conn = opts.connection ?? {};
1626
+ this.queue = new Queue(this.name, conn);
1627
+ this.worker = new Worker(this.name, wrappedProcessor, {
1628
+ ...conn,
1629
+ concurrency: opts.concurrency,
1630
+ autorun: opts.autorun,
1631
+ heartbeatIntervalS: opts.heartbeatInterval !== undefined ? opts.heartbeatInterval / 1000 : undefined,
1632
+ batchSize: opts.batchSize,
1633
+ pollTimeoutMs: opts.pollTimeout
1634
+ });
1635
+ this.dlqrl = new DlqRateLimitManager(this.queue);
1636
+ if (opts.dlq) {
1637
+ this.dlqrl.setDlqConfig(opts.dlq).catch((err) => {
1638
+ if (this.worker.listenerCount("error") > 0) {
1639
+ this.worker.emit("error", err instanceof Error ? err : new Error(String(err)));
1640
+ }
1641
+ });
1642
+ }
1643
+ this.cb = opts.circuitBreaker ? new WorkerCircuitBreaker(opts.circuitBreaker, this.worker) : null;
1644
+ this.triggerMgr = new TriggerManager(this.queue, this.worker);
1645
+ this.ager = opts.priorityAging ? new PriorityAger(opts.priorityAging, this.queue) : null;
1646
+ this.ager?.start();
1647
+ }
1648
+ buildRouteProcessor(routes) {
1649
+ const routeMap = routes;
1650
+ return (job) => {
1651
+ const handler = routeMap[job.name ?? ""];
1652
+ if (!handler)
1653
+ throw new Error(`No route for job "${job.name}" in queue "${this.name}"`);
1654
+ return handler(job);
1655
+ };
1656
+ }
1657
+ buildDefaultJobOptions(opts) {
1658
+ const base = { ...opts.defaultJobOptions };
1659
+ if (opts.removeOnComplete !== undefined)
1660
+ base.removeOnComplete ??= opts.removeOnComplete;
1661
+ if (opts.removeOnFail !== undefined)
1662
+ base.removeOnFail ??= opts.removeOnFail;
1663
+ return Object.keys(base).length > 0 ? base : undefined;
1664
+ }
1665
+ async processJob(job) {
1666
+ if (this.rateGate) {
1667
+ this.rateGate.prune();
1668
+ await this.rateGate.acquire(this.rateGate.groupFor(job.data));
1669
+ }
1670
+ if (this.cb?.isOpen()) {
1671
+ throw new Error("Circuit breaker is open");
1672
+ }
1673
+ if (this.ttlChecker?.isExpired(job.name ?? "", job.timestamp)) {
1674
+ throw new Error(`Job expired (age: ${Date.now() - job.timestamp}ms)`);
1675
+ }
1676
+ const ac = this.cancellation.register(job.id);
1677
+ const runChain = () => this.runMiddlewareChain(job, ac);
1678
+ const execute = this.retryConfig ? executeWithRetry(runChain, this.retryConfig) : runChain();
1679
+ return execute.then((result) => {
1680
+ this.cb?.onSuccess();
1681
+ this.cancellation.unregister(job.id);
1682
+ return result;
1683
+ }, (err) => {
1684
+ this.cb?.onFailure();
1685
+ this.cancellation.unregister(job.id);
1686
+ throw err;
1687
+ });
1688
+ }
1689
+ runMiddlewareChain(job, ac) {
1690
+ if (this.middlewares.length === 0) {
1691
+ const result = this.baseProcessor(job);
1692
+ return result instanceof Promise ? result : Promise.resolve(result);
1693
+ }
1694
+ let index = 0;
1695
+ const mws = this.middlewares;
1696
+ const base = this.baseProcessor;
1697
+ const next = () => {
1698
+ if (ac.signal.aborted)
1699
+ return Promise.reject(new Error("Job cancelled"));
1700
+ if (index < mws.length)
1701
+ return mws[index++](job, next);
1702
+ const result = base(job);
1703
+ return result instanceof Promise ? result : Promise.resolve(result);
1704
+ };
1705
+ return next();
1706
+ }
1707
+ use(middleware) {
1708
+ this.middlewares.push(middleware);
1709
+ return this;
1710
+ }
1711
+ add(name, data, opts) {
1712
+ const merged = { ...this.defaultJobOptions, ...opts };
1713
+ return this.queue.add(name, data, this.merger.merge(name, merged, data));
1714
+ }
1715
+ addBulk(jobs) {
1716
+ return this.queue.addBulk(jobs.map((j) => ({
1717
+ ...j,
1718
+ opts: this.merger.merge(j.name, { ...this.defaultJobOptions, ...j.opts }, j.data)
1719
+ })));
1720
+ }
1721
+ getJob(id) {
1722
+ return this.queue.getJob(id);
1723
+ }
1724
+ getJobCounts() {
1725
+ return this.queue.getJobCounts();
1726
+ }
1727
+ getJobCountsAsync() {
1728
+ return this.queue.getJobCounts();
1729
+ }
1730
+ count() {
1731
+ return this.queue.count();
1732
+ }
1733
+ countAsync() {
1734
+ return this.queue.count();
1735
+ }
1736
+ }
1737
+ Object.assign(Bunqueue.prototype, bunqueueApi);
1738
+ // src/flow-commit.ts
1739
+ function validateFlowSnapshots(jobs, snapshots) {
1740
+ if (!Array.isArray(snapshots) || snapshots.length !== jobs.length) {
1741
+ throw new Error("Invalid PUSHF response: committed job snapshots are missing");
1742
+ }
1743
+ const expected = new Map(jobs.map((job) => [job.id, job.queue]));
1744
+ const byId = new Map;
1745
+ for (const value of snapshots) {
1746
+ if (!value || typeof value !== "object") {
1747
+ throw new Error("Invalid PUSHF response: job snapshot is invalid");
1748
+ }
1749
+ const snapshot = value;
1750
+ if (typeof snapshot.id !== "string" || !expected.has(snapshot.id)) {
1751
+ throw new Error("Invalid PUSHF response: committed job IDs do not match the request");
1752
+ }
1753
+ if (byId.has(snapshot.id) || snapshot.queue !== expected.get(snapshot.id)) {
1754
+ throw new Error("Invalid PUSHF response: committed job IDs do not match the request");
1755
+ }
1756
+ byId.set(snapshot.id, snapshot);
1757
+ }
1758
+ return byId;
1759
+ }
1760
+ async function commitFlow(connection, jobs) {
1761
+ if (jobs.length === 0)
1762
+ return new Map;
1763
+ const response = await connection.call({
1764
+ cmd: "PUSHF",
1765
+ jobs
1766
+ });
1767
+ return validateFlowSnapshots(jobs, response.data?.jobs);
1768
+ }
1769
+
1770
+ // src/flow-plan.ts
1771
+ import { randomUUID } from "node:crypto";
1772
+ var MAX_FLOW_DEPTH = 100;
1773
+ var MAX_FLOW_JOBS = 1e4;
1774
+ var QUEUE_RE = /^[a-zA-Z0-9_\-.:]+$/;
1775
+ function assertNameAndQueue(name, queueName, depth) {
1776
+ if (typeof name !== "string" || name.length === 0 || name.length > 256) {
1777
+ throw new Error("flow job name must be a non-empty string of at most 256 characters");
1778
+ }
1779
+ if (typeof queueName !== "string" || queueName.length === 0 || queueName.length > 256 || !QUEUE_RE.test(queueName)) {
1780
+ throw new Error("flow queueName is invalid");
1781
+ }
1782
+ if (depth > MAX_FLOW_DEPTH) {
1783
+ throw new Error(`flow exceeds the ${MAX_FLOW_DEPTH} level depth limit`);
1784
+ }
1785
+ }
1786
+ function assertAtomicOptions(opts) {
1787
+ if (opts.repeat !== undefined)
1788
+ throw new Error("repeat is not supported inside an atomic flow");
1789
+ if (opts.deduplication !== undefined) {
1790
+ throw new Error("deduplication is not supported inside an atomic flow");
1791
+ }
1792
+ if (opts.debounce !== undefined) {
1793
+ throw new Error("debounce is not supported inside an atomic flow");
1794
+ }
1795
+ if (opts.parentId !== undefined || opts.dependsOn !== undefined || opts.childrenIds !== undefined) {
1796
+ throw new Error("flow topology options are owned by FlowProducer");
1797
+ }
1798
+ }
1799
+ function assertUserData(data) {
1800
+ if (!data || typeof data !== "object" || Array.isArray(data))
1801
+ return;
1802
+ for (const key of Object.keys(data)) {
1803
+ if (key === "name" || key.startsWith("__")) {
1804
+ throw new Error(`flow job data key is reserved: ${key}`);
1805
+ }
1806
+ }
1807
+ }
1808
+ function flowData(name, data, internal = {}) {
1809
+ assertUserData(data);
1810
+ if (data && typeof data === "object" && !Array.isArray(data)) {
1811
+ return { ...data, name, ...internal };
1812
+ }
1813
+ return data === undefined || data === null ? { name, ...internal } : { name, payload: data, ...internal };
1814
+ }
1815
+ function flowInput(data, opts, links = {}) {
1816
+ assertAtomicOptions(opts);
1817
+ const mapped = { ...wireJobOptions(opts) };
1818
+ delete mapped.jobId;
1819
+ delete mapped.parentId;
1820
+ delete mapped.dependsOn;
1821
+ delete mapped.childrenIds;
1822
+ return compact2({
1823
+ data,
1824
+ ...mapped,
1825
+ customId: opts.jobId,
1826
+ parentId: links.parentId,
1827
+ dependsOn: links.dependsOn,
1828
+ childrenIds: links.childrenIds
1829
+ });
1830
+ }
1831
+ function allocateFlowId(opts, ids, idFactory) {
1832
+ const id = opts.jobId ?? idFactory();
1833
+ if (typeof id !== "string" || id.length === 0 || id.length > 1024 || id.includes(":")) {
1834
+ throw new Error("flow jobId must be non-empty and cannot contain a colon");
1835
+ }
1836
+ if (ids.has(id))
1837
+ throw new Error(`duplicate flow job id: ${id}`);
1838
+ ids.add(id);
1839
+ return id;
1840
+ }
1841
+ function visit(node, parent, depth, options, state) {
1842
+ if (!node || typeof node !== "object")
1843
+ throw new Error("flow node must be an object");
1844
+ assertNameAndQueue(node.name, node.queueName, depth);
1845
+ if (node.children !== undefined && !Array.isArray(node.children)) {
1846
+ throw new Error("flow children must be an array");
1847
+ }
1848
+ if (state.seen.has(node))
1849
+ throw new Error("flow contains a cycle or shared node");
1850
+ state.seen.add(node);
1851
+ state.count += 1;
1852
+ if (state.count > MAX_FLOW_JOBS) {
1853
+ throw new Error(`flow exceeds the ${MAX_FLOW_JOBS} job limit`);
1854
+ }
1855
+ const defaults = options?.queuesOptions?.[node.queueName];
1856
+ const opts = defaults ? { ...defaults, ...node.opts } : node.opts ?? {};
1857
+ assertAtomicOptions(opts);
1858
+ const id = allocateFlowId(opts, state.ids, state.idFactory);
1859
+ const children = (node.children ?? []).map((child) => visit(child, { id, queue: node.queueName }, depth + 1, options, state));
1860
+ const childIds = children.map((child) => child.id);
1861
+ const internal = {};
1862
+ if (parent) {
1863
+ internal.__parentId = parent.id;
1864
+ internal.__parentQueue = parent.queue;
1865
+ }
1866
+ if (childIds.length > 0)
1867
+ internal.__childrenIds = childIds;
1868
+ const data = flowData(node.name, node.data, internal);
1869
+ state.jobs.push({
1870
+ id,
1871
+ queue: node.queueName,
1872
+ input: flowInput(data, opts, {
1873
+ parentId: parent?.id,
1874
+ dependsOn: childIds.length > 0 ? childIds : undefined,
1875
+ childrenIds: childIds.length > 0 ? childIds : undefined
1876
+ })
1877
+ });
1878
+ return {
1879
+ id,
1880
+ name: node.name,
1881
+ queueName: node.queueName,
1882
+ data: node.data,
1883
+ children: children.length > 0 ? children : undefined
1884
+ };
1885
+ }
1886
+ function planFlows(flows, options, idFactory = randomUUID) {
1887
+ for (const defaults of Object.values(options?.queuesOptions ?? {})) {
1888
+ if (defaults.jobId !== undefined) {
1889
+ throw new Error("jobId cannot be a queue default");
1890
+ }
1891
+ }
1892
+ const state = {
1893
+ ids: new Set,
1894
+ seen: new WeakSet,
1895
+ jobs: [],
1896
+ idFactory,
1897
+ count: 0
1898
+ };
1899
+ const roots = flows.map((flow) => visit(flow, undefined, 0, options, state));
1900
+ return { jobs: state.jobs, roots };
1901
+ }
1902
+
1903
+ // src/flow-plan-legacy.ts
1904
+ import { randomUUID as randomUUID2 } from "node:crypto";
1905
+ var MAX_FLOW_JOBS2 = 1e4;
1906
+ var QUEUE_RE2 = /^[a-zA-Z0-9_\-.:]+$/;
1907
+ function allocateSteps(steps, ids, idFactory) {
1908
+ if (steps.length > MAX_FLOW_JOBS2) {
1909
+ throw new Error(`flow exceeds the ${MAX_FLOW_JOBS2} job limit`);
1910
+ }
1911
+ return steps.map((step) => {
1912
+ if (!step || typeof step !== "object")
1913
+ throw new Error("flow step must be an object");
1914
+ if (typeof step.name !== "string" || !step.name || step.name.length > 256) {
1915
+ throw new Error("flow job name must be a non-empty string of at most 256 characters");
1916
+ }
1917
+ if (typeof step.queueName !== "string" || !step.queueName || step.queueName.length > 256 || !QUEUE_RE2.test(step.queueName)) {
1918
+ throw new Error("flow queueName is invalid");
1919
+ }
1920
+ const children = step.children;
1921
+ if (children !== undefined && !Array.isArray(children)) {
1922
+ throw new Error("flow children must be an array");
1923
+ }
1924
+ if ((children?.length ?? 0) > 0) {
1925
+ throw new Error("nested children are not supported by this flow method");
1926
+ }
1927
+ return allocateFlowId(step.opts ?? {}, ids, idFactory);
1928
+ });
1929
+ }
1930
+ function planChain(steps, idFactory = randomUUID2) {
1931
+ const ids = allocateSteps(steps, new Set, idFactory);
1932
+ const jobs = steps.map((step, index) => {
1933
+ const dependency = index > 0 ? ids[index - 1] : undefined;
1934
+ const data = flowData(step.name, step.data, {
1935
+ __flowParentId: dependency ?? null
1936
+ });
1937
+ return {
1938
+ id: ids[index],
1939
+ queue: step.queueName,
1940
+ input: flowInput(data, step.opts ?? {}, {
1941
+ dependsOn: dependency ? [dependency] : undefined
1942
+ })
1943
+ };
1944
+ });
1945
+ return { jobs, ids };
1946
+ }
1947
+ function planBulkThen(parallel, final, idFactory = randomUUID2) {
1948
+ if (parallel.length >= MAX_FLOW_JOBS2) {
1949
+ throw new Error(`flow exceeds the ${MAX_FLOW_JOBS2} job limit`);
1950
+ }
1951
+ const ids = new Set;
1952
+ const parallelIds = allocateSteps(parallel, ids, idFactory);
1953
+ const [finalId] = allocateSteps([final], ids, idFactory);
1954
+ const parallelJobs = parallel.map((step, index) => ({
1955
+ id: parallelIds[index],
1956
+ queue: step.queueName,
1957
+ input: flowInput(flowData(step.name, step.data, {
1958
+ __parentId: finalId,
1959
+ __parentQueue: final.queueName
1960
+ }), step.opts ?? {}, { parentId: finalId })
1961
+ }));
1962
+ const finalJob = {
1963
+ id: finalId,
1964
+ queue: final.queueName,
1965
+ input: flowInput(flowData(final.name, final.data, {
1966
+ __flowParentIds: parallelIds,
1967
+ __childrenIds: parallelIds
1968
+ }), final.opts ?? {}, {
1969
+ dependsOn: parallelIds.length > 0 ? parallelIds : undefined,
1970
+ childrenIds: parallelIds.length > 0 ? parallelIds : undefined
1971
+ })
1972
+ };
1973
+ return { jobs: [...parallelJobs, finalJob], parallelIds, finalId };
1974
+ }
1975
+
1976
+ // src/flow.ts
1977
+ class FlowProducer {
1978
+ connection;
1979
+ ownsConnection;
1980
+ constructor(opts = {}) {
1981
+ this.connection = opts.connection ?? new Connection2({
1982
+ host: opts.host,
1983
+ port: opts.port,
1984
+ token: opts.token,
1985
+ tls: opts.tls,
1986
+ logger: opts.logger,
1987
+ onTelemetry: opts.onTelemetry
1988
+ });
1989
+ this.ownsConnection = opts.connection === undefined;
1990
+ }
1991
+ async add(flow, options) {
1992
+ const plan = planFlows([flow], options);
1993
+ const snapshots = await commitFlow(this.connection, plan.jobs);
1994
+ return this.buildNode(plan.roots[0], snapshots);
1995
+ }
1996
+ async addBulk(flows) {
1997
+ const plan = planFlows(flows);
1998
+ const snapshots = await commitFlow(this.connection, plan.jobs);
1999
+ return plan.roots.map((root) => this.buildNode(root, snapshots));
2000
+ }
2001
+ getFlow(opts) {
2002
+ return this.fetchNode(opts.id, opts.depth ?? Number.POSITIVE_INFINITY, opts.maxChildren, new Set);
2003
+ }
2004
+ async addChain(steps) {
2005
+ if (steps.length === 0)
2006
+ return { jobIds: [] };
2007
+ const plan = planChain(steps);
2008
+ await commitFlow(this.connection, plan.jobs);
2009
+ return { jobIds: plan.ids };
2010
+ }
2011
+ async addBulkThen(parallel, final) {
2012
+ const plan = planBulkThen(parallel, final);
2013
+ await commitFlow(this.connection, plan.jobs);
2014
+ return { parallelIds: plan.parallelIds, finalId: plan.finalId };
2015
+ }
2016
+ close() {
2017
+ if (this.ownsConnection)
2018
+ this.connection.close();
2019
+ }
2020
+ buildNode(node, snapshots) {
2021
+ const snapshot = snapshots.get(node.id);
2022
+ if (!snapshot)
2023
+ throw new Error(`Committed flow snapshot missing for ${node.id}`);
2024
+ const children = node.children?.map((child) => this.buildNode(child, snapshots));
2025
+ return {
2026
+ job: new Job(snapshot, this.connection),
2027
+ children: children && children.length > 0 ? children : undefined
2028
+ };
2029
+ }
2030
+ async fetchNode(id, depth, maxChildren, visited) {
2031
+ if (visited.has(id))
2032
+ return null;
2033
+ visited.add(id);
2034
+ let response;
2035
+ try {
2036
+ response = await this.connection.call({ cmd: "GetJob", id });
2037
+ } catch (err) {
2038
+ if (err instanceof CommandError2 && /not found/i.test(err.message))
2039
+ return null;
2040
+ throw err;
2041
+ }
2042
+ const raw = response.job;
2043
+ if (!raw)
2044
+ return null;
2045
+ const job = new Job(raw, this.connection);
2046
+ if (depth <= 0 || job.childrenIds.length === 0)
2047
+ return { job };
2048
+ const limit = maxChildren ?? job.childrenIds.length;
2049
+ const children = [];
2050
+ for (const childId of job.childrenIds.slice(0, limit)) {
2051
+ const child = await this.fetchNode(childId, depth - 1, maxChildren, visited);
2052
+ if (child)
2053
+ children.push(child);
2054
+ }
2055
+ return { job, children: children.length > 0 ? children : undefined };
2056
+ }
2057
+ }
2058
+
2059
+ // src/legacy.ts
2060
+ var __version__ = "0.2.0";
2061
+ export {
2062
+ AuthError2 as AuthError,
2063
+ Bunqueue,
2064
+ BunqueueError2 as BunqueueError,
2065
+ CommandError2 as CommandError,
2066
+ CommandTimeoutError2 as CommandTimeoutError,
2067
+ Connection2 as Connection,
2068
+ ConnectionClosedError2 as ConnectionClosedError,
2069
+ ConnectionPool2 as ConnectionPool,
2070
+ FlowProducer,
2071
+ Job,
2072
+ MAX_FRAME_SIZE2 as MAX_FRAME_SIZE,
2073
+ PROTOCOL_VERSION2 as PROTOCOL_VERSION,
2074
+ Queue,
2075
+ SerializationError2 as SerializationError,
2076
+ UnrecoverableError2 as UnrecoverableError,
2077
+ Worker,
2078
+ __version__,
2079
+ consoleLogger2 as consoleLogger,
2080
+ noopLogger2 as noopLogger
2081
+ };