@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.
- package/LICENSE +1 -1
- package/README.md +79 -43
- package/array/index.cjs +355 -0
- package/array/index.d.ts +317 -0
- package/array/index.mjs +327 -0
- package/async/index.cjs +484 -0
- package/async/index.d.ts +299 -0
- package/async/index.mjs +463 -0
- package/cache/index.cjs +292 -0
- package/cache/index.d.ts +179 -0
- package/cache/index.mjs +290 -0
- package/config/index.cjs +150 -0
- package/config/index.d.ts +88 -0
- package/config/index.mjs +143 -0
- package/context-store/index.cjs +267 -0
- package/context-store/index.d.ts +216 -0
- package/context-store/index.mjs +261 -0
- package/crypto/index.cjs +182 -0
- package/crypto/index.d.ts +187 -0
- package/crypto/index.mjs +166 -0
- package/date/index.cjs +340 -0
- package/date/index.d.ts +214 -0
- package/date/index.mjs +326 -0
- package/decorators/index.cjs +2051 -0
- package/decorators/index.d.ts +708 -0
- package/decorators/index.mjs +2010 -0
- package/dir/index.cjs +417 -0
- package/dir/index.d.ts +219 -0
- package/dir/index.mjs +390 -0
- package/env/index.cjs +745 -0
- package/env/index.d.ts +403 -0
- package/env/index.mjs +742 -0
- package/exception/index.cjs +362 -0
- package/exception/index.d.ts +256 -0
- package/exception/index.mjs +338 -0
- package/fs/index.cjs +287 -0
- package/fs/index.d.ts +229 -0
- package/fs/index.mjs +258 -0
- package/http-status-codes/index.cjs +96 -0
- package/http-status-codes/index.d.ts +291 -0
- package/http-status-codes/index.mjs +94 -0
- package/id/index.cjs +62 -0
- package/id/index.d.ts +61 -0
- package/id/index.mjs +56 -0
- package/index.cjs +218 -0
- package/index.d.ts +51 -0
- package/index.mjs +51 -0
- package/logger/index.cjs +334 -0
- package/logger/index.d.ts +213 -0
- package/logger/index.mjs +313 -0
- package/middleware/index.cjs +177 -0
- package/middleware/index.d.ts +127 -0
- package/middleware/index.mjs +170 -0
- package/obj/index.cjs +305 -0
- package/obj/index.d.ts +160 -0
- package/obj/index.mjs +289 -0
- package/package.json +172 -20
- package/performance/index.cjs +231 -0
- package/performance/index.d.ts +162 -0
- package/performance/index.mjs +225 -0
- package/request/index.cjs +202 -0
- package/request/index.d.ts +265 -0
- package/request/index.mjs +194 -0
- package/response/index.cjs +234 -0
- package/response/index.d.ts +342 -0
- package/response/index.mjs +222 -0
- package/server/index.cjs +1631 -0
- package/server/index.d.ts +809 -0
- package/server/index.mjs +1622 -0
- package/stream/index.cjs +151 -0
- package/stream/index.d.ts +114 -0
- package/stream/index.mjs +144 -0
- package/string/index.cjs +109 -0
- package/string/index.d.ts +126 -0
- package/string/index.mjs +95 -0
- package/type/index.cjs +129 -0
- package/type/index.d.ts +131 -0
- package/type/index.mjs +119 -0
- package/types/index.cjs +34 -0
- package/types/index.d.ts +798 -0
- package/types/index.mjs +32 -0
- package/url/index.cjs +199 -0
- package/url/index.d.ts +166 -0
- package/url/index.mjs +187 -0
- package/validation/index.cjs +259 -0
- package/validation/index.d.ts +209 -0
- package/validation/index.mjs +231 -0
- package/build/index.cjs +0 -7694
- package/build/index.d.ts +0 -5792
- package/build/index.mjs +0 -7386
package/async/index.d.ts
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
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
|
+
/**
|
|
26
|
+
* Delays execution for a specified number of milliseconds.
|
|
27
|
+
*
|
|
28
|
+
* @param {number} ms - The number of milliseconds to sleep.
|
|
29
|
+
* @returns {Promise<void>} A Promise that resolves after the given time.
|
|
30
|
+
*/
|
|
31
|
+
declare function sleep(ms: number): Promise<void>;
|
|
32
|
+
/**
|
|
33
|
+
* Creates a debounced version of a function that delays its execution.
|
|
34
|
+
* Provides `.cancel()` and `.flush()` methods.
|
|
35
|
+
*
|
|
36
|
+
* @template T
|
|
37
|
+
* @param {T} fn - The function to debounce.
|
|
38
|
+
* @param {number} delay - Delay in milliseconds.
|
|
39
|
+
* @returns {T & { cancel: () => void; flush: () => void }} A debounced function.
|
|
40
|
+
*/
|
|
41
|
+
declare function debounce<T extends (...args: any[]) => void>(fn: T, delay: number): {
|
|
42
|
+
(...args: Parameters<T>): void;
|
|
43
|
+
cancel(): void;
|
|
44
|
+
flush(): void;
|
|
45
|
+
} & {
|
|
46
|
+
cancel: () => void;
|
|
47
|
+
flush: () => void;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Creates a throttled version of a function that limits its execution rate.
|
|
51
|
+
* Allows control over leading/trailing invocation.
|
|
52
|
+
*
|
|
53
|
+
* @template T
|
|
54
|
+
* @param {T} fn - The function to throttle.
|
|
55
|
+
* @param {number} limit - Minimum time between calls in milliseconds.
|
|
56
|
+
* @param {{ leading?: boolean, trailing?: boolean }} [opts] - Options for leading/trailing edge throttling.
|
|
57
|
+
* @returns {(...args: Parameters<T>) => void} A throttled function.
|
|
58
|
+
*/
|
|
59
|
+
declare function throttle<T extends (...args: any[]) => void>(fn: T, limit: number, opts?: {
|
|
60
|
+
leading?: boolean;
|
|
61
|
+
trailing?: boolean;
|
|
62
|
+
}): (...args: Parameters<T>) => void;
|
|
63
|
+
/**
|
|
64
|
+
* Retries an asynchronous function a given number of times with optional delay/backoff.
|
|
65
|
+
*
|
|
66
|
+
* @template T
|
|
67
|
+
* @param {() => Promise<T>} fn - The async function to retry.
|
|
68
|
+
* @param {number} [retries=3] - Number of retry attempts.
|
|
69
|
+
* @param {number} [delay=500] - Delay in milliseconds between retries.
|
|
70
|
+
* @param {boolean} [backoff=false] - Use exponential backoff between attempts.
|
|
71
|
+
* @param {(error: unknown, attempt: number) => void} [onRetry] - Callback for each retry attempt.
|
|
72
|
+
* @returns {Promise<T>} The result of the async function if successful.
|
|
73
|
+
* @throws {*} The last encountered error if all retries fail.
|
|
74
|
+
*/
|
|
75
|
+
declare function retry<T>(fn: () => Promise<T>, retries?: number, delay?: number, backoff?: boolean, onRetry?: (error: unknown, attempt: number) => void): Promise<T>;
|
|
76
|
+
/**
|
|
77
|
+
* Wraps a promise and rejects it if it doesn't resolve within the specified timeout.
|
|
78
|
+
*
|
|
79
|
+
* @template T
|
|
80
|
+
* @param {Promise<T>} promise - The original promise.
|
|
81
|
+
* @param {number} ms - Timeout in milliseconds.
|
|
82
|
+
* @param {string} [message="Operation timed out"] - Optional timeout message.
|
|
83
|
+
* @returns {Promise<T>} A promise that resolves or rejects within the timeout.
|
|
84
|
+
*/
|
|
85
|
+
declare function withTimeout<T>(promise: Promise<T>, ms: number, message?: string): Promise<T>;
|
|
86
|
+
/**
|
|
87
|
+
* Executes async tasks in true batches.
|
|
88
|
+
* Each batch runs in parallel, but batches run sequentially.
|
|
89
|
+
* All tasks in a batch start at the same time, next batch waits for full completion.
|
|
90
|
+
* NOTE: For more granular concurrency, use a "queue" or "pooled" approach.
|
|
91
|
+
*
|
|
92
|
+
* @template T
|
|
93
|
+
* @param {Array<() => Promise<T>>} tasks - An array of functions that return Promises.
|
|
94
|
+
* @param {number} limit - Number of tasks to run in parallel per batch.
|
|
95
|
+
* @returns {Promise<T[]>} A promise that resolves to an array of resolved values.
|
|
96
|
+
*/
|
|
97
|
+
declare function runInBatches<T>(tasks: (() => Promise<T>)[], limit: number): Promise<T[]>;
|
|
98
|
+
/**
|
|
99
|
+
* Wraps a function and ensures it is only called once at a time.
|
|
100
|
+
* Calls made while one is in progress will wait for the same Promise.
|
|
101
|
+
* Optionally, new calls can be dropped while in progress (drop=true).
|
|
102
|
+
*
|
|
103
|
+
* @template TArgs
|
|
104
|
+
* @template TResult
|
|
105
|
+
* @param {(...args: TArgs) => Promise<TResult>} fn - The async function to wrap.
|
|
106
|
+
* @param {boolean} [drop=false] - If true, new calls while one is pending are rejected.
|
|
107
|
+
* @returns {(...args: TArgs) => Promise<TResult>} A wrapped function with singleton behavior.
|
|
108
|
+
*/
|
|
109
|
+
declare function singletonAsync<TArgs extends unknown[], TResult>(fn: (...args: TArgs) => Promise<TResult>, drop?: boolean): (...args: TArgs) => Promise<TResult>;
|
|
110
|
+
/**
|
|
111
|
+
* Resolves a list of async tasks in parallel, returning both resolved and rejected results.
|
|
112
|
+
*
|
|
113
|
+
* @template T
|
|
114
|
+
* @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
|
|
115
|
+
* @returns {Promise<PromiseSettledResult<T>[]>} Results including status and value/reason.
|
|
116
|
+
*/
|
|
117
|
+
declare function settleAll<T>(tasks: (() => Promise<T>)[]): Promise<PromiseSettledResult<T>[]>;
|
|
118
|
+
interface TaskQueue {
|
|
119
|
+
<T>(taskFn: () => Promise<T>): Promise<T>;
|
|
120
|
+
pause: () => void;
|
|
121
|
+
resume: () => void;
|
|
122
|
+
readonly length: number;
|
|
123
|
+
readonly isPaused: boolean;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* A simple task queue that executes async tasks with a concurrency limit.
|
|
127
|
+
* Exposes pause, resume, and queue length getters.
|
|
128
|
+
*
|
|
129
|
+
* @param {number} limit - Maximum number of concurrent tasks.
|
|
130
|
+
* @returns {function & { pause: () => void, resume: () => void, length: number, isPaused: boolean }}
|
|
131
|
+
* Enqueue function plus queue controls.
|
|
132
|
+
*/
|
|
133
|
+
declare function createTaskQueue(limit: number): TaskQueue;
|
|
134
|
+
/**
|
|
135
|
+
* Executes async functions sequentially and collects results.
|
|
136
|
+
* Useful when order matters or tasks depend on each other.
|
|
137
|
+
*
|
|
138
|
+
* @template T
|
|
139
|
+
* @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
|
|
140
|
+
* @returns {Promise<T[]>} Array of resolved values.
|
|
141
|
+
*/
|
|
142
|
+
declare function runInSeries<T>(tasks: (() => Promise<T>)[]): Promise<T[]>;
|
|
143
|
+
/**
|
|
144
|
+
* Memoizes an async function, caching results for repeated calls with identical arguments.
|
|
145
|
+
* Optional TTL (time-to-live) for cached entries.
|
|
146
|
+
*
|
|
147
|
+
* @template T Function return type
|
|
148
|
+
* @template Args Function arguments types
|
|
149
|
+
* @param {(...args: Args) => Promise<T>} fn - The async function to memoize
|
|
150
|
+
* @param {object} [options] - Memoization options
|
|
151
|
+
* @param {number} [options.ttl] - Cache TTL in milliseconds (optional)
|
|
152
|
+
* @param {(args: Args) => string} [options.keyFn] - Custom key generator function
|
|
153
|
+
* @returns {(...args: Args) => Promise<T>} Memoized function
|
|
154
|
+
*/
|
|
155
|
+
declare function memoizeAsync<T, Args extends any[]>(fn: (...args: Args) => Promise<T>, options?: {
|
|
156
|
+
ttl?: number;
|
|
157
|
+
keyFn?: (args: Args) => string;
|
|
158
|
+
}): (...args: Args) => Promise<T>;
|
|
159
|
+
/**
|
|
160
|
+
* Creates an abortable version of a promise that can be cancelled using an AbortController.
|
|
161
|
+
*
|
|
162
|
+
* @template T
|
|
163
|
+
* @param {Promise<T>} promise - The promise to make abortable
|
|
164
|
+
* @param {AbortSignal} signal - AbortSignal from AbortController
|
|
165
|
+
* @param {any} [abortValue] - Value to use when rejecting on abort
|
|
166
|
+
* @returns {Promise<T>} Promise that rejects if the signal is aborted
|
|
167
|
+
*/
|
|
168
|
+
declare function abortable<T>(promise: Promise<T>, signal: AbortSignal, abortValue?: any): Promise<T>;
|
|
169
|
+
/**
|
|
170
|
+
* Creates a promise with external resolve/reject functions.
|
|
171
|
+
* Useful for creating promises that can be resolved or rejected from outside.
|
|
172
|
+
*
|
|
173
|
+
* @template T
|
|
174
|
+
* @returns {[Promise<T>, (value: T | PromiseLike<T>) => void, (reason?: any) => void]}
|
|
175
|
+
* Tuple of [promise, resolve, reject]
|
|
176
|
+
*/
|
|
177
|
+
declare function createDeferred<T>(): [Promise<T>, (value: T | PromiseLike<T>) => void, (reason?: any) => void];
|
|
178
|
+
/**
|
|
179
|
+
* Chains a series of async functions, passing the result of each to the next.
|
|
180
|
+
* Similar to function composition but for async functions.
|
|
181
|
+
*
|
|
182
|
+
* @template T
|
|
183
|
+
* @param {Array<(input: any) => Promise<any>>} fns - Array of async functions to compose
|
|
184
|
+
* @returns {(input: any) => Promise<T>} Composed function
|
|
185
|
+
*/
|
|
186
|
+
declare function waterfall<T>(fns: Array<(input: any) => Promise<any>>): (initialValue: any) => Promise<T>;
|
|
187
|
+
/**
|
|
188
|
+
* Creates a rate limiter that ensures functions aren't called more than
|
|
189
|
+
* a specified number of times per interval.
|
|
190
|
+
*
|
|
191
|
+
* @template T
|
|
192
|
+
* @param {(...args: any[]) => Promise<T>} fn - Function to rate limit
|
|
193
|
+
* @param {number} maxCalls - Maximum calls allowed per interval
|
|
194
|
+
* @param {number} interval - Time interval in milliseconds
|
|
195
|
+
* @returns {(...args: any[]) => Promise<T>} Rate limited function
|
|
196
|
+
*/
|
|
197
|
+
declare function rateLimit<T>(fn: (...args: any[]) => Promise<T>, maxCalls: number, interval: number): (...args: any[]) => Promise<T>;
|
|
198
|
+
/**
|
|
199
|
+
* Circuit breaker pattern implementation for protecting against cascading failures.
|
|
200
|
+
* Tracks failures and prevents calling the function when too many failures occur.
|
|
201
|
+
*
|
|
202
|
+
* @param fn - Function to protect with circuit breaker
|
|
203
|
+
* @param options - Circuit breaker options
|
|
204
|
+
* @returns Function wrapped with circuit breaker logic
|
|
205
|
+
*
|
|
206
|
+
* @example
|
|
207
|
+
* ```typescript
|
|
208
|
+
* const protectedFetch = circuitBreaker(
|
|
209
|
+
* async (url) => {
|
|
210
|
+
* const response = await fetch(url);
|
|
211
|
+
* if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
|
|
212
|
+
* return response.json();
|
|
213
|
+
* },
|
|
214
|
+
* {
|
|
215
|
+
* failureThreshold: 3,
|
|
216
|
+
* resetTimeout: 30000,
|
|
217
|
+
* onOpen: () => console.log('Circuit breaker opened'),
|
|
218
|
+
* onClose: () => console.log('Circuit breaker closed')
|
|
219
|
+
* }
|
|
220
|
+
* );
|
|
221
|
+
*
|
|
222
|
+
* // Will throw CircuitBreakerOpenError after failureThreshold consecutive failures
|
|
223
|
+
* try {
|
|
224
|
+
* const data = await protectedFetch('https://api.example.com');
|
|
225
|
+
* } catch (error) {
|
|
226
|
+
* if (error instanceof CircuitBreakerOpenError) {
|
|
227
|
+
* console.log('Service is currently unavailable, please try again later');
|
|
228
|
+
* }
|
|
229
|
+
* }
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
declare class CircuitBreakerOpenError extends Error {
|
|
233
|
+
constructor(message?: string);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Circuit breaker states
|
|
237
|
+
*/
|
|
238
|
+
declare enum CircuitBreakerState {
|
|
239
|
+
CLOSED = "CLOSED",
|
|
240
|
+
OPEN = "OPEN",
|
|
241
|
+
HALF_OPEN = "HALF_OPEN"
|
|
242
|
+
}
|
|
243
|
+
interface CircuitBreakerOptions {
|
|
244
|
+
/** Number of consecutive failures before opening circuit (default: 5) */
|
|
245
|
+
failureThreshold?: number;
|
|
246
|
+
/** Time in milliseconds to wait before trying again (default: 10000) */
|
|
247
|
+
resetTimeout?: number;
|
|
248
|
+
/** Number of successful calls to close the circuit again (default: 1) */
|
|
249
|
+
successThreshold?: number;
|
|
250
|
+
/** Callback when circuit opens */
|
|
251
|
+
onOpen?: () => void;
|
|
252
|
+
/** Callback when circuit closes */
|
|
253
|
+
onClose?: () => void;
|
|
254
|
+
/** Callback when circuit enters half-open state */
|
|
255
|
+
onHalfOpen?: () => void;
|
|
256
|
+
}
|
|
257
|
+
declare function circuitBreaker<T, Args extends any[]>(fn: (...args: Args) => Promise<T>, options?: CircuitBreakerOptions): (...args: Args) => Promise<T>;
|
|
258
|
+
/**
|
|
259
|
+
* Run multiple async tasks with concurrency control.
|
|
260
|
+
*
|
|
261
|
+
* @param tasks - Array of async tasks to run
|
|
262
|
+
* @param options - Concurrency options
|
|
263
|
+
* @returns Promise that resolves when all tasks are complete
|
|
264
|
+
*
|
|
265
|
+
* @example
|
|
266
|
+
* ```typescript
|
|
267
|
+
* const urls = ['https://example.com/1', 'https://example.com/2', many more ];
|
|
268
|
+
*
|
|
269
|
+
* // Process up to 5 requests at a time, with progress reporting
|
|
270
|
+
* const results = await runWithConcurrency(
|
|
271
|
+
* urls.map(url => () => fetch(url).then(res => res.json())),
|
|
272
|
+
* {
|
|
273
|
+
* concurrency: 5,
|
|
274
|
+
* onProgress: (completed, total) => {
|
|
275
|
+
* console.log(`Progress: ${completed}/${total}`);
|
|
276
|
+
* }
|
|
277
|
+
* }
|
|
278
|
+
* );
|
|
279
|
+
* ```
|
|
280
|
+
*/
|
|
281
|
+
declare function runWithConcurrency<T>(tasks: Array<() => Promise<T>>, options?: {
|
|
282
|
+
/** Maximum number of tasks to run at once (default: 3) */
|
|
283
|
+
concurrency?: number;
|
|
284
|
+
/** Called whenever a task completes */
|
|
285
|
+
onProgress?: (completed: number, total: number) => void;
|
|
286
|
+
/** Abort signal to cancel execution */
|
|
287
|
+
signal?: AbortSignal;
|
|
288
|
+
}): Promise<T[]>;
|
|
289
|
+
/**
|
|
290
|
+
* Optionally requires a module, returning null if not found.
|
|
291
|
+
*
|
|
292
|
+
* @template T
|
|
293
|
+
* @param {string} name - The name of the module to require.
|
|
294
|
+
* @returns {T | null} The required module or null if not found.
|
|
295
|
+
*/
|
|
296
|
+
declare function optionalRequire<T = any>(name: string): T | null;
|
|
297
|
+
|
|
298
|
+
export { CircuitBreakerOpenError, CircuitBreakerState, abortable, circuitBreaker, createDeferred, createTaskQueue, debounce, memoizeAsync, optionalRequire, rateLimit, retry, runInBatches, runInSeries, runWithConcurrency, settleAll, singletonAsync, sleep, throttle, waterfall, withTimeout };
|
|
299
|
+
export type { CircuitBreakerOptions, TaskQueue };
|