semola 0.6.0 → 0.6.1

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 (43) hide show
  1. package/README.md +17 -5
  2. package/dist/lib/api/index.cjs +1 -537
  3. package/dist/lib/api/index.d.cts +1 -271
  4. package/dist/lib/api/index.d.mts +80 -84
  5. package/dist/lib/api/index.mjs +1 -535
  6. package/dist/lib/cache/index.cjs +1 -99
  7. package/dist/lib/cache/index.d.cts +1 -27
  8. package/dist/lib/cache/index.mjs +1 -98
  9. package/dist/lib/cron/index.cjs +1 -735
  10. package/dist/lib/cron/index.d.cts +1 -146
  11. package/dist/lib/cron/index.d.mts +99 -36
  12. package/dist/lib/cron/index.mjs +1 -726
  13. package/dist/lib/errors/index.cjs +1 -30
  14. package/dist/lib/errors/index.d.cts +1 -13
  15. package/dist/lib/errors/index.mjs +1 -26
  16. package/dist/lib/i18n/index.cjs +1 -42
  17. package/dist/lib/i18n/index.d.cts +1 -28
  18. package/dist/lib/i18n/index.mjs +1 -41
  19. package/dist/lib/logging/index.cjs +1 -388
  20. package/dist/lib/logging/index.d.cts +1 -108
  21. package/dist/lib/logging/index.mjs +1 -374
  22. package/dist/lib/orm/index.cjs +1 -1642
  23. package/dist/lib/orm/index.d.cts +1 -402
  24. package/dist/lib/orm/index.d.mts +4 -2
  25. package/dist/lib/orm/index.mjs +1 -1630
  26. package/dist/lib/policy/index.cjs +1 -285
  27. package/dist/lib/policy/index.d.cts +1 -77
  28. package/dist/lib/policy/index.mjs +1 -265
  29. package/dist/lib/prompts/index.cjs +6 -769
  30. package/dist/lib/prompts/index.d.cts +1 -75
  31. package/dist/lib/prompts/index.mjs +6 -762
  32. package/dist/lib/pubsub/index.cjs +1 -141
  33. package/dist/lib/pubsub/index.d.cts +1 -26
  34. package/dist/lib/pubsub/index.mjs +1 -140
  35. package/dist/lib/queue/index.cjs +1 -212
  36. package/dist/lib/queue/index.d.cts +1 -81
  37. package/dist/lib/queue/index.mjs +1 -209
  38. package/dist/lib/workflow/index.cjs +1 -537
  39. package/dist/lib/workflow/index.d.cts +1 -150
  40. package/dist/lib/workflow/index.mjs +1 -527
  41. package/dist/rolldown-runtime-CMqjfN_6.cjs +1 -0
  42. package/package.json +7 -5
  43. package/dist/chunk-CKQMccvm.cjs +0 -28
