@cloudnux/local-cloud-provider 0.18.0 → 0.20.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.
@@ -1,1013 +1,8 @@
1
- // src/logging/pretty-writer.ts
2
- import chalk from "chalk";
3
- import { EOL as EOL2 } from "os";
4
-
5
- // ../../../node_modules/lodash-es/_freeGlobal.js
6
- var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
7
- var freeGlobal_default = freeGlobal;
8
-
9
- // ../../../node_modules/lodash-es/_root.js
10
- var freeSelf = typeof self == "object" && self && self.Object === Object && self;
11
- var root = freeGlobal_default || freeSelf || Function("return this")();
12
- var root_default = root;
13
-
14
- // ../../../node_modules/lodash-es/_Symbol.js
15
- var Symbol = root_default.Symbol;
16
- var Symbol_default = Symbol;
17
-
18
- // ../../../node_modules/lodash-es/_getRawTag.js
19
- var objectProto = Object.prototype;
20
- var hasOwnProperty = objectProto.hasOwnProperty;
21
- var nativeObjectToString = objectProto.toString;
22
- var symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0;
23
- function getRawTag(value) {
24
- var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
25
- try {
26
- value[symToStringTag] = void 0;
27
- var unmasked = true;
28
- } catch (e) {
29
- }
30
- var result = nativeObjectToString.call(value);
31
- if (unmasked) {
32
- if (isOwn) {
33
- value[symToStringTag] = tag;
34
- } else {
35
- delete value[symToStringTag];
36
- }
37
- }
38
- return result;
39
- }
40
- var getRawTag_default = getRawTag;
41
-
42
- // ../../../node_modules/lodash-es/_objectToString.js
43
- var objectProto2 = Object.prototype;
44
- var nativeObjectToString2 = objectProto2.toString;
45
- function objectToString(value) {
46
- return nativeObjectToString2.call(value);
47
- }
48
- var objectToString_default = objectToString;
49
-
50
- // ../../../node_modules/lodash-es/_baseGetTag.js
51
- var nullTag = "[object Null]";
52
- var undefinedTag = "[object Undefined]";
53
- var symToStringTag2 = Symbol_default ? Symbol_default.toStringTag : void 0;
54
- function baseGetTag(value) {
55
- if (value == null) {
56
- return value === void 0 ? undefinedTag : nullTag;
57
- }
58
- return symToStringTag2 && symToStringTag2 in Object(value) ? getRawTag_default(value) : objectToString_default(value);
59
- }
60
- var baseGetTag_default = baseGetTag;
61
-
62
- // ../../../node_modules/lodash-es/isObjectLike.js
63
- function isObjectLike(value) {
64
- return value != null && typeof value == "object";
65
- }
66
- var isObjectLike_default = isObjectLike;
67
-
68
- // ../../../node_modules/lodash-es/isSymbol.js
69
- var symbolTag = "[object Symbol]";
70
- function isSymbol(value) {
71
- return typeof value == "symbol" || isObjectLike_default(value) && baseGetTag_default(value) == symbolTag;
72
- }
73
- var isSymbol_default = isSymbol;
74
-
75
- // ../../../node_modules/lodash-es/_arrayMap.js
76
- function arrayMap(array2, iteratee) {
77
- var index = -1, length = array2 == null ? 0 : array2.length, result = Array(length);
78
- while (++index < length) {
79
- result[index] = iteratee(array2[index], index, array2);
80
- }
81
- return result;
82
- }
83
- var arrayMap_default = arrayMap;
84
-
85
- // ../../../node_modules/lodash-es/isArray.js
86
- var isArray = Array.isArray;
87
- var isArray_default = isArray;
88
-
89
- // ../../../node_modules/lodash-es/_baseToString.js
90
- var INFINITY = 1 / 0;
91
- var symbolProto = Symbol_default ? Symbol_default.prototype : void 0;
92
- var symbolToString = symbolProto ? symbolProto.toString : void 0;
93
- function baseToString(value) {
94
- if (typeof value == "string") {
95
- return value;
96
- }
97
- if (isArray_default(value)) {
98
- return arrayMap_default(value, baseToString) + "";
99
- }
100
- if (isSymbol_default(value)) {
101
- return symbolToString ? symbolToString.call(value) : "";
102
- }
103
- var result = value + "";
104
- return result == "0" && 1 / value == -INFINITY ? "-0" : result;
105
- }
106
- var baseToString_default = baseToString;
107
-
108
- // ../../../node_modules/lodash-es/_trimmedEndIndex.js
109
- var reWhitespace = /\s/;
110
- function trimmedEndIndex(string) {
111
- var index = string.length;
112
- while (index-- && reWhitespace.test(string.charAt(index))) {
113
- }
114
- return index;
115
- }
116
- var trimmedEndIndex_default = trimmedEndIndex;
117
-
118
- // ../../../node_modules/lodash-es/_baseTrim.js
119
- var reTrimStart = /^\s+/;
120
- function baseTrim(string) {
121
- return string ? string.slice(0, trimmedEndIndex_default(string) + 1).replace(reTrimStart, "") : string;
122
- }
123
- var baseTrim_default = baseTrim;
124
-
125
- // ../../../node_modules/lodash-es/isObject.js
126
- function isObject(value) {
127
- var type = typeof value;
128
- return value != null && (type == "object" || type == "function");
129
- }
130
- var isObject_default = isObject;
131
-
132
- // ../../../node_modules/lodash-es/isFunction.js
133
- var asyncTag = "[object AsyncFunction]";
134
- var funcTag = "[object Function]";
135
- var genTag = "[object GeneratorFunction]";
136
- var proxyTag = "[object Proxy]";
137
- function isFunction(value) {
138
- if (!isObject_default(value)) {
139
- return false;
140
- }
141
- var tag = baseGetTag_default(value);
142
- return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
143
- }
144
- var isFunction_default = isFunction;
145
-
146
- // ../../../node_modules/lodash-es/_coreJsData.js
147
- var coreJsData = root_default["__core-js_shared__"];
148
- var coreJsData_default = coreJsData;
149
-
150
- // ../../../node_modules/lodash-es/_isMasked.js
151
- var maskSrcKey = function() {
152
- var uid = /[^.]+$/.exec(coreJsData_default && coreJsData_default.keys && coreJsData_default.keys.IE_PROTO || "");
153
- return uid ? "Symbol(src)_1." + uid : "";
154
- }();
155
- function isMasked(func) {
156
- return !!maskSrcKey && maskSrcKey in func;
157
- }
158
- var isMasked_default = isMasked;
159
-
160
- // ../../../node_modules/lodash-es/_toSource.js
161
- var funcProto = Function.prototype;
162
- var funcToString = funcProto.toString;
163
- function toSource(func) {
164
- if (func != null) {
165
- try {
166
- return funcToString.call(func);
167
- } catch (e) {
168
- }
169
- try {
170
- return func + "";
171
- } catch (e) {
172
- }
173
- }
174
- return "";
175
- }
176
- var toSource_default = toSource;
177
-
178
- // ../../../node_modules/lodash-es/_baseIsNative.js
179
- var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
180
- var reIsHostCtor = /^\[object .+?Constructor\]$/;
181
- var funcProto2 = Function.prototype;
182
- var objectProto3 = Object.prototype;
183
- var funcToString2 = funcProto2.toString;
184
- var hasOwnProperty2 = objectProto3.hasOwnProperty;
185
- var reIsNative = RegExp(
186
- "^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
187
- );
188
- function baseIsNative(value) {
189
- if (!isObject_default(value) || isMasked_default(value)) {
190
- return false;
191
- }
192
- var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor;
193
- return pattern.test(toSource_default(value));
194
- }
195
- var baseIsNative_default = baseIsNative;
196
-
197
- // ../../../node_modules/lodash-es/_getValue.js
198
- function getValue(object, key) {
199
- return object == null ? void 0 : object[key];
200
- }
201
- var getValue_default = getValue;
202
-
203
- // ../../../node_modules/lodash-es/_getNative.js
204
- function getNative(object, key) {
205
- var value = getValue_default(object, key);
206
- return baseIsNative_default(value) ? value : void 0;
207
- }
208
- var getNative_default = getNative;
209
-
210
- // ../../../node_modules/lodash-es/_baseFindIndex.js
211
- function baseFindIndex(array2, predicate, fromIndex, fromRight) {
212
- var length = array2.length, index = fromIndex + (fromRight ? 1 : -1);
213
- while (fromRight ? index-- : ++index < length) {
214
- if (predicate(array2[index], index, array2)) {
215
- return index;
216
- }
217
- }
218
- return -1;
219
- }
220
- var baseFindIndex_default = baseFindIndex;
221
-
222
- // ../../../node_modules/lodash-es/_baseIsNaN.js
223
- function baseIsNaN(value) {
224
- return value !== value;
225
- }
226
- var baseIsNaN_default = baseIsNaN;
227
-
228
- // ../../../node_modules/lodash-es/_strictIndexOf.js
229
- function strictIndexOf(array2, value, fromIndex) {
230
- var index = fromIndex - 1, length = array2.length;
231
- while (++index < length) {
232
- if (array2[index] === value) {
233
- return index;
234
- }
235
- }
236
- return -1;
237
- }
238
- var strictIndexOf_default = strictIndexOf;
239
-
240
- // ../../../node_modules/lodash-es/_baseIndexOf.js
241
- function baseIndexOf(array2, value, fromIndex) {
242
- return value === value ? strictIndexOf_default(array2, value, fromIndex) : baseFindIndex_default(array2, baseIsNaN_default, fromIndex);
243
- }
244
- var baseIndexOf_default = baseIndexOf;
245
-
246
- // ../../../node_modules/lodash-es/_isIndex.js
247
- var MAX_SAFE_INTEGER = 9007199254740991;
248
- var reIsUint = /^(?:0|[1-9]\d*)$/;
249
- function isIndex(value, length) {
250
- var type = typeof value;
251
- length = length == null ? MAX_SAFE_INTEGER : length;
252
- return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
253
- }
254
- var isIndex_default = isIndex;
255
-
256
- // ../../../node_modules/lodash-es/eq.js
257
- function eq(value, other) {
258
- return value === other || value !== value && other !== other;
259
- }
260
- var eq_default = eq;
261
-
262
- // ../../../node_modules/lodash-es/isLength.js
263
- var MAX_SAFE_INTEGER2 = 9007199254740991;
264
- function isLength(value) {
265
- return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
266
- }
267
- var isLength_default = isLength;
268
-
269
- // ../../../node_modules/lodash-es/_baseIsArguments.js
270
- var argsTag = "[object Arguments]";
271
- function baseIsArguments(value) {
272
- return isObjectLike_default(value) && baseGetTag_default(value) == argsTag;
273
- }
274
- var baseIsArguments_default = baseIsArguments;
275
-
276
- // ../../../node_modules/lodash-es/isArguments.js
277
- var objectProto4 = Object.prototype;
278
- var hasOwnProperty3 = objectProto4.hasOwnProperty;
279
- var propertyIsEnumerable = objectProto4.propertyIsEnumerable;
280
- var isArguments = baseIsArguments_default(/* @__PURE__ */ function() {
281
- return arguments;
282
- }()) ? baseIsArguments_default : function(value) {
283
- return isObjectLike_default(value) && hasOwnProperty3.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
284
- };
285
- var isArguments_default = isArguments;
286
-
287
- // ../../../node_modules/lodash-es/_isKey.js
288
- var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
289
- var reIsPlainProp = /^\w*$/;
290
- function isKey(value, object) {
291
- if (isArray_default(value)) {
292
- return false;
293
- }
294
- var type = typeof value;
295
- if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol_default(value)) {
296
- return true;
297
- }
298
- return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
299
- }
300
- var isKey_default = isKey;
301
-
302
- // ../../../node_modules/lodash-es/_nativeCreate.js
303
- var nativeCreate = getNative_default(Object, "create");
304
- var nativeCreate_default = nativeCreate;
305
-
306
- // ../../../node_modules/lodash-es/_hashClear.js
307
- function hashClear() {
308
- this.__data__ = nativeCreate_default ? nativeCreate_default(null) : {};
309
- this.size = 0;
310
- }
311
- var hashClear_default = hashClear;
312
-
313
- // ../../../node_modules/lodash-es/_hashDelete.js
314
- function hashDelete(key) {
315
- var result = this.has(key) && delete this.__data__[key];
316
- this.size -= result ? 1 : 0;
317
- return result;
318
- }
319
- var hashDelete_default = hashDelete;
320
-
321
- // ../../../node_modules/lodash-es/_hashGet.js
322
- var HASH_UNDEFINED = "__lodash_hash_undefined__";
323
- var objectProto5 = Object.prototype;
324
- var hasOwnProperty4 = objectProto5.hasOwnProperty;
325
- function hashGet(key) {
326
- var data = this.__data__;
327
- if (nativeCreate_default) {
328
- var result = data[key];
329
- return result === HASH_UNDEFINED ? void 0 : result;
330
- }
331
- return hasOwnProperty4.call(data, key) ? data[key] : void 0;
332
- }
333
- var hashGet_default = hashGet;
334
-
335
- // ../../../node_modules/lodash-es/_hashHas.js
336
- var objectProto6 = Object.prototype;
337
- var hasOwnProperty5 = objectProto6.hasOwnProperty;
338
- function hashHas(key) {
339
- var data = this.__data__;
340
- return nativeCreate_default ? data[key] !== void 0 : hasOwnProperty5.call(data, key);
341
- }
342
- var hashHas_default = hashHas;
343
-
344
- // ../../../node_modules/lodash-es/_hashSet.js
345
- var HASH_UNDEFINED2 = "__lodash_hash_undefined__";
346
- function hashSet(key, value) {
347
- var data = this.__data__;
348
- this.size += this.has(key) ? 0 : 1;
349
- data[key] = nativeCreate_default && value === void 0 ? HASH_UNDEFINED2 : value;
350
- return this;
351
- }
352
- var hashSet_default = hashSet;
353
-
354
- // ../../../node_modules/lodash-es/_Hash.js
355
- function Hash(entries) {
356
- var index = -1, length = entries == null ? 0 : entries.length;
357
- this.clear();
358
- while (++index < length) {
359
- var entry = entries[index];
360
- this.set(entry[0], entry[1]);
361
- }
362
- }
363
- Hash.prototype.clear = hashClear_default;
364
- Hash.prototype["delete"] = hashDelete_default;
365
- Hash.prototype.get = hashGet_default;
366
- Hash.prototype.has = hashHas_default;
367
- Hash.prototype.set = hashSet_default;
368
- var Hash_default = Hash;
369
-
370
- // ../../../node_modules/lodash-es/_listCacheClear.js
371
- function listCacheClear() {
372
- this.__data__ = [];
373
- this.size = 0;
374
- }
375
- var listCacheClear_default = listCacheClear;
376
-
377
- // ../../../node_modules/lodash-es/_assocIndexOf.js
378
- function assocIndexOf(array2, key) {
379
- var length = array2.length;
380
- while (length--) {
381
- if (eq_default(array2[length][0], key)) {
382
- return length;
383
- }
384
- }
385
- return -1;
386
- }
387
- var assocIndexOf_default = assocIndexOf;
388
-
389
- // ../../../node_modules/lodash-es/_listCacheDelete.js
390
- var arrayProto = Array.prototype;
391
- var splice = arrayProto.splice;
392
- function listCacheDelete(key) {
393
- var data = this.__data__, index = assocIndexOf_default(data, key);
394
- if (index < 0) {
395
- return false;
396
- }
397
- var lastIndex = data.length - 1;
398
- if (index == lastIndex) {
399
- data.pop();
400
- } else {
401
- splice.call(data, index, 1);
402
- }
403
- --this.size;
404
- return true;
405
- }
406
- var listCacheDelete_default = listCacheDelete;
407
-
408
- // ../../../node_modules/lodash-es/_listCacheGet.js
409
- function listCacheGet(key) {
410
- var data = this.__data__, index = assocIndexOf_default(data, key);
411
- return index < 0 ? void 0 : data[index][1];
412
- }
413
- var listCacheGet_default = listCacheGet;
414
-
415
- // ../../../node_modules/lodash-es/_listCacheHas.js
416
- function listCacheHas(key) {
417
- return assocIndexOf_default(this.__data__, key) > -1;
418
- }
419
- var listCacheHas_default = listCacheHas;
420
-
421
- // ../../../node_modules/lodash-es/_listCacheSet.js
422
- function listCacheSet(key, value) {
423
- var data = this.__data__, index = assocIndexOf_default(data, key);
424
- if (index < 0) {
425
- ++this.size;
426
- data.push([key, value]);
427
- } else {
428
- data[index][1] = value;
429
- }
430
- return this;
431
- }
432
- var listCacheSet_default = listCacheSet;
433
-
434
- // ../../../node_modules/lodash-es/_ListCache.js
435
- function ListCache(entries) {
436
- var index = -1, length = entries == null ? 0 : entries.length;
437
- this.clear();
438
- while (++index < length) {
439
- var entry = entries[index];
440
- this.set(entry[0], entry[1]);
441
- }
442
- }
443
- ListCache.prototype.clear = listCacheClear_default;
444
- ListCache.prototype["delete"] = listCacheDelete_default;
445
- ListCache.prototype.get = listCacheGet_default;
446
- ListCache.prototype.has = listCacheHas_default;
447
- ListCache.prototype.set = listCacheSet_default;
448
- var ListCache_default = ListCache;
449
-
450
- // ../../../node_modules/lodash-es/_Map.js
451
- var Map = getNative_default(root_default, "Map");
452
- var Map_default = Map;
453
-
454
- // ../../../node_modules/lodash-es/_mapCacheClear.js
455
- function mapCacheClear() {
456
- this.size = 0;
457
- this.__data__ = {
458
- "hash": new Hash_default(),
459
- "map": new (Map_default || ListCache_default)(),
460
- "string": new Hash_default()
461
- };
462
- }
463
- var mapCacheClear_default = mapCacheClear;
464
-
465
- // ../../../node_modules/lodash-es/_isKeyable.js
466
- function isKeyable(value) {
467
- var type = typeof value;
468
- return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
469
- }
470
- var isKeyable_default = isKeyable;
471
-
472
- // ../../../node_modules/lodash-es/_getMapData.js
473
- function getMapData(map, key) {
474
- var data = map.__data__;
475
- return isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
476
- }
477
- var getMapData_default = getMapData;
478
-
479
- // ../../../node_modules/lodash-es/_mapCacheDelete.js
480
- function mapCacheDelete(key) {
481
- var result = getMapData_default(this, key)["delete"](key);
482
- this.size -= result ? 1 : 0;
483
- return result;
484
- }
485
- var mapCacheDelete_default = mapCacheDelete;
486
-
487
- // ../../../node_modules/lodash-es/_mapCacheGet.js
488
- function mapCacheGet(key) {
489
- return getMapData_default(this, key).get(key);
490
- }
491
- var mapCacheGet_default = mapCacheGet;
492
-
493
- // ../../../node_modules/lodash-es/_mapCacheHas.js
494
- function mapCacheHas(key) {
495
- return getMapData_default(this, key).has(key);
496
- }
497
- var mapCacheHas_default = mapCacheHas;
498
-
499
- // ../../../node_modules/lodash-es/_mapCacheSet.js
500
- function mapCacheSet(key, value) {
501
- var data = getMapData_default(this, key), size = data.size;
502
- data.set(key, value);
503
- this.size += data.size == size ? 0 : 1;
504
- return this;
505
- }
506
- var mapCacheSet_default = mapCacheSet;
507
-
508
- // ../../../node_modules/lodash-es/_MapCache.js
509
- function MapCache(entries) {
510
- var index = -1, length = entries == null ? 0 : entries.length;
511
- this.clear();
512
- while (++index < length) {
513
- var entry = entries[index];
514
- this.set(entry[0], entry[1]);
515
- }
516
- }
517
- MapCache.prototype.clear = mapCacheClear_default;
518
- MapCache.prototype["delete"] = mapCacheDelete_default;
519
- MapCache.prototype.get = mapCacheGet_default;
520
- MapCache.prototype.has = mapCacheHas_default;
521
- MapCache.prototype.set = mapCacheSet_default;
522
- var MapCache_default = MapCache;
523
-
524
- // ../../../node_modules/lodash-es/memoize.js
525
- var FUNC_ERROR_TEXT = "Expected a function";
526
- function memoize(func, resolver) {
527
- if (typeof func != "function" || resolver != null && typeof resolver != "function") {
528
- throw new TypeError(FUNC_ERROR_TEXT);
529
- }
530
- var memoized = function() {
531
- var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
532
- if (cache.has(key)) {
533
- return cache.get(key);
534
- }
535
- var result = func.apply(this, args);
536
- memoized.cache = cache.set(key, result) || cache;
537
- return result;
538
- };
539
- memoized.cache = new (memoize.Cache || MapCache_default)();
540
- return memoized;
541
- }
542
- memoize.Cache = MapCache_default;
543
- var memoize_default = memoize;
544
-
545
- // ../../../node_modules/lodash-es/_memoizeCapped.js
546
- var MAX_MEMOIZE_SIZE = 500;
547
- function memoizeCapped(func) {
548
- var result = memoize_default(func, function(key) {
549
- if (cache.size === MAX_MEMOIZE_SIZE) {
550
- cache.clear();
551
- }
552
- return key;
553
- });
554
- var cache = result.cache;
555
- return result;
556
- }
557
- var memoizeCapped_default = memoizeCapped;
558
-
559
- // ../../../node_modules/lodash-es/_stringToPath.js
560
- var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
561
- var reEscapeChar = /\\(\\)?/g;
562
- var stringToPath = memoizeCapped_default(function(string) {
563
- var result = [];
564
- if (string.charCodeAt(0) === 46) {
565
- result.push("");
566
- }
567
- string.replace(rePropName, function(match, number, quote, subString) {
568
- result.push(quote ? subString.replace(reEscapeChar, "$1") : number || match);
569
- });
570
- return result;
571
- });
572
- var stringToPath_default = stringToPath;
573
-
574
- // ../../../node_modules/lodash-es/toString.js
575
- function toString(value) {
576
- return value == null ? "" : baseToString_default(value);
577
- }
578
- var toString_default = toString;
579
-
580
- // ../../../node_modules/lodash-es/_castPath.js
581
- function castPath(value, object) {
582
- if (isArray_default(value)) {
583
- return value;
584
- }
585
- return isKey_default(value, object) ? [value] : stringToPath_default(toString_default(value));
586
- }
587
- var castPath_default = castPath;
588
-
589
- // ../../../node_modules/lodash-es/_toKey.js
590
- var INFINITY2 = 1 / 0;
591
- function toKey(value) {
592
- if (typeof value == "string" || isSymbol_default(value)) {
593
- return value;
594
- }
595
- var result = value + "";
596
- return result == "0" && 1 / value == -INFINITY2 ? "-0" : result;
597
- }
598
- var toKey_default = toKey;
599
-
600
- // ../../../node_modules/lodash-es/_baseSlice.js
601
- function baseSlice(array2, start, end) {
602
- var index = -1, length = array2.length;
603
- if (start < 0) {
604
- start = -start > length ? 0 : length + start;
605
- }
606
- end = end > length ? length : end;
607
- if (end < 0) {
608
- end += length;
609
- }
610
- length = start > end ? 0 : end - start >>> 0;
611
- start >>>= 0;
612
- var result = Array(length);
613
- while (++index < length) {
614
- result[index] = array2[index + start];
615
- }
616
- return result;
617
- }
618
- var baseSlice_default = baseSlice;
619
-
620
- // ../../../node_modules/lodash-es/_castSlice.js
621
- function castSlice(array2, start, end) {
622
- var length = array2.length;
623
- end = end === void 0 ? length : end;
624
- return !start && end >= length ? array2 : baseSlice_default(array2, start, end);
625
- }
626
- var castSlice_default = castSlice;
627
-
628
- // ../../../node_modules/lodash-es/_hasUnicode.js
629
- var rsAstralRange = "\\ud800-\\udfff";
630
- var rsComboMarksRange = "\\u0300-\\u036f";
631
- var reComboHalfMarksRange = "\\ufe20-\\ufe2f";
632
- var rsComboSymbolsRange = "\\u20d0-\\u20ff";
633
- var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;
634
- var rsVarRange = "\\ufe0e\\ufe0f";
635
- var rsZWJ = "\\u200d";
636
- var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]");
637
- function hasUnicode(string) {
638
- return reHasUnicode.test(string);
639
- }
640
- var hasUnicode_default = hasUnicode;
641
-
642
- // ../../../node_modules/lodash-es/_asciiToArray.js
643
- function asciiToArray(string) {
644
- return string.split("");
645
- }
646
- var asciiToArray_default = asciiToArray;
647
-
648
- // ../../../node_modules/lodash-es/_unicodeToArray.js
649
- var rsAstralRange2 = "\\ud800-\\udfff";
650
- var rsComboMarksRange2 = "\\u0300-\\u036f";
651
- var reComboHalfMarksRange2 = "\\ufe20-\\ufe2f";
652
- var rsComboSymbolsRange2 = "\\u20d0-\\u20ff";
653
- var rsComboRange2 = rsComboMarksRange2 + reComboHalfMarksRange2 + rsComboSymbolsRange2;
654
- var rsVarRange2 = "\\ufe0e\\ufe0f";
655
- var rsAstral = "[" + rsAstralRange2 + "]";
656
- var rsCombo = "[" + rsComboRange2 + "]";
657
- var rsFitz = "\\ud83c[\\udffb-\\udfff]";
658
- var rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")";
659
- var rsNonAstral = "[^" + rsAstralRange2 + "]";
660
- var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}";
661
- var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]";
662
- var rsZWJ2 = "\\u200d";
663
- var reOptMod = rsModifier + "?";
664
- var rsOptVar = "[" + rsVarRange2 + "]?";
665
- var rsOptJoin = "(?:" + rsZWJ2 + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*";
666
- var rsSeq = rsOptVar + reOptMod + rsOptJoin;
667
- var rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")";
668
- var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");
669
- function unicodeToArray(string) {
670
- return string.match(reUnicode) || [];
671
- }
672
- var unicodeToArray_default = unicodeToArray;
673
-
674
- // ../../../node_modules/lodash-es/_stringToArray.js
675
- function stringToArray(string) {
676
- return hasUnicode_default(string) ? unicodeToArray_default(string) : asciiToArray_default(string);
677
- }
678
- var stringToArray_default = stringToArray;
679
-
680
- // ../../../node_modules/lodash-es/_hasPath.js
681
- function hasPath(object, path2, hasFunc) {
682
- path2 = castPath_default(path2, object);
683
- var index = -1, length = path2.length, result = false;
684
- while (++index < length) {
685
- var key = toKey_default(path2[index]);
686
- if (!(result = object != null && hasFunc(object, key))) {
687
- break;
688
- }
689
- object = object[key];
690
- }
691
- if (result || ++index != length) {
692
- return result;
693
- }
694
- length = object == null ? 0 : object.length;
695
- return !!length && isLength_default(length) && isIndex_default(key, length) && (isArray_default(object) || isArguments_default(object));
696
- }
697
- var hasPath_default = hasPath;
698
-
699
- // ../../../node_modules/lodash-es/_baseHas.js
700
- var objectProto7 = Object.prototype;
701
- var hasOwnProperty6 = objectProto7.hasOwnProperty;
702
- function baseHas(object, key) {
703
- return object != null && hasOwnProperty6.call(object, key);
704
- }
705
- var baseHas_default = baseHas;
706
-
707
- // ../../../node_modules/lodash-es/has.js
708
- function has(object, path2) {
709
- return object != null && hasPath_default(object, path2, baseHas_default);
710
- }
711
- var has_default = has;
712
-
713
- // ../../../node_modules/lodash-es/_charsEndIndex.js
714
- function charsEndIndex(strSymbols, chrSymbols) {
715
- var index = strSymbols.length;
716
- while (index-- && baseIndexOf_default(chrSymbols, strSymbols[index], 0) > -1) {
717
- }
718
- return index;
719
- }
720
- var charsEndIndex_default = charsEndIndex;
721
-
722
- // ../../../node_modules/lodash-es/_charsStartIndex.js
723
- function charsStartIndex(strSymbols, chrSymbols) {
724
- var index = -1, length = strSymbols.length;
725
- while (++index < length && baseIndexOf_default(chrSymbols, strSymbols[index], 0) > -1) {
726
- }
727
- return index;
728
- }
729
- var charsStartIndex_default = charsStartIndex;
730
-
731
- // ../../../node_modules/lodash-es/trim.js
732
- function trim(string, chars, guard) {
733
- string = toString_default(string);
734
- if (string && (guard || chars === void 0)) {
735
- return baseTrim_default(string);
736
- }
737
- if (!string || !(chars = baseToString_default(chars))) {
738
- return string;
739
- }
740
- var strSymbols = stringToArray_default(string), chrSymbols = stringToArray_default(chars), start = charsStartIndex_default(strSymbols, chrSymbols), end = charsEndIndex_default(strSymbols, chrSymbols) + 1;
741
- return castSlice_default(strSymbols, start, end).join("");
742
- }
743
- var trim_default = trim;
744
-
745
- // ../../utils/src/config/env.ts
746
- function _env(key, defaultValue) {
747
- return has_default(process.env, key) ? process.env[key] ?? "" : defaultValue ?? "";
748
- }
749
- function int(key, defaultValue) {
750
- if (!has_default(process.env, key)) {
751
- return defaultValue ?? 0;
752
- }
753
- const value = process.env[key] ?? "0";
754
- return parseInt(value, 10);
755
- }
756
- function float(key, defaultValue) {
757
- if (!has_default(process.env, key)) {
758
- return defaultValue ?? 0;
759
- }
760
- const value = process.env[key] ?? "0";
761
- return parseFloat(value);
762
- }
763
- function bool(key, defaultValue) {
764
- if (!has_default(process.env, key)) {
765
- return defaultValue ?? false;
766
- }
767
- const value = process.env[key];
768
- return value === "true";
769
- }
770
- function json(key, defaultValue) {
771
- if (!has_default(process.env, key)) {
772
- return defaultValue ?? {};
773
- }
774
- const value = process.env[key] ?? "{}";
775
- try {
776
- return JSON.parse(value);
777
- } catch (error) {
778
- throw new Error(`Invalid json environment variable ${key}: ${error.message}`);
779
- }
780
- }
781
- function array(key, defaultValue) {
782
- if (!has_default(process.env, key)) {
783
- return defaultValue ?? [];
784
- }
785
- let value = process.env[key] ?? "";
786
- if (value.startsWith("[") && value.endsWith("]")) {
787
- value = value.substring(1, value.length - 1);
788
- }
789
- return value.split(",").map((v) => {
790
- return trim_default(trim_default(v, " "), '"');
791
- });
792
- }
793
- function date(key, defaultValue) {
794
- if (!has_default(process.env, key)) {
795
- return defaultValue ?? /* @__PURE__ */ new Date();
796
- }
797
- const value = process.env[key] ?? Date();
798
- return new Date(value);
799
- }
800
- var utils = {
801
- int,
802
- float,
803
- bool,
804
- json,
805
- array,
806
- date,
807
- /**
808
- * Gets a value from env that matches oneOf provided values
809
- * @param {string} key
810
- * @param {string[]} expectedValues
811
- * @param {string|undefined} defaultValue
812
- * @returns {string|undefined}
813
- */
814
- oneOf(key, expectedValues, defaultValue) {
815
- if (!expectedValues) {
816
- throw new Error(`env.oneOf requires expectedValues`);
817
- }
818
- if (defaultValue && !expectedValues.includes(defaultValue)) {
819
- throw new Error(`env.oneOf requires defaultValue to be included in expectedValues`);
820
- }
821
- const rawValue = env(key, defaultValue);
822
- return expectedValues.includes(rawValue) ? rawValue : defaultValue ?? "";
823
- }
824
- };
825
- var env = Object.assign(_env, utils);
826
-
827
- // ../../utils/src/logging/types.ts
828
- var logLevels = {
829
- fatal: -1,
830
- error: 0,
831
- warn: 1,
832
- info: 2,
833
- debug: 3,
834
- trace: 4
835
- };
836
-
837
- // ../../utils/src/logging/error-to-string.ts
838
- var safeJsonStringify = (value) => {
839
- const seen = /* @__PURE__ */ new WeakSet();
840
- return JSON.stringify(value, (key, currentValue) => {
841
- if (key === "constructor") return void 0;
842
- if (typeof currentValue === "object" && currentValue !== null) {
843
- if (seen.has(currentValue)) return "[Circular]";
844
- seen.add(currentValue);
845
- }
846
- return currentValue;
847
- });
848
- };
849
- var hasOwnConstructorProp = (value) => {
850
- if (typeof value !== "object" || value === null) return false;
851
- return Object.prototype.hasOwnProperty.call(value, "constructor");
852
- };
853
- var errorToString = (error) => {
854
- if (error === null) return "Null error";
855
- if (error === void 0) return "Undefined error";
856
- if (error instanceof Error) {
857
- return [
858
- `Name: ${error.name}`,
859
- `Message: ${error.message}`,
860
- `Stack: ${error.stack || "No stack trace available"}`,
861
- // Handle additional properties that might exist on custom errors
862
- ...Object.entries(error).filter(
863
- ([key, value]) => !["name", "message", "stack"].includes(key) && !hasOwnConstructorProp(value)
864
- ).map(([key, value]) => `${key}: ${safeJsonStringify(value)}`)
865
- ].join("\n");
866
- }
867
- if (typeof error === "string") return error;
868
- if (typeof error === "object") {
869
- try {
870
- return JSON.stringify(
871
- error,
872
- (key, value) => {
873
- if (key === "constructor") return void 0;
874
- return value;
875
- },
876
- 2
877
- );
878
- } catch {
879
- return `[Object that cannot be stringified: ${Object.prototype.toString.call(error)}]`;
880
- }
881
- }
882
- return String(error);
883
- };
884
-
885
- // ../../utils/src/logging/writer.ts
886
- import { EOL } from "os";
887
- var jsonWriter = (entry) => {
888
- process.stdout.write(JSON.stringify(entry) + EOL);
889
- };
890
- var _writer = jsonWriter;
891
- function setWriter(writer) {
892
- _writer = writer;
893
- }
894
- function getWriter() {
895
- return _writer;
896
- }
897
-
898
- // ../../utils/src/logging/index.ts
899
- var levelValues = {
900
- fatal: 70,
901
- error: 60,
902
- warn: 50,
903
- info: 40,
904
- debug: 30,
905
- trace: 20
906
- };
907
- var currentLogLevel = 2;
908
- var _module = "default";
909
- var _requestId = "";
910
- function writeLine(level, mergeObject, msg, bindings) {
911
- getWriter()({
912
- level: levelValues[level],
913
- levelName: level,
914
- time: Date.now(),
915
- module: bindings.module || _module,
916
- reqId: bindings.reqId || _requestId,
917
- msg: level === "error" || level === "fatal" ? errorToString(msg) : msg,
918
- ...mergeObject ? { meta: mergeObject } : {}
919
- });
920
- }
921
- function createLogger(bindings = {}) {
922
- const currentLogLevelName = env("LOG_LEVEL")?.toLowerCase() ?? "info";
923
- currentLogLevel = logLevels[currentLogLevelName] ?? logLevels.info;
924
- return {
925
- level: currentLogLevelName,
926
- fatal: (mergeObject, msg) => {
927
- if (currentLogLevel >= logLevels.fatal) {
928
- typeof mergeObject === "string" || mergeObject instanceof Error ? writeLine("fatal", null, mergeObject, bindings) : writeLine("fatal", mergeObject, msg ?? "", bindings);
929
- }
930
- },
931
- error: (mergeObject, msg) => {
932
- if (currentLogLevel >= logLevels.error) {
933
- typeof mergeObject === "string" || mergeObject instanceof Error ? writeLine("error", null, mergeObject, bindings) : writeLine("error", mergeObject, msg ?? "", bindings);
934
- }
935
- },
936
- warn: (mergeObject, msg) => {
937
- if (currentLogLevel >= logLevels.warn) {
938
- typeof mergeObject === "string" ? writeLine("warn", null, mergeObject, bindings) : writeLine("warn", mergeObject, msg ?? "", bindings);
939
- }
940
- },
941
- info: (mergeObject, msg) => {
942
- if (currentLogLevel >= logLevels.info) {
943
- typeof mergeObject === "string" ? writeLine("info", null, mergeObject, bindings) : writeLine("info", mergeObject, msg ?? "", bindings);
944
- }
945
- },
946
- debug: (mergeObject, msg) => {
947
- if (currentLogLevel >= logLevels.debug) {
948
- typeof mergeObject === "string" ? writeLine("debug", null, mergeObject, bindings) : writeLine("debug", mergeObject, msg ?? "", bindings);
949
- }
950
- },
951
- trace: (mergeObject, msg) => {
952
- if (currentLogLevel >= logLevels.trace) {
953
- typeof mergeObject === "string" ? writeLine("trace", null, mergeObject, bindings) : writeLine("trace", mergeObject, msg ?? "", bindings);
954
- }
955
- },
956
- silent: () => {
957
- },
958
- child: (childBindings) => createLogger({ ...bindings, ...childBindings })
959
- };
960
- }
961
- var logger = createLogger();
962
-
963
- // src/logging/pretty-writer.ts
964
- var levelColor = {
965
- fatal: chalk.bgRed.white,
966
- error: chalk.red,
967
- warn: chalk.yellow,
968
- info: chalk.cyan,
969
- debug: chalk.gray,
970
- trace: chalk.white
971
- };
972
- function formatTime(ms) {
973
- return new Date(ms).toTimeString().slice(0, 8);
974
- }
975
- function formatMeta(meta) {
976
- const { req, res, ...rest } = meta;
977
- const lines = [];
978
- if (req) {
979
- const reqParts = [`${req.method} ${req.url}`];
980
- if (req.remoteAddress) reqParts.push(`from ${req.remoteAddress}:${req.remotePort ?? ""}`);
981
- if (req.headers) reqParts.push(`headers=${JSON.stringify(req.headers, null, 2)}`);
982
- if (req.body !== void 0) reqParts.push(`body=${typeof req.body === "string" ? req.body : JSON.stringify(req.body, null, 2)}`);
983
- lines.push(chalk.dim(" req: " + reqParts.join(" ")));
984
- }
985
- if (res) {
986
- const resParts = [`${res.statusCode}`];
987
- if (res.headers) resParts.push(`headers=${JSON.stringify(res.headers, null, 2)}`);
988
- if (res.body !== void 0) resParts.push(`body=${typeof res.body === "string" ? res.body : JSON.stringify(res.body, null, 2)}`);
989
- lines.push(chalk.dim(" res: " + resParts.join(" ")));
990
- }
991
- if (Object.keys(rest).length) {
992
- lines.push(chalk.dim(" " + JSON.stringify(rest, null, 2)));
993
- }
994
- return lines.length ? EOL2 + lines.join(EOL2) : "";
995
- }
996
- var prettyWriter = (entry) => {
997
- const color = levelColor[entry.levelName] ?? chalk.white;
998
- const time = chalk.dim(formatTime(entry.time));
999
- const level = color(entry.levelName.toUpperCase().padEnd(5));
1000
- const module = chalk.magenta(entry.module);
1001
- const reqId = entry.reqId ? chalk.dim(`[${entry.reqId}]`) + " " : "";
1002
- const meta = entry.meta ? formatMeta(entry.meta) : "";
1003
- process.stdout.write(`${time} ${level} ${module} ${reqId}- ${entry.msg}${meta}${EOL2}`);
1004
- };
1005
- setWriter(prettyWriter);
1006
-
1007
1
  // src/queue-plugin/plugin.ts
