@catbee/utils 0.0.8-rc.3 → 1.0.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 (129) hide show
  1. package/README.md +3 -2
  2. package/build/index.cjs +6912 -0
  3. package/build/index.d.ts +5284 -0
  4. package/build/index.mjs +6635 -0
  5. package/package.json +13 -292
  6. package/build/cjs/config.d.ts +0 -121
  7. package/build/cjs/config.js +0 -137
  8. package/build/cjs/index.d.ts +0 -26
  9. package/build/cjs/index.js +0 -68
  10. package/build/cjs/servers/server.builder.d.ts +0 -507
  11. package/build/cjs/servers/server.builder.js +0 -658
  12. package/build/cjs/servers/server.d.ts +0 -255
  13. package/build/cjs/servers/server.js +0 -970
  14. package/build/cjs/types/api-response.d.ts +0 -151
  15. package/build/cjs/types/api-response.js +0 -36
  16. package/build/cjs/types/index.d.ts +0 -124
  17. package/build/cjs/types/index.js +0 -25
  18. package/build/cjs/types/server.d.ts +0 -267
  19. package/build/cjs/types/server.js +0 -25
  20. package/build/cjs/utils/array.utils.d.ts +0 -167
  21. package/build/cjs/utils/array.utils.js +0 -363
  22. package/build/cjs/utils/async.utils.d.ts +0 -264
  23. package/build/cjs/utils/async.utils.js +0 -640
  24. package/build/cjs/utils/cache.utils.d.ts +0 -152
  25. package/build/cjs/utils/cache.utils.js +0 -298
  26. package/build/cjs/utils/context-store.utils.d.ts +0 -188
  27. package/build/cjs/utils/context-store.utils.js +0 -297
  28. package/build/cjs/utils/crypto.utils.d.ts +0 -159
  29. package/build/cjs/utils/crypto.utils.js +0 -295
  30. package/build/cjs/utils/date.utils.d.ts +0 -158
  31. package/build/cjs/utils/date.utils.js +0 -395
  32. package/build/cjs/utils/decorators.utils.d.ts +0 -511
  33. package/build/cjs/utils/decorators.utils.js +0 -1035
  34. package/build/cjs/utils/dir.utils.d.ts +0 -195
  35. package/build/cjs/utils/dir.utils.js +0 -500
  36. package/build/cjs/utils/env.utils.d.ts +0 -376
  37. package/build/cjs/utils/env.utils.js +0 -786
  38. package/build/cjs/utils/exception.utils.d.ts +0 -229
  39. package/build/cjs/utils/exception.utils.js +0 -408
  40. package/build/cjs/utils/fs.utils.d.ts +0 -163
  41. package/build/cjs/utils/fs.utils.js +0 -371
  42. package/build/cjs/utils/http-status-codes.d.ts +0 -265
  43. package/build/cjs/utils/http-status-codes.js +0 -297
  44. package/build/cjs/utils/id.utils.d.ts +0 -35
  45. package/build/cjs/utils/id.utils.js +0 -90
  46. package/build/cjs/utils/logger.utils.d.ts +0 -159
  47. package/build/cjs/utils/logger.utils.js +0 -350
  48. package/build/cjs/utils/middleware.utils.d.ts +0 -99
  49. package/build/cjs/utils/middleware.utils.js +0 -243
  50. package/build/cjs/utils/obj.utils.d.ts +0 -123
  51. package/build/cjs/utils/obj.utils.js +0 -428
  52. package/build/cjs/utils/performance.utils.d.ts +0 -135
  53. package/build/cjs/utils/performance.utils.js +0 -280
  54. package/build/cjs/utils/request.utils.d.ts +0 -85
  55. package/build/cjs/utils/request.utils.js +0 -199
  56. package/build/cjs/utils/response.utils.d.ts +0 -162
  57. package/build/cjs/utils/response.utils.js +0 -274
  58. package/build/cjs/utils/stream.utils.d.ts +0 -87
  59. package/build/cjs/utils/stream.utils.js +0 -217
  60. package/build/cjs/utils/string.utils.d.ts +0 -92
  61. package/build/cjs/utils/string.utils.js +0 -178
  62. package/build/cjs/utils/type.utils.d.ts +0 -89
  63. package/build/cjs/utils/type.utils.js +0 -195
  64. package/build/cjs/utils/url.utils.d.ts +0 -140
  65. package/build/cjs/utils/url.utils.js +0 -316
  66. package/build/cjs/utils/validate.utils.d.ts +0 -176
  67. package/build/cjs/utils/validate.utils.js +0 -344
  68. package/build/esm/config.d.ts +0 -121
  69. package/build/esm/config.js +0 -132
  70. package/build/esm/index.d.ts +0 -26
  71. package/build/esm/index.js +0 -49
  72. package/build/esm/servers/server.builder.d.ts +0 -507
  73. package/build/esm/servers/server.builder.js +0 -654
  74. package/build/esm/servers/server.d.ts +0 -255
  75. package/build/esm/servers/server.js +0 -963
  76. package/build/esm/types/api-response.d.ts +0 -151
  77. package/build/esm/types/api-response.js +0 -33
  78. package/build/esm/types/index.d.ts +0 -124
  79. package/build/esm/types/index.js +0 -24
  80. package/build/esm/types/server.d.ts +0 -267
  81. package/build/esm/types/server.js +0 -24
  82. package/build/esm/utils/array.utils.d.ts +0 -167
  83. package/build/esm/utils/array.utils.js +0 -344
  84. package/build/esm/utils/async.utils.d.ts +0 -264
  85. package/build/esm/utils/async.utils.js +0 -619
  86. package/build/esm/utils/cache.utils.d.ts +0 -152
  87. package/build/esm/utils/cache.utils.js +0 -294
  88. package/build/esm/utils/context-store.utils.d.ts +0 -188
  89. package/build/esm/utils/context-store.utils.js +0 -290
  90. package/build/esm/utils/crypto.utils.d.ts +0 -159
  91. package/build/esm/utils/crypto.utils.js +0 -278
  92. package/build/esm/utils/date.utils.d.ts +0 -158
  93. package/build/esm/utils/date.utils.js +0 -383
  94. package/build/esm/utils/decorators.utils.d.ts +0 -511
  95. package/build/esm/utils/decorators.utils.js +0 -1013
  96. package/build/esm/utils/dir.utils.d.ts +0 -195
  97. package/build/esm/utils/dir.utils.js +0 -476
  98. package/build/esm/utils/env.utils.d.ts +0 -376
  99. package/build/esm/utils/env.utils.js +0 -782
  100. package/build/esm/utils/exception.utils.d.ts +0 -229
  101. package/build/esm/utils/exception.utils.js +0 -382
  102. package/build/esm/utils/fs.utils.d.ts +0 -163
  103. package/build/esm/utils/fs.utils.js +0 -348
  104. package/build/esm/utils/http-status-codes.d.ts +0 -265
  105. package/build/esm/utils/http-status-codes.js +0 -294
  106. package/build/esm/utils/id.utils.d.ts +0 -35
  107. package/build/esm/utils/id.utils.js +0 -83
  108. package/build/esm/utils/logger.utils.d.ts +0 -159
  109. package/build/esm/utils/logger.utils.js +0 -304
  110. package/build/esm/utils/middleware.utils.d.ts +0 -99
  111. package/build/esm/utils/middleware.utils.js +0 -235
  112. package/build/esm/utils/obj.utils.d.ts +0 -123
  113. package/build/esm/utils/obj.utils.js +0 -412
  114. package/build/esm/utils/performance.utils.d.ts +0 -135
  115. package/build/esm/utils/performance.utils.js +0 -273
  116. package/build/esm/utils/request.utils.d.ts +0 -85
  117. package/build/esm/utils/request.utils.js +0 -190
  118. package/build/esm/utils/response.utils.d.ts +0 -162
  119. package/build/esm/utils/response.utils.js +0 -261
  120. package/build/esm/utils/stream.utils.d.ts +0 -87
  121. package/build/esm/utils/stream.utils.js +0 -209
  122. package/build/esm/utils/string.utils.d.ts +0 -92
  123. package/build/esm/utils/string.utils.js +0 -164
  124. package/build/esm/utils/type.utils.d.ts +0 -89
  125. package/build/esm/utils/type.utils.js +0 -186
  126. package/build/esm/utils/url.utils.d.ts +0 -140
  127. package/build/esm/utils/url.utils.js +0 -303
  128. package/build/esm/utils/validate.utils.d.ts +0 -176
  129. package/build/esm/utils/validate.utils.js +0 -319
