@catbee/utils 0.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 (183) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +295 -0
  3. package/build/esm/config.d.ts +22 -0
  4. package/build/esm/config.js +21 -0
  5. package/build/esm/config.js.map +1 -0
  6. package/build/esm/index.d.ts +19 -0
  7. package/build/esm/index.js +19 -0
  8. package/build/esm/index.js.map +1 -0
  9. package/build/esm/types/api-response.d.ts +44 -0
  10. package/build/esm/types/api-response.js +2 -0
  11. package/build/esm/types/api-response.js.map +1 -0
  12. package/build/esm/utils/array.utils.d.ts +105 -0
  13. package/build/esm/utils/array.utils.js +232 -0
  14. package/build/esm/utils/array.utils.js.map +1 -0
  15. package/build/esm/utils/async.utils.d.ts +119 -0
  16. package/build/esm/utils/async.utils.js +474 -0
  17. package/build/esm/utils/async.utils.js.map +1 -0
  18. package/build/esm/utils/cache.utils.d.ts +90 -0
  19. package/build/esm/utils/cache.utils.js +294 -0
  20. package/build/esm/utils/cache.utils.js.map +1 -0
  21. package/build/esm/utils/context-store.utils.d.ts +85 -0
  22. package/build/esm/utils/context-store.utils.js +99 -0
  23. package/build/esm/utils/context-store.utils.js.map +1 -0
  24. package/build/esm/utils/crypto.utils.d.ts +58 -0
  25. package/build/esm/utils/crypto.utils.js +76 -0
  26. package/build/esm/utils/crypto.utils.js.map +1 -0
  27. package/build/esm/utils/dir.utils.d.ts +75 -0
  28. package/build/esm/utils/dir.utils.js +400 -0
  29. package/build/esm/utils/dir.utils.js.map +1 -0
  30. package/build/esm/utils/env.utils.d.ts +131 -0
  31. package/build/esm/utils/env.utils.js +218 -0
  32. package/build/esm/utils/env.utils.js.map +1 -0
  33. package/build/esm/utils/exception.utils.d.ts +114 -0
  34. package/build/esm/utils/exception.utils.js +217 -0
  35. package/build/esm/utils/exception.utils.js.map +1 -0
  36. package/build/esm/utils/fs.utils.d.ts +32 -0
  37. package/build/esm/utils/fs.utils.js +140 -0
  38. package/build/esm/utils/fs.utils.js.map +1 -0
  39. package/build/esm/utils/http-status-codes.d.ts +357 -0
  40. package/build/esm/utils/http-status-codes.js +358 -0
  41. package/build/esm/utils/http-status-codes.js.map +1 -0
  42. package/build/esm/utils/id.utils.d.ts +35 -0
  43. package/build/esm/utils/id.utils.js +55 -0
  44. package/build/esm/utils/id.utils.js.map +1 -0
  45. package/build/esm/utils/logger.utils.d.ts +15 -0
  46. package/build/esm/utils/logger.utils.js +59 -0
  47. package/build/esm/utils/logger.utils.js.map +1 -0
  48. package/build/esm/utils/obj.utils.d.ts +55 -0
  49. package/build/esm/utils/obj.utils.js +121 -0
  50. package/build/esm/utils/obj.utils.js.map +1 -0
  51. package/build/esm/utils/response.utils.d.ts +48 -0
  52. package/build/esm/utils/response.utils.js +80 -0
  53. package/build/esm/utils/response.utils.js.map +1 -0
  54. package/build/esm/utils/string.utils.d.ts +37 -0
  55. package/build/esm/utils/string.utils.js +56 -0
  56. package/build/esm/utils/string.utils.js.map +1 -0
  57. package/build/esm/utils/url.utils.d.ts +24 -0
  58. package/build/esm/utils/url.utils.js +73 -0
  59. package/build/esm/utils/url.utils.js.map +1 -0
  60. package/build/esm/utils/validate.utils.d.ts +60 -0
  61. package/build/esm/utils/validate.utils.js +121 -0
  62. package/build/esm/utils/validate.utils.js.map +1 -0
  63. package/build/esnext/config.d.ts +22 -0
  64. package/build/esnext/config.js +21 -0
  65. package/build/esnext/config.js.map +1 -0
  66. package/build/esnext/index.d.ts +19 -0
  67. package/build/esnext/index.js +19 -0
  68. package/build/esnext/index.js.map +1 -0
  69. package/build/esnext/types/api-response.d.ts +44 -0
  70. package/build/esnext/types/api-response.js +2 -0
  71. package/build/esnext/types/api-response.js.map +1 -0
  72. package/build/esnext/utils/array.utils.d.ts +105 -0
  73. package/build/esnext/utils/array.utils.js +203 -0
  74. package/build/esnext/utils/array.utils.js.map +1 -0
  75. package/build/esnext/utils/async.utils.d.ts +119 -0
  76. package/build/esnext/utils/async.utils.js +291 -0
  77. package/build/esnext/utils/async.utils.js.map +1 -0
  78. package/build/esnext/utils/cache.utils.d.ts +90 -0
  79. package/build/esnext/utils/cache.utils.js +142 -0
  80. package/build/esnext/utils/cache.utils.js.map +1 -0
  81. package/build/esnext/utils/context-store.utils.d.ts +85 -0
  82. package/build/esnext/utils/context-store.utils.js +95 -0
  83. package/build/esnext/utils/context-store.utils.js.map +1 -0
  84. package/build/esnext/utils/crypto.utils.d.ts +58 -0
  85. package/build/esnext/utils/crypto.utils.js +72 -0
  86. package/build/esnext/utils/crypto.utils.js.map +1 -0
  87. package/build/esnext/utils/dir.utils.d.ts +75 -0
  88. package/build/esnext/utils/dir.utils.js +150 -0
  89. package/build/esnext/utils/dir.utils.js.map +1 -0
  90. package/build/esnext/utils/env.utils.d.ts +131 -0
  91. package/build/esnext/utils/env.utils.js +211 -0
  92. package/build/esnext/utils/env.utils.js.map +1 -0
  93. package/build/esnext/utils/exception.utils.d.ts +114 -0
  94. package/build/esnext/utils/exception.utils.js +148 -0
  95. package/build/esnext/utils/exception.utils.js.map +1 -0
  96. package/build/esnext/utils/fs.utils.d.ts +32 -0
  97. package/build/esnext/utils/fs.utils.js +62 -0
  98. package/build/esnext/utils/fs.utils.js.map +1 -0
  99. package/build/esnext/utils/http-status-codes.d.ts +357 -0
  100. package/build/esnext/utils/http-status-codes.js +358 -0
  101. package/build/esnext/utils/http-status-codes.js.map +1 -0
  102. package/build/esnext/utils/id.utils.d.ts +35 -0
  103. package/build/esnext/utils/id.utils.js +53 -0
  104. package/build/esnext/utils/id.utils.js.map +1 -0
  105. package/build/esnext/utils/logger.utils.d.ts +15 -0
  106. package/build/esnext/utils/logger.utils.js +59 -0
  107. package/build/esnext/utils/logger.utils.js.map +1 -0
  108. package/build/esnext/utils/obj.utils.d.ts +55 -0
  109. package/build/esnext/utils/obj.utils.js +94 -0
  110. package/build/esnext/utils/obj.utils.js.map +1 -0
  111. package/build/esnext/utils/response.utils.d.ts +48 -0
  112. package/build/esnext/utils/response.utils.js +58 -0
  113. package/build/esnext/utils/response.utils.js.map +1 -0
  114. package/build/esnext/utils/string.utils.d.ts +37 -0
  115. package/build/esnext/utils/string.utils.js +46 -0
  116. package/build/esnext/utils/string.utils.js.map +1 -0
  117. package/build/esnext/utils/url.utils.d.ts +24 -0
  118. package/build/esnext/utils/url.utils.js +35 -0
  119. package/build/esnext/utils/url.utils.js.map +1 -0
  120. package/build/esnext/utils/validate.utils.d.ts +60 -0
  121. package/build/esnext/utils/validate.utils.js +105 -0
  122. package/build/esnext/utils/validate.utils.js.map +1 -0
  123. package/build/src/config.d.ts +22 -0
  124. package/build/src/config.js +24 -0
  125. package/build/src/config.js.map +1 -0
  126. package/build/src/index.d.ts +19 -0
  127. package/build/src/index.js +35 -0
  128. package/build/src/index.js.map +1 -0
  129. package/build/src/types/api-response.d.ts +44 -0
  130. package/build/src/types/api-response.js +3 -0
  131. package/build/src/types/api-response.js.map +1 -0
  132. package/build/src/utils/array.utils.d.ts +105 -0
  133. package/build/src/utils/array.utils.js +216 -0
  134. package/build/src/utils/array.utils.js.map +1 -0
  135. package/build/src/utils/async.utils.d.ts +119 -0
  136. package/build/src/utils/async.utils.js +304 -0
  137. package/build/src/utils/async.utils.js.map +1 -0
  138. package/build/src/utils/cache.utils.d.ts +90 -0
  139. package/build/src/utils/cache.utils.js +146 -0
  140. package/build/src/utils/cache.utils.js.map +1 -0
  141. package/build/src/utils/context-store.utils.d.ts +85 -0
  142. package/build/src/utils/context-store.utils.js +100 -0
  143. package/build/src/utils/context-store.utils.js.map +1 -0
  144. package/build/src/utils/crypto.utils.d.ts +58 -0
  145. package/build/src/utils/crypto.utils.js +82 -0
  146. package/build/src/utils/crypto.utils.js.map +1 -0
  147. package/build/src/utils/dir.utils.d.ts +75 -0
  148. package/build/src/utils/dir.utils.js +164 -0
  149. package/build/src/utils/dir.utils.js.map +1 -0
  150. package/build/src/utils/env.utils.d.ts +131 -0
  151. package/build/src/utils/env.utils.js +215 -0
  152. package/build/src/utils/env.utils.js.map +1 -0
  153. package/build/src/utils/exception.utils.d.ts +114 -0
  154. package/build/src/utils/exception.utils.js +162 -0
  155. package/build/src/utils/exception.utils.js.map +1 -0
  156. package/build/src/utils/fs.utils.d.ts +32 -0
  157. package/build/src/utils/fs.utils.js +71 -0
  158. package/build/src/utils/fs.utils.js.map +1 -0
  159. package/build/src/utils/http-status-codes.d.ts +357 -0
  160. package/build/src/utils/http-status-codes.js +361 -0
  161. package/build/src/utils/http-status-codes.js.map +1 -0
  162. package/build/src/utils/id.utils.d.ts +35 -0
  163. package/build/src/utils/id.utils.js +60 -0
  164. package/build/src/utils/id.utils.js.map +1 -0
  165. package/build/src/utils/logger.utils.d.ts +15 -0
  166. package/build/src/utils/logger.utils.js +96 -0
  167. package/build/src/utils/logger.utils.js.map +1 -0
  168. package/build/src/utils/obj.utils.d.ts +55 -0
  169. package/build/src/utils/obj.utils.js +103 -0
  170. package/build/src/utils/obj.utils.js.map +1 -0
  171. package/build/src/utils/response.utils.d.ts +48 -0
  172. package/build/src/utils/response.utils.js +63 -0
  173. package/build/src/utils/response.utils.js.map +1 -0
  174. package/build/src/utils/string.utils.d.ts +37 -0
  175. package/build/src/utils/string.utils.js +54 -0
  176. package/build/src/utils/string.utils.js.map +1 -0
  177. package/build/src/utils/url.utils.d.ts +24 -0
  178. package/build/src/utils/url.utils.js +39 -0
  179. package/build/src/utils/url.utils.js.map +1 -0
  180. package/build/src/utils/validate.utils.d.ts +60 -0
  181. package/build/src/utils/validate.utils.js +115 -0
  182. package/build/src/utils/validate.utils.js.map +1 -0
  183. package/package.json +80 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.utils.js","sourceRoot":"","sources":["../../../src/utils/cache.utils.ts"],"names":[],"mappings":"AAQA;;;;;;;;;;GAUG;AACH,MAAM,OAAO,QAAQ;IAGnB;;OAEG;IACH,YAAoB,QAAgB,CAAC,GAAG,EAAE,GAAG,IAAI;QAA7B,UAAK,GAAL,KAAK,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C,SAAS,EAAE,CAAC;gBAClC,MAAM,KAAK,CAAC,KAAK,CAAC;YACpB,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Represents a cached entry with a value and an expiration timestamp.\n */\ntype CacheEntry<T> = {\n value: T;\n expiresAt: number;\n};\n\n/**\n * An in-memory cache with time-to-live (TTL) support for each entry.\n *\n * @typeParam K - Type of the key.\n * @typeParam V - Type of the value.\n *\n * @example\n * const cache = new TTLCache<string, number>(1000);\n * cache.set(\"x\", 123);\n * const value = cache.get(\"x\"); // 123\n */\nexport class TTLCache<K, V> {\n private cache = new Map<K, CacheEntry<V>>();\n\n /**\n * @param ttlMs - Default time-to-live in milliseconds for cache entries.\n */\n constructor(private ttlMs: number = 5 * 60 * 1000) {}\n\n /**\n * Sets a key-value pair in the cache with the default TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n */\n set(key: K, value: V): void {\n const expiresAt = Date.now() + this.ttlMs;\n this.cache.set(key, { value, expiresAt });\n }\n\n /**\n * Sets a key-value pair in the cache with a custom TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n * @param ttlMs - Time-to-live in milliseconds.\n */\n setWithTTL(key: K, value: V, ttlMs: number): void {\n const expiresAt = Date.now() + ttlMs;\n this.cache.set(key, { value, expiresAt });\n }\n\n /**\n * Retrieves the value for a given key if it hasn't expired.\n *\n * @param key - The key to retrieve.\n * @returns The cached value, or undefined if not found or expired.\n */\n get(key: K): V | undefined {\n const entry = this.cache.get(key);\n if (!entry) return undefined;\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n return undefined;\n }\n return entry.value;\n }\n\n /**\n * Checks if the key exists and hasn't expired.\n *\n * @param key - The key to check.\n * @returns `true` if key exists and is valid, otherwise `false`.\n */\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n /**\n * Deletes a key from the cache.\n *\n * @param key - The key to delete.\n * @returns `true` if the key existed and was removed, `false` otherwise.\n */\n delete(key: K): boolean {\n return this.cache.delete(key);\n }\n\n /**\n * Clears all entries from the cache.\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).\n *\n * @returns Number of items in the cache (may include expired keys).\n */\n size(): number {\n return this.cache.size;\n }\n\n /**\n * Removes all expired entries from the cache.\n *\n * @returns Number of entries removed.\n */\n cleanup(): number {\n let removed = 0;\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n removed++;\n }\n }\n return removed;\n }\n\n /**\n * Returns an iterator of all current valid [key, value] pairs.\n *\n * @returns IterableIterator<[K, V]>\n */\n *entries(): IterableIterator<[K, V]> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield [key, entry.value];\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid keys.\n *\n * @returns IterableIterator<K>\n */\n *keys(): IterableIterator<K> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield key;\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid values.\n *\n * @returns IterableIterator<V>\n */\n *values(): IterableIterator<V> {\n for (const entry of this.cache.values()) {\n if (Date.now() <= entry.expiresAt) {\n yield entry.value;\n }\n }\n }\n}\n"]}