1008
2
  import fsPlugin from "fastify-plugin";
1009
3
 
1010
4
  // src/queue-plugin/core.ts
5
+ var MAX_MESSAGE_HISTORY = 500;
1011
6
  var DEFAULT_CONFIG = {
1012
7
  batchSize: 10,
1013
8
  batchWindowMs: 500,
@@ -1015,12 +10,12 @@ var DEFAULT_CONFIG = {
1015
10
  parallel: true,
1016
11
  maxConcurrent: 5,
1017
12
  retryBackoff: true,
13
+ tickIntervalMs: 50,
1018
14
  persistence: {
1019
15
  enabled: true,
1020
16
  directory: "./.develop/queue-data",
1021
17
  saveInterval: 6e4,
1022
- saveOnShutdown: false,
1023
- loadOnStartup: true
18
+ saveOnShutdown: false
1024
19
  }
1025
20
  };
1026
21
  var mergeConfig = (defaultConfig, userConfig) => ({
@@ -1036,7 +31,6 @@ var createQueueService = (handler, module) => ({
1036
31
  incoming: [],
1037
32
  processing: [],
1038
33
  dlq: [],
1039
- timeoutId: null,
1040
34
  processingBatch: false,
1041
35
  module
1042
36
  });
@@ -1055,6 +49,12 @@ var createQueueMessage = (body, headers) => {
1055
49
  }
1056
50
  return message;
1057
51
  };
52
+ var scheduleRetry = (queueService, message, delayMs) => {
53
+ removeFromProcessing(queueService, message.id);
54
+ message.attempts += 1;
55
+ message.nextAttempt = new Date(Date.now() + delayMs);
56
+ queueService.incoming.push(message);
57
+ };
1058
58
  var isMessageReady = (message, now = Date.now()) => {
1059
59
  return !message.nextAttempt || message.nextAttempt.getTime() <= now;
1060
60
  };
@@ -1072,11 +72,6 @@ var moveToProcessing = (queueService, batchSize) => {
1072
72
  queueService.incoming = remaining;
1073
73
  return ready;
1074
74
  };
1075
- var getNextReadyDelay = (queueService) => {
1076
- const nextAttempts = queueService.incoming.filter((message) => message.nextAttempt).map((message) => message.nextAttempt.getTime());
1077
- if (nextAttempts.length === 0) return null;
1078
- return Math.max(0, Math.min(...nextAttempts) - Date.now());
1079
- };
1080
75
  var removeFromProcessing = (queueService, messageId) => {
1081
76
  queueService.processing = queueService.processing.filter((msg) => msg.id !== messageId);
1082
77
  };
@@ -1088,21 +83,9 @@ var moveToDLQ = (queueService, message, error) => {
1088
83
  });
1089
84
  removeFromProcessing(queueService, message.id);
1090
85
  };