@@ -1,412 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/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
- * Checks whether the object has no own enumerable properties.
26
- *
27
- * @param {Record<any, any>} obj - The object to check.
28
- * @returns {boolean} True if the object is empty, false otherwise.
29
- */
30
- export function isObjEmpty(obj) {
31
- return !!obj && typeof obj === 'object' && Object.keys(obj).length === 0;
32
- }
33
- /**
34
- * Returns a new object with only the specified keys picked.
35
- *
36
- * @template T
37
- * @template K
38
- * @param {T} obj - The source object.
39
- * @param {K[]} keys - Keys to pick from the object.
40
- * @returns {Pick<T, K>} New object with picked keys.
41
- */
42
- export function pick(obj, keys) {
43
- return Object.fromEntries(keys.map(key => [key, obj[key]]));
44
- }
45
- /**
46
- * Returns a new object with the specified keys omitted.
47
- *
48
- * @template T
49
- * @template K
50
- * @param {T} obj - The source object.
51
- * @param {K[]} keys - Keys to omit from the object.
52
- * @returns {Omit<T, K>} New object without omitted keys.
53
- */
54
- export function omit(obj, keys) {
55
- return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key)));
56
- }
57
- /**
58
- * Deeply merges multiple objects into the target object (mutates and returns the target object, not pure).
59
- *
60
- * @template T
61
- * @param {T} target - The object to merge into (will be mutated).
62
- * @param {...any[]} sources - The objects to merge from.
63
- * @returns {T} The merged object (same as target).
64
- */
65
- export function deepObjMerge(target, ...sources) {
66
- if (!sources.length)
67
- return target;
68
- const seen = new WeakMap();
69
- seen.set(target, target);
70
- for (const s of sources) {
71
- if (s && typeof s === 'object') {
72
- seen.set(s, target);
73
- }
74
- }
75
- function deepClone(value) {
76
- if (value === null || typeof value !== 'object')
77
- return value;
78
- if (seen.has(value))
79
- return seen.get(value);
80
- // Date
81
- if (value instanceof Date) {
82
- return new Date(value.getTime());
83
- }
84
- // Array
85
- if (Array.isArray(value)) {
86
- const clone = [];
87
- seen.set(value, clone);
88
- value.forEach((item, i) => (clone[i] = deepClone(item)));
89
- return clone;
90
- }
91
- // Set
92
- if (value instanceof Set) {
93
- const clone = new Set();
94
- seen.set(value, clone);
95
- value.forEach(item => clone.add(deepClone(item)));
96
- return clone;
97
- }
98
- // Map
99
- if (value instanceof Map) {
100
- const clone = new Map();
101
- seen.set(value, clone);
102
- value.forEach((val, key) => clone.set(key, deepClone(val)));
103
- return clone;
104
- }
105
- // RegExp
106
- if (value instanceof RegExp) {
107
- return new RegExp(value.source, value.flags);
108
- }
109
- // ArrayBuffer
110
- if (value instanceof ArrayBuffer) {
111
- return value.slice(0);
112
- }
113
- // TypedArrays
114
- if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
115
- const typed = value; // cast for TS
116
- const ctor = typed.constructor;
117
- // List of standard TypedArray constructors
118
- const typedArrayCtors = [
119
- Int8Array,
120
- Uint8Array,
121
- Uint8ClampedArray,
122
- Int16Array,
123
- Uint16Array,
124
- Int32Array,
125
- Uint32Array,
126
- Float32Array,
127
- Float64Array,
128
- BigInt64Array,
129
- BigUint64Array
130
- ].filter(Boolean); // filter out undefined (for environments without BigInt)
131
- const typedArrayCtorSet = new Set(typedArrayCtors);
132
- if (typeof ctor === 'function' && typedArrayCtorSet.has(ctor)) {
133
- // Defensive: ensure buffer is an ArrayBuffer and slice is available
134
- const buffer = typed.buffer && typeof typed.buffer.slice === 'function' ? typed.buffer.slice(0) : typed.buffer;
135
- const clone = new ctor(buffer, typed.byteOffset, typed.length);
136
- seen.set(value, clone);
137
- return clone;
138
- }
139
- else if (typeof typed.slice === 'function') {
140
- // Fallback: try using slice if available (e.g., Node.js Buffer)
141
- const clone = typed.slice();
142
- seen.set(value, clone);
143
- return clone;
144
- }
145
- else {
146
- // Could not safely clone, throw an error for better debugging
147
- throw new Error('Cannot deep clone unknown TypedArray type: ' + (typed && typed.constructor && typed.constructor.name));
148
- }
149
- }
150
- const clone = Object.create(Object.getPrototypeOf(value));
151
- seen.set(value, clone);
152
- Reflect.ownKeys(value).forEach(key => {
153
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
154
- if (descriptor.get || descriptor.set) {
155
- Object.defineProperty(clone, key, descriptor);
156
- }
157
- else {
158
- clone[key] = deepClone(value[key]);
159
- }
160
- });
161
- return clone;
162
- }
163
- function mergeProp(target, source, key) {
164
- const targetValue = target[key];
165
- const sourceValue = source[key];
166
- // Ignore undefined in source
167
- if (sourceValue === undefined)
168
- return;
169
- // Primitives → overwrite directly
170
- if (sourceValue === null || typeof sourceValue !== 'object') {
171
- target[key] = sourceValue;
172
- return;
173
- }
174
- // Arrays → replace (lodash behavior)
175
- if (Array.isArray(sourceValue)) {
176
- target[key] = deepClone(sourceValue);
177
- return;
178
- }
179
- // Special cloneable objects
180
- if (sourceValue instanceof Date ||
181
- sourceValue instanceof RegExp ||
182
- sourceValue instanceof Set ||
183
- sourceValue instanceof Map ||
184
- sourceValue instanceof ArrayBuffer ||
185
- (ArrayBuffer.isView(sourceValue) && !(sourceValue instanceof DataView))) {
186
- target[key] = deepClone(sourceValue);
187
- return;
188
- }
189
- // Plain objects → recursive merge
190
- if (isPlainObject(sourceValue) && isPlainObject(targetValue)) {
191
- for (const k of Reflect.ownKeys(sourceValue)) {
192
- mergeProp(targetValue, sourceValue, k);
193
- }
194
- return;
195
- }
196
- // Default → overwrite with clone
197
- target[key] = deepClone(sourceValue);
198
- }
199
- for (const source of sources) {
200
- if (source == null)
201
- continue;
202
- for (const key of Reflect.ownKeys(source)) {
203
- mergeProp(target, source, key);
204
- }
205
- }
206
- return target;
207
- }
208
- /**
209
- * Checks if a value is a plain object (i.e., not an array, null, or a built-in object).
210
- *
211
- * @param value - The value to check.
212
- * @returns True if the value is a plain object, false otherwise.
213
- */
214
- export function isPlainObject(value) {
215
- if (typeof value !== 'object' || value === null)
216
- return false;
217
- if (Array.isArray(value))
218
- return false;
219
- const proto = Object.getPrototypeOf(value);
220
- return proto === Object.prototype || proto === null;
221
- }
222
- /**
223
- * Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ "a.b": 1 }`).
224
- *
225
- * @template T
226
- * @param {T} obj - The object to flatten.
227
- * @param {string} [prefix=""] - Optional prefix for nested keys (used internally).
228
- * @returns {Record<string, any>} A new object with flattened keys.
229
- */
230
- export function flattenObject(obj, prefix = '') {
231
- return Object.entries(obj).reduce((acc, [key, value]) => {
232
- const newKey = prefix ? `${prefix}.${key}` : key;
233
- if (value && typeof value === 'object' && !Array.isArray(value)) {
234
- Object.assign(acc, flattenObject(value, newKey));
235
- }
236
- else {
237
- acc[newKey] = value;
238
- }
239
- return acc;
240
- }, {});
241
- }
242
- /**
243
- * Safely gets the value of a deeply nested key in an object using dot/bracket notation path.
244
- *
245
- * @template T
246
- * @param {T} obj - The object to extract from.
247
- * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').
248
- * @returns {any} The value at the given path, or undefined if not found.
249
- */
250
- export function getValueByPath(obj, path) {
251
- if (!obj || typeof obj !== 'object')
252
- return undefined;
253
- // Convert path like "a.b[0].c" into ["a", "b", "0", "c"]
254
- const parts = path
255
- .replace(/\[(\d+)\]/g, '.$1') // convert [0] to .0
256
- .split('.')
257
- .filter(Boolean); // remove empty strings
258
- return parts.reduce((acc, key) => acc?.[key], obj);
259
- }
260
- /**
261
- * Sets a value at a deeply nested key in an object using dot/bracket notation path.
262
- * Creates intermediate objects and arrays as needed.
263
- *
264
- * @template T
265
- * @param {T} obj - The object to modify.
266
- * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').
267
- * @param {any} value - The value to set at the path.
268
- * @returns {T} The modified object.
269
- */
270
- export function setValueByPath(obj, path, value) {
271
- if (!obj || typeof obj !== 'object')
272
- return obj;
273
- // Convert path like "a.b[0].c" into ["a", "b", "0", "c"]
274
- const parts = path
275
- .replace(/\[(\d+)\]/g, '.$1') // convert [0] to .0
276
- .split('.')
277
- .filter(Boolean); // remove empty strings
278
- // Handle empty path
279
- if (parts.length === 0)
280
- return obj;
281
- let current = obj;
282
- // Navigate to the parent of the target property
283
- for (let i = 0; i < parts.length - 1; i++) {
284
- const key = parts[i];
285
- const isArrayIndex = !isNaN(Number(parts[i + 1]));
286
- if (current[key] === undefined) {
287
- // Create intermediate object or array based on next key type
288
- current[key] = isArrayIndex ? [] : {};
289
- }
290
- current = current[key];
291
- }
292
- // Set the value at the final key
293
- const finalKey = parts[parts.length - 1];
294
- current[finalKey] = value;
295
- return obj;
296
- }
297
- /**
298
- * Performs a deep equality check between two objects.
299
- *
300
- * @param {any} a - First value to compare.
301
- * @param {any} b - Second value to compare.
302
- * @returns {boolean} True if values are deeply equal.
303
- */
304
- export function isEqual(a, b) {
305
- // Check if primitives or references to the same object
306
- if (a === b)
307
- return true;
308
- // Check if either is null/undefined or not an object
309
- if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {
310
- return false;
311
- }
312
- // Handle Date objects
313
- if (a instanceof Date && b instanceof Date) {
314
- return a.getTime() === b.getTime();
315
- }
316
- // If one is Date but the other isn't
317
- if (a instanceof Date || b instanceof Date) {
318
- return false;
319
- }
320
- // Handle arrays
321
- if (Array.isArray(a) && Array.isArray(b)) {
322
- if (a.length !== b.length)
323
- return false;
324
- // Check each element
325
- for (let i = 0; i < a.length; i++) {
326
- if (!isEqual(a[i], b[i]))
327
- return false;
328
- }
329
- return true;
330
- }
331
- // If one is Array but the other isn't
332
- if (Array.isArray(a) || Array.isArray(b)) {
333
- return false;
334
- }
335
- // Compare object keys
336
- const keysA = Object.keys(a);
337
- const keysB = Object.keys(b);
338
- if (keysA.length !== keysB.length)
339
- return false;
340
- // Check if every key in A exists in B and has the same value
341
- return keysA.every(key => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));
342
- }
343
- /**
344
- * Filters object properties based on a predicate function.
345
- *
346
- * @template T
347
- * @param {T} obj - The source object.
348
- * @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.
349
- * @returns {Partial<T>} New object with filtered properties.
350
- */
351
- export function filterObject(obj, predicate) {
352
- return Object.fromEntries(Object.entries(obj).filter(([key, value]) => predicate(value, key, obj)));
353
- }
354
- /**
355
- * Maps object values to new values using a mapping function.
356
- *
357
- * @template T
358
- * @template U
359
- * @param {T} obj - The source object.
360
- * @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.
361
- * @returns {Record<keyof T, U>} New object with mapped values.
362
- */
363
- export function mapObject(obj, mapFn) {
364
- return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, mapFn(value, key, obj)]));
365
- }
366
- /**
367
- * Recursively freezes an object and all its properties.
368
- * Makes an object immutable.
369
- *
370
- * @template T
371
- * @param {T} obj - The object to freeze.
372
- * @returns {Readonly<T>} The frozen object.
373
- */
374
- export function deepFreeze(obj) {
375
- // Freeze primitive properties
376
- Object.freeze(obj);
377
- // Recursively freeze nested objects
378
- for (const prop of Object.getOwnPropertyNames(obj)) {
379
- const value = obj[prop];
380
- if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
381
- deepFreeze(value);
382
- }
383
- }
384
- return obj;
385
- }
386
- /**
387
- * Safely checks if a value is an object (not null, not array).
388
- *
389
- * @param {unknown} value - Value to check.
390
- * @returns {boolean} True if value is a non-null, non-array object.
391
- */
392
- export function isObject(value) {
393
- return value !== null && typeof value === 'object' && !Array.isArray(value);
394
- }
395
- /**
396
- * Gets all paths in an object using dot notation.
397
- *
398
- * @param {Record<string, any>} obj - Object to analyze.
399
- * @param {string} [parentPath=""] - Internal param for recursion.
400
- * @returns {string[]} Array of all paths in dot notation.
401
- */
402
- export function getAllPaths(obj, parentPath = '') {
403
- if (!isObject(obj))
404
- return [];
405
- return Object.entries(obj).flatMap(([key, value]) => {
406
- const currentPath = parentPath ? `${parentPath}.${key}` : key;
407
- if (isObject(value)) {
408
- return [currentPath, ...getAllPaths(value, currentPath)];
409
- }
410
- return [currentPath];
411
- });
412
- }
@@ -1,135 +0,0 @@
1
- /**
2
- * Options for timing function execution.
3
- */
4
- export interface TimingOptions {
5
- /** Optional label for the timing (defaults to function name) */
6
- label?: string;
7
- /** Whether to log the timing (default: false) */
8
- log?: boolean;
9
- /** Log level to use if logging is enabled (default: 'debug') */
10
- logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error';
11
- }
12
- /**
13
- * Result of a timing operation.
14
- */
15
- export interface TimingResult {
16
- /** Duration in milliseconds */
17
- durationMs: number;
18
- /** Duration in seconds */
19
- durationSec: number;
20
- /** Start timestamp */
21
- startTime: number;
22
- /** End timestamp */
23
- endTime: number;
24
- /** Label used for the timing */
25
- label: string;
26
- }
27
- /**
28
- * Measure the execution time of a synchronous function.
29
- *
30
- * @param fn - Function to measure
31
- * @param options - Timing options
32
- * @returns Result containing the return value and timing information
33
- *
34
- * @example
35
- * ```typescript
36
- * const { result, timing } = timeSync(() => {
37
- * // Some expensive operation
38
- * return computeResult();
39
- * }, { label: 'Computation', log: true });
40
- *
41
- * console.log(`Result: ${result}, took ${timing.durationMs}ms`);
42
- * ```
43
- */
44
- export declare function timeSync<T>(fn: () => T, options?: TimingOptions): {
45
- result: T;
46
- timing: TimingResult;
47
- };
48
- /**
49
- * Measure the execution time of an asynchronous function.
50
- *
51
- * @param fn - Async function to measure
52
- * @param options - Timing options
53
- * @returns Promise resolving to result and timing information
54
- *
55
- * @example
56
- * ```typescript
57
- * const { result, timing } = await timeAsync(async () => {
58
- * // Some expensive async operation
59
- * const data = await fetchData();
60
- * return processData(data);
61
- * }, { label: 'API Request', log: true });
62
- *
63
- * console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`);
64
- * ```
65
- */
66
- export declare function timeAsync<T>(fn: () => Promise<T>, options?: TimingOptions): Promise<{
67
- result: T;
68
- timing: TimingResult;
69
- }>;
70
- /**
71
- * Create a timing decorator for class methods.
72
- *
73
- * @param options - Timing options
74
- * @returns Method decorator
75
- *
76
- * @example
77
- * ```typescript
78
- * class DataService {
79
- * @timed({ log: true, logLevel: 'info' })
80
- * async fetchData() {
81
- * // ...implementation
82
- * }
83
- * }
84
- * ```
85
- */
86
- export declare function timed(options?: TimingOptions): (target: any, propertyKeyOrContext: string | symbol | any, descriptor?: PropertyDescriptor) => void;
87
- /**
88
- * Memoize function results with optional TTL and max cache size.
89
- *
90
- * @param fn - Function to memoize
91
- * @param options - Memoization options
92
- * @returns Memoized function
93
- *
94
- * @example
95
- * ```typescript
96
- * // Cache results for 30 seconds, with a maximum of 100 entries
97
- * const cachedFetch = memoize(
98
- * async (url) => {
99
- * const response = await fetch(url);
100
- * return response.json();
101
- * },
102
- * { ttl: 30000, maxSize: 100, cacheKey: (url) => url }
103
- * );
104
- * ```
105
- */
106
- export declare function memoize<T, Args extends any[]>(fn: (...args: Args) => T, options?: {
107
- /** Time-to-live in milliseconds (default: indefinite) */
108
- ttl?: number;
109
- /** Maximum cache size (default: unlimited) */
110
- maxSize?: number;
111
- /** Function to generate a cache key from arguments */
112
- cacheKey?: (...args: Args) => string;
113
- /** Auto-cleanup interval in milliseconds (default: disabled) */
114
- autoCleanupMs?: number;
115
- }): (...args: Args) => T;
116
- /**
117
- * Track memory usage for a function execution.
118
- *
119
- * @param fn - Function to track
120
- * @param options - Memory tracking options
121
- * @returns Result and memory usage information
122
- */
123
- export declare function trackMemoryUsage<T>(fn: () => T, options?: {
124
- /** Whether to log the memory usage (default: false) */
125
- log?: boolean;
126
- /** Label for the memory tracking (default: function name) */
127
- label?: string;
128
- }): {
129
- result: T;
130
- memoryUsage: {
131
- before: NodeJS.MemoryUsage;
132
- after: NodeJS.MemoryUsage;
133
- diff: Record<string, number>;
134
- };
135
- };