@@ -1,141 +1 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_lib_errors_index = require("../errors/index.cjs");
3
- //#region src/lib/pubsub/errors.ts
4
- var UnsubscribeError = class extends Error {
5
- constructor(message) {
6
- super(message);
7
- this.name = "UnsubscribeError";
8
- }
9
- };
10
- var SerializationError = class extends Error {
11
- constructor(message) {
12
- super(message);
13
- this.name = "SerializationError";
14
- }
15
- };
16
- var PublishError = class extends Error {
17
- constructor(message) {
18
- super(message);
19
- this.name = "PublishError";
20
- }
21
- };
22
- var SubscribeError = class extends Error {
23
- constructor(message) {
24
- super(message);
25
- this.name = "SubscribeError";
26
- }
27
- };
28
- //#endregion
29
- //#region src/lib/pubsub/index.ts
30
- var PubSub = class {
31
- options;
32
- isSubscribed = false;
33
- nextHandlerId = 0;
34
- handlers = /* @__PURE__ */ new Map();
35
- unsubscribeInFlight = null;
36
- subscribeInFlight = null;
37
- constructor(options) {
38
- this.options = options;
39
- }
40
- async onMessage(message, channel) {
41
- const [parseError, parsed] = require_lib_errors_index.mightThrowSync(() => JSON.parse(message));
42
- if (parseError) return;
43
- if (!parsed) return;
44
- const handlers = Array.from(this.handlers.values());
45
- for (const handler of handlers) await require_lib_errors_index.mightThrow(Promise.resolve().then(() => handler(parsed, channel)));
46
- }
47
- async unsubscribeHandler(handlerId) {
48
- const inFlightUnsubscribe = this.unsubscribeInFlight;
49
- if (inFlightUnsubscribe) await inFlightUnsubscribe;
50
- const handler = this.handlers.get(handlerId);
51
- if (!handler) throw new UnsubscribeError("Not subscribed");
52
- this.handlers.delete(handlerId);
53
- if (this.handlers.size > 0) return;
54
- this.isSubscribed = false;
55
- this.unsubscribeInFlight = require_lib_errors_index.mightThrow(this.options.subscriber.unsubscribe(this.options.channel));
56
- const unsubscribeInFlight = this.unsubscribeInFlight;
57
- if (!unsubscribeInFlight) {
58
- this.handlers.set(handlerId, handler);
59
- this.isSubscribed = true;
60
- throw new UnsubscribeError(`Unable to unsubscribe from ${this.options.channel}`);
61
- }
62
- const [unsubscribeError] = await unsubscribeInFlight;
63
- if (unsubscribeError) {
64
- this.handlers.set(handlerId, handler);
65
- this.isSubscribed = true;
66
- this.unsubscribeInFlight = null;
67
- throw new UnsubscribeError(`Unable to unsubscribe from ${this.options.channel}`);
68
- }
69
- this.unsubscribeInFlight = null;
70
- }
71
- async publish(message) {
72
- const [stringifyError, stringified] = require_lib_errors_index.mightThrowSync(() => JSON.stringify(message));
73
- if (stringifyError || !stringified) throw new SerializationError("Unable to serialize message");
74
- const [publishError, count] = await require_lib_errors_index.mightThrow(this.options.publisher.publish(this.options.channel, stringified));
75
- if (publishError) throw new PublishError(`Unable to publish to ${this.options.channel}`);
76
- return count;
77
- }
78
- async subscribe(handler) {
79
- const inFlightUnsubscribe = this.unsubscribeInFlight;
80
- if (inFlightUnsubscribe) await inFlightUnsubscribe;
81
- const handlerId = this.nextHandlerId;
82
- this.nextHandlerId += 1;
83
- this.handlers.set(handlerId, handler);
84
- if (this.isActive()) return () => this.unsubscribeHandler(handlerId);
85
- const inFlightSubscribe = this.subscribeInFlight;
86
- if (inFlightSubscribe) {
87
- const [inFlightError] = await inFlightSubscribe;
88
- if (inFlightError || !this.isSubscribed) {
89
- this.handlers.delete(handlerId);
90
- throw new SubscribeError(`Unable to subscribe to ${this.options.channel}`);
91
- }
92
- return () => this.unsubscribeHandler(handlerId);
93
- }
94
- this.subscribeInFlight = require_lib_errors_index.mightThrow(this.options.subscriber.subscribe(this.options.channel, async (message, channel) => this.onMessage(message, channel)));
95
- const subscribeInFlight = this.subscribeInFlight;
96
- if (!subscribeInFlight) {
97
- this.handlers.delete(handlerId);
98
- throw new SubscribeError(`Unable to subscribe to ${this.options.channel}`);
99
- }
100
- const [subscribeError, count] = await subscribeInFlight;
101
- this.subscribeInFlight = null;
102
- if (subscribeError) {
103
- this.handlers.delete(handlerId);
104
- throw new SubscribeError(`Unable to subscribe to ${this.options.channel}`);
105
- }
106
- if (!count) {
107
- this.handlers.delete(handlerId);
108
- throw new SubscribeError(`Unable to subscribe to ${this.options.channel}`);
109
- }
110
- this.isSubscribed = true;
111
- return () => this.unsubscribeHandler(handlerId);
112
- }
113
- async unsubscribe() {
114
- const inFlightUnsubscribe = this.unsubscribeInFlight;
115
- if (inFlightUnsubscribe) await inFlightUnsubscribe;
116
- if (!this.isActive()) throw new UnsubscribeError("Not subscribed");
117
- const handlers = new Map(this.handlers);
118
- this.handlers.clear();
119
- this.isSubscribed = false;
120
- this.unsubscribeInFlight = require_lib_errors_index.mightThrow(this.options.subscriber.unsubscribe(this.options.channel));
121
- const unsubscribeInFlight = this.unsubscribeInFlight;
122
- if (!unsubscribeInFlight) {
123
- this.handlers = handlers;
124
- this.isSubscribed = true;
125
- throw new UnsubscribeError(`Unable to unsubscribe from ${this.options.channel}`);
126
- }
127
- const [unsubscribeError] = await unsubscribeInFlight;
128
- if (unsubscribeError) {
129
- this.handlers = handlers;
130
- this.isSubscribed = true;
131
- this.unsubscribeInFlight = null;
132
- throw new UnsubscribeError(`Unable to unsubscribe from ${this.options.channel}`);
133
- }
134
- this.unsubscribeInFlight = null;
135
- }
136
- isActive() {
137
- return this.handlers.size > 0 && this.isSubscribed;
138
- }
139
- };
140
- //#endregion
141
- exports.PubSub = PubSub;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../errors/index.cjs");var t=class extends Error{constructor(e){super(e),this.name=`UnsubscribeError`}},n=class extends Error{constructor(e){super(e),this.name=`SerializationError`}},r=class extends Error{constructor(e){super(e),this.name=`PublishError`}},i=class extends Error{constructor(e){super(e),this.name=`SubscribeError`}},a=class{options;isSubscribed=!1;nextHandlerId=0;handlers=new Map;unsubscribeInFlight=null;subscribeInFlight=null;constructor(e){this.options=e}async onMessage(t,n){let[r,i]=e.mightThrowSync(()=>JSON.parse(t));if(r||!i)return;let a=Array.from(this.handlers.values());for(let t of a)await e.mightThrow(Promise.resolve().then(()=>t(i,n)))}async unsubscribeHandler(n){let r=this.unsubscribeInFlight;r&&await r;let i=this.handlers.get(n);if(!i)throw new t(`Not subscribed`);if(this.handlers.delete(n),this.handlers.size>0)return;this.isSubscribed=!1,this.unsubscribeInFlight=e.mightThrow(this.options.subscriber.unsubscribe(this.options.channel));let a=this.unsubscribeInFlight;if(!a)throw this.handlers.set(n,i),this.isSubscribed=!0,new t(`Unable to unsubscribe from ${this.options.channel}`);let[o]=await a;if(o)throw this.handlers.set(n,i),this.isSubscribed=!0,this.unsubscribeInFlight=null,new t(`Unable to unsubscribe from ${this.options.channel}`);this.unsubscribeInFlight=null}async publish(t){let[i,a]=e.mightThrowSync(()=>JSON.stringify(t));if(i||!a)throw new n(`Unable to serialize message`);let[o,s]=await e.mightThrow(this.options.publisher.publish(this.options.channel,a));if(o)throw new r(`Unable to publish to ${this.options.channel}`);return s}async subscribe(t){let n=this.unsubscribeInFlight;n&&await n;let r=this.nextHandlerId;if(this.nextHandlerId+=1,this.handlers.set(r,t),this.isActive())return()=>this.unsubscribeHandler(r);let a=this.subscribeInFlight;if(a){let[e]=await a;if(e||!this.isSubscribed)throw this.handlers.delete(r),new i(`Unable to subscribe to ${this.options.channel}`);return()=>this.unsubscribeHandler(r)}this.subscribeInFlight=e.mightThrow(this.options.subscriber.subscribe(this.options.channel,async(e,t)=>this.onMessage(e,t)));let o=this.subscribeInFlight;if(!o)throw this.handlers.delete(r),new i(`Unable to subscribe to ${this.options.channel}`);let[s,c]=await o;if(this.subscribeInFlight=null,s||!c)throw this.handlers.delete(r),new i(`Unable to subscribe to ${this.options.channel}`);return this.isSubscribed=!0,()=>this.unsubscribeHandler(r)}async unsubscribe(){let n=this.unsubscribeInFlight;if(n&&await n,!this.isActive())throw new t(`Not subscribed`);let r=new Map(this.handlers);this.handlers.clear(),this.isSubscribed=!1,this.unsubscribeInFlight=e.mightThrow(this.options.subscriber.unsubscribe(this.options.channel));let i=this.unsubscribeInFlight;if(!i)throw this.handlers=r,this.isSubscribed=!0,new t(`Unable to unsubscribe from ${this.options.channel}`);let[a]=await i;if(a)throw this.handlers=r,this.isSubscribed=!0,this.unsubscribeInFlight=null,new t(`Unable to unsubscribe from ${this.options.channel}`);this.unsubscribeInFlight=null}isActive(){return this.handlers.size>0&&this.isSubscribed}};exports.PubSub=a;
@@ -1,26 +1 @@
1
- //#region src/lib/pubsub/types.d.ts
2
- type PubSubOptions = {
3
- subscriber: Bun.RedisClient;
4
- publisher: Bun.RedisClient;
5
- channel: string;
6
- };
7
- type MessageHandler<T> = (message: T, channel: string) => void | Promise<void>;
8
- //#endregion
9
- //#region src/lib/pubsub/index.d.ts
10
- declare class PubSub<T extends Record<string, unknown>> {
11
- private options;
12
- private isSubscribed;
13
- private nextHandlerId;
14
- private handlers;
15
- private unsubscribeInFlight;
16
- private subscribeInFlight;
17
- constructor(options: PubSubOptions);
18
- private onMessage;
19
- private unsubscribeHandler;
20
- publish(message: T): Promise<number>;
21
- subscribe(handler: MessageHandler<T>): Promise<() => Promise<void>>;
22
- unsubscribe(): Promise<void>;
23
- isActive(): boolean;
24
- }
25
- //#endregion
26
- export { PubSub };
1
+ export type * from './index.d.mts'
@@ -1,140 +1 @@
1
- import { mightThrow, mightThrowSync } from "../errors/index.mjs";
2
- //#region src/lib/pubsub/errors.ts
3
- var UnsubscribeError = class extends Error {
4
- constructor(message) {
5
- super(message);
6
- this.name = "UnsubscribeError";
7
- }
8
- };
9
- var SerializationError = class extends Error {
10
- constructor(message) {
11
- super(message);
12
- this.name = "SerializationError";
13
- }
14
- };
15
- var PublishError = class extends Error {
16
- constructor(message) {
17
- super(message);
18
- this.name = "PublishError";
19
- }
20
- };
21
- var SubscribeError = class extends Error {
22
- constructor(message) {
23
- super(message);
24
- this.name = "SubscribeError";
25
- }
26
- };
27
- //#endregion
28
- //#region src/lib/pubsub/index.ts
29
- var PubSub = class {
30
- options;
31
- isSubscribed = false;
32
- nextHandlerId = 0;
33
- handlers = /* @__PURE__ */ new Map();
34
- unsubscribeInFlight = null;
35
- subscribeInFlight = null;
36
- constructor(options) {
37
- this.options = options;
38
- }
39
- async onMessage(message, channel) {
40
- const [parseError, parsed] = mightThrowSync(() => JSON.parse(message));
41
- if (parseError) return;
42
- if (!parsed) return;
43
- const handlers = Array.from(this.handlers.values());
44
- for (const handler of handlers) await mightThrow(Promise.resolve().then(() => handler(parsed, channel)));
45
- }
46
- async unsubscribeHandler(handlerId) {
47
- const inFlightUnsubscribe = this.unsubscribeInFlight;
48
- if (inFlightUnsubscribe) await inFlightUnsubscribe;
49
- const handler = this.handlers.get(handlerId);
50
- if (!handler) throw new UnsubscribeError("Not subscribed");
51
- this.handlers.delete(handlerId);
52
- if (this.handlers.size > 0) return;
53
- this.isSubscribed = false;
54
- this.unsubscribeInFlight = mightThrow(this.options.subscriber.unsubscribe(this.options.channel));
55
- const unsubscribeInFlight = this.unsubscribeInFlight;
56
- if (!unsubscribeInFlight) {
57
- this.handlers.set(handlerId, handler);
58
- this.isSubscribed = true;
59
- throw new UnsubscribeError(`Unable to unsubscribe from ${this.options.channel}`);
60
- }
61
- const [unsubscribeError] = await unsubscribeInFlight;
62
- if (unsubscribeError) {
63
- this.handlers.set(handlerId, handler);
64
- this.isSubscribed = true;
65
- this.unsubscribeInFlight = null;
66
- throw new UnsubscribeError(`Unable to unsubscribe from ${this.options.channel}`);
67
- }
68
- this.unsubscribeInFlight = null;
69
- }
70
- async publish(message) {
71
- const [stringifyError, stringified] = mightThrowSync(() => JSON.stringify(message));
72
- if (stringifyError || !stringified) throw new SerializationError("Unable to serialize message");
73
- const [publishError, count] = await mightThrow(this.options.publisher.publish(this.options.channel, stringified));
74
- if (publishError) throw new PublishError(`Unable to publish to ${this.options.channel}`);
75
- return count;
76
- }
77
- async subscribe(handler) {
78
- const inFlightUnsubscribe = this.unsubscribeInFlight;
79
- if (inFlightUnsubscribe) await inFlightUnsubscribe;
80
- const handlerId = this.nextHandlerId;
81
- this.nextHandlerId += 1;
82
- this.handlers.set(handlerId, handler);
83
- if (this.isActive()) return () => this.unsubscribeHandler(handlerId);
84
- const inFlightSubscribe = this.subscribeInFlight;
85
- if (inFlightSubscribe) {
86
- const [inFlightError] = await inFlightSubscribe;
87
- if (inFlightError || !this.isSubscribed) {
88
- this.handlers.delete(handlerId);
89
- throw new SubscribeError(`Unable to subscribe to ${this.options.channel}`);
90
- }
91
- return () => this.unsubscribeHandler(handlerId);
92
- }
93
- this.subscribeInFlight = mightThrow(this.options.subscriber.subscribe(this.options.channel, async (message, channel) => this.onMessage(message, channel)));
94
- const subscribeInFlight = this.subscribeInFlight;
95
- if (!subscribeInFlight) {
96
- this.handlers.delete(handlerId);
97
- throw new SubscribeError(`Unable to subscribe to ${this.options.channel}`);
98
- }
99
- const [subscribeError, count] = await subscribeInFlight;
100
- this.subscribeInFlight = null;
101
- if (subscribeError) {
102
- this.handlers.delete(handlerId);
103
- throw new SubscribeError(`Unable to subscribe to ${this.options.channel}`);
104
- }
105
- if (!count) {
106
- this.handlers.delete(handlerId);
107
- throw new SubscribeError(`Unable to subscribe to ${this.options.channel}`);
108
- }
109
- this.isSubscribed = true;
110
- return () => this.unsubscribeHandler(handlerId);
111
- }
112
- async unsubscribe() {
113
- const inFlightUnsubscribe = this.unsubscribeInFlight;
114
- if (inFlightUnsubscribe) await inFlightUnsubscribe;
115
- if (!this.isActive()) throw new UnsubscribeError("Not subscribed");
116
- const handlers = new Map(this.handlers);
117
- this.handlers.clear();
118
- this.isSubscribed = false;
119
- this.unsubscribeInFlight = mightThrow(this.options.subscriber.unsubscribe(this.options.channel));
120
- const unsubscribeInFlight = this.unsubscribeInFlight;
121
- if (!unsubscribeInFlight) {
122
- this.handlers = handlers;
123
- this.isSubscribed = true;
124
- throw new UnsubscribeError(`Unable to unsubscribe from ${this.options.channel}`);
125
- }
126
- const [unsubscribeError] = await unsubscribeInFlight;
127
- if (unsubscribeError) {
128
- this.handlers = handlers;
129
- this.isSubscribed = true;
130
- this.unsubscribeInFlight = null;
131
- throw new UnsubscribeError(`Unable to unsubscribe from ${this.options.channel}`);
132
- }
133
- this.unsubscribeInFlight = null;
134
- }
135
- isActive() {
136
- return this.handlers.size > 0 && this.isSubscribed;
137
- }
138
- };
139
- //#endregion
140
- export { PubSub };
1
+ import{mightThrow as e,mightThrowSync as t}from"../errors/index.mjs";var n=class extends Error{constructor(e){super(e),this.name=`UnsubscribeError`}},r=class extends Error{constructor(e){super(e),this.name=`SerializationError`}},i=class extends Error{constructor(e){super(e),this.name=`PublishError`}},a=class extends Error{constructor(e){super(e),this.name=`SubscribeError`}},o=class{options;isSubscribed=!1;nextHandlerId=0;handlers=new Map;unsubscribeInFlight=null;subscribeInFlight=null;constructor(e){this.options=e}async onMessage(n,r){let[i,a]=t(()=>JSON.parse(n));if(i||!a)return;let o=Array.from(this.handlers.values());for(let t of o)await e(Promise.resolve().then(()=>t(a,r)))}async unsubscribeHandler(t){let r=this.unsubscribeInFlight;r&&await r;let i=this.handlers.get(t);if(!i)throw new n(`Not subscribed`);if(this.handlers.delete(t),this.handlers.size>0)return;this.isSubscribed=!1,this.unsubscribeInFlight=e(this.options.subscriber.unsubscribe(this.options.channel));let a=this.unsubscribeInFlight;if(!a)throw this.handlers.set(t,i),this.isSubscribed=!0,new n(`Unable to unsubscribe from ${this.options.channel}`);let[o]=await a;if(o)throw this.handlers.set(t,i),this.isSubscribed=!0,this.unsubscribeInFlight=null,new n(`Unable to unsubscribe from ${this.options.channel}`);this.unsubscribeInFlight=null}async publish(n){let[a,o]=t(()=>JSON.stringify(n));if(a||!o)throw new r(`Unable to serialize message`);let[s,c]=await e(this.options.publisher.publish(this.options.channel,o));if(s)throw new i(`Unable to publish to ${this.options.channel}`);return c}async subscribe(t){let n=this.unsubscribeInFlight;n&&await n;let r=this.nextHandlerId;if(this.nextHandlerId+=1,this.handlers.set(r,t),this.isActive())return()=>this.unsubscribeHandler(r);let i=this.subscribeInFlight;if(i){let[e]=await i;if(e||!this.isSubscribed)throw this.handlers.delete(r),new a(`Unable to subscribe to ${this.options.channel}`);return()=>this.unsubscribeHandler(r)}this.subscribeInFlight=e(this.options.subscriber.subscribe(this.options.channel,async(e,t)=>this.onMessage(e,t)));let o=this.subscribeInFlight;if(!o)throw this.handlers.delete(r),new a(`Unable to subscribe to ${this.options.channel}`);let[s,c]=await o;if(this.subscribeInFlight=null,s||!c)throw this.handlers.delete(r),new a(`Unable to subscribe to ${this.options.channel}`);return this.isSubscribed=!0,()=>this.unsubscribeHandler(r)}async unsubscribe(){let t=this.unsubscribeInFlight;if(t&&await t,!this.isActive())throw new n(`Not subscribed`);let r=new Map(this.handlers);this.handlers.clear(),this.isSubscribed=!1,this.unsubscribeInFlight=e(this.options.subscriber.unsubscribe(this.options.channel));let i=this.unsubscribeInFlight;if(!i)throw this.handlers=r,this.isSubscribed=!0,new n(`Unable to unsubscribe from ${this.options.channel}`);let[a]=await i;if(a)throw this.handlers=r,this.isSubscribed=!0,this.unsubscribeInFlight=null,new n(`Unable to unsubscribe from ${this.options.channel}`);this.unsubscribeInFlight=null}isActive(){return this.handlers.size>0&&this.isSubscribed}};export{o as PubSub};
@@ -1,212 +1 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_chunk = require("../../chunk-CKQMccvm.cjs");
3
- const require_lib_errors_index = require("../errors/index.cjs");
4
- let node_assert = require("node:assert");
5
- node_assert = require_chunk.__toESM(node_assert);
6
- //#region src/lib/queue/errors.ts
7
- var SerializationError = class extends Error {
8
- constructor(message) {
9
- super(message);
10
- this.name = "SerializationError";
11
- }
12
- };
13
- var EnqueueError = class extends Error {
14
- constructor(message) {
15
- super(message);
16
- this.name = "EnqueueError";
17
- }
18
- };
19
- //#endregion
20
- //#region src/lib/queue/index.ts
21
- const toMinimalJob = (jobState) => ({
22
- id: jobState.id,
23
- data: jobState.data,
24
- attempts: jobState.attempts,
25
- maxRetries: jobState.maxRetries,
26
- createdAt: jobState.createdAt
27
- });
28
- const DEFAULT_RETRIES = 3;
29
- const DEFAULT_TIMEOUT = 3e4;
30
- const DEFAULT_CONCURRENCY = 1;
31
- const DEFAULT_POLL_INTERVAL = 100;
32
- const DEFAULT_RETRY_MAX_DELAY = 6e4;
33
- const DEFAULT_RETRY_BASE_DELAY = 1e3;
34
- const DEFAULT_RETRY_MULTIPLIER = 2;
35
- const SHUTDOWN_POLL_INTERVAL = 10;
36
- var Queue = class {
37
- options;
38
- running = true;
39
- activeWorkers = 0;
40
- retries;
41
- timeout;
42
- concurrency;
43
- pollInterval;
44
- retryBaseDelay;
45
- retryMultiplier;
46
- retryMaxDelay;
47
- constructor(options) {
48
- this.options = options;
49
- this.retries = options.retries ?? DEFAULT_RETRIES;
50
- this.timeout = options.timeout ?? DEFAULT_TIMEOUT;
51
- this.concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
52
- this.pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;
53
- this.retryBaseDelay = options.retryBackoff?.baseDelay ?? DEFAULT_RETRY_BASE_DELAY;
54
- this.retryMultiplier = options.retryBackoff?.multiplier ?? DEFAULT_RETRY_MULTIPLIER;
55
- this.retryMaxDelay = options.retryBackoff?.maxDelay ?? DEFAULT_RETRY_MAX_DELAY;
56
- node_assert.default.ok(Number.isFinite(this.retryBaseDelay) && this.retryBaseDelay > 0, "Invalid retryBackoff.baseDelay: must be a positive finite number");
57
- node_assert.default.ok(Number.isFinite(this.retryMultiplier) && this.retryMultiplier > 0, "Invalid retryBackoff.multiplier: must be a positive finite number");
58
- node_assert.default.ok(Number.isFinite(this.retryMaxDelay) && this.retryMaxDelay > 0, "Invalid retryBackoff.maxDelay: must be a positive finite number");
59
- this.startWorkers();
60
- }
61
- computeBackoffDelay(attempt) {
62
- return Math.min(this.retryBaseDelay * this.retryMultiplier ** (attempt - 1), this.retryMaxDelay);
63
- }
64
- async enqueue(data) {
65
- const job = {
66
- id: crypto.randomUUID(),
67
- data,
68
- attempts: 0,
69
- maxRetries: this.retries,
70
- createdAt: Date.now()
71
- };
72
- const [serializeError, serialized] = this.serializeJob(job);
73
- if (serializeError || !serialized) throw new SerializationError("Unable to serialize job data");
74
- const [enqueueError] = await this.enqueueJobData(serialized);
75
- if (enqueueError) throw new EnqueueError("Unable to enqueue job");
76
- return job.id;
77
- }
78
- async stop() {
79
- this.running = false;
80
- while (this.activeWorkers > 0) await new Promise((resolve) => setTimeout(resolve, SHUTDOWN_POLL_INTERVAL));
81
- }
82
- waitForPollInterval() {
83
- return new Promise((resolve) => setTimeout(resolve, this.pollInterval));
84
- }
85
- serializeJob(job) {
86
- return require_lib_errors_index.mightThrowSync(() => JSON.stringify(job));
87
- }
88
- async enqueueJobData(serialized) {
89
- const queueKey = `queue:${this.options.name}:jobs`;
90
- return require_lib_errors_index.mightThrow(this.options.redis.lpush(queueKey, serialized));
91
- }
92
- async moveToDeadLetterQueue(jobData, parseError) {
93
- const deadLetterKey = `queue:${this.options.name}:dead-letter`;
94
- const deadLetterEntry = JSON.stringify({
95
- jobData,
96
- parseError: this.formatErrorMessage(parseError),
97
- timestamp: Date.now()
98
- });
99
- return require_lib_errors_index.mightThrow(this.options.redis.lpush(deadLetterKey, deadLetterEntry));
100
- }
101
- formatErrorMessage(error) {
102
- if (!error) return "Unknown error";
103
- return error.message;
104
- }
105
- startWorkers() {
106
- for (let i = 0; i < this.concurrency; i++) this.processJobs();
107
- }
108
- async processJobs() {
109
- while (this.running) {
110
- const queueKey = `queue:${this.options.name}:jobs`;
111
- const [popError, jobData] = await require_lib_errors_index.mightThrow(this.options.redis.rpop(queueKey));
112
- if (popError) {
113
- await this.waitForPollInterval();
114
- continue;
115
- }
116
- if (!jobData) {
117
- await this.waitForPollInterval();
118
- continue;
119
- }
120
- const [parseError, job] = require_lib_errors_index.mightThrowSync(() => JSON.parse(jobData));
121
- if (parseError || !job) {
122
- await this.callOnErrorForParseFailure(jobData, parseError);
123
- await this.moveToDeadLetterQueue(jobData, parseError);
124
- await this.waitForPollInterval();
125
- continue;
126
- }
127
- if (!this.running) {
128
- const [stringifyError, serialized] = this.serializeJob(job);
129
- if (!stringifyError && serialized) await require_lib_errors_index.mightThrow(this.options.redis.lpush(queueKey, serialized));
130
- break;
131
- }
132
- this.activeWorkers++;
133
- await require_lib_errors_index.mightThrow(this.handleJob(job));
134
- this.activeWorkers--;
135
- }
136
- }
137
- async handleJob(job) {
138
- const controller = new AbortController();
139
- const handlerPromise = Promise.resolve().then(() => this.options.handler(job.data, controller.signal));
140
- let timerId;
141
- const timeoutPromise = new Promise((_, reject) => {
142
- timerId = setTimeout(() => {
143
- reject(/* @__PURE__ */ new Error(`Job timeout after ${this.timeout}ms`));
144
- }, this.timeout);
145
- });
146
- const [handlerError] = await require_lib_errors_index.mightThrow(Promise.race([handlerPromise.then(() => void 0), timeoutPromise]));
147
- if (timerId) clearTimeout(timerId);
148
- if (handlerError && !controller.signal.aborted) controller.abort();
149
- if (!handlerError) {
150
- if (this.options.onSuccess) await require_lib_errors_index.mightThrow(Promise.resolve(this.options.onSuccess(toMinimalJob(job))));
151
- return;
152
- }
153
- job.attempts++;
154
- const errorMsg = this.formatErrorMessage(handlerError);
155
- job.error = errorMsg;
156
- if (!job.errorHistory) job.errorHistory = [];
157
- job.errorHistory.push({
158
- attempt: job.attempts,
159
- error: errorMsg,
160
- timestamp: Date.now()
161
- });
162
- if (job.attempts <= job.maxRetries) {
163
- if (this.options.onRetry) {
164
- const delay = this.computeBackoffDelay(job.attempts);
165
- await require_lib_errors_index.mightThrow(Promise.resolve(this.options.onRetry({
166
- job: toMinimalJob(job),
167
- error: errorMsg,
168
- nextRetryDelayMs: delay,
169
- retriesRemaining: job.maxRetries - job.attempts,
170
- backoffMultiplier: this.retryMultiplier
171
- })));
172
- }
173
- await this.retryJob(job);
174
- } else await this.callOnError(job);
175
- }
176
- async callOnError(job) {
177
- if (!this.options.onError) return;
178
- await require_lib_errors_index.mightThrow(Promise.resolve(this.options.onError({
179
- job: toMinimalJob(job),
180
- lastError: job.error ?? "",
181
- totalDurationMs: Date.now() - job.createdAt,
182
- totalAttempts: job.attempts,
183
- errorHistory: job.errorHistory ?? []
184
- })));
185
- }
186
- async callOnErrorForParseFailure(jobData, parseError) {
187
- if (!this.options.onParseError) return;
188
- await require_lib_errors_index.mightThrow(Promise.resolve(this.options.onParseError({
189
- rawJobData: jobData,
190
- parseError: this.formatErrorMessage(parseError),
191
- timestamp: Date.now()
192
- })));
193
- }
194
- async retryJob(job) {
195
- const delay = this.computeBackoffDelay(job.attempts);
196
- await new Promise((resolve) => setTimeout(resolve, delay));
197
- const [stringifyError, serialized] = this.serializeJob(job);
198
- if (stringifyError || !serialized) {
199
- job.error = `Failed to serialize job for retry: ${this.formatErrorMessage(stringifyError)}`;
200
- await this.callOnError(job);
201
- return;
202
- }
203
- const queueKey = `queue:${this.options.name}:jobs`;
204
- const [pushError] = await require_lib_errors_index.mightThrow(this.options.redis.lpush(queueKey, serialized));
205
- if (pushError) {
206
- job.error = `Failed to re-enqueue job for retry: ${this.formatErrorMessage(pushError)}`;
207
- await this.callOnError(job);
208
- }
209
- }
210
- };
211
- //#endregion
212
- exports.Queue = Queue;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../../rolldown-runtime-CMqjfN_6.cjs"),t=require("../errors/index.cjs");let n=require("node:assert");n=e.t(n,1);var r=class extends Error{constructor(e){super(e),this.name=`SerializationError`}},i=class extends Error{constructor(e){super(e),this.name=`EnqueueError`}};const a=e=>({id:e.id,data:e.data,attempts:e.attempts,maxRetries:e.maxRetries,createdAt:e.createdAt});var o=class{options;running=!0;activeWorkers=0;retries;timeout;concurrency;pollInterval;retryBaseDelay;retryMultiplier;retryMaxDelay;constructor(e){this.options=e,this.retries=e.retries??3,this.timeout=e.timeout??3e4,this.concurrency=e.concurrency??1,this.pollInterval=e.pollInterval??100,this.retryBaseDelay=e.retryBackoff?.baseDelay??1e3,this.retryMultiplier=e.retryBackoff?.multiplier??2,this.retryMaxDelay=e.retryBackoff?.maxDelay??6e4,n.default.ok(Number.isFinite(this.retryBaseDelay)&&this.retryBaseDelay>0,`Invalid retryBackoff.baseDelay: must be a positive finite number`),n.default.ok(Number.isFinite(this.retryMultiplier)&&this.retryMultiplier>0,`Invalid retryBackoff.multiplier: must be a positive finite number`),n.default.ok(Number.isFinite(this.retryMaxDelay)&&this.retryMaxDelay>0,`Invalid retryBackoff.maxDelay: must be a positive finite number`),this.startWorkers()}computeBackoffDelay(e){return Math.min(this.retryBaseDelay*this.retryMultiplier**(e-1),this.retryMaxDelay)}async enqueue(e){let t={id:crypto.randomUUID(),data:e,attempts:0,maxRetries:this.retries,createdAt:Date.now()},[n,a]=this.serializeJob(t);if(n||!a)throw new r(`Unable to serialize job data`);let[o]=await this.enqueueJobData(a);if(o)throw new i(`Unable to enqueue job`);return t.id}async stop(){for(this.running=!1;this.activeWorkers>0;)await new Promise(e=>setTimeout(e,10))}waitForPollInterval(){return new Promise(e=>setTimeout(e,this.pollInterval))}serializeJob(e){return t.mightThrowSync(()=>JSON.stringify(e))}async enqueueJobData(e){let n=`queue:${this.options.name}:jobs`;return t.mightThrow(this.options.redis.lpush(n,e))}async moveToDeadLetterQueue(e,n){let r=`queue:${this.options.name}:dead-letter`,i=JSON.stringify({jobData:e,parseError:this.formatErrorMessage(n),timestamp:Date.now()});return t.mightThrow(this.options.redis.lpush(r,i))}formatErrorMessage(e){return e?e.message:`Unknown error`}startWorkers(){for(let e=0;e<this.concurrency;e++)this.processJobs()}async processJobs(){for(;this.running;){let e=`queue:${this.options.name}:jobs`,[n,r]=await t.mightThrow(this.options.redis.rpop(e));if(n){await this.waitForPollInterval();continue}if(!r){await this.waitForPollInterval();continue}let[i,a]=t.mightThrowSync(()=>JSON.parse(r));if(i||!a){await this.callOnErrorForParseFailure(r,i),await this.moveToDeadLetterQueue(r,i),await this.waitForPollInterval();continue}if(!this.running){let[n,r]=this.serializeJob(a);!n&&r&&await t.mightThrow(this.options.redis.lpush(e,r));break}this.activeWorkers++,await t.mightThrow(this.handleJob(a)),this.activeWorkers--}}async handleJob(e){let n=new AbortController,r=Promise.resolve().then(()=>this.options.handler(e.data,n.signal)),i,o=new Promise((e,t)=>{i=setTimeout(()=>{t(Error(`Job timeout after ${this.timeout}ms`))},this.timeout)}),[s]=await t.mightThrow(Promise.race([r.then(()=>void 0),o]));if(i&&clearTimeout(i),s&&!n.signal.aborted&&n.abort(),!s){this.options.onSuccess&&await t.mightThrow(Promise.resolve(this.options.onSuccess(a(e))));return}e.attempts++;let c=this.formatErrorMessage(s);if(e.error=c,e.errorHistory||=[],e.errorHistory.push({attempt:e.attempts,error:c,timestamp:Date.now()}),e.attempts<=e.maxRetries){if(this.options.onRetry){let n=this.computeBackoffDelay(e.attempts);await t.mightThrow(Promise.resolve(this.options.onRetry({job:a(e),error:c,nextRetryDelayMs:n,retriesRemaining:e.maxRetries-e.attempts,backoffMultiplier:this.retryMultiplier})))}await this.retryJob(e)}else await this.callOnError(e)}async callOnError(e){this.options.onError&&await t.mightThrow(Promise.resolve(this.options.onError({job:a(e),lastError:e.error??``,totalDurationMs:Date.now()-e.createdAt,totalAttempts:e.attempts,errorHistory:e.errorHistory??[]})))}async callOnErrorForParseFailure(e,n){this.options.onParseError&&await t.mightThrow(Promise.resolve(this.options.onParseError({rawJobData:e,parseError:this.formatErrorMessage(n),timestamp:Date.now()})))}async retryJob(e){let n=this.computeBackoffDelay(e.attempts);await new Promise(e=>setTimeout(e,n));let[r,i]=this.serializeJob(e);if(r||!i){e.error=`Failed to serialize job for retry: ${this.formatErrorMessage(r)}`,await this.callOnError(e);return}let a=`queue:${this.options.name}:jobs`,[o]=await t.mightThrow(this.options.redis.lpush(a,i));o&&(e.error=`Failed to re-enqueue job for retry: ${this.formatErrorMessage(o)}`,await this.callOnError(e))}};exports.Queue=o;
@@ -1,81 +1 @@
1
- //#region src/lib/queue/types.d.ts
2
- type Job<T> = {
3
- id: string;
4
- data: T;
5
- attempts: number;
6
- maxRetries: number;
7
- createdAt: number;
8
- };
9
- type RetryContext<T> = {
10
- job: Job<T>;
11
- error: string;
12
- nextRetryDelayMs: number;
13
- retriesRemaining: number;
14
- backoffMultiplier: number;
15
- };
16
- type ErrorContext<T> = {
17
- job: Job<T>;
18
- lastError: string;
19
- totalDurationMs: number;
20
- totalAttempts: number;
21
- errorHistory: Array<{
22
- attempt: number;
23
- error: string;
24
- timestamp: number;
25
- }>;
26
- };
27
- type ParseErrorContext = {
28
- rawJobData: string;
29
- parseError: string;
30
- timestamp: number;
31
- };
32
- type QueueRetryBackoff = {
33
- baseDelay?: number;
34
- multiplier?: number;
35
- maxDelay?: number;
36
- };
37
- type QueueOptions<T> = {
38
- name: string;
39
- redis: Bun.RedisClient;
40
- handler: (data: T, signal?: AbortSignal) => void | Promise<void>;
41
- onSuccess?: (job: Job<T>) => void | Promise<void>;
42
- onRetry?: (context: RetryContext<T>) => void | Promise<void>;
43
- onError?: (context: ErrorContext<T>) => void | Promise<void>;
44
- onParseError?: (context: ParseErrorContext) => void | Promise<void>;
45
- retries?: number;
46
- retryBackoff?: QueueRetryBackoff;
47
- timeout?: number;
48
- concurrency?: number;
49
- pollInterval?: number;
50
- };
51
- //#endregion
52
- //#region src/lib/queue/index.d.ts
53
- declare class Queue<T> {
54
- private options;
55
- private running;
56
- private activeWorkers;
57
- private retries;
58
- private timeout;
59
- private concurrency;
60
- private pollInterval;
61
- private retryBaseDelay;
62
- private retryMultiplier;
63
- private retryMaxDelay;
64
- constructor(options: QueueOptions<T>);
65
- private computeBackoffDelay;
66
- enqueue(data: T): Promise<string>;
67
- stop(): Promise<void>;
68
- private waitForPollInterval;
69
- private serializeJob;
70
- private enqueueJobData;
71
- private moveToDeadLetterQueue;
72
- private formatErrorMessage;
73
- private startWorkers;
74
- private processJobs;
75
- private handleJob;
76
- private callOnError;
77
- private callOnErrorForParseFailure;
78
- private retryJob;
79
- }
80
- //#endregion
81
- export { Queue };
1
+ export type * from './index.d.mts'