1091
- var incrementAttempts = (queueService, messageId) => {
1092
- const index = queueService.processing.findIndex((m) => m.id === messageId);
1093
- if (index >= 0) {
1094
- queueService.processing[index].attempts += 1;
1095
- return queueService.processing[index];
1096
- }
1097
- return null;
1098
- };
1099
86
  var calculateBackoffDelay = (attempts) => {
1100
87
  return Math.pow(2, attempts) * 100;
1101
88
  };
1102
- var setNextAttemptTime = (message, delayMs) => ({
1103
- ...message,
1104
- nextAttempt: new Date(Date.now() + delayMs)
1105
- });
1106
89
  var createQueueSummary = (queueService, config) => ({
1107
90
  incoming: queueService.incoming.length,
1108
91
  processing: queueService.processing.length,
@@ -1142,93 +125,21 @@ var purgeDLQ = (queueService) => {
1142
125
  queueService.dlq = [];
1143
126
  return dlqCount;
1144
127
  };
1145
- var logSuccess = (message, messageId, queueName) => {
1146
- logger.debug(`Success: ${message} ${messageId} in queue ${queueName}`);
1147
- };
1148
- var logError = (message, messageId, queueName, error) => {
1149
- logger.error(`Error: ${message} ${messageId} in queue ${queueName}: ${error}`);
1150
- };
1151
- var logRetryScheduled = (messageId, delayMs) => {
1152
- logger.debug(`Scheduling retry for message ${messageId} in ${delayMs}ms`);
1153
- };
1154
- var logDLQOperation = (operation, count, queueName) => {
1155
- logger.warn(`${operation} ${count} messages from DLQ for ${queueName}`);
1156
- };
1157
-
1158
- // src/queue-plugin/processing.ts
1159
- var createProcessMessageHandler = (config) => async (queueName, message, queueService) => {
1160
- try {
1161
- const result = await queueService.handler(message);
1162
- if (result?.failureId) {
1163
- await handleProcessingError(queueName, message, queueService, config);
1164
- } else {
1165
- removeFromProcessing(queueService, message.id);
1166
- logSuccess("Successfully processed message", message.id, queueName);
1167
- }
1168
- } catch {
1169
- await handleProcessingError(queueName, message, queueService, config);
1170
- }
1171
- };
1172
- var handleProcessingError = async (queueName, message, queueService, config) => {
1173
- logError("Error processing message", message.id, queueName, "handler returned failure");
1174
- if (message.attempts >= config.maxRetries) {
1175
- moveToDLQ(queueService, message, "max retries exceeded");
1176
- return;
1177
- }
1178
- const updatedMessage = incrementAttempts(queueService, message.id);
1179
- if (!updatedMessage) return;
1180
- if (config.retryBackoff) {
1181
- const delayMs = calculateBackoffDelay(updatedMessage.attempts);
1182
- const messageWithNextAttempt = setNextAttemptTime(updatedMessage, delayMs);
1183
- logRetryScheduled(message.id, delayMs);
1184
- setTimeout(() => {
1185
- createProcessMessageHandler(config)(queueName, messageWithNextAttempt, queueService);
1186
- }, delayMs);
1187
- }
1188
- };
1189
- var createBatchProcessor = (processMessage, config, dirtyQueues, schedulerRef) => async (queueName, queueService) => {
1190
- if (queueService.timeoutId) {
1191
- clearTimeout(queueService.timeoutId);
1192
- queueService.timeoutId = null;
1193
- }
1194
- if (queueService.processingBatch) {
1195
- return;
1196
- }
1197
- try {
1198
- queueService.processingBatch = true;
1199
- const messagesToProcess = moveToProcessing(queueService, config.batchSize);
1200
- if (messagesToProcess.length > 0) {
1201
- queueService.processing.push(...messagesToProcess);
1202
- await Promise.all(messagesToProcess.map((message) => {
1203
- return processMessage(queueName, message, queueService);
1204
- }));
1205
- if (config.persistence.enabled && dirtyQueues) {
1206
- dirtyQueues.add(queueName);
1207
- }
1208
- }
1209
- } finally {
1210
- queueService.processingBatch = false;
1211
- const nextReadyDelay = getNextReadyDelay(queueService);
1212
- if (nextReadyDelay !== null) {
1213
- schedulerRef?.current?.(queueName, queueService, nextReadyDelay);
1214
- }
1215
- }
1216
- };
1217
- var createProcessingScheduler = (processBatch, config) => (queueName, queueService, overrideDelay = null) => {
1218
- if (!queueService.timeoutId) {
1219
- const delay = overrideDelay ?? config.batchWindowMs;
1220
- queueService.timeoutId = setTimeout(() => {
1221
- processBatch(queueName, queueService);
1222
- }, delay);
1223
- }
1224
- };
1225
- var handleImmediateProcessing = (queueService, config, processBatch, queueName) => {
1226
- if (queueService.incoming.length >= config.batchSize) {
1227
- if (queueService.timeoutId) {
1228
- clearTimeout(queueService.timeoutId);
1229
- queueService.timeoutId = null;
1230
- }
1231
- setImmediate(() => processBatch(queueName, queueService));
128
+ var createHistoryEntry = (queueName, message, status, error) => ({
129
+ id: message.id,
130
+ queueName,
131
+ status,
132
+ timestamp: message.timestamp,
133
+ completedAt: /* @__PURE__ */ new Date(),
134
+ attempts: message.attempts,
135
+ payload: message.payload,
136
+ attributes: message.attributes,
137
+ error
138
+ });
139
+ var recordMessageHistory = (history, entry) => {
140
+ history.push(entry);
141
+ if (history.length > MAX_MESSAGE_HISTORY) {
142
+ history.splice(0, history.length - MAX_MESSAGE_HISTORY);
1232
143
  }
1233
144
  };
1234
145
 
@@ -1248,123 +159,358 @@ var restoreDates = (messages) => {
1248
159
  if (msg.failedAt) msg.failedAt = new Date(msg.failedAt);
1249
160
  });
1250
161
  };
1251
- var createPersistenceInitializer = (config, loadAllQueueStates, saveDirtyQueueStates, saveAllQueueStates, intervalIdHolder) => async () => {
162
+ var saveQueueState = async (runtime, queueName, queueService) => {
1252
163
  try {
1253
- await fs.mkdir(config.persistence.directory, { recursive: true });
1254
- if (config.persistence.loadOnStartup) {
1255
- await loadAllQueueStates();
1256
- }
1257
- if (config.persistence.saveInterval && config.persistence.saveInterval > 0) {
1258
- intervalIdHolder.id = setInterval(saveDirtyQueueStates, config.persistence.saveInterval);
1259
- }
1260
- if (config.persistence.saveOnShutdown) {
1261
- const shutdownHandler = async () => {
1262
- logger.debug("Saving queue state before shutdown...");
1263
- if (intervalIdHolder.id) {
1264
- clearInterval(intervalIdHolder.id);
1265
- }
1266
- await saveAllQueueStates();
1267
- process.exit(0);
1268
- };
1269
- process.on("SIGINT", shutdownHandler);
1270
- process.on("SIGTERM", shutdownHandler);
1271
- }
1272
- logger.debug(`Queue persistence initialized: ${config.persistence.directory}`);
1273
- } catch (error) {
1274
- logger.error(`Failed to initialize queue persistence: ${error?.message}`);
1275
- }
1276
- };
1277
- var createQueueStateSaver = (config) => async (queueName, queueService) => {
1278
- try {
1279
- if (!queueService) return;
1280
164
  const queueData = createQueueData(queueService);
1281
165
  const now = Date.now();
1282
- const queueFilePath = path.join(config.persistence.directory, `${queueName}.json`);
1283
- const tempFilePath = path.join(config.persistence.directory, `${queueName}.${now}temp.json`);
166
+ const queueFilePath = path.join(runtime.config.persistence.directory, `${queueName}.json`);
167
+ const tempFilePath = path.join(runtime.config.persistence.directory, `${queueName}.${now}temp.json`);
1284
168
  await fs.writeFile(tempFilePath, JSON.stringify(queueData, null, 2), "utf8");
1285
169
  await fs.rename(tempFilePath, queueFilePath);
1286
- logger.debug(`Queue state saved: ${queueName}`);
170
+ runtime.logging.debug({ module: queueService.module }, `Queue state saved: ${queueName}`);
1287
171
  } catch (error) {
1288
- logger.error(`Failed to save queue state for ${queueName}:`, error?.message);
172
+ runtime.logging.error(
173
+ { module: queueService.module, error: error?.message },
174
+ `Failed to save queue state for ${queueName}`
175
+ );
1289
176
  }
1290
177
  };
1291
- var createAllQueuesStateSaver = (config, saveQueueState) => (queues) => async () => {
178
+ var saveAllQueueStates = async (runtime) => {
1292
179
  try {
1293
- for (const [queueName, queueService] of Object.entries(queues)) {
1294
- await saveQueueState(queueName, queueService);
180
+ for (const [queueName, queueService] of Object.entries(runtime.queues)) {
181
+ await saveQueueState(runtime, queueName, queueService);
1295
182
  }
1296
- logger.debug(`All queue states saved to ${config.persistence.directory}`);
183
+ runtime.logging.debug(`All queue states saved to ${runtime.config.persistence.directory}`);
1297
184
  } catch (error) {
1298
- logger.error(`Failed to save all queue states: ${error?.message}`);
185
+ runtime.logging.error({ error: error?.message }, `Failed to save all queue states`);
1299
186
  }
1300
187
  };
1301
- var createDirtyQueuesStateSaver = (saveQueueState, dirtyQueues) => (queues) => async () => {
1302
- if (dirtyQueues.size === 0) return;
188
+ var saveDirtyQueueStates = async (runtime) => {
189
+ if (runtime.dirtyQueues.size === 0) return;
1303
190
  try {
1304
- const queueNames = [...dirtyQueues];
1305
- dirtyQueues.clear();
191
+ const queueNames = [...runtime.dirtyQueues];
192
+ runtime.dirtyQueues.clear();
1306
193
  for (const queueName of queueNames) {
1307
- if (queues[queueName]) {
1308
- await saveQueueState(queueName, queues[queueName]);
194
+ if (runtime.queues[queueName]) {
195
+ await saveQueueState(runtime, queueName, runtime.queues[queueName]);
1309
196
  }
1310
197
  }
1311
198
  } catch (error) {
1312
- logger.error(`Failed to save dirty queue states: ${error?.message}`);
199
+ runtime.logging.error({ error: error?.message }, `Failed to save dirty queue states`);
1313
200
  }
1314
201
  };
1315
- var createQueueStateLoader = (config, scheduleProcessing, processMessage) => (queues) => async (queueName) => {
202
+ var loadQueueState = async (runtime, queueName) => {
1316
203
  try {
1317
- if (!queues[queueName]) {
1318
- logger.warn(`Skipping load for non-existent queue: ${queueName}`);
204
+ const queueService = runtime.queues[queueName];
205
+ if (!queueService) {
206
+ runtime.logging.warn(`Skipping load for non-existent queue: ${queueName}`);
1319
207
  return;
1320
208
  }
1321
- const queueFilePath = path.join(config.persistence.directory, `${queueName}.json`);
209
+ const queueFilePath = path.join(runtime.config.persistence.directory, `${queueName}.json`);
1322
210
  try {
1323
211
  const data = await fs.readFile(queueFilePath, "utf8");
1324
212
  const queueData = JSON.parse(data);
1325
213
  restoreDates(queueData.incoming);
1326
214
  restoreDates(queueData.processing);
1327
215
  restoreDates(queueData.dlq);
1328
- queues[queueName].incoming = queueData.incoming;
1329
- queues[queueName].processing = queueData.processing;
1330
- queues[queueName].dlq = queueData.dlq;
1331
- logger.debug(`Queue state loaded: ${queueName} (saved at ${queueData.savedAt})`);
1332
- if (queues[queueName].incoming.length > 0) {
1333
- scheduleProcessing(queueName, queues[queueName]);
1334
- }
1335
- if (queues[queueName].processing.length > 0) {
1336
- for (const message of [...queues[queueName].processing]) {
1337
- if (message.attempts >= config.maxRetries) continue;
1338
- setTimeout(() => {
1339
- processMessage(queueName, message, queues[queueName]);
1340
- }, 100 * (Math.random() * 10));
216
+ queueService.incoming = queueData.incoming;
217
+ queueService.dlq = queueData.dlq;
218
+ queueService.processing = [];
219
+ for (const message of queueData.processing) {
220
+ if (message.attempts >= runtime.config.maxRetries) {
221
+ queueService.dlq.push({ ...message, error: "max retries exceeded before restart", failedAt: /* @__PURE__ */ new Date() });
222
+ } else {
223
+ message.nextAttempt = /* @__PURE__ */ new Date();
224
+ queueService.incoming.push(message);
1341
225
  }
1342
226
  }
227
+ runtime.logging.debug(
228
+ { module: queueService.module },
229
+ `Queue state loaded: ${queueName} (saved at ${queueData.savedAt})`
230
+ );
1343
231
  } catch (error) {
1344
232
  if (error.code === "ENOENT") {
1345
- logger.debug(`No saved state found for queue: ${queueName}`);
233
+ runtime.logging.debug({ module: queueService.module }, `No saved state found for queue: ${queueName}`);
1346
234
  } else {
1347
235
  throw error;
1348
236
  }
1349
237
  }
1350
238
  } catch (error) {
1351
- logger.error(`Failed to load queue state for ${queueName}:`, error?.message);
239
+ runtime.logging.error({ error: error?.message }, `Failed to load queue state for ${queueName}`);
1352
240
  }
1353
241
  };
1354
- var createAllQueuesStateLoader = (config, loadQueueState) => async () => {
242
+ var initializePersistence = async (runtime) => {
1355
243
  try {
1356
- const files = await fs.readdir(config.persistence.directory);
1357
- const queueFiles = files.filter((file) => file.endsWith(".json") && !file.includes(".temp."));
1358
- for (const file of queueFiles) {
1359
- const queueName = path.basename(file, ".json");
1360
- await loadQueueState(queueName);
244
+ await fs.mkdir(runtime.config.persistence.directory, { recursive: true });
245
+ if (runtime.config.persistence.saveOnShutdown) {
246
+ const shutdownHandler = async () => {
247
+ runtime.logging.debug("Saving queue state before shutdown...");
248
+ await saveAllQueueStates(runtime);
249
+ process.exit(0);
250
+ };
251
+ process.on("SIGINT", shutdownHandler);
252
+ process.on("SIGTERM", shutdownHandler);
1361
253
  }
1362
- logger.debug("All queue states loaded");
254
+ runtime.logging.debug(`Queue persistence initialized: ${runtime.config.persistence.directory}`);
1363
255
  } catch (error) {
1364
- logger.error("Failed to load queue states:", error?.message);
256
+ runtime.logging.error({ error: error?.message }, `Failed to initialize queue persistence`);
1365
257
  }
1366
258
  };
1367
259
 
260
+ // src/queue-plugin/processing.ts
261
+ var processMessage = async (runtime, queueName, message, queueService) => {
262
+ try {
263
+ const result = await queueService.handler(message);
264
+ if (result?.failureId) {
265
+ handleFailure(runtime, queueName, message, queueService);
266
+ } else {
267
+ removeFromProcessing(queueService, message.id);
268
+ recordMessageHistory(runtime.messageHistory, createHistoryEntry(queueName, message, "completed"));
269
+ runtime.logging.debug(`Successfully processed message ${message.id} in queue ${queueName}`);
270
+ }
271
+ } catch {
272
+ handleFailure(runtime, queueName, message, queueService);
273
+ }
274
+ };
275
+ var handleFailure = (runtime, queueName, message, queueService) => {
276
+ runtime.logging.error(`Error processing message ${message.id} in queue ${queueName}: handler returned failure`);
277
+ if (message.attempts >= runtime.config.maxRetries) {
278
+ moveToDLQ(queueService, message, "max retries exceeded");
279
+ recordMessageHistory(runtime.messageHistory, createHistoryEntry(queueName, message, "failed", "max retries exceeded"));
280
+ return;
281
+ }
282
+ const delayMs = runtime.config.retryBackoff ? calculateBackoffDelay(message.attempts + 1) : 0;
283
+ scheduleRetry(queueService, message, delayMs);
284
+ runtime.logging.debug(`Scheduling retry for message ${message.id} in ${delayMs}ms`);
285
+ };
286
+ var processBatch = async (runtime, queueName, queueService) => {
287
+ if (queueService.processingBatch) {
288
+ return;
289
+ }
290
+ try {
291
+ queueService.processingBatch = true;
292
+ const messagesToProcess = moveToProcessing(queueService, runtime.config.batchSize);
293
+ if (messagesToProcess.length === 0) {
294
+ return;
295
+ }
296
+ queueService.processing.push(...messagesToProcess);
297
+ await Promise.all(
298
+ messagesToProcess.map((message) => runtime.logging.runWithLogContext(
299
+ { module: queueService.module, reqId: message.id },
300
+ () => processMessage(runtime, queueName, message, queueService)
301
+ ))
302
+ );
303
+ if (runtime.config.persistence.enabled) {
304
+ runtime.dirtyQueues.add(queueName);
305
+ }
306
+ } finally {
307
+ queueService.processingBatch = false;
308
+ }
309
+ };
310
+ var dispatchBatchIfDue = (runtime, queueName, queueService, now) => {
311
+ if (queueService.processingBatch) {
312
+ return;
313
+ }
314
+ const ready = queueService.incoming.filter((message) => isMessageReady(message, now));
315
+ if (ready.length === 0) {
316
+ return;
317
+ }
318
+ const dueBySize = ready.length >= runtime.config.batchSize;
319
+ const oldestReadyAge = now - Math.min(...ready.map((message) => message.timestamp.getTime()));
320
+ const dueByWindow = oldestReadyAge >= runtime.config.batchWindowMs;
321
+ if (dueBySize || dueByWindow) {
322
+ processBatch(runtime, queueName, queueService);
323
+ }
324
+ };
325
+ var maybeSavePersistence = (runtime, now) => {
326
+ if (!runtime.config.persistence.enabled) {
327
+ return;
328
+ }
329
+ const saveInterval = runtime.config.persistence.saveInterval ?? 0;
330
+ if (saveInterval > 0 && now - runtime.lastSavedAt >= saveInterval) {
331
+ runtime.lastSavedAt = now;
332
+ saveDirtyQueueStates(runtime);
333
+ }
334
+ };
335
+ var tick = (runtime) => {
336
+ const now = Date.now();
337
+ for (const [queueName, queueService] of Object.entries(runtime.queues)) {
338
+ dispatchBatchIfDue(runtime, queueName, queueService, now);
339
+ }
340
+ maybeSavePersistence(runtime, now);
341
+ };
342
+
343
+ // src/queue-plugin/decorator.ts
344
+ var isValidQueueName = (queueName) => {
345
+ return typeof queueName === "string" && queueName.length > 0 && /^[a-zA-Z0-9_-]+$/.test(queueName);
346
+ };
347
+ var validateQueueName = (queueName) => {
348
+ if (!queueName || typeof queueName !== "string") {
349
+ throw new Error("Queue name must be a non-empty string");
350
+ }
351
+ if (!isValidQueueName(queueName)) {
352
+ throw new Error("Queue name must contain only alphanumeric characters, hyphens, and underscores");
353
+ }
354
+ };
355
+ var validateHandler = (handler) => {
356
+ if (typeof handler !== "function") {
357
+ throw new Error("Handler must be a function");
358
+ }
359
+ };
360
+ var addQueue = async (runtime, queueName, handler, module) => {
361
+ try {
362
+ validateQueueName(queueName);
363
+ validateHandler(handler);
364
+ if (runtime.queues[queueName]) {
365
+ runtime.logging.warn({ module }, `Queue already exists: ${queueName}.`);
366
+ return;
367
+ }
368
+ runtime.queues[queueName] = createQueueService(handler, module);
369
+ if (runtime.config.persistence.enabled) {
370
+ await loadQueueState(runtime, queueName);
371
+ }
372
+ runtime.logging.info({ module }, `Queue added: ${queueName}`);
373
+ } catch (error) {
374
+ runtime.logging.error({ module, error: error.message }, `Failed to add queue ${queueName}`);
375
+ throw error;
376
+ }
377
+ };
378
+ var removeQueue = async (runtime, queueName) => {
379
+ try {
380
+ validateQueueName(queueName);
381
+ const queueService = runtime.queues[queueName];
382
+ if (!queueService) {
383
+ throw new Error(`Queue '${queueName}' does not exist`);
384
+ }
385
+ const totalMessages = queueService.incoming.length + queueService.processing.length;
386
+ if (totalMessages > 0) {
387
+ runtime.logging.warn(
388
+ { module: queueService.module },
389
+ `Removing queue with ${totalMessages} pending messages: ${queueName}`
390
+ );
391
+ }
392
+ if (runtime.config.persistence.enabled) {
393
+ await saveQueueState(runtime, queueName, queueService);
394
+ }
395
+ delete runtime.queues[queueName];
396
+ runtime.logging.info({ module: queueService.module }, `Queue removed: ${queueName}`);
397
+ } catch (error) {
398
+ runtime.logging.error({ error: error.message }, `Failed to remove queue ${queueName}`);
399
+ throw error;
400
+ }
401
+ };
402
+ var hasQueue = (runtime, queueName) => {
403
+ try {
404
+ validateQueueName(queueName);
405
+ return queueName in runtime.queues;
406
+ } catch {
407
+ return false;
408
+ }
409
+ };
410
+ var listQueues = (runtime, module) => {
411
+ return Object.keys(runtime.queues).filter((queueName) => !module || runtime.queues[queueName].module === module).sort();
412
+ };
413
+ var getQueueStats = (runtime, queueName) => {
414
+ try {
415
+ validateQueueName(queueName);
416
+ return runtime.queues[queueName] || null;
417
+ } catch {
418
+ return null;
419
+ }
420
+ };
421
+ var getQueuesMap = (runtime) => {
422
+ return { ...runtime.queues };
423
+ };
424
+ var getDashboardSummary = (runtime) => createDashboardSummary(runtime.queues, runtime.config);
425
+ var getQueueSummary = (runtime, queueName) => {
426
+ const queue = runtime.queues[queueName];
427
+ if (!queue) {
428
+ return null;
429
+ }
430
+ return {
431
+ stats: createQueueSummary(queue, runtime.config),
432
+ messages: {
433
+ incoming: queue.incoming,
434
+ processing: queue.processing,
435
+ dlq: queue.dlq
436
+ }
437
+ };
438
+ };
439
+ var enqueueMessage = async (runtime, queueName, body, attributes) => {
440
+ const queueService = runtime.queues[queueName];
441
+ if (!queueService) {
442
+ return null;
443
+ }
444
+ const message = createQueueMessage(body, attributes);
445
+ queueService.incoming.push(message);
446
+ if (runtime.config.persistence.enabled) {
447
+ runtime.dirtyQueues.add(queueName);
448
+ }
449
+ return { id: message.id, queueName };
450
+ };
451
+ var processDlq = async (runtime, queueName) => {
452
+ const queueService = runtime.queues[queueName];
453
+ if (!queueService) {
454
+ return null;
455
+ }
456
+ const processedCount = moveDLQToIncoming(queueService);
457
+ if (processedCount === 0) {
458
+ return { status: "success", message: "No messages in DLQ to process", processed: 0 };
459
+ }
460
+ runtime.logging.warn(
461
+ { module: queueService.module },
462
+ `Moving ${processedCount} messages from DLQ for ${queueName}`
463
+ );
464
+ if (runtime.config.persistence.enabled) {
465
+ runtime.dirtyQueues.add(queueName);
466
+ }
467
+ return {
468
+ status: "success",
469
+ message: `Moved ${processedCount} messages from DLQ to processing queue`,
470
+ processed: processedCount
471
+ };
472
+ };
473
+ var purgeDlq = async (runtime, queueName) => {
474
+ const queueService = runtime.queues[queueName];
475
+ if (!queueService) {
476
+ return null;
477
+ }
478
+ const purgedCount = purgeDLQ(queueService);
479
+ if (purgedCount === 0) {
480
+ return { status: "success", message: "No messages in DLQ to purge", purged: 0 };
481
+ }
482
+ runtime.logging.warn(
483
+ { module: queueService.module },
484
+ `Purging ${purgedCount} messages from DLQ for ${queueName}`
485
+ );
486
+ if (runtime.config.persistence.enabled) {
487
+ runtime.dirtyQueues.add(queueName);
488
+ }
489
+ return {
490
+ status: "success",
491
+ message: `Purged ${purgedCount} messages from DLQ`,
492
+ purged: purgedCount
493
+ };
494
+ };
495
+ var getMessageHistory = (runtime, queueName, limit = 50) => {
496
+ return runtime.messageHistory.filter((entry) => entry.queueName === queueName).slice(-limit).reverse();
497
+ };
498
+ var createQueueManager = (runtime) => ({
499
+ addQueue: (queueName, handler, module) => addQueue(runtime, queueName, handler, module),
500
+ removeQueue: (queueName) => removeQueue(runtime, queueName),
501
+ hasQueue: (queueName) => hasQueue(runtime, queueName),
502
+ listQueues: (module) => listQueues(runtime, module),
503
+ getQueueStats: (queueName) => getQueueStats(runtime, queueName),
504
+ getQueuesMap: () => getQueuesMap(runtime),
505
+ getConfig: () => runtime.config,
506
+ getDashboardSummary: () => getDashboardSummary(runtime),
507
+ getQueueSummary: (queueName) => getQueueSummary(runtime, queueName),
508
+ enqueueMessage: (queueName, body, attributes) => enqueueMessage(runtime, queueName, body, attributes),
509
+ processDlq: (queueName) => processDlq(runtime, queueName),
510
+ purgeDlq: (queueName) => purgeDlq(runtime, queueName),
511
+ getMessageHistory: (queueName, limit) => getMessageHistory(runtime, queueName, limit)
512
+ });
513
+
1368
514
  // src/queue-plugin/routes.ts
1369
515
  var registerQueueRoutes = (app, prefix = "") => {
1370
516
  app.get(
@@ -1420,258 +566,23 @@ var registerQueueRoutes = (app, prefix = "") => {
1420
566
  );
1421
567
  };
1422
568
 
1423
- // src/queue-plugin/decorator.ts
1424
- var isValidQueueName = (queueName) => {
1425
- return typeof queueName === "string" && queueName.length > 0 && /^[a-zA-Z0-9_-]+$/.test(queueName);
1426
- };
1427
- var createQueueManager = ({
1428
- config,
1429
- queues,
1430
- dirtyQueues,
1431
- saveQueueState,
1432
- loadQueueState,
1433
- scheduleProcessing,
1434
- processBatch
1435
- }) => {
1436
- const validateQueueName = (queueName) => {
1437
- if (!queueName || typeof queueName !== "string") {
1438
- throw new Error("Queue name must be a non-empty string");
1439
- }
1440
- if (!isValidQueueName(queueName)) {
1441
- throw new Error("Queue name must contain only alphanumeric characters, hyphens, and underscores");
1442
- }
1443
- };
1444
- const validateHandler = (handler) => {
1445
- if (typeof handler !== "function") {
1446
- throw new Error("Handler must be a function");
1447
- }
1448
- };
1449
- const addQueue = async (queueName, handler, module) => {
1450
- try {
1451
- validateQueueName(queueName);
1452
- validateHandler(handler);
1453
- if (queues[queueName]) {
1454
- logger.warn(`Queue already exists: ${queueName}.`);
1455
- return;
1456
- }
1457
- queues[queueName] = createQueueService(handler, module);
1458
- if (config.persistence.enabled && loadQueueState) {
1459
- await loadQueueState(queueName);
1460
- }
1461
- logger.info(`Queue added: ${queueName}`);
1462
- } catch (error) {
1463
- logger.error(`Failed to add queue ${queueName}: ${error.message}`);
1464
- throw error;
1465
- }
1466
- };
1467
- const removeQueue = async (queueName) => {
1468
- try {
1469
- validateQueueName(queueName);
1470
- if (!queues[queueName]) {
1471
- throw new Error(`Queue '${queueName}' does not exist`);
1472
- }
1473
- const queueService = queues[queueName];
1474
- const totalMessages = queueService.incoming.length + queueService.processing.length;
1475
- if (totalMessages > 0) {
1476
- logger.warn(`Removing queue with ${totalMessages} pending messages: ${queueName}`);
1477
- }
1478
- if (queueService.timeoutId) {
1479
- clearTimeout(queueService.timeoutId);
1480
- }
1481
- if (config.persistence.enabled && saveQueueState) {
1482
- await saveQueueState(queueName, queueService);
1483
- }
1484
- delete queues[queueName];
1485
- logger.info(`Queue removed: ${queueName}`);
1486
- } catch (error) {
1487
- logger.error(`Failed to remove queue ${queueName}: ${error.message}`);
1488
- throw error;
1489
- }
1490
- };
1491
- const hasQueue = (queueName) => {
1492
- try {
1493
- validateQueueName(queueName);
1494
- return queueName in queues;
1495
- } catch {
1496
- return false;
1497
- }
1498
- };
1499
- const listQueues = (module) => {
1500
- return Object.keys(queues).filter((queueName) => {
1501
- const queueService = queues[queueName];
1502
- return !module || queueService.module === module;
1503
- }).sort();
1504
- };
1505
- const getQueueStats = (queueName) => {
1506
- try {
1507
- validateQueueName(queueName);
1508
- return queues[queueName] || null;
1509
- } catch {
1510
- return null;
1511
- }
1512
- };
1513
- const getQueuesMap = () => {
1514
- return { ...queues };
1515
- };
1516
- const getConfig = () => config;
1517
- const getDashboardSummary = () => createDashboardSummary(queues, config);
1518
- const getQueueSummary = (queueName) => {
1519
- if (!queues[queueName]) {
1520
- return null;
1521
- }
1522
- const queue = queues[queueName];
1523
- const stats = createQueueSummary(queue, config);
1524
- return {
1525
- stats,
1526
- messages: {
1527
- incoming: queue.incoming,
1528
- processing: queue.processing,
1529
- dlq: queue.dlq
1530
- }
1531
- };
1532
- };
1533
- const enqueueMessage = async (queueName, body, attributes) => {
1534
- if (!queues[queueName]) {
1535
- return null;
1536
- }
1537
- const message = createQueueMessage(body, attributes);
1538
- queues[queueName].incoming.push(message);
1539
- scheduleProcessing(queueName, queues[queueName]);
1540
- handleImmediateProcessing(queues[queueName], config, processBatch, queueName);
1541
- if (config.persistence.enabled) {
1542
- dirtyQueues.add(queueName);
1543
- }
1544
- return {
1545
- id: message.id,
1546
- queueName
1547
- };
1548
- };
1549
- const processDlq = async (queueName) => {
1550
- if (!queues[queueName]) {
1551
- return null;
1552
- }
1553
- const processedCount = moveDLQToIncoming(queues[queueName]);
1554
- if (processedCount === 0) {
1555
- return {
1556
- status: "success",
1557
- message: "No messages in DLQ to process",
1558
- processed: 0
1559
- };
1560
- }
1561
- logDLQOperation("Moving", processedCount, queueName);
1562
- scheduleProcessing(queueName, queues[queueName]);
1563
- if (config.persistence.enabled) {
1564
- dirtyQueues.add(queueName);
1565
- }
1566
- return {
1567
- status: "success",
1568
- message: `Moved ${processedCount} messages from DLQ to processing queue`,
1569
- processed: processedCount
1570
- };
1571
- };
1572
- const purgeDlq = async (queueName) => {
1573
- if (!queues[queueName]) {
1574
- return null;
1575
- }
1576
- const purgedCount = purgeDLQ(queues[queueName]);
1577
- if (purgedCount === 0) {
1578
- return {
1579
- status: "success",
1580
- message: "No messages in DLQ to purge",
1581
- purged: 0
1582
- };
1583
- }
1584
- logDLQOperation("Purging", purgedCount, queueName);
1585
- if (config.persistence.enabled) {
1586
- dirtyQueues.add(queueName);
1587
- }
1588
- return {
1589
- status: "success",
1590
- message: `Purged ${purgedCount} messages from DLQ`,
1591
- purged: purgedCount
1592
- };
1593
- };
1594
- return {
1595
- addQueue,
1596
- removeQueue,
1597
- hasQueue,
1598
- listQueues,
1599
- getQueueStats,
1600
- getQueuesMap,
1601
- getConfig,
1602
- getDashboardSummary,
1603
- getQueueSummary,
1604
- enqueueMessage,
1605
- processDlq,
1606
- purgeDlq
1607
- };
1608
- };
1609
- var createQueueDecorator = (queueManager) => (app) => {
1610
- app.decorate("queues", queueManager);
1611
- };
1612
-
1613
569
  // src/queue-plugin/plugin.ts
1614
570
  var queuesPlugin = fsPlugin(async (app, options) => {
1615
- const config = mergeConfig(DEFAULT_CONFIG, options.config);
1616
- const queues = {};
1617
- const dirtyQueues = /* @__PURE__ */ new Set();
1618
- const intervalIdHolder = {};
1619
- const processMessage = createProcessMessageHandler(config);
1620
- const saveQueueState = config.persistence.enabled ? createQueueStateSaver(config) : void 0;
1621
- const saveAllQueueStates = config.persistence.enabled && saveQueueState ? createAllQueuesStateSaver(config, saveQueueState)(queues) : async () => {
1622
- };
1623
- const saveDirtyQueueStates = config.persistence.enabled && saveQueueState ? createDirtyQueuesStateSaver(saveQueueState, dirtyQueues)(queues) : async () => {
1624
- };
1625
- const schedulerRef = {};
1626
- const processBatch = createBatchProcessor(
1627
- processMessage,
1628
- config,
1629
- config.persistence.enabled ? dirtyQueues : void 0,
1630
- schedulerRef
1631
- );
1632
- const scheduleProcessing = createProcessingScheduler(processBatch, config);
1633
- schedulerRef.current = scheduleProcessing;
1634
- const loadQueueState = config.persistence.enabled ? createQueueStateLoader(
1635
- config,
1636
- scheduleProcessing,
1637
- processMessage
1638
- )(queues) : async () => {
1639
- };
1640
- const loadAllQueueStates = config.persistence.enabled ? createAllQueuesStateLoader(config, loadQueueState) : async () => {
1641
- };
1642
- const initializePersistence = config.persistence.enabled ? createPersistenceInitializer(config, loadAllQueueStates, saveDirtyQueueStates, saveAllQueueStates, intervalIdHolder) : async () => {
571
+ const runtime = {
572
+ config: mergeConfig(DEFAULT_CONFIG, options.config),
573
+ queues: {},
574
+ dirtyQueues: /* @__PURE__ */ new Set(),
575
+ lastSavedAt: Date.now(),
576
+ messageHistory: [],
577
+ logging: app.logging
1643
578
  };
1644
- const queueManager = createQueueManager({
1645
- config,
1646
- queues,
1647
- dirtyQueues,
1648
- saveQueueState: saveQueueState ? (queueName) => saveQueueState(queueName, queues[queueName]) : void 0,
1649
- loadQueueState,
1650
- scheduleProcessing,
1651
- processBatch
1652
- });
1653
- const decorateQueues = createQueueDecorator(queueManager);
1654
- decorateQueues(app);
1655
- registerQueueRoutes(
1656
- app,
1657
- options.prefix
1658
- );
1659
- await initializePersistence();
579
+ const tickIntervalId = setInterval(() => tick(runtime), runtime.config.tickIntervalMs);
580
+ app.addHook("onClose", async () => clearInterval(tickIntervalId));
581
+ app.decorate("queues", createQueueManager(runtime));
582
+ registerQueueRoutes(app, options.prefix);
583
+ await initializePersistence(runtime);
1660
584
  });
1661
585
  export {
1662
586
  queuesPlugin
1663
587
  };
1664
- /*! Bundled license information:
1665
-
1666
- lodash-es/lodash.js:
1667
- (**
1668
- * @license
1669
- * Lodash (Custom Build) <https://lodash.com/>
1670
- * Build: `lodash modularize exports="es" -o ./`
1671
- * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
1672
- * Released under MIT license <https://lodash.com/license>
1673
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
1674
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
1675
- *)
1676
- */
1677
588
  //# sourceMappingURL=index.js.map