@catbee/utils 1.1.0 → 2.0.0-next.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 (90) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +79 -43
  3. package/array/index.cjs +355 -0
  4. package/array/index.d.ts +317 -0
  5. package/array/index.mjs +327 -0
  6. package/async/index.cjs +484 -0
  7. package/async/index.d.ts +299 -0
  8. package/async/index.mjs +463 -0
  9. package/cache/index.cjs +292 -0
  10. package/cache/index.d.ts +179 -0
  11. package/cache/index.mjs +290 -0
  12. package/config/index.cjs +150 -0
  13. package/config/index.d.ts +88 -0
  14. package/config/index.mjs +143 -0
  15. package/context-store/index.cjs +267 -0
  16. package/context-store/index.d.ts +216 -0
  17. package/context-store/index.mjs +261 -0
  18. package/crypto/index.cjs +182 -0
  19. package/crypto/index.d.ts +187 -0
  20. package/crypto/index.mjs +166 -0
  21. package/date/index.cjs +340 -0
  22. package/date/index.d.ts +214 -0
  23. package/date/index.mjs +326 -0
  24. package/decorators/index.cjs +2051 -0
  25. package/decorators/index.d.ts +708 -0
  26. package/decorators/index.mjs +2010 -0
  27. package/dir/index.cjs +417 -0
  28. package/dir/index.d.ts +219 -0
  29. package/dir/index.mjs +390 -0
  30. package/env/index.cjs +745 -0
  31. package/env/index.d.ts +403 -0
  32. package/env/index.mjs +742 -0
  33. package/exception/index.cjs +362 -0
  34. package/exception/index.d.ts +256 -0
  35. package/exception/index.mjs +338 -0
  36. package/fs/index.cjs +287 -0
  37. package/fs/index.d.ts +229 -0
  38. package/fs/index.mjs +258 -0
  39. package/http-status-codes/index.cjs +96 -0
  40. package/http-status-codes/index.d.ts +291 -0
  41. package/http-status-codes/index.mjs +94 -0
  42. package/id/index.cjs +62 -0
  43. package/id/index.d.ts +61 -0
  44. package/id/index.mjs +56 -0
  45. package/index.cjs +218 -0
  46. package/index.d.ts +51 -0
  47. package/index.mjs +51 -0
  48. package/logger/index.cjs +334 -0
  49. package/logger/index.d.ts +213 -0
  50. package/logger/index.mjs +313 -0
  51. package/middleware/index.cjs +177 -0
  52. package/middleware/index.d.ts +127 -0
  53. package/middleware/index.mjs +170 -0
  54. package/obj/index.cjs +305 -0
  55. package/obj/index.d.ts +160 -0
  56. package/obj/index.mjs +289 -0
  57. package/package.json +172 -20
  58. package/performance/index.cjs +231 -0
  59. package/performance/index.d.ts +162 -0
  60. package/performance/index.mjs +225 -0
  61. package/request/index.cjs +202 -0
  62. package/request/index.d.ts +265 -0
  63. package/request/index.mjs +194 -0
  64. package/response/index.cjs +234 -0
  65. package/response/index.d.ts +342 -0
  66. package/response/index.mjs +222 -0
  67. package/server/index.cjs +1631 -0
  68. package/server/index.d.ts +809 -0
  69. package/server/index.mjs +1622 -0
  70. package/stream/index.cjs +151 -0
  71. package/stream/index.d.ts +114 -0
  72. package/stream/index.mjs +144 -0
  73. package/string/index.cjs +109 -0
  74. package/string/index.d.ts +126 -0
  75. package/string/index.mjs +95 -0
  76. package/type/index.cjs +129 -0
  77. package/type/index.d.ts +131 -0
  78. package/type/index.mjs +119 -0
  79. package/types/index.cjs +34 -0
  80. package/types/index.d.ts +798 -0
  81. package/types/index.mjs +32 -0
  82. package/url/index.cjs +199 -0
  83. package/url/index.d.ts +166 -0
  84. package/url/index.mjs +187 -0
  85. package/validation/index.cjs +259 -0
  86. package/validation/index.d.ts +209 -0
  87. package/validation/index.mjs +231 -0
  88. package/build/index.cjs +0 -7694
  89. package/build/index.d.ts +0 -5792
  90. package/build/index.mjs +0 -7386
