@catbee/utils 0.0.7 → 0.0.8-next.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.
Files changed (285) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +26 -1
  3. package/build/index.cjs +6888 -0
  4. package/build/index.d.ts +5242 -0
  5. package/build/index.mjs +6615 -0
  6. package/package.json +26 -99
  7. package/build/esm/config.d.ts +0 -122
  8. package/build/esm/config.js +0 -133
  9. package/build/esm/config.js.map +0 -1
  10. package/build/esm/index.d.ts +0 -27
  11. package/build/esm/index.js +0 -50
  12. package/build/esm/index.js.map +0 -1
  13. package/build/esm/servers/server.builder.d.ts +0 -508
  14. package/build/esm/servers/server.builder.js +0 -702
  15. package/build/esm/servers/server.builder.js.map +0 -1
  16. package/build/esm/servers/server.d.ts +0 -256
  17. package/build/esm/servers/server.js +0 -1201
  18. package/build/esm/servers/server.js.map +0 -1
  19. package/build/esm/types/api-response.d.ts +0 -152
  20. package/build/esm/types/api-response.js +0 -34
  21. package/build/esm/types/api-response.js.map +0 -1
  22. package/build/esm/types/index.d.ts +0 -125
  23. package/build/esm/types/index.js +0 -25
  24. package/build/esm/types/index.js.map +0 -1
  25. package/build/esm/types/server.d.ts +0 -268
  26. package/build/esm/types/server.js +0 -25
  27. package/build/esm/types/server.js.map +0 -1
  28. package/build/esm/utils/array.utils.d.ts +0 -168
  29. package/build/esm/utils/array.utils.js +0 -382
  30. package/build/esm/utils/array.utils.js.map +0 -1
  31. package/build/esm/utils/async.utils.d.ts +0 -265
  32. package/build/esm/utils/async.utils.js +0 -896
  33. package/build/esm/utils/async.utils.js.map +0 -1
  34. package/build/esm/utils/cache.utils.d.ts +0 -153
  35. package/build/esm/utils/cache.utils.js +0 -499
  36. package/build/esm/utils/cache.utils.js.map +0 -1
  37. package/build/esm/utils/context-store.utils.d.ts +0 -189
  38. package/build/esm/utils/context-store.utils.js +0 -307
  39. package/build/esm/utils/context-store.utils.js.map +0 -1
  40. package/build/esm/utils/crypto.utils.d.ts +0 -160
  41. package/build/esm/utils/crypto.utils.js +0 -375
  42. package/build/esm/utils/crypto.utils.js.map +0 -1
  43. package/build/esm/utils/date.utils.d.ts +0 -159
  44. package/build/esm/utils/date.utils.js +0 -389
  45. package/build/esm/utils/date.utils.js.map +0 -1
  46. package/build/esm/utils/decorators.utils.d.ts +0 -315
  47. package/build/esm/utils/decorators.utils.js +0 -666
  48. package/build/esm/utils/decorators.utils.js.map +0 -1
  49. package/build/esm/utils/dir.utils.d.ts +0 -196
  50. package/build/esm/utils/dir.utils.js +0 -998
  51. package/build/esm/utils/dir.utils.js.map +0 -1
  52. package/build/esm/utils/env.utils.d.ts +0 -377
  53. package/build/esm/utils/env.utils.js +0 -873
  54. package/build/esm/utils/env.utils.js.map +0 -1
  55. package/build/esm/utils/exception.utils.d.ts +0 -230
  56. package/build/esm/utils/exception.utils.js +0 -559
  57. package/build/esm/utils/exception.utils.js.map +0 -1
  58. package/build/esm/utils/fs.utils.d.ts +0 -164
  59. package/build/esm/utils/fs.utils.js +0 -580
  60. package/build/esm/utils/fs.utils.js.map +0 -1
  61. package/build/esm/utils/http-status-codes.d.ts +0 -266
  62. package/build/esm/utils/http-status-codes.js +0 -295
  63. package/build/esm/utils/http-status-codes.js.map +0 -1
  64. package/build/esm/utils/id.utils.d.ts +0 -36
  65. package/build/esm/utils/id.utils.js +0 -87
  66. package/build/esm/utils/id.utils.js.map +0 -1
  67. package/build/esm/utils/logger.utils.d.ts +0 -160
  68. package/build/esm/utils/logger.utils.js +0 -341
  69. package/build/esm/utils/logger.utils.js.map +0 -1
  70. package/build/esm/utils/middleware.utils.d.ts +0 -83
  71. package/build/esm/utils/middleware.utils.js +0 -206
  72. package/build/esm/utils/middleware.utils.js.map +0 -1
  73. package/build/esm/utils/obj.utils.d.ts +0 -124
  74. package/build/esm/utils/obj.utils.js +0 -519
  75. package/build/esm/utils/obj.utils.js.map +0 -1
  76. package/build/esm/utils/performance.utils.d.ts +0 -136
  77. package/build/esm/utils/performance.utils.js +0 -376
  78. package/build/esm/utils/performance.utils.js.map +0 -1
  79. package/build/esm/utils/request.utils.d.ts +0 -86
  80. package/build/esm/utils/request.utils.js +0 -223
  81. package/build/esm/utils/request.utils.js.map +0 -1
  82. package/build/esm/utils/response.utils.d.ts +0 -163
  83. package/build/esm/utils/response.utils.js +0 -284
  84. package/build/esm/utils/response.utils.js.map +0 -1
  85. package/build/esm/utils/stream.utils.d.ts +0 -88
  86. package/build/esm/utils/stream.utils.js +0 -284
  87. package/build/esm/utils/stream.utils.js.map +0 -1
  88. package/build/esm/utils/string.utils.d.ts +0 -93
  89. package/build/esm/utils/string.utils.js +0 -169
  90. package/build/esm/utils/string.utils.js.map +0 -1
  91. package/build/esm/utils/type.utils.d.ts +0 -90
  92. package/build/esm/utils/type.utils.js +0 -190
  93. package/build/esm/utils/type.utils.js.map +0 -1
  94. package/build/esm/utils/url.utils.d.ts +0 -141
  95. package/build/esm/utils/url.utils.js +0 -381
  96. package/build/esm/utils/url.utils.js.map +0 -1
  97. package/build/esm/utils/validate.utils.d.ts +0 -177
  98. package/build/esm/utils/validate.utils.js +0 -336
  99. package/build/esm/utils/validate.utils.js.map +0 -1
  100. package/build/esnext/config.d.ts +0 -122
  101. package/build/esnext/config.js +0 -133
  102. package/build/esnext/config.js.map +0 -1
  103. package/build/esnext/index.d.ts +0 -27
  104. package/build/esnext/index.js +0 -50
  105. package/build/esnext/index.js.map +0 -1
  106. package/build/esnext/servers/server.builder.d.ts +0 -508
  107. package/build/esnext/servers/server.builder.js +0 -657
  108. package/build/esnext/servers/server.builder.js.map +0 -1
  109. package/build/esnext/servers/server.d.ts +0 -256
  110. package/build/esnext/servers/server.js +0 -908
  111. package/build/esnext/servers/server.js.map +0 -1
  112. package/build/esnext/types/api-response.d.ts +0 -152
  113. package/build/esnext/types/api-response.js +0 -34
  114. package/build/esnext/types/api-response.js.map +0 -1
  115. package/build/esnext/types/index.d.ts +0 -125
  116. package/build/esnext/types/index.js +0 -25
  117. package/build/esnext/types/index.js.map +0 -1
  118. package/build/esnext/types/server.d.ts +0 -268
  119. package/build/esnext/types/server.js +0 -25
  120. package/build/esnext/types/server.js.map +0 -1
  121. package/build/esnext/utils/array.utils.d.ts +0 -168
  122. package/build/esnext/utils/array.utils.js +0 -345
  123. package/build/esnext/utils/array.utils.js.map +0 -1
  124. package/build/esnext/utils/async.utils.d.ts +0 -265
  125. package/build/esnext/utils/async.utils.js +0 -620
  126. package/build/esnext/utils/async.utils.js.map +0 -1
  127. package/build/esnext/utils/cache.utils.d.ts +0 -153
  128. package/build/esnext/utils/cache.utils.js +0 -293
  129. package/build/esnext/utils/cache.utils.js.map +0 -1
  130. package/build/esnext/utils/context-store.utils.d.ts +0 -189
  131. package/build/esnext/utils/context-store.utils.js +0 -289
  132. package/build/esnext/utils/context-store.utils.js.map +0 -1
  133. package/build/esnext/utils/crypto.utils.d.ts +0 -160
  134. package/build/esnext/utils/crypto.utils.js +0 -276
  135. package/build/esnext/utils/crypto.utils.js.map +0 -1
  136. package/build/esnext/utils/date.utils.d.ts +0 -159
  137. package/build/esnext/utils/date.utils.js +0 -384
  138. package/build/esnext/utils/date.utils.js.map +0 -1
  139. package/build/esnext/utils/decorators.utils.d.ts +0 -315
  140. package/build/esnext/utils/decorators.utils.js +0 -504
  141. package/build/esnext/utils/decorators.utils.js.map +0 -1
  142. package/build/esnext/utils/dir.utils.d.ts +0 -196
  143. package/build/esnext/utils/dir.utils.js +0 -477
  144. package/build/esnext/utils/dir.utils.js.map +0 -1
  145. package/build/esnext/utils/env.utils.d.ts +0 -377
  146. package/build/esnext/utils/env.utils.js +0 -785
  147. package/build/esnext/utils/env.utils.js.map +0 -1
  148. package/build/esnext/utils/exception.utils.d.ts +0 -230
  149. package/build/esnext/utils/exception.utils.js +0 -381
  150. package/build/esnext/utils/exception.utils.js.map +0 -1
  151. package/build/esnext/utils/fs.utils.d.ts +0 -164
  152. package/build/esnext/utils/fs.utils.js +0 -349
  153. package/build/esnext/utils/fs.utils.js.map +0 -1
  154. package/build/esnext/utils/http-status-codes.d.ts +0 -266
  155. package/build/esnext/utils/http-status-codes.js +0 -295
  156. package/build/esnext/utils/http-status-codes.js.map +0 -1
  157. package/build/esnext/utils/id.utils.d.ts +0 -36
  158. package/build/esnext/utils/id.utils.js +0 -84
  159. package/build/esnext/utils/id.utils.js.map +0 -1
  160. package/build/esnext/utils/logger.utils.d.ts +0 -160
  161. package/build/esnext/utils/logger.utils.js +0 -300
  162. package/build/esnext/utils/logger.utils.js.map +0 -1
  163. package/build/esnext/utils/middleware.utils.d.ts +0 -83
  164. package/build/esnext/utils/middleware.utils.js +0 -199
  165. package/build/esnext/utils/middleware.utils.js.map +0 -1
  166. package/build/esnext/utils/obj.utils.d.ts +0 -124
  167. package/build/esnext/utils/obj.utils.js +0 -413
  168. package/build/esnext/utils/obj.utils.js.map +0 -1
  169. package/build/esnext/utils/performance.utils.d.ts +0 -136
  170. package/build/esnext/utils/performance.utils.js +0 -271
  171. package/build/esnext/utils/performance.utils.js.map +0 -1
  172. package/build/esnext/utils/request.utils.d.ts +0 -86
  173. package/build/esnext/utils/request.utils.js +0 -186
  174. package/build/esnext/utils/request.utils.js.map +0 -1
  175. package/build/esnext/utils/response.utils.d.ts +0 -163
  176. package/build/esnext/utils/response.utils.js +0 -247
  177. package/build/esnext/utils/response.utils.js.map +0 -1
  178. package/build/esnext/utils/stream.utils.d.ts +0 -88
  179. package/build/esnext/utils/stream.utils.js +0 -210
  180. package/build/esnext/utils/stream.utils.js.map +0 -1
  181. package/build/esnext/utils/string.utils.d.ts +0 -93
  182. package/build/esnext/utils/string.utils.js +0 -165
  183. package/build/esnext/utils/string.utils.js.map +0 -1
  184. package/build/esnext/utils/type.utils.d.ts +0 -90
  185. package/build/esnext/utils/type.utils.js +0 -187
  186. package/build/esnext/utils/type.utils.js.map +0 -1
  187. package/build/esnext/utils/url.utils.d.ts +0 -141
  188. package/build/esnext/utils/url.utils.js +0 -304
  189. package/build/esnext/utils/url.utils.js.map +0 -1
  190. package/build/esnext/utils/validate.utils.d.ts +0 -177
  191. package/build/esnext/utils/validate.utils.js +0 -320
  192. package/build/esnext/utils/validate.utils.js.map +0 -1
  193. package/build/src/config.d.ts +0 -122
  194. package/build/src/config.js +0 -138
  195. package/build/src/config.js.map +0 -1
  196. package/build/src/index.d.ts +0 -27
  197. package/build/src/index.js +0 -69
  198. package/build/src/index.js.map +0 -1
  199. package/build/src/servers/server.builder.d.ts +0 -508
  200. package/build/src/servers/server.builder.js +0 -661
  201. package/build/src/servers/server.builder.js.map +0 -1
  202. package/build/src/servers/server.d.ts +0 -256
  203. package/build/src/servers/server.js +0 -948
  204. package/build/src/servers/server.js.map +0 -1
  205. package/build/src/types/api-response.d.ts +0 -152
  206. package/build/src/types/api-response.js +0 -37
  207. package/build/src/types/api-response.js.map +0 -1
  208. package/build/src/types/index.d.ts +0 -125
  209. package/build/src/types/index.js +0 -26
  210. package/build/src/types/index.js.map +0 -1
  211. package/build/src/types/server.d.ts +0 -268
  212. package/build/src/types/server.js +0 -26
  213. package/build/src/types/server.js.map +0 -1
  214. package/build/src/utils/array.utils.d.ts +0 -168
  215. package/build/src/utils/array.utils.js +0 -364
  216. package/build/src/utils/array.utils.js.map +0 -1
  217. package/build/src/utils/async.utils.d.ts +0 -265
  218. package/build/src/utils/async.utils.js +0 -641
  219. package/build/src/utils/async.utils.js.map +0 -1
  220. package/build/src/utils/cache.utils.d.ts +0 -153
  221. package/build/src/utils/cache.utils.js +0 -297
  222. package/build/src/utils/cache.utils.js.map +0 -1
  223. package/build/src/utils/context-store.utils.d.ts +0 -189
  224. package/build/src/utils/context-store.utils.js +0 -296
  225. package/build/src/utils/context-store.utils.js.map +0 -1
  226. package/build/src/utils/crypto.utils.d.ts +0 -160
  227. package/build/src/utils/crypto.utils.js +0 -293
  228. package/build/src/utils/crypto.utils.js.map +0 -1
  229. package/build/src/utils/date.utils.d.ts +0 -159
  230. package/build/src/utils/date.utils.js +0 -396
  231. package/build/src/utils/date.utils.js.map +0 -1
  232. package/build/src/utils/decorators.utils.d.ts +0 -315
  233. package/build/src/utils/decorators.utils.js +0 -516
  234. package/build/src/utils/decorators.utils.js.map +0 -1
  235. package/build/src/utils/dir.utils.d.ts +0 -196
  236. package/build/src/utils/dir.utils.js +0 -501
  237. package/build/src/utils/dir.utils.js.map +0 -1
  238. package/build/src/utils/env.utils.d.ts +0 -377
  239. package/build/src/utils/env.utils.js +0 -789
  240. package/build/src/utils/env.utils.js.map +0 -1
  241. package/build/src/utils/exception.utils.d.ts +0 -230
  242. package/build/src/utils/exception.utils.js +0 -407
  243. package/build/src/utils/exception.utils.js.map +0 -1
  244. package/build/src/utils/fs.utils.d.ts +0 -164
  245. package/build/src/utils/fs.utils.js +0 -372
  246. package/build/src/utils/fs.utils.js.map +0 -1
  247. package/build/src/utils/http-status-codes.d.ts +0 -266
  248. package/build/src/utils/http-status-codes.js +0 -298
  249. package/build/src/utils/http-status-codes.js.map +0 -1
  250. package/build/src/utils/id.utils.d.ts +0 -36
  251. package/build/src/utils/id.utils.js +0 -91
  252. package/build/src/utils/id.utils.js.map +0 -1
  253. package/build/src/utils/logger.utils.d.ts +0 -160
  254. package/build/src/utils/logger.utils.js +0 -346
  255. package/build/src/utils/logger.utils.js.map +0 -1
  256. package/build/src/utils/middleware.utils.d.ts +0 -83
  257. package/build/src/utils/middleware.utils.js +0 -206
  258. package/build/src/utils/middleware.utils.js.map +0 -1
  259. package/build/src/utils/obj.utils.d.ts +0 -124
  260. package/build/src/utils/obj.utils.js +0 -429
  261. package/build/src/utils/obj.utils.js.map +0 -1
  262. package/build/src/utils/performance.utils.d.ts +0 -136
  263. package/build/src/utils/performance.utils.js +0 -278
  264. package/build/src/utils/performance.utils.js.map +0 -1
  265. package/build/src/utils/request.utils.d.ts +0 -86
  266. package/build/src/utils/request.utils.js +0 -195
  267. package/build/src/utils/request.utils.js.map +0 -1
  268. package/build/src/utils/response.utils.d.ts +0 -163
  269. package/build/src/utils/response.utils.js +0 -260
  270. package/build/src/utils/response.utils.js.map +0 -1
  271. package/build/src/utils/stream.utils.d.ts +0 -88
  272. package/build/src/utils/stream.utils.js +0 -218
  273. package/build/src/utils/stream.utils.js.map +0 -1
  274. package/build/src/utils/string.utils.d.ts +0 -93
  275. package/build/src/utils/string.utils.js +0 -179
  276. package/build/src/utils/string.utils.js.map +0 -1
  277. package/build/src/utils/type.utils.d.ts +0 -90
  278. package/build/src/utils/type.utils.js +0 -196
  279. package/build/src/utils/type.utils.js.map +0 -1
  280. package/build/src/utils/url.utils.d.ts +0 -141
  281. package/build/src/utils/url.utils.js +0 -317
  282. package/build/src/utils/url.utils.js.map +0 -1
  283. package/build/src/utils/validate.utils.d.ts +0 -177
  284. package/build/src/utils/validate.utils.js +0 -345
  285. package/build/src/utils/validate.utils.js.map +0 -1