@@ -0,0 +1,85 @@
1
+ import { AsyncLocalStorage } from "async_hooks";
2
+ /**
3
+ * Type representing the store object used in AsyncLocalStorage.
4
+ * Keys must be unique symbols to ensure isolation and prevent collisions.
5
+ */
6
+ export interface Store {
7
+ [key: symbol]: unknown;
8
+ }
9
+ /**
10
+ * Predefined symbols used as keys in AsyncLocalStorage.
11
+ * Add new symbols here to avoid duplication.
12
+ */
13
+ export declare const StoreKeys: {
14
+ LOGGER: symbol;
15
+ REQUEST_ID: symbol;
16
+ };
17
+ /**
18
+ * Retrieves the current request ID from the async context, if available.
19
+ *
20
+ * @returns {string | undefined} The request ID string or undefined if not present in the current context.
21
+ */
22
+ export declare function getRequestId(): string | undefined;
23
+ /**
24
+ * ContextStore manages per-request scoped context using AsyncLocalStorage.
25
+ * It allows storing and retrieving data across async calls (e.g., request ID, logger).
26
+ *
27
+ * Example (Express middleware):
28
+ * ```
29
+ * // Middleware to initialize context and logger
30
+ * app.use((req, res, next) => {
31
+ * const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
32
+ * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
33
+ * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ reqId: requestId }));
34
+ * next();
35
+ * });
36
+ * });
37
+ * ```
38
+ */
39
+ export declare class ContextStore {
40
+ /**
41
+ * The underlying AsyncLocalStorage instance for context.
42
+ * @private
43
+ */
44
+ private static readonly storage;
45
+ /**
46
+ * Returns the raw AsyncLocalStorage instance for advanced access.
47
+ *
48
+ * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.
49
+ */
50
+ static getInstance(): AsyncLocalStorage<Store>;
51
+ /**
52
+ * Retrieves a value from the async context store by symbol key.
53
+ *
54
+ * @typeParam T - The expected return type of the value.
55
+ * @param {symbol} key - Unique symbol used as the store key.
56
+ * @returns {T | undefined} The value found (typed) or undefined if not present.
57
+ */
58
+ static get<T>(key: symbol): T | undefined;
59
+ /**
60
+ * Sets a value in the current context store by symbol key.
61
+ *
62
+ * @typeParam T - The value type to set.
63
+ * @param {symbol} key - Unique symbol key.
64
+ * @param {T} value - Value to set in context.
65
+ * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).
66
+ */
67
+ static set<T>(key: symbol, value: T): void;
68
+ /**
69
+ * Retrieves the entire context store object for the current async context.
70
+ *
71
+ * @returns {Store | undefined} The current store object or undefined if called outside a context.
72
+ */
73
+ static getAll(): Store | undefined;
74
+ /**
75
+ * Initializes a new async context and executes a callback within it.
76
+ * This must be called at the beginning of a request or logical async flow.
77
+ *
78
+ * @typeParam T - The callback's return type.
79
+ * @param {Store} store - The initial key-value store object.
80
+ * @param {() => T} callback - The function to run within the new context.
81
+ * @returns {T} The result of the callback function.
82
+ */
83
+ static run<T>(store: Store, callback: () => T): T;
84
+ }
85
+ //# sourceMappingURL=context-store.utils.d.ts.map
@@ -0,0 +1,95 @@
1
+ import { AsyncLocalStorage } from "async_hooks";
2
+ /**
3
+ * Predefined symbols used as keys in AsyncLocalStorage.
4
+ * Add new symbols here to avoid duplication.
5
+ */
6
+ export const StoreKeys = {
7
+ LOGGER: Symbol("logger"),
8
+ REQUEST_ID: Symbol("requestId"),
9
+ };
10
+ /**
11
+ * Retrieves the current request ID from the async context, if available.
12
+ *
13
+ * @returns {string | undefined} The request ID string or undefined if not present in the current context.
14
+ */
15
+ export function getRequestId() {
16
+ return ContextStore.get(StoreKeys.REQUEST_ID);
17
+ }
18
+ /**
19
+ * ContextStore manages per-request scoped context using AsyncLocalStorage.
20
+ * It allows storing and retrieving data across async calls (e.g., request ID, logger).
21
+ *
22
+ * Example (Express middleware):
23
+ * ```
24
+ * // Middleware to initialize context and logger
25
+ * app.use((req, res, next) => {
26
+ * const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
27
+ * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
28
+ * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ reqId: requestId }));
29
+ * next();
30
+ * });
31
+ * });
32
+ * ```
33
+ */
34
+ export class ContextStore {
35
+ /**
36
+ * Returns the raw AsyncLocalStorage instance for advanced access.
37
+ *
38
+ * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.
39
+ */
40
+ static getInstance() {
41
+ return this.storage;
42
+ }
43
+ /**
44
+ * Retrieves a value from the async context store by symbol key.
45
+ *
46
+ * @typeParam T - The expected return type of the value.
47
+ * @param {symbol} key - Unique symbol used as the store key.
48
+ * @returns {T | undefined} The value found (typed) or undefined if not present.
49
+ */
50
+ static get(key) {
51
+ const store = this.storage.getStore();
52
+ return store === null || store === void 0 ? void 0 : store[key];
53
+ }
54
+ /**
55
+ * Sets a value in the current context store by symbol key.
56
+ *
57
+ * @typeParam T - The value type to set.
58
+ * @param {symbol} key - Unique symbol key.
59
+ * @param {T} value - Value to set in context.
60
+ * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).
61
+ */
62
+ static set(key, value) {
63
+ const store = this.storage.getStore();
64
+ if (!store) {
65
+ throw new Error(`Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`);
66
+ }
67
+ store[key] = value;
68
+ }
69
+ /**
70
+ * Retrieves the entire context store object for the current async context.
71
+ *
72
+ * @returns {Store | undefined} The current store object or undefined if called outside a context.
73
+ */
74
+ static getAll() {
75
+ return this.storage.getStore();
76
+ }
77
+ /**
78
+ * Initializes a new async context and executes a callback within it.
79
+ * This must be called at the beginning of a request or logical async flow.
80
+ *
81
+ * @typeParam T - The callback's return type.
82
+ * @param {Store} store - The initial key-value store object.
83
+ * @param {() => T} callback - The function to run within the new context.
84
+ * @returns {T} The result of the callback function.
85
+ */
86
+ static run(store, callback) {
87
+ return this.storage.run(store, callback);
88
+ }
89
+ }
90
+ /**
91
+ * The underlying AsyncLocalStorage instance for context.
92
+ * @private
93
+ */
94
+ ContextStore.storage = new AsyncLocalStorage();
95
+ //# sourceMappingURL=context-store.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-store.utils.js","sourceRoot":"","sources":["../../../src/utils/context-store.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAUhD;;;GAGG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC;CAChC,CAAC;AAEF;;;;GAIG;AACH,MAAM,UAAU,YAAY;IAC1B,OAAO,YAAY,CAAC,GAAG,CAAS,SAAS,CAAC,UAAU,CAAC,CAAC;AACxD,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,YAAY;IAOvB;;;;OAIG;IACH,MAAM,CAAC,WAAW;QAChB,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,GAAG,CAAI,GAAW;QACvB,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;QACtC,OAAO,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAG,GAAG,CAAkB,CAAC;IACvC,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,GAAG,CAAI,GAAW,EAAE,KAAQ;QACjC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;QACtC,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,KAAK,CACb,iBAAiB,MAAM,CAAC,GAAG,CAAC,+CAA+C,CAC5E,CAAC;QACJ,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACrB,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,MAAM;QACX,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;IACjC,CAAC;IAED;;;;;;;;OAQG;IACH,MAAM,CAAC,GAAG,CAAI,KAAY,EAAE,QAAiB;QAC3C,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAC3C,CAAC;;AAjED;;;GAGG;AACqB,oBAAO,GAAG,IAAI,iBAAiB,EAAS,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"async_hooks\";\n\n/**\n * Type representing the store object used in AsyncLocalStorage.\n * Keys must be unique symbols to ensure isolation and prevent collisions.\n */\nexport interface Store {\n [key: symbol]: unknown;\n}\n\n/**\n * Predefined symbols used as keys in AsyncLocalStorage.\n * Add new symbols here to avoid duplication.\n */\nexport const StoreKeys = {\n LOGGER: Symbol(\"logger\"),\n REQUEST_ID: Symbol(\"requestId\"),\n};\n\n/**\n * Retrieves the current request ID from the async context, if available.\n *\n * @returns {string | undefined} The request ID string or undefined if not present in the current context.\n */\nexport function getRequestId(): string | undefined {\n return ContextStore.get<string>(StoreKeys.REQUEST_ID);\n}\n\n/**\n * ContextStore manages per-request scoped context using AsyncLocalStorage.\n * It allows storing and retrieving data across async calls (e.g., request ID, logger).\n *\n * Example (Express middleware):\n * ```\n * // Middleware to initialize context and logger\n * app.use((req, res, next) => {\n * const requestId = req.headers[\"x-request-id\"]?.toString() || crypto.randomUUID();\n * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ reqId: requestId }));\n * next();\n * });\n * });\n * ```\n */\nexport class ContextStore {\n /**\n * The underlying AsyncLocalStorage instance for context.\n * @private\n */\n private static readonly storage = new AsyncLocalStorage<Store>();\n\n /**\n * Returns the raw AsyncLocalStorage instance for advanced access.\n *\n * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.\n */\n static getInstance(): AsyncLocalStorage<Store> {\n return this.storage;\n }\n\n /**\n * Retrieves a value from the async context store by symbol key.\n *\n * @typeParam T - The expected return type of the value.\n * @param {symbol} key - Unique symbol used as the store key.\n * @returns {T | undefined} The value found (typed) or undefined if not present.\n */\n static get<T>(key: symbol): T | undefined {\n const store = this.storage.getStore();\n return store?.[key] as T | undefined;\n }\n\n /**\n * Sets a value in the current context store by symbol key.\n *\n * @typeParam T - The value type to set.\n * @param {symbol} key - Unique symbol key.\n * @param {T} value - Value to set in context.\n * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).\n */\n static set<T>(key: symbol, value: T): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(\n `Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`,\n );\n }\n store[key] = value;\n }\n\n /**\n * Retrieves the entire context store object for the current async context.\n *\n * @returns {Store | undefined} The current store object or undefined if called outside a context.\n */\n static getAll(): Store | undefined {\n return this.storage.getStore();\n }\n\n /**\n * Initializes a new async context and executes a callback within it.\n * This must be called at the beginning of a request or logical async flow.\n *\n * @typeParam T - The callback's return type.\n * @param {Store} store - The initial key-value store object.\n * @param {() => T} callback - The function to run within the new context.\n * @returns {T} The result of the callback function.\n */\n static run<T>(store: Store, callback: () => T): T {\n return this.storage.run(store, callback);\n }\n}\n"]}
@@ -0,0 +1,58 @@
1
+ import { BinaryToTextEncoding } from "crypto";
2
+ /**
3
+ * Generates an HMAC digest using the specified algorithm and secret key.
4
+ *
5
+ * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').
6
+ * @param {string} input - The string to hash.
7
+ * @param {string} secret - The secret key for HMAC.
8
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
9
+ * @returns {string} HMAC digest as a string.
10
+ */
11
+ export declare const hmac: (algorithm: string, input: string, secret: string, encoding?: BinaryToTextEncoding) => string;
12
+ /**
13
+ * Generates a hash digest using the specified algorithm.
14
+ *
15
+ * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').
16
+ * @param {string} input - The string to hash.
17
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
18
+ * @returns {string} Hash digest as a string.
19
+ */
20
+ export declare const hash: (algorithm: string, input: string, encoding?: BinaryToTextEncoding) => string;
21
+ /**
22
+ * Generates an HMAC-SHA256 digest.
23
+ *
24
+ * @param {string} input - The string to hash.
25
+ * @param {string} secret - The secret key.
26
+ * @returns {string} SHA-256 HMAC digest as a string.
27
+ */
28
+ export declare const sha256Hmac: (input: string, secret: string) => string;
29
+ /**
30
+ * Generates a SHA1 hash digest.
31
+ *
32
+ * @param {string} input - The string to hash.
33
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
34
+ * @returns {string} SHA-1 hash as a string.
35
+ */
36
+ export declare const sha1: (input: string, encoding?: BinaryToTextEncoding) => string;
37
+ /**
38
+ * Generates a SHA256 hash digest.
39
+ *
40
+ * @param {string} input - The string to hash.
41
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
42
+ * @returns {string} SHA-256 hash as a string.
43
+ */
44
+ export declare const sha256: (input: string, encoding?: BinaryToTextEncoding) => string;
45
+ /**
46
+ * Generates an MD5 hash digest.
47
+ *
48
+ * @param {string} input - The string to hash.
49
+ * @returns {string} MD5 hash as a string.
50
+ */
51
+ export declare const md5: (input: string) => string;
52
+ /**
53
+ * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
54
+ *
55
+ * @returns {string} Random string hashed with SHA-256 (hex encoding).
56
+ */
57
+ export declare const randomString: () => string;
58
+ //# sourceMappingURL=crypto.utils.d.ts.map
@@ -0,0 +1,72 @@
1
+ import { createHmac, createHash, randomUUID, } from "crypto";
2
+ /**
3
+ * Generates an HMAC digest using the specified algorithm and secret key.
4
+ *
5
+ * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').
6
+ * @param {string} input - The string to hash.
7
+ * @param {string} secret - The secret key for HMAC.
8
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
9
+ * @returns {string} HMAC digest as a string.
10
+ */
11
+ export const hmac = (algorithm, input, secret, encoding = "hex") => {
12
+ return createHmac(algorithm, secret).update(input).digest(encoding);
13
+ };
14
+ /**
15
+ * Generates a hash digest using the specified algorithm.
16
+ *
17
+ * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').
18
+ * @param {string} input - The string to hash.
19
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
20
+ * @returns {string} Hash digest as a string.
21
+ */
22
+ export const hash = (algorithm, input, encoding = "hex") => {
23
+ return createHash(algorithm).update(input).digest(encoding);
24
+ };
25
+ /**
26
+ * Generates an HMAC-SHA256 digest.
27
+ *
28
+ * @param {string} input - The string to hash.
29
+ * @param {string} secret - The secret key.
30
+ * @returns {string} SHA-256 HMAC digest as a string.
31
+ */
32
+ export const sha256Hmac = (input, secret) => {
33
+ return hmac("sha256", input, secret);
34
+ };
35
+ /**
36
+ * Generates a SHA1 hash digest.
37
+ *
38
+ * @param {string} input - The string to hash.
39
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
40
+ * @returns {string} SHA-1 hash as a string.
41
+ */
42
+ export const sha1 = (input, encoding = "hex") => {
43
+ return hash("sha1", input, encoding);
44
+ };
45
+ /**
46
+ * Generates a SHA256 hash digest.
47
+ *
48
+ * @param {string} input - The string to hash.
49
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
50
+ * @returns {string} SHA-256 hash as a string.
51
+ */
52
+ export const sha256 = (input, encoding = "hex") => {
53
+ return hash("sha256", input, encoding);
54
+ };
55
+ /**
56
+ * Generates an MD5 hash digest.
57
+ *
58
+ * @param {string} input - The string to hash.
59
+ * @returns {string} MD5 hash as a string.
60
+ */
61
+ export const md5 = (input) => {
62
+ return hash("md5", input);
63
+ };
64
+ /**
65
+ * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
66
+ *
67
+ * @returns {string} Random string hashed with SHA-256 (hex encoding).
68
+ */
69
+ export const randomString = () => {
70
+ return sha256(randomUUID());
71
+ };
72
+ //# sourceMappingURL=crypto.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,UAAU,EAEV,UAAU,GACX,MAAM,QAAQ,CAAC;AAEhB;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAClB,SAAiB,EACjB,KAAa,EACb,MAAc,EACd,WAAiC,KAAK,EAC9B,EAAE;IACV,OAAO,UAAU,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACtE,CAAC,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAClB,SAAiB,EACjB,KAAa,EACb,WAAiC,KAAK,EAC9B,EAAE;IACV,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC9D,CAAC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,KAAa,EAAE,MAAc,EAAU,EAAE;IAClE,OAAO,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AACvC,CAAC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAClB,KAAa,EACb,WAAiC,KAAK,EAC9B,EAAE;IACV,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AACvC,CAAC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CACpB,KAAa,EACb,WAAiC,KAAK,EAC9B,EAAE;IACV,OAAO,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AACzC,CAAC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,KAAa,EAAU,EAAE;IAC3C,OAAO,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AAC5B,CAAC,CAAC;AAEF;;;;GAIG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,GAAW,EAAE;IACvC,OAAO,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;AAC9B,CAAC,CAAC","sourcesContent":["import {\n createHmac,\n createHash,\n BinaryToTextEncoding,\n randomUUID,\n} from \"crypto\";\n\n/**\n * Generates an HMAC digest using the specified algorithm and secret key.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key for HMAC.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} HMAC digest as a string.\n */\nexport const hmac = (\n algorithm: string,\n input: string,\n secret: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string => {\n return createHmac(algorithm, secret).update(input).digest(encoding);\n};\n\n/**\n * Generates a hash digest using the specified algorithm.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} Hash digest as a string.\n */\nexport const hash = (\n algorithm: string,\n input: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string => {\n return createHash(algorithm).update(input).digest(encoding);\n};\n\n/**\n * Generates an HMAC-SHA256 digest.\n *\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key.\n * @returns {string} SHA-256 HMAC digest as a string.\n */\nexport const sha256Hmac = (input: string, secret: string): string => {\n return hmac(\"sha256\", input, secret);\n};\n\n/**\n * Generates a SHA1 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-1 hash as a string.\n */\nexport const sha1 = (\n input: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string => {\n return hash(\"sha1\", input, encoding);\n};\n\n/**\n * Generates a SHA256 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-256 hash as a string.\n */\nexport const sha256 = (\n input: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string => {\n return hash(\"sha256\", input, encoding);\n};\n\n/**\n * Generates an MD5 hash digest.\n *\n * @param {string} input - The string to hash.\n * @returns {string} MD5 hash as a string.\n */\nexport const md5 = (input: string): string => {\n return hash(\"md5\", input);\n};\n\n/**\n * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.\n *\n * @returns {string} Random string hashed with SHA-256 (hex encoding).\n */\nexport const randomString = (): string => {\n return sha256(randomUUID());\n};\n"]}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).
3
+ *
4
+ * @param {string} dirPath - The directory path to ensure.
5
+ * @returns {Promise<void>} Resolves when the directory exists.
6
+ * @throws {Error} If directory cannot be created.
7
+ */
8
+ export declare function ensureDir(dirPath: string): Promise<void>;
9
+ /**
10
+ * Recursively lists all files in a directory.
11
+ *
12
+ * @param {string} dirPath - The base directory.
13
+ * @param {boolean} [recursive=false] - Whether to recurse into subdirectories.
14
+ * @returns {Promise<string[]>} Array of absolute file paths.
15
+ * @throws {Error} If the directory cannot be read.
16
+ */
17
+ export declare function listFiles(dirPath: string, recursive?: boolean): Promise<string[]>;
18
+ /**
19
+ * Deletes a directory and all its contents recursively (like `rm -rf`).
20
+ *
21
+ * @param {string} dirPath - Directory to delete.
22
+ * @returns {Promise<void>} Resolves when deletion is complete.
23
+ * @throws {Error} If deletion fails.
24
+ */
25
+ export declare function deleteDirRecursive(dirPath: string): Promise<void>;
26
+ /**
27
+ * Checks whether a given path is a directory.
28
+ *
29
+ * @param {string} pathStr - Path to check.
30
+ * @returns {Promise<boolean>} True if the path is a directory, else false.
31
+ */
32
+ export declare function isDirectory(pathStr: string): Promise<boolean>;
33
+ /**
34
+ * Recursively copies a directory and all its contents to a destination.
35
+ *
36
+ * @param {string} src - Source directory path.
37
+ * @param {string} dest - Destination directory path.
38
+ * @returns {Promise<void>} Resolves when copy is complete.
39
+ * @throws {Error} If source does not exist or copy fails.
40
+ */
41
+ export declare function copyDir(src: string, dest: string): Promise<void>;
42
+ /**
43
+ * Moves a directory to a new location by copying and deleting the original.
44
+ *
45
+ * @param {string} src - Source directory path.
46
+ * @param {string} dest - Destination directory path.
47
+ * @returns {Promise<void>} Resolves when move is complete.
48
+ * @throws {Error} If copy or deletion fails.
49
+ */
50
+ export declare function moveDir(src: string, dest: string): Promise<void>;
51
+ /**
52
+ * Empties a directory by deleting all files and subdirectories inside it.
53
+ *
54
+ * @param {string} dirPath - Path to the directory to empty.
55
+ * @returns {Promise<void>} Resolves when the directory has been emptied.
56
+ * @throws {Error} If files or subdirectories cannot be removed.
57
+ */
58
+ export declare function emptyDir(dirPath: string): Promise<void>;
59
+ /**
60
+ * Calculates the total size (in bytes) of all files in a directory (recursive).
61
+ *
62
+ * @param {string} dirPath - Path to the directory.
63
+ * @returns {Promise<number>} Total size in bytes.
64
+ * @throws {Error} If any file stats cannot be read.
65
+ */
66
+ export declare function getDirSize(dirPath: string): Promise<number>;
67
+ /**
68
+ * Watches a directory for file changes and calls a callback on each event.
69
+ *
70
+ * @param {string} dirPath - Directory path to watch.
71
+ * @param {(eventType: "rename" | "change", filename: string | null) => void} callback - Callback for each change event.
72
+ * @returns {() => void} A function to stop watching the directory.
73
+ */
74
+ export declare function watchDir(dirPath: string, callback: (eventType: "rename" | "change", filename: string | null) => void): () => void;
75
+ //# sourceMappingURL=dir.utils.d.ts.map
@@ -0,0 +1,150 @@
1
+ import fs from "fs";
2
+ import fsp from "fs/promises";
3
+ import path from "path";
4
+ /**
5
+ * Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).
6
+ *
7
+ * @param {string} dirPath - The directory path to ensure.
8
+ * @returns {Promise<void>} Resolves when the directory exists.
9
+ * @throws {Error} If directory cannot be created.
10
+ */
11
+ export async function ensureDir(dirPath) {
12
+ await fsp.mkdir(dirPath, { recursive: true });
13
+ }
14
+ /**
15
+ * Recursively lists all files in a directory.
16
+ *
17
+ * @param {string} dirPath - The base directory.
18
+ * @param {boolean} [recursive=false] - Whether to recurse into subdirectories.
19
+ * @returns {Promise<string[]>} Array of absolute file paths.
20
+ * @throws {Error} If the directory cannot be read.
21
+ */
22
+ export async function listFiles(dirPath, recursive = false) {
23
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true });
24
+ const files = [];
25
+ for (const entry of entries) {
26
+ const fullPath = path.join(dirPath, entry.name);
27
+ if (entry.isFile()) {
28
+ files.push(fullPath);
29
+ }
30
+ else if (recursive && entry.isDirectory()) {
31
+ const nestedFiles = await listFiles(fullPath, true);
32
+ files.push(...nestedFiles);
33
+ }
34
+ }
35
+ return files;
36
+ }
37
+ /**
38
+ * Deletes a directory and all its contents recursively (like `rm -rf`).
39
+ *
40
+ * @param {string} dirPath - Directory to delete.
41
+ * @returns {Promise<void>} Resolves when deletion is complete.
42
+ * @throws {Error} If deletion fails.
43
+ */
44
+ export async function deleteDirRecursive(dirPath) {
45
+ await fsp.rm(dirPath, { recursive: true, force: true });
46
+ }
47
+ /**
48
+ * Checks whether a given path is a directory.
49
+ *
50
+ * @param {string} pathStr - Path to check.
51
+ * @returns {Promise<boolean>} True if the path is a directory, else false.
52
+ */
53
+ export async function isDirectory(pathStr) {
54
+ try {
55
+ const stat = await fsp.stat(pathStr);
56
+ return stat.isDirectory();
57
+ }
58
+ catch (_a) {
59
+ return false;
60
+ }
61
+ }
62
+ /**
63
+ * Recursively copies a directory and all its contents to a destination.
64
+ *
65
+ * @param {string} src - Source directory path.
66
+ * @param {string} dest - Destination directory path.
67
+ * @returns {Promise<void>} Resolves when copy is complete.
68
+ * @throws {Error} If source does not exist or copy fails.
69
+ */
70
+ export async function copyDir(src, dest) {
71
+ await ensureDir(dest);
72
+ const entries = await fsp.readdir(src, { withFileTypes: true });
73
+ for (const entry of entries) {
74
+ const srcPath = path.join(src, entry.name);
75
+ const destPath = path.join(dest, entry.name);
76
+ if (entry.isDirectory()) {
77
+ await copyDir(srcPath, destPath);
78
+ }
79
+ else {
80
+ await fsp.copyFile(srcPath, destPath);
81
+ }
82
+ }
83
+ }
84
+ /**
85
+ * Moves a directory to a new location by copying and deleting the original.
86
+ *
87
+ * @param {string} src - Source directory path.
88
+ * @param {string} dest - Destination directory path.
89
+ * @returns {Promise<void>} Resolves when move is complete.
90
+ * @throws {Error} If copy or deletion fails.
91
+ */
92
+ export async function moveDir(src, dest) {
93
+ await copyDir(src, dest);
94
+ await deleteDirRecursive(src);
95
+ }
96
+ /**
97
+ * Empties a directory by deleting all files and subdirectories inside it.
98
+ *
99
+ * @param {string} dirPath - Path to the directory to empty.
100
+ * @returns {Promise<void>} Resolves when the directory has been emptied.
101
+ * @throws {Error} If files or subdirectories cannot be removed.
102
+ */
103
+ export async function emptyDir(dirPath) {
104
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true });
105
+ for (const entry of entries) {
106
+ const entryPath = path.join(dirPath, entry.name);
107
+ if (entry.isDirectory()) {
108
+ await fsp.rm(entryPath, { recursive: true, force: true });
109
+ }
110
+ else {
111
+ await fsp.unlink(entryPath);
112
+ }
113
+ }
114
+ }
115
+ /**
116
+ * Calculates the total size (in bytes) of all files in a directory (recursive).
117
+ *
118
+ * @param {string} dirPath - Path to the directory.
119
+ * @returns {Promise<number>} Total size in bytes.
120
+ * @throws {Error} If any file stats cannot be read.
121
+ */
122
+ export async function getDirSize(dirPath) {
123
+ let total = 0;
124
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true });
125
+ for (const entry of entries) {
126
+ const entryPath = path.join(dirPath, entry.name);
127
+ if (entry.isDirectory()) {
128
+ total += await getDirSize(entryPath);
129
+ }
130
+ else {
131
+ const stat = await fsp.stat(entryPath);
132
+ total += stat.size;
133
+ }
134
+ }
135
+ return total;
136
+ }
137
+ /**
138
+ * Watches a directory for file changes and calls a callback on each event.
139
+ *
140
+ * @param {string} dirPath - Directory path to watch.
141
+ * @param {(eventType: "rename" | "change", filename: string | null) => void} callback - Callback for each change event.
142
+ * @returns {() => void} A function to stop watching the directory.
143
+ */
144
+ export function watchDir(dirPath, callback) {
145
+ const watcher = fs.watch(dirPath, (eventType, filename) => {
146
+ callback(eventType, filename);
147
+ });
148
+ return () => watcher.close();
149
+ }
150
+ //# sourceMappingURL=dir.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dir.utils.js","sourceRoot":"","sources":["../../../src/utils/dir.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,GAAG,MAAM,aAAa,CAAC;AAC9B,OAAO,IAAI,MAA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,CAAC,CAAC;IAChC,CAAC,CAAC,CAAC;IAEH,OAAO,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["import fs from \"fs\";\nimport fsp from \"fs/promises\";\nimport path from \"path\";\n\n/**\n * Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).\n *\n * @param {string} dirPath - The directory path to ensure.\n * @returns {Promise<void>} Resolves when the directory exists.\n * @throws {Error} If directory cannot be created.\n */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await fsp.mkdir(dirPath, { recursive: true });\n}\n\n/**\n * Recursively lists all files in a directory.\n *\n * @param {string} dirPath - The base directory.\n * @param {boolean} [recursive=false] - Whether to recurse into subdirectories.\n * @returns {Promise<string[]>} Array of absolute file paths.\n * @throws {Error} If the directory cannot be read.\n */\nexport async function listFiles(\n dirPath: string,\n recursive = false,\n): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const files: string[] = [];\n\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry.name);\n\n if (entry.isFile()) {\n files.push(fullPath);\n } else if (recursive && entry.isDirectory()) {\n const nestedFiles = await listFiles(fullPath, true);\n files.push(...nestedFiles);\n }\n }\n\n return files;\n}\n\n/**\n * Deletes a directory and all its contents recursively (like `rm -rf`).\n *\n * @param {string} dirPath - Directory to delete.\n * @returns {Promise<void>} Resolves when deletion is complete.\n * @throws {Error} If deletion fails.\n */\nexport async function deleteDirRecursive(dirPath: string): Promise<void> {\n await fsp.rm(dirPath, { recursive: true, force: true });\n}\n\n/**\n * Checks whether a given path is a directory.\n *\n * @param {string} pathStr - Path to check.\n * @returns {Promise<boolean>} True if the path is a directory, else false.\n */\nexport async function isDirectory(pathStr: string): Promise<boolean> {\n try {\n const stat = await fsp.stat(pathStr);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Recursively copies a directory and all its contents to a destination.\n *\n * @param {string} src - Source directory path.\n * @param {string} dest - Destination directory path.\n * @returns {Promise<void>} Resolves when copy is complete.\n * @throws {Error} If source does not exist or copy fails.\n */\nexport async function copyDir(src: string, dest: string): Promise<void> {\n await ensureDir(dest);\n const entries = await fsp.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await copyDir(srcPath, destPath);\n } else {\n await fsp.copyFile(srcPath, destPath);\n }\n }\n}\n\n/**\n * Moves a directory to a new location by copying and deleting the original.\n *\n * @param {string} src - Source directory path.\n * @param {string} dest - Destination directory path.\n * @returns {Promise<void>} Resolves when move is complete.\n * @throws {Error} If copy or deletion fails.\n */\nexport async function moveDir(src: string, dest: string): Promise<void> {\n await copyDir(src, dest);\n await deleteDirRecursive(src);\n}\n\n/**\n * Empties a directory by deleting all files and subdirectories inside it.\n *\n * @param {string} dirPath - Path to the directory to empty.\n * @returns {Promise<void>} Resolves when the directory has been emptied.\n * @throws {Error} If files or subdirectories cannot be removed.\n */\nexport async function emptyDir(dirPath: string): Promise<void> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n\n if (entry.isDirectory()) {\n await fsp.rm(entryPath, { recursive: true, force: true });\n } else {\n await fsp.unlink(entryPath);\n }\n }\n}\n\n/**\n * Calculates the total size (in bytes) of all files in a directory (recursive).\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<number>} Total size in bytes.\n * @throws {Error} If any file stats cannot be read.\n */\nexport async function getDirSize(dirPath: string): Promise<number> {\n let total = 0;\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n if (entry.isDirectory()) {\n total += await getDirSize(entryPath);\n } else {\n const stat = await fsp.stat(entryPath);\n total += stat.size;\n }\n }\n\n return total;\n}\n\n/**\n * Watches a directory for file changes and calls a callback on each event.\n *\n * @param {string} dirPath - Directory path to watch.\n * @param {(eventType: \"rename\" | \"change\", filename: string | null) => void} callback - Callback for each change event.\n * @returns {() => void} A function to stop watching the directory.\n */\nexport function watchDir(\n dirPath: string,\n callback: (eventType: \"rename\" | \"change\", filename: string | null) => void,\n): () => void {\n const watcher = fs.watch(dirPath, (eventType, filename) => {\n callback(eventType, filename);\n });\n\n return () => watcher.close();\n}\n"]}