@@ -0,0 +1,463 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { getLogger } from '@catbee/utils/logger';
26
+
27
+ var __defProp = Object.defineProperty;
28
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
29
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
30
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
31
+ }) : x)(function(x) {
32
+ if (typeof require !== "undefined") return require.apply(this, arguments);
33
+ throw Error('Dynamic require of "' + x + '" is not supported');
34
+ });
35
+ function sleep(ms) {
36
+ return new Promise((resolve) => setTimeout(resolve, ms));
37
+ }
38
+ __name(sleep, "sleep");
39
+ function debounce(fn, delay) {
40
+ let timer = null;
41
+ let pendingArgs = null;
42
+ function debounced(...args) {
43
+ pendingArgs = args;
44
+ if (timer) clearTimeout(timer);
45
+ timer = setTimeout(() => {
46
+ try {
47
+ fn(...pendingArgs);
48
+ } catch (err) {
49
+ getLogger().error({
50
+ err
51
+ }, "Error in debounced function");
52
+ }
53
+ timer = null;
54
+ }, delay);
55
+ }
56
+ __name(debounced, "debounced");
57
+ debounced.cancel = () => {
58
+ if (timer) clearTimeout(timer);
59
+ timer = null;
60
+ pendingArgs = null;
61
+ };
62
+ debounced.flush = () => {
63
+ if (timer) {
64
+ clearTimeout(timer);
65
+ try {
66
+ fn(...pendingArgs);
67
+ } catch (err) {
68
+ getLogger().error({
69
+ err
70
+ }, "Error in debounced.flush");
71
+ }
72
+ timer = null;
73
+ pendingArgs = null;
74
+ }
75
+ };
76
+ return debounced;
77
+ }
78
+ __name(debounce, "debounce");
79
+ function throttle(fn, limit, opts = {
80
+ leading: true,
81
+ trailing: false
82
+ }) {
83
+ let lastCall = 0;
84
+ let timer = null;
85
+ let savedArgs = null;
86
+ return function(...args) {
87
+ const now = Date.now();
88
+ const { leading = true, trailing = false } = opts;
89
+ if (!lastCall && !leading) lastCall = now;
90
+ const remaining = limit - (now - lastCall);
91
+ if (remaining <= 0) {
92
+ if (timer) {
93
+ clearTimeout(timer);
94
+ timer = null;
95
+ }
96
+ lastCall = now;
97
+ try {
98
+ fn(...args);
99
+ } catch (err) {
100
+ getLogger().error({
101
+ err
102
+ }, "Error in throttled function");
103
+ }
104
+ } else if (trailing) {
105
+ savedArgs = args;
106
+ if (!timer) {
107
+ timer = setTimeout(() => {
108
+ lastCall = leading ? Date.now() : 0;
109
+ timer = null;
110
+ if (savedArgs) {
111
+ try {
112
+ fn(...savedArgs);
113
+ } catch (err) {
114
+ getLogger().error({
115
+ err
116
+ }, "Error in throttled trailing call");
117
+ }
118
+ }
119
+ }, remaining);
120
+ }
121
+ }
122
+ };
123
+ }
124
+ __name(throttle, "throttle");
125
+ async function retry(fn, retries = 3, delay = 500, backoff = false, onRetry) {
126
+ for (let i = 0; i < retries; i++) {
127
+ try {
128
+ return await fn();
129
+ } catch (e) {
130
+ if (i === retries - 1) throw e;
131
+ if (onRetry) onRetry(e, i + 1);
132
+ await sleep(backoff ? delay * Math.pow(2, i) : delay);
133
+ }
134
+ }
135
+ throw new Error("Retry failed");
136
+ }
137
+ __name(retry, "retry");
138
+ function withTimeout(promise, ms, message = "Operation timed out") {
139
+ return new Promise((resolve, reject) => {
140
+ const timeoutHandle = setTimeout(() => reject(new Error(message)), ms);
141
+ promise.then((result) => {
142
+ clearTimeout(timeoutHandle);
143
+ resolve(result);
144
+ }).catch((err) => {
145
+ clearTimeout(timeoutHandle);
146
+ reject(err);
147
+ });
148
+ });
149
+ }
150
+ __name(withTimeout, "withTimeout");
151
+ async function runInBatches(tasks, limit) {
152
+ const results = [];
153
+ for (let i = 0; i < tasks.length; i += limit) {
154
+ const batch = tasks.slice(i, i + limit);
155
+ const batchResults = await Promise.all(batch.map((fn) => fn()));
156
+ results.push(...batchResults);
157
+ }
158
+ return results;
159
+ }
160
+ __name(runInBatches, "runInBatches");
161
+ function singletonAsync(fn, drop = false) {
162
+ let promise = null;
163
+ return async (...args) => {
164
+ if (!promise) {
165
+ promise = fn(...args).finally(() => {
166
+ promise = null;
167
+ });
168
+ } else if (drop) {
169
+ throw new Error("Function is already in progress");
170
+ }
171
+ return promise;
172
+ };
173
+ }
174
+ __name(singletonAsync, "singletonAsync");
175
+ async function settleAll(tasks) {
176
+ return Promise.allSettled(tasks.map((task) => task()));
177
+ }
178
+ __name(settleAll, "settleAll");
179
+ function createTaskQueue(limit) {
180
+ const queue = [];
181
+ let activeCount = 0;
182
+ let paused = false;
183
+ const state = {
184
+ /**
185
+ * Pause task processing.
186
+ */
187
+ pause() {
188
+ paused = true;
189
+ },
190
+ /**
191
+ * Resume task processing.
192
+ */
193
+ resume() {
194
+ paused = false;
195
+ next();
196
+ }};
197
+ const next = /* @__PURE__ */ __name(() => {
198
+ if (paused || queue.length === 0 || activeCount >= limit) return;
199
+ const task = queue.shift();
200
+ activeCount++;
201
+ task().finally(() => {
202
+ activeCount--;
203
+ next();
204
+ });
205
+ }, "next");
206
+ const enqueue = /* @__PURE__ */ __name(async function(taskFn) {
207
+ return new Promise((resolve, reject) => {
208
+ queue.push(async () => {
209
+ try {
210
+ const result = await taskFn();
211
+ resolve(result);
212
+ } catch (err) {
213
+ reject(err);
214
+ }
215
+ });
216
+ next();
217
+ });
218
+ }, "enqueue");
219
+ enqueue.pause = state.pause;
220
+ enqueue.resume = state.resume;
221
+ Object.defineProperty(enqueue, "length", {
222
+ get: /* @__PURE__ */ __name(() => queue.length, "get")
223
+ });
224
+ Object.defineProperty(enqueue, "isPaused", {
225
+ get: /* @__PURE__ */ __name(() => paused, "get")
226
+ });
227
+ return enqueue;
228
+ }
229
+ __name(createTaskQueue, "createTaskQueue");
230
+ async function runInSeries(tasks) {
231
+ const results = [];
232
+ for (const task of tasks) {
233
+ results.push(await task());
234
+ }
235
+ return results;
236
+ }
237
+ __name(runInSeries, "runInSeries");
238
+ function memoizeAsync(fn, options = {}) {
239
+ const cache = /* @__PURE__ */ new Map();
240
+ const { ttl } = options;
241
+ const generateKey = /* @__PURE__ */ __name((args) => {
242
+ try {
243
+ return options.keyFn?.(args) ?? JSON.stringify(args);
244
+ } catch {
245
+ getLogger().warn("memoizeAsync: key generation failed, falling back to JSON.stringify");
246
+ return JSON.stringify(args);
247
+ }
248
+ }, "generateKey");
249
+ return async (...args) => {
250
+ const key = generateKey(args);
251
+ const cached = cache.get(key);
252
+ if (cached && Date.now() < cached.expires) {
253
+ return cached.value;
254
+ }
255
+ const result = await fn(...args);
256
+ cache.set(key, {
257
+ value: result,
258
+ expires: ttl ? Date.now() + ttl : Infinity
259
+ });
260
+ return result;
261
+ };
262
+ }
263
+ __name(memoizeAsync, "memoizeAsync");
264
+ function abortable(promise, signal, abortValue = new Error("Operation aborted")) {
265
+ if (signal.aborted) {
266
+ return Promise.reject(abortValue);
267
+ }
268
+ return Promise.race([
269
+ promise,
270
+ new Promise((_, reject) => {
271
+ const abort = /* @__PURE__ */ __name(() => {
272
+ reject(abortValue);
273
+ signal.removeEventListener("abort", abort);
274
+ }, "abort");
275
+ signal.addEventListener("abort", abort, {
276
+ once: true
277
+ });
278
+ promise.finally(() => signal.removeEventListener("abort", abort));
279
+ })
280
+ ]);
281
+ }
282
+ __name(abortable, "abortable");
283
+ function createDeferred() {
284
+ let resolve;
285
+ let reject;
286
+ const promise = new Promise((res, rej) => {
287
+ resolve = res;
288
+ reject = rej;
289
+ });
290
+ return [
291
+ promise,
292
+ resolve,
293
+ reject
294
+ ];
295
+ }
296
+ __name(createDeferred, "createDeferred");
297
+ function waterfall(fns) {
298
+ return async (initialValue) => {
299
+ return fns.reduce(async (acc, fn) => fn(await acc), Promise.resolve(initialValue));
300
+ };
301
+ }
302
+ __name(waterfall, "waterfall");
303
+ function rateLimit(fn, maxCalls, interval) {
304
+ const calls = [];
305
+ return async function(...args) {
306
+ const now = Date.now();
307
+ calls.splice(0, calls.length, ...calls.filter((time) => now - time < interval));
308
+ if (calls.length >= maxCalls) {
309
+ const oldestCall = calls[0];
310
+ const delay = interval - (now - oldestCall);
311
+ await sleep(Math.max(1, delay));
312
+ const currentTime = Date.now();
313
+ calls.splice(0, calls.length, ...calls.filter((time) => currentTime - time < interval));
314
+ if (calls.length >= maxCalls) {
315
+ const nextDelay = interval - (currentTime - calls[0]);
316
+ await sleep(Math.max(1, nextDelay));
317
+ calls.splice(0, calls.length, ...calls.filter((time) => Date.now() - time < interval));
318
+ }
319
+ }
320
+ calls.push(Date.now());
321
+ return fn(...args);
322
+ };
323
+ }
324
+ __name(rateLimit, "rateLimit");
325
+ var CircuitBreakerOpenError = class extends Error {
326
+ static {
327
+ __name(this, "CircuitBreakerOpenError");
328
+ }
329
+ constructor(message = "Circuit breaker is open") {
330
+ super(message);
331
+ this.name = "CircuitBreakerOpenError";
332
+ }
333
+ };
334
+ var CircuitBreakerState = /* @__PURE__ */ (function(CircuitBreakerState2) {
335
+ CircuitBreakerState2["CLOSED"] = "CLOSED";
336
+ CircuitBreakerState2["OPEN"] = "OPEN";
337
+ CircuitBreakerState2["HALF_OPEN"] = "HALF_OPEN";
338
+ return CircuitBreakerState2;
339
+ })({});
340
+ function circuitBreaker(fn, options = {}) {
341
+ const { failureThreshold = 5, resetTimeout = 1e4, successThreshold = 1, onOpen, onClose, onHalfOpen } = options;
342
+ let state = "CLOSED";
343
+ let fails = 0;
344
+ let halfSuccess = 0;
345
+ let unlockAt = 0;
346
+ const reset = /* @__PURE__ */ __name(() => {
347
+ fails = 0;
348
+ halfSuccess = 0;
349
+ state = "CLOSED";
350
+ onClose?.();
351
+ }, "reset");
352
+ const open = /* @__PURE__ */ __name(() => {
353
+ state = "OPEN";
354
+ unlockAt = Date.now() + resetTimeout;
355
+ onOpen?.();
356
+ }, "open");
357
+ const halfOpen = /* @__PURE__ */ __name(() => {
358
+ state = "HALF_OPEN";
359
+ onHalfOpen?.();
360
+ }, "halfOpen");
361
+ return async (...args) => {
362
+ const now = Date.now();
363
+ if (state === "OPEN" && now < unlockAt) {
364
+ throw new CircuitBreakerOpenError();
365
+ }
366
+ if (state === "OPEN" && now >= unlockAt) {
367
+ halfOpen();
368
+ }
369
+ try {
370
+ const res = await fn(...args);
371
+ if (state === "HALF_OPEN") {
372
+ halfSuccess++;
373
+ if (halfSuccess >= successThreshold) {
374
+ reset();
375
+ } else {
376
+ state = "HALF_OPEN";
377
+ }
378
+ } else {
379
+ fails = 0;
380
+ }
381
+ return res;
382
+ } catch (err) {
383
+ fails++;
384
+ if (state === "HALF_OPEN" || state === "CLOSED") {
385
+ if (fails >= failureThreshold) {
386
+ open();
387
+ }
388
+ }
389
+ throw err;
390
+ }
391
+ };
392
+ }
393
+ __name(circuitBreaker, "circuitBreaker");
394
+ async function runWithConcurrency(tasks, options = {}) {
395
+ const { concurrency = 3, onProgress, signal } = options;
396
+ const results = [];
397
+ const totalTasks = tasks.length;
398
+ let completed = 0;
399
+ if (totalTasks === 0) return results;
400
+ if (signal?.aborted) {
401
+ throw new Error("Aborted");
402
+ }
403
+ return new Promise((resolve, reject) => {
404
+ let taskIndex = 0;
405
+ let rejected = false;
406
+ const processNext = /* @__PURE__ */ __name(async () => {
407
+ if (rejected) return;
408
+ const currentTaskIndex = taskIndex++;
409
+ if (currentTaskIndex >= totalTasks) return;
410
+ try {
411
+ const result = await tasks[currentTaskIndex]();
412
+ if (signal?.aborted) {
413
+ rejected = true;
414
+ reject(new Error("Aborted"));
415
+ return;
416
+ }
417
+ results[currentTaskIndex] = result;
418
+ completed++;
419
+ if (onProgress) {
420
+ try {
421
+ onProgress(completed, totalTasks);
422
+ } catch (err) {
423
+ getLogger().error({
424
+ err
425
+ }, "Error in onProgress callback");
426
+ }
427
+ }
428
+ } catch (error) {
429
+ rejected = true;
430
+ reject(error);
431
+ return;
432
+ }
433
+ if (completed === totalTasks) {
434
+ resolve(results);
435
+ return;
436
+ }
437
+ processNext();
438
+ }, "processNext");
439
+ const initialBatch = Math.min(concurrency, totalTasks);
440
+ for (let i = 0; i < initialBatch; i++) {
441
+ processNext();
442
+ }
443
+ if (signal) {
444
+ signal.addEventListener("abort", () => {
445
+ rejected = true;
446
+ reject(new Error("Aborted"));
447
+ }, {
448
+ once: true
449
+ });
450
+ }
451
+ });
452
+ }
453
+ __name(runWithConcurrency, "runWithConcurrency");
454
+ function optionalRequire(name) {
455
+ try {
456
+ return __require(name);
457
+ } catch {
458
+ return null;
459
+ }
460
+ }
461
+ __name(optionalRequire, "optionalRequire");
462
+
463
+ export { CircuitBreakerOpenError, CircuitBreakerState, abortable, circuitBreaker, createDeferred, createTaskQueue, debounce, memoizeAsync, optionalRequire, rateLimit, retry, runInBatches, runInSeries, runWithConcurrency, settleAll, singletonAsync, sleep, throttle, waterfall, withTimeout };