@@ -1,136 +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
- };
136
- //# sourceMappingURL=performance.utils.d.ts.map
@@ -1,278 +0,0 @@
1
- "use strict";
2
- /*
3
- * The MIT License
4
- *
5
- * Copyright (c) 2025 Catbee Technologies
6
- *
7
- * Permission is hereby granted, free of charge, to any person obtaining a copy
8
- * of this software and associated documentation files (the "Software"), to deal
9
- * in the Software without restriction, including without limitation the rights
10
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- * copies of the Software, and to permit persons to whom the Software is
12
- * furnished to do so, subject to the following conditions:
13
- *
14
- * The above copyright notice and this permission notice shall be included in all
15
- * copies or substantial portions of the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
- * SOFTWARE.
24
- */
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.timeSync = timeSync;
27
- exports.timeAsync = timeAsync;
28
- exports.timed = timed;
29
- exports.memoize = memoize;
30
- exports.trackMemoryUsage = trackMemoryUsage;
31
- const cache_utils_1 = require("./cache.utils");
32
- const logger_utils_1 = require("./logger.utils");
33
- /**
34
- * Measure the execution time of a synchronous function.
35
- *
36
- * @param fn - Function to measure
37
- * @param options - Timing options
38
- * @returns Result containing the return value and timing information
39
- *
40
- * @example
41
- * ```typescript
42
- * const { result, timing } = timeSync(() => {
43
- * // Some expensive operation
44
- * return computeResult();
45
- * }, { label: 'Computation', log: true });
46
- *
47
- * console.log(`Result: ${result}, took ${timing.durationMs}ms`);
48
- * ```
49
- */
50
- function timeSync(fn, options = {}) {
51
- const { label = fn.name || 'anonymous function', log = false, logLevel = 'debug' } = options;
52
- const startTime = performance.now();
53
- const result = fn();
54
- const endTime = performance.now();
55
- const durationMs = endTime - startTime;
56
- const durationSec = durationMs / 1000;
57
- const timing = {
58
- durationMs,
59
- durationSec,
60
- startTime,
61
- endTime,
62
- label
63
- };
64
- if (log) {
65
- const logger = (0, logger_utils_1.getLogger)();
66
- const message = `${label} completed in ${durationMs.toFixed(2)}ms`;
67
- switch (logLevel) {
68
- case 'trace':
69
- logger.trace({ timing }, message);
70
- break;
71
- case 'debug':
72
- logger.debug({ timing }, message);
73
- break;
74
- case 'info':
75
- logger.info({ timing }, message);
76
- break;
77
- case 'warn':
78
- logger.warn({ timing }, message);
79
- break;
80
- case 'error':
81
- logger.error({ timing }, message);
82
- break;
83
- default:
84
- logger.debug({ timing }, message);
85
- break;
86
- }
87
- }
88
- return { result, timing };
89
- }
90
- /**
91
- * Measure the execution time of an asynchronous function.
92
- *
93
- * @param fn - Async function to measure
94
- * @param options - Timing options
95
- * @returns Promise resolving to result and timing information
96
- *
97
- * @example
98
- * ```typescript
99
- * const { result, timing } = await timeAsync(async () => {
100
- * // Some expensive async operation
101
- * const data = await fetchData();
102
- * return processData(data);
103
- * }, { label: 'API Request', log: true });
104
- *
105
- * console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`);
106
- * ```
107
- */
108
- async function timeAsync(fn, options = {}) {
109
- const { label = fn.name || 'anonymous async function', log = false, logLevel = 'debug' } = options;
110
- const startTime = performance.now();
111
- const result = await fn();
112
- const endTime = performance.now();
113
- const durationMs = endTime - startTime;
114
- const durationSec = durationMs / 1000;
115
- const timing = {
116
- durationMs,
117
- durationSec,
118
- startTime,
119
- endTime,
120
- label
121
- };
122
- if (log) {
123
- const logger = (0, logger_utils_1.getLogger)();
124
- const message = `${label} completed in ${durationMs.toFixed(2)}ms`;
125
- switch (logLevel) {
126
- case 'trace':
127
- logger.trace({ timing }, message);
128
- break;
129
- case 'debug':
130
- logger.debug({ timing }, message);
131
- break;
132
- case 'info':
133
- logger.info({ timing }, message);
134
- break;
135
- case 'warn':
136
- logger.warn({ timing }, message);
137
- break;
138
- case 'error':
139
- logger.error({ timing }, message);
140
- break;
141
- default:
142
- logger.debug({ timing }, message);
143
- break;
144
- }
145
- }
146
- return { result, timing };
147
- }
148
- /**
149
- * Create a timing decorator for class methods.
150
- *
151
- * @param options - Timing options
152
- * @returns Method decorator
153
- *
154
- * @example
155
- * ```typescript
156
- * class DataService {
157
- * @timed({ log: true, logLevel: 'info' })
158
- * async fetchData() {
159
- * // ...implementation
160
- * }
161
- * }
162
- * ```
163
- */
164
- function timed(options = {}) {
165
- return function (target, propertyKeyOrContext, descriptor) {
166
- let propertyKey;
167
- let actualDescriptor;
168
- // ESNext decorator: second argument is context object
169
- if (typeof propertyKeyOrContext === 'object' && propertyKeyOrContext !== null && 'name' in propertyKeyOrContext) {
170
- propertyKey = propertyKeyOrContext.name;
171
- actualDescriptor = descriptor !== null && descriptor !== void 0 ? descriptor : Object.getOwnPropertyDescriptor(target, propertyKey);
172
- }
173
- else {
174
- // Legacy decorator: second argument is property key
175
- propertyKey = propertyKeyOrContext;
176
- actualDescriptor = descriptor !== null && descriptor !== void 0 ? descriptor : Object.getOwnPropertyDescriptor(target, propertyKey);
177
- }
178
- const originalMethod = actualDescriptor.value;
179
- actualDescriptor.value = function (...args) {
180
- const methodOptions = Object.assign(Object.assign({}, options), { label: options.label || `${target.constructor.name}.${String(propertyKey)}` });
181
- if (originalMethod.constructor.name === 'AsyncFunction') {
182
- return timeAsync(() => originalMethod.apply(this, args), methodOptions).then(({ result }) => result);
183
- }
184
- else {
185
- return timeSync(() => originalMethod.apply(this, args), methodOptions).result;
186
- }
187
- };
188
- // For legacy decorators, assign the new descriptor
189
- if (descriptor) {
190
- descriptor.value = actualDescriptor.value;
191
- }
192
- else {
193
- Object.defineProperty(target, propertyKey, actualDescriptor);
194
- }
195
- // No return needed for method decorators
196
- };
197
- }
198
- /**
199
- * Memoize function results with optional TTL and max cache size.
200
- *
201
- * @param fn - Function to memoize
202
- * @param options - Memoization options
203
- * @returns Memoized function
204
- *
205
- * @example
206
- * ```typescript
207
- * // Cache results for 30 seconds, with a maximum of 100 entries
208
- * const cachedFetch = memoize(
209
- * async (url) => {
210
- * const response = await fetch(url);
211
- * return response.json();
212
- * },
213
- * { ttl: 30000, maxSize: 100, cacheKey: (url) => url }
214
- * );
215
- * ```
216
- */
217
- function memoize(fn, options = {}) {
218
- const { ttl, maxSize, autoCleanupMs, cacheKey = (...args) => JSON.stringify(args) } = options;
219
- // Create a properly configured TTLCache instance
220
- const cache = new cache_utils_1.TTLCache({
221
- ttlMs: ttl,
222
- maxSize: maxSize,
223
- autoCleanupMs: autoCleanupMs
224
- });
225
- return function (...args) {
226
- const key = cacheKey(...args);
227
- // Try to get from cache first - TTLCache handles expiration internally
228
- const cachedValue = cache.get(key);
229
- if (cachedValue !== undefined) {
230
- return cachedValue;
231
- }
232
- // Calculate the value and store in cache with configured TTL
233
- const value = fn(...args);
234
- cache.set(key, value);
235
- return value;
236
- };
237
- }
238
- /**
239
- * Track memory usage for a function execution.
240
- *
241
- * @param fn - Function to track
242
- * @param options - Memory tracking options
243
- * @returns Result and memory usage information
244
- */
245
- function trackMemoryUsage(fn, options = {}) {
246
- const { log = false, label = fn.name || 'anonymous function' } = options;
247
- // Collect garbage before measuring (optional)
248
- if (global.gc) {
249
- global.gc();
250
- }
251
- const beforeMemory = process.memoryUsage();
252
- const result = fn();
253
- const afterMemory = process.memoryUsage();
254
- // Calculate differences
255
- const diff = {};
256
- for (const key in afterMemory) {
257
- if (Object.prototype.hasOwnProperty.call(afterMemory, key)) {
258
- diff[key] = afterMemory[key] - beforeMemory[key];
259
- }
260
- }
261
- if (log) {
262
- (0, logger_utils_1.getLogger)().info({
263
- label,
264
- memoryBefore: beforeMemory,
265
- memoryAfter: afterMemory,
266
- memoryDiff: diff
267
- }, `Memory usage for ${label}`);
268
- }
269
- return {
270
- result,
271
- memoryUsage: {
272
- before: beforeMemory,
273
- after: afterMemory,
274
- diff
275
- }
276
- };
277
- }
278
- //# sourceMappingURL=performance.utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"performance.utils.js","sourceRoot":"","sources":["../../../src/utils/performance.utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;AAkDH,4BA6CC;AAoBD,8BAgDC;AAkBD,sBAsCC;AAqBD,0BAoCC;AASD,4CAgDC;AA3UD,+CAAyC;AACzC,iDAA2C;AA8B3C;;;;;;;;;;;;;;;;GAgBG;AACH,SAAgB,QAAQ,CAAI,EAAW,EAAE,UAAyB,EAAE;IAClE,MAAM,EAAE,KAAK,GAAG,EAAE,CAAC,IAAI,IAAI,oBAAoB,EAAE,GAAG,GAAG,KAAK,EAAE,QAAQ,GAAG,OAAO,EAAE,GAAG,OAAO,CAAC;IAE7F,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACpC,MAAM,MAAM,GAAG,EAAE,EAAE,CAAC;IACpB,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IAElC,MAAM,UAAU,GAAG,OAAO,GAAG,SAAS,CAAC;IACvC,MAAM,WAAW,GAAG,UAAU,GAAG,IAAI,CAAC;IAEtC,MAAM,MAAM,GAAiB;QAC3B,UAAU;QACV,WAAW;QACX,SAAS;QACT,O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AAG,EAAE,CAAC,IAAI,IAAI,oBAAoB,EAAE,GAAG,OAAO,CAAC;IAEzE,8CAA8C;IAC9C,IAAI,MAAM,CAAC,EAAE,EAAE,CAAC;QACd,MAAM,CAAC,EAAE,EAAE,CAAC;IACd,CAAC;IAED,MAAM,YAAY,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAC3C,MAAM,MAAM,GAAG,EAAE,EAAE,CAAC;IACpB,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAE1C,wBAAwB;IACxB,MAAM,IAAI,GAA2B,EAAE,CAAC;IACxC,KAAK,MAAM,GAAG,IAAI,WAAW,EAAE,CAAC;QAC9B,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,CAAC,EAAE,CAAC;YAC3D,IAAI,CAAC,GAAG,CAAC,GAAI,WAAmB,CAAC,GAAG,CAAC,GAAI,YAAoB,CAAC,GAAG,CAAC,CAAC;QACrE,CAAC;IACH,CAAC;IAED,IAAI,GAAG,EAAE,CAAC;QACR,IAAA,wBAAS,GAAE,CAAC,IAAI,CACd;YACE,KAAK;YACL,YAAY,EAAE,YAAY;YAC1B,WAAW,EAAE,WAAW;YACxB,UAAU,EAAE,IAAI;SACjB,EACD,oBAAoB,KAAK,EAAE,CAC5B,CAAC;IACJ,CAAC;IAED,OAAO;QACL,MAAM;QACN,WAAW,EAAE;YACX,MAAM,EAAE,YAAY;YACpB,KAAK,EAAE,WAAW;YAClB,IAAI;SACL;KACF,CAAC;AACJ,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { TTLCache } from './cache.utils';\nimport { getLogger } from './logger.utils';\n\n/**\n * Options for timing function execution.\n */\nexport interface TimingOptions {\n /** Optional label for the timing (defaults to function name) */\n label?: string;\n /** Whether to log the timing (default: false) */\n log?: boolean;\n /** Log level to use if logging is enabled (default: 'debug') */\n logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error';\n}\n\n/**\n * Result of a timing operation.\n */\nexport interface TimingResult {\n /** Duration in milliseconds */\n durationMs: number;\n /** Duration in seconds */\n durationSec: number;\n /** Start timestamp */\n startTime: number;\n /** End timestamp */\n endTime: number;\n /** Label used for the timing */\n label: string;\n}\n\n/**\n * Measure the execution time of a synchronous function.\n *\n * @param fn - Function to measure\n * @param options - Timing options\n * @returns Result containing the return value and timing information\n *\n * @example\n * ```typescript\n * const { result, timing } = timeSync(() => {\n * // Some expensive operation\n * return computeResult();\n * }, { label: 'Computation', log: true });\n *\n * console.log(`Result: ${result}, took ${timing.durationMs}ms`);\n * ```\n */\nexport function timeSync<T>(fn: () => T, options: TimingOptions = {}): { result: T; timing: TimingResult } {\n const { label = fn.name || 'anonymous function', log = false, logLevel = 'debug' } = options;\n\n const startTime = performance.now();\n const result = fn();\n const endTime = performance.now();\n\n const durationMs = endTime - startTime;\n const durationSec = durationMs / 1000;\n\n const timing: TimingResult = {\n durationMs,\n durationSec,\n startTime,\n endTime,\n label\n };\n\n if (log) {\n const logger = getLogger();\n const message = `${label} completed in ${durationMs.toFixed(2)}ms`;\n\n switch (logLevel) {\n case 'trace':\n logger.trace({ timing }, message);\n break;\n case 'debug':\n logger.debug({ timing }, message);\n break;\n case 'info':\n logger.info({ timing }, message);\n break;\n case 'warn':\n logger.warn({ timing }, message);\n break;\n case 'error':\n logger.error({ timing }, message);\n break;\n default:\n logger.debug({ timing }, message);\n break;\n }\n }\n\n return { result, timing };\n}\n\n/**\n * Measure the execution time of an asynchronous function.\n *\n * @param fn - Async function to measure\n * @param options - Timing options\n * @returns Promise resolving to result and timing information\n *\n * @example\n * ```typescript\n * const { result, timing } = await timeAsync(async () => {\n * // Some expensive async operation\n * const data = await fetchData();\n * return processData(data);\n * }, { label: 'API Request', log: true });\n *\n * console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`);\n * ```\n */\nexport async function timeAsync<T>(\n fn: () => Promise<T>,\n options: TimingOptions = {}\n): Promise<{ result: T; timing: TimingResult }> {\n const { label = fn.name || 'anonymous async function', log = false, logLevel = 'debug' } = options;\n\n const startTime = performance.now();\n const result = await fn();\n const endTime = performance.now();\n\n const durationMs = endTime - startTime;\n const durationSec = durationMs / 1000;\n\n const timing: TimingResult = {\n durationMs,\n durationSec,\n startTime,\n endTime,\n label\n };\n\n if (log) {\n const logger = getLogger();\n const message = `${label} completed in ${durationMs.toFixed(2)}ms`;\n\n switch (logLevel) {\n case 'trace':\n logger.trace({ timing }, message);\n break;\n case 'debug':\n logger.debug({ timing }, message);\n break;\n case 'info':\n logger.info({ timing }, message);\n break;\n case 'warn':\n logger.warn({ timing }, message);\n break;\n case 'error':\n logger.error({ timing }, message);\n break;\n default:\n logger.debug({ timing }, message);\n break;\n }\n }\n\n return { result, timing };\n}\n\n/**\n * Create a timing decorator for class methods.\n *\n * @param options - Timing options\n * @returns Method decorator\n *\n * @example\n * ```typescript\n * class DataService {\n * @timed({ log: true, logLevel: 'info' })\n * async fetchData() {\n * // ...implementation\n * }\n * }\n * ```\n */\nexport function timed(options: TimingOptions = {}) {\n return function (target: any, propertyKeyOrContext: string | symbol | any, descriptor?: PropertyDescriptor): void {\n let propertyKey: string | symbol;\n let actualDescriptor: PropertyDescriptor;\n\n // ESNext decorator: second argument is context object\n if (typeof propertyKeyOrContext === 'object' && propertyKeyOrContext !== null && 'name' in propertyKeyOrContext) {\n propertyKey = propertyKeyOrContext.name;\n actualDescriptor = descriptor ?? Object.getOwnPropertyDescriptor(target, propertyKey)!;\n } else {\n // Legacy decorator: second argument is property key\n propertyKey = propertyKeyOrContext;\n actualDescriptor = descriptor ?? Object.getOwnPropertyDescriptor(target, propertyKey)!;\n }\n\n const originalMethod = actualDescriptor.value;\n\n actualDescriptor.value = function (...args: any[]) {\n const methodOptions = {\n ...options,\n label: options.label || `${target.constructor.name}.${String(propertyKey)}`\n };\n\n if (originalMethod.constructor.name === 'AsyncFunction') {\n return timeAsync(() => originalMethod.apply(this, args), methodOptions).then(({ result }) => result);\n } else {\n return timeSync(() => originalMethod.apply(this, args), methodOptions).result;\n }\n };\n\n // For legacy decorators, assign the new descriptor\n if (descriptor) {\n descriptor.value = actualDescriptor.value;\n } else {\n Object.defineProperty(target, propertyKey, actualDescriptor);\n }\n // No return needed for method decorators\n };\n}\n\n/**\n * Memoize function results with optional TTL and max cache size.\n *\n * @param fn - Function to memoize\n * @param options - Memoization options\n * @returns Memoized function\n *\n * @example\n * ```typescript\n * // Cache results for 30 seconds, with a maximum of 100 entries\n * const cachedFetch = memoize(\n * async (url) => {\n * const response = await fetch(url);\n * return response.json();\n * },\n * { ttl: 30000, maxSize: 100, cacheKey: (url) => url }\n * );\n * ```\n */\nexport function memoize<T, Args extends any[]>(\n fn: (...args: Args) => T,\n options: {\n /** Time-to-live in milliseconds (default: indefinite) */\n ttl?: number;\n /** Maximum cache size (default: unlimited) */\n maxSize?: number;\n /** Function to generate a cache key from arguments */\n cacheKey?: (...args: Args) => string;\n /** Auto-cleanup interval in milliseconds (default: disabled) */\n autoCleanupMs?: number;\n } = {}\n) {\n const { ttl, maxSize, autoCleanupMs, cacheKey = (...args) => JSON.stringify(args) } = options;\n\n // Create a properly configured TTLCache instance\n const cache = new TTLCache<string, T>({\n ttlMs: ttl,\n maxSize: maxSize,\n autoCleanupMs: autoCleanupMs\n });\n\n return function (...args: Args): T {\n const key = cacheKey(...args);\n\n // Try to get from cache first - TTLCache handles expiration internally\n const cachedValue = cache.get(key);\n if (cachedValue !== undefined) {\n return cachedValue;\n }\n\n // Calculate the value and store in cache with configured TTL\n const value = fn(...args);\n cache.set(key, value);\n return value;\n };\n}\n\n/**\n * Track memory usage for a function execution.\n *\n * @param fn - Function to track\n * @param options - Memory tracking options\n * @returns Result and memory usage information\n */\nexport function trackMemoryUsage<T>(\n fn: () => T,\n options: {\n /** Whether to log the memory usage (default: false) */\n log?: boolean;\n /** Label for the memory tracking (default: function name) */\n label?: string;\n } = {}\n): { result: T; memoryUsage: { before: NodeJS.MemoryUsage; after: NodeJS.MemoryUsage; diff: Record<string, number> } } {\n const { log = false, label = fn.name || 'anonymous function' } = options;\n\n // Collect garbage before measuring (optional)\n if (global.gc) {\n global.gc();\n }\n\n const beforeMemory = process.memoryUsage();\n const result = fn();\n const afterMemory = process.memoryUsage();\n\n // Calculate differences\n const diff: Record<string, number> = {};\n for (const key in afterMemory) {\n if (Object.prototype.hasOwnProperty.call(afterMemory, key)) {\n diff[key] = (afterMemory as any)[key] - (beforeMemory as any)[key];\n }\n }\n\n if (log) {\n getLogger().info(\n {\n label,\n memoryBefore: beforeMemory,\n memoryAfter: afterMemory,\n memoryDiff: diff\n },\n `Memory usage for ${label}`\n );\n }\n\n return {\n result,\n memoryUsage: {\n before: beforeMemory,\n after: afterMemory,\n diff\n }\n };\n}\n"]}
@@ -1,86 +0,0 @@
1
- import { Request } from 'express';
2
- import { WithPagination } from '../types/api-response';
3
- /**
4
- * Options for parsing and validating request parameters.
5
- */
6
- export interface ValidationOptions {
7
- /** Whether to throw an error on validation failure */
8
- throwOnError?: boolean;
9
- /** Custom error message for validation failures */
10
- errorMessage?: string;
11
- /** Default value to use if parameter is missing */
12
- defaultValue?: any;
13
- /** Whether the parameter is required */
14
- required?: boolean;
15
- }
16
- /**
17
- * Result of a parameter validation operation.
18
- */
19
- export interface ValidationResult<T> {
20
- /** Whether validation was successful */
21
- isValid: boolean;
22
- /** The validated and potentially transformed value */
23
- value: T | null;
24
- /** Error message if validation failed */
25
- error?: string;
26
- }
27
- /**
28
- * Extracts pagination, sorting, and optional search params from a request.
29
- *
30
- * @param req - Express request
31
- * @returns Object containing validated pagination, sorting, and additional query params
32
- */
33
- export declare const getPaginationParams: <T = {}>(req: Request) => WithPagination<T>;
34
- /**
35
- * Safely parses a string parameter to a number.
36
- *
37
- * @param value - String value to parse
38
- * @param options - Validation options
39
- * @returns Validation result containing the parsed number or error
40
- */
41
- export declare function parseNumberParam(value: string | undefined, options?: ValidationOptions): ValidationResult<number>;
42
- /**
43
- * Safely parses a string parameter to a boolean.
44
- *
45
- * @param value - String value to parse
46
- * @param options - Validation options
47
- * @returns Validation result containing the parsed boolean or error
48
- */
49
- export declare function parseBooleanParam(value: string | undefined, options?: ValidationOptions): ValidationResult<boolean>;
50
- /**
51
- * Extracts pagination parameters from request query parameters.
52
- *
53
- * @param query - Query parameters object
54
- * @param defaultPage - Default page number if not specified (defaults to 1)
55
- * @param defaultLimit - Default per page size if not specified (defaults to 20)
56
- * @param maxLimitSize - Maximum allowed per page size (defaults to 100)
57
- * @returns Object containing validated page and limit
58
- */
59
- export declare function extractPaginationParams(query: Record<string, string | string[]>, defaultPage?: number, defaultLimit?: number, maxLimitSize?: number): {
60
- page: number;
61
- limit: number;
62
- };
63
- /**
64
- * Extracts sorting parameters from request query parameters.
65
- *
66
- * @param query - Query parameters object
67
- * @param allowedFields - Array of field names that are allowed to be sorted
68
- * @param defaultSort - Default sort configuration if not specified
69
- * @returns Object containing sort field and direction
70
- */
71
- export declare function extractSortParams(query: Record<string, string | string[]>, allowedFields: string[], defaultSort?: {
72
- sortBy: string;
73
- sortOrder: 'asc' | 'desc';
74
- }): {
75
- sortBy: string;
76
- sortOrder: 'asc' | 'desc';
77
- };
78
- /**
79
- * Extracts filter parameters from query parameters based on allowed filter fields.
80
- *
81
- * @param query - Query parameters object
82
- * @param allowedFilters - Array of field names that are allowed to be used as filters
83
- * @returns Object containing the filters as key-value pairs
84
- */
85
- export declare function extractFilterParams(query: Record<string, string | string[]>, allowedFilters: string[]): Record<string, string | string[]>;
86
- //# sourceMappingURL=request.utils.d.ts.map