@catbee/utils 0.0.2 → 0.0.4

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 (170) hide show
  1. package/README.md +1 -4
  2. package/build/esm/config.d.ts +1 -5
  3. package/build/esm/config.js +6 -10
  4. package/build/esm/config.js.map +1 -1
  5. package/build/esm/index.d.ts +20 -19
  6. package/build/esm/index.js +20 -19
  7. package/build/esm/index.js.map +1 -1
  8. package/build/esm/types/api-response.d.ts +2 -2
  9. package/build/esm/types/api-response.js.map +1 -1
  10. package/build/esm/utils/array.utils.d.ts +1 -1
  11. package/build/esm/utils/array.utils.js +17 -27
  12. package/build/esm/utils/array.utils.js.map +1 -1
  13. package/build/esm/utils/async.utils.d.ts +1 -5
  14. package/build/esm/utils/async.utils.js +17 -20
  15. package/build/esm/utils/async.utils.js.map +1 -1
  16. package/build/esm/utils/cache.utils.js +2 -2
  17. package/build/esm/utils/cache.utils.js.map +1 -1
  18. package/build/esm/utils/context-store.utils.d.ts +1 -1
  19. package/build/esm/utils/context-store.utils.js +8 -8
  20. package/build/esm/utils/context-store.utils.js.map +1 -1
  21. package/build/esm/utils/crypto.utils.d.ts +2 -2
  22. package/build/esm/utils/crypto.utils.js +37 -45
  23. package/build/esm/utils/crypto.utils.js.map +1 -1
  24. package/build/esm/utils/decorators.utils.d.ts +2 -18
  25. package/build/esm/utils/decorators.utils.js +31 -31
  26. package/build/esm/utils/decorators.utils.js.map +1 -1
  27. package/build/esm/utils/dir.utils.d.ts +4 -4
  28. package/build/esm/utils/dir.utils.js +18 -20
  29. package/build/esm/utils/dir.utils.js.map +1 -1
  30. package/build/esm/utils/env.utils.js +22 -26
  31. package/build/esm/utils/env.utils.js.map +1 -1
  32. package/build/esm/utils/exception.utils.d.ts +1 -1
  33. package/build/esm/utils/exception.utils.js +26 -29
  34. package/build/esm/utils/exception.utils.js.map +1 -1
  35. package/build/esm/utils/fs.utils.d.ts +3 -3
  36. package/build/esm/utils/fs.utils.js +19 -23
  37. package/build/esm/utils/fs.utils.js.map +1 -1
  38. package/build/esm/utils/http-status-codes.js.map +1 -1
  39. package/build/esm/utils/id.utils.js +8 -8
  40. package/build/esm/utils/id.utils.js.map +1 -1
  41. package/build/esm/utils/logger.utils.d.ts +13 -4
  42. package/build/esm/utils/logger.utils.js +16 -18
  43. package/build/esm/utils/logger.utils.js.map +1 -1
  44. package/build/esm/utils/middleware.utils.d.ts +15 -26
  45. package/build/esm/utils/middleware.utils.js +80 -59
  46. package/build/esm/utils/middleware.utils.js.map +1 -1
  47. package/build/esm/utils/obj.utils.js +16 -27
  48. package/build/esm/utils/obj.utils.js.map +1 -1
  49. package/build/esm/utils/response.utils.d.ts +2 -2
  50. package/build/esm/utils/response.utils.js +11 -11
  51. package/build/esm/utils/response.utils.js.map +1 -1
  52. package/build/esm/utils/string.utils.js +17 -17
  53. package/build/esm/utils/string.utils.js.map +1 -1
  54. package/build/esm/utils/url.utils.js +20 -22
  55. package/build/esm/utils/url.utils.js.map +1 -1
  56. package/build/esm/utils/validate.utils.js +11 -15
  57. package/build/esm/utils/validate.utils.js.map +1 -1
  58. package/build/esnext/config.d.ts +1 -5
  59. package/build/esnext/config.js +6 -10
  60. package/build/esnext/config.js.map +1 -1
  61. package/build/esnext/index.d.ts +20 -19
  62. package/build/esnext/index.js +20 -19
  63. package/build/esnext/index.js.map +1 -1
  64. package/build/esnext/types/api-response.d.ts +2 -2
  65. package/build/esnext/types/api-response.js.map +1 -1
  66. package/build/esnext/utils/array.utils.d.ts +1 -1
  67. package/build/esnext/utils/array.utils.js +23 -31
  68. package/build/esnext/utils/array.utils.js.map +1 -1
  69. package/build/esnext/utils/async.utils.d.ts +1 -5
  70. package/build/esnext/utils/async.utils.js +22 -22
  71. package/build/esnext/utils/async.utils.js.map +1 -1
  72. package/build/esnext/utils/cache.utils.js +3 -3
  73. package/build/esnext/utils/cache.utils.js.map +1 -1
  74. package/build/esnext/utils/context-store.utils.d.ts +1 -1
  75. package/build/esnext/utils/context-store.utils.js +10 -10
  76. package/build/esnext/utils/context-store.utils.js.map +1 -1
  77. package/build/esnext/utils/crypto.utils.d.ts +2 -2
  78. package/build/esnext/utils/crypto.utils.js +37 -47
  79. package/build/esnext/utils/crypto.utils.js.map +1 -1
  80. package/build/esnext/utils/decorators.utils.d.ts +2 -18
  81. package/build/esnext/utils/decorators.utils.js +33 -33
  82. package/build/esnext/utils/decorators.utils.js.map +1 -1
  83. package/build/esnext/utils/dir.utils.d.ts +4 -4
  84. package/build/esnext/utils/dir.utils.js +22 -24
  85. package/build/esnext/utils/dir.utils.js.map +1 -1
  86. package/build/esnext/utils/env.utils.js +24 -26
  87. package/build/esnext/utils/env.utils.js.map +1 -1
  88. package/build/esnext/utils/exception.utils.d.ts +1 -1
  89. package/build/esnext/utils/exception.utils.js +26 -29
  90. package/build/esnext/utils/exception.utils.js.map +1 -1
  91. package/build/esnext/utils/fs.utils.d.ts +3 -3
  92. package/build/esnext/utils/fs.utils.js +21 -25
  93. package/build/esnext/utils/fs.utils.js.map +1 -1
  94. package/build/esnext/utils/http-status-codes.js.map +1 -1
  95. package/build/esnext/utils/id.utils.js +8 -8
  96. package/build/esnext/utils/id.utils.js.map +1 -1
  97. package/build/esnext/utils/logger.utils.d.ts +13 -4
  98. package/build/esnext/utils/logger.utils.js +16 -18
  99. package/build/esnext/utils/logger.utils.js.map +1 -1
  100. package/build/esnext/utils/middleware.utils.d.ts +15 -26
  101. package/build/esnext/utils/middleware.utils.js +78 -59
  102. package/build/esnext/utils/middleware.utils.js.map +1 -1
  103. package/build/esnext/utils/obj.utils.js +17 -26
  104. package/build/esnext/utils/obj.utils.js.map +1 -1
  105. package/build/esnext/utils/response.utils.d.ts +2 -2
  106. package/build/esnext/utils/response.utils.js +11 -11
  107. package/build/esnext/utils/response.utils.js.map +1 -1
  108. package/build/esnext/utils/string.utils.js +17 -17
  109. package/build/esnext/utils/string.utils.js.map +1 -1
  110. package/build/esnext/utils/url.utils.js +21 -23
  111. package/build/esnext/utils/url.utils.js.map +1 -1
  112. package/build/esnext/utils/validate.utils.js +14 -16
  113. package/build/esnext/utils/validate.utils.js.map +1 -1
  114. package/build/src/config.d.ts +1 -5
  115. package/build/src/config.js +5 -9
  116. package/build/src/config.js.map +1 -1
  117. package/build/src/index.d.ts +20 -19
  118. package/build/src/index.js +1 -0
  119. package/build/src/index.js.map +1 -1
  120. package/build/src/types/api-response.d.ts +2 -2
  121. package/build/src/types/api-response.js.map +1 -1
  122. package/build/src/utils/array.utils.d.ts +1 -1
  123. package/build/src/utils/array.utils.js +22 -30
  124. package/build/src/utils/array.utils.js.map +1 -1
  125. package/build/src/utils/async.utils.d.ts +1 -5
  126. package/build/src/utils/async.utils.js +22 -22
  127. package/build/src/utils/async.utils.js.map +1 -1
  128. package/build/src/utils/cache.utils.js +2 -2
  129. package/build/src/utils/cache.utils.js.map +1 -1
  130. package/build/src/utils/context-store.utils.d.ts +1 -1
  131. package/build/src/utils/context-store.utils.js +9 -9
  132. package/build/src/utils/context-store.utils.js.map +1 -1
  133. package/build/src/utils/crypto.utils.d.ts +2 -2
  134. package/build/src/utils/crypto.utils.js +35 -45
  135. package/build/src/utils/crypto.utils.js.map +1 -1
  136. package/build/src/utils/decorators.utils.d.ts +2 -18
  137. package/build/src/utils/decorators.utils.js +32 -32
  138. package/build/src/utils/decorators.utils.js.map +1 -1
  139. package/build/src/utils/dir.utils.d.ts +4 -4
  140. package/build/src/utils/dir.utils.js +16 -18
  141. package/build/src/utils/dir.utils.js.map +1 -1
  142. package/build/src/utils/env.utils.js +22 -24
  143. package/build/src/utils/env.utils.js.map +1 -1
  144. package/build/src/utils/exception.utils.d.ts +1 -1
  145. package/build/src/utils/exception.utils.js +23 -26
  146. package/build/src/utils/exception.utils.js.map +1 -1
  147. package/build/src/utils/fs.utils.d.ts +3 -3
  148. package/build/src/utils/fs.utils.js +15 -19
  149. package/build/src/utils/fs.utils.js.map +1 -1
  150. package/build/src/utils/http-status-codes.js.map +1 -1
  151. package/build/src/utils/id.utils.js +7 -7
  152. package/build/src/utils/id.utils.js.map +1 -1
  153. package/build/src/utils/logger.utils.d.ts +13 -4
  154. package/build/src/utils/logger.utils.js +13 -15
  155. package/build/src/utils/logger.utils.js.map +1 -1
  156. package/build/src/utils/middleware.utils.d.ts +15 -26
  157. package/build/src/utils/middleware.utils.js +72 -52
  158. package/build/src/utils/middleware.utils.js.map +1 -1
  159. package/build/src/utils/obj.utils.js +17 -26
  160. package/build/src/utils/obj.utils.js.map +1 -1
  161. package/build/src/utils/response.utils.d.ts +2 -2
  162. package/build/src/utils/response.utils.js +9 -9
  163. package/build/src/utils/response.utils.js.map +1 -1
  164. package/build/src/utils/string.utils.js +17 -17
  165. package/build/src/utils/string.utils.js.map +1 -1
  166. package/build/src/utils/url.utils.js +20 -22
  167. package/build/src/utils/url.utils.js.map +1 -1
  168. package/build/src/utils/validate.utils.js +14 -16
  169. package/build/src/utils/validate.utils.js.map +1 -1
  170. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"dir.utils.js","sourceRoot":"","sources":["../../../src/utils/dir.utils.ts"],"names":[],"mappings":";;;;;AAcA,8BAEC;AAUD,8BAmBC;AASD,gDAEC;AAQD,kCAOC;AAUD,0BAcC;AAUD,0BAGC;AASD,4BAYC;AASD,gCAeC;AASD,4BASC;AAaD,gDAMC;AAUD,8CAiBC;AASD,wCAcC;AAYD,sCAoCC;AAUD,wCAeC;AAUD,wCAeC;AAWD,8BAuBC;AAWD,8CAwDC;AASD,kCA2BC;AAYD,0BAwDC;AA/hBD,4CAAoB;AACpB,4CAAoB;AACpB,2DAA8B;AAC9B,gDAAwB;AACxB,+BAA4B;AAC5B,mCAAqC;AAErC;;;;;;GAMG;AACI,KAAK,UAAU,SAAS,CAAC,OAAe;IAC7C,MAAM,kBAAG,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;AAChD,CAAC;AAED;;;;;;;GAOG;AACI,KAAK,U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M,KAAK,GAAG,MAAM,kBAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtC,MAAM,SAAS,GAAG;YAChB,IAAI,EAAE,OAAO;YACb,IAAI,EAAE,cAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;YAC5B,WAAW,EAAE,IAAI;YACjB,KAAK;SACN,CAAC;QACF,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IACrC,CAAC;AACH,CAAC","sourcesContent":["import os from \"os\";\nimport fs from \"fs\";\nimport fsp from \"fs/promises\";\nimport path from \"path\";\nimport { glob } from \"glob\";\nimport { randomBytes } from \"crypto\";\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\n/**\n * Finds files matching a glob pattern.\n *\n * @param {string} pattern - Glob pattern to match files.\n * @param {object} [options] - Options for glob pattern matching.\n * @param {string} [options.cwd] - Current working directory for relative patterns.\n * @param {boolean} [options.dot=false] - Include dotfiles in matches.\n * @param {boolean} [options.nodir=true] - Only match files, not directories.\n * @returns {Promise<string[]>} Array of matched file paths.\n * @throws {Error} If pattern matching fails.\n */\nexport async function findFilesByPattern(\n pattern: string,\n options: { cwd?: string; dot?: boolean; nodir?: boolean } = {},\n): Promise<string[]> {\n const defaultOptions = { nodir: true, ...options };\n return glob(pattern, defaultOptions);\n}\n\n/**\n * Gets all subdirectories in a directory.\n *\n * @param {string} dirPath - The directory to search in.\n * @param {boolean} [recursive=false] - Whether to include subdirectories recursively.\n * @returns {Promise<string[]>} Array of absolute subdirectory paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function getSubdirectories(\n dirPath: string,\n recursive = false,\n): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const dirs = entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => path.join(dirPath, entry.name));\n\n if (recursive && dirs.length > 0) {\n const nestedDirs = await Promise.all(\n dirs.map((dir) => getSubdirectories(dir, true)),\n );\n return [...dirs, ...nestedDirs.flat()];\n }\n\n return dirs;\n}\n\n/**\n * Ensures a directory exists and is empty.\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<void>} Resolves when the directory exists and is empty.\n * @throws {Error} If directory cannot be created or emptied.\n */\nexport async function ensureEmptyDir(dirPath: string): Promise<void> {\n if (await isDirectory(dirPath)) {\n await emptyDir(dirPath);\n } else {\n try {\n await fsp.unlink(dirPath);\n } catch (error) {\n // Ignore if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw error;\n }\n }\n await ensureDir(dirPath);\n }\n}\n\n/**\n * Creates a temporary directory with optional auto-cleanup.\n *\n * @param {object} [options] - Options for the temporary directory.\n * @param {string} [options.prefix='tmp-'] - Prefix for the directory name.\n * @param {string} [options.parentDir=os.tmpdir()] - Parent directory.\n * @param {boolean} [options.cleanup=false] - Whether to register cleanup on process exit.\n * @returns {Promise<{ path: string, cleanup: () => Promise<void> }>} Object with directory path and cleanup function.\n * @throws {Error} If directory cannot be created.\n */\nexport async function createTempDir(\n options: { prefix?: string; parentDir?: string; cleanup?: boolean } = {},\n): Promise<{ path: string; cleanup: () => Promise<void> }> {\n const prefix = options.prefix || \"tmp-\";\n const parentDir = options.parentDir || os.tmpdir();\n const dirName = `${prefix}${randomBytes(6).toString(\"hex\")}`;\n const tempDirPath = path.join(parentDir, dirName);\n\n await ensureDir(tempDirPath);\n\n const cleanup = async () => {\n try {\n await deleteDirRecursive(tempDirPath);\n } catch {\n // Ignore cleanup errors\n }\n };\n\n if (options.cleanup) {\n process.once(\"exit\", () => {\n try {\n fs.rmSync(tempDirPath, { recursive: true, force: true });\n } catch {\n // Ignore cleanup errors on exit\n }\n });\n\n // Handle signals for better cleanup\n [\"SIGINT\", \"SIGTERM\", \"SIGUSR1\", \"SIGUSR2\"].forEach((signal) => {\n process.once(signal as NodeJS.Signals, () => {\n cleanup().then(() => process.exit());\n });\n });\n }\n\n return { path: tempDirPath, cleanup };\n}\n\n/**\n * Finds the newest file in a directory.\n *\n * @param {string} dirPath - Directory to search.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string | null>} Path to the newest file or null if no files.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findNewestFile(\n dirPath: string,\n recursive = false,\n): Promise<string | null> {\n const files = await listFiles(dirPath, recursive);\n if (files.length === 0) return null;\n\n const stats = await Promise.all(\n files.map(async (file) => ({\n path: file,\n mtime: (await fsp.stat(file)).mtime,\n })),\n );\n\n return stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0].path;\n}\n\n/**\n * Finds the oldest file in a directory.\n *\n * @param {string} dirPath - Directory to search.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string | null>} Path to the oldest file or null if no files.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findOldestFile(\n dirPath: string,\n recursive = false,\n): Promise<string | null> {\n const files = await listFiles(dirPath, recursive);\n if (files.length === 0) return null;\n\n const stats = await Promise.all(\n files.map(async (file) => ({\n path: file,\n mtime: (await fsp.stat(file)).mtime,\n })),\n );\n\n return stats.sort((a, b) => a.mtime.getTime() - b.mtime.getTime())[0].path;\n}\n\n/**\n * Finds files or directories in a directory matching a predicate function.\n *\n * @param {string} dirPath - Directory to search.\n * @param {(path: string, stat: fs.Stats) => boolean | Promise<boolean>} predicate - Function to test each path.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string[]>} Array of matching paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findInDir(\n dirPath: string,\n predicate: (path: string, stat: fs.Stats) => boolean | Promise<boolean>,\n recursive = false,\n): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const results: string[] = [];\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n const stat = await fsp.stat(entryPath);\n\n if (await predicate(entryPath, stat)) {\n results.push(entryPath);\n }\n\n if (recursive && entry.isDirectory()) {\n const nestedResults = await findInDir(entryPath, predicate, true);\n results.push(...nestedResults);\n }\n }\n\n return results;\n}\n\n/**\n * Watches a directory recursively for file changes.\n *\n * @param {string} dirPath - Base directory path to watch.\n * @param {(eventType: \"rename\" | \"change\", filename: string) => void} callback - Callback for each change event.\n * @param {boolean} [includeSubdirs=true] - Whether to watch subdirectories.\n * @returns {Promise<() => void>} A function to stop watching the directory.\n * @throws {Error} If directory cannot be watched.\n */\nexport async function watchDirRecursive(\n dirPath: string,\n callback: (eventType: \"rename\" | \"change\", filename: string) => void,\n includeSubdirs = true,\n): Promise<() => void> {\n // Normalize the path to ensure consistent path separators\n const normalizedBasePath = path.normalize(dirPath);\n\n // Create watchers for the base dir and all subdirectories\n const watchers: fs.FSWatcher[] = [];\n\n // Helper function to add a watcher for a directory\n const addWatcher = (dir: string) => {\n try {\n const watcher = fs.watch(dir, (eventType, filename) => {\n if (!filename) return;\n\n const fullPath = path.join(dir, filename);\n // Make the path relative to the base directory\n const relativePath = path.relative(normalizedBasePath, fullPath);\n callback(eventType, relativePath);\n\n // If a new directory is created, we should watch it\n if (eventType === \"rename\" && includeSubdirs) {\n setTimeout(async () => {\n try {\n if (await isDirectory(fullPath)) {\n addWatcher(fullPath);\n }\n } catch {\n // Ignore errors checking newly created items\n }\n }, 100);\n }\n });\n watchers.push(watcher);\n } catch {\n // Silently ignore directories we can't watch\n }\n };\n\n // Add watcher for the base directory\n addWatcher(normalizedBasePath);\n\n // If watching subdirectories, add watchers for all existing subdirectories\n if (includeSubdirs) {\n const subdirs = await getSubdirectories(normalizedBasePath, true);\n for (const subdir of subdirs) {\n addWatcher(subdir);\n }\n }\n\n // Return a function to close all watchers\n return () => {\n watchers.forEach((watcher) => watcher.close());\n };\n}\n\n/**\n * Gets detailed directory statistics including file count, directory count, and size.\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<{ fileCount: number, dirCount: number, totalSize: number }>} Directory statistics.\n * @throws {Error} If directory cannot be read.\n */\nexport async function getDirStats(\n dirPath: string,\n): Promise<{ fileCount: number; dirCount: number; totalSize: number }> {\n let fileCount = 0;\n let dirCount = 0;\n let totalSize = 0;\n\n async function processDir(currentPath: string): Promise<void> {\n const entries = await fsp.readdir(currentPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(currentPath, entry.name);\n\n if (entry.isDirectory()) {\n dirCount++;\n await processDir(entryPath);\n } else if (entry.isFile()) {\n fileCount++;\n const stat = await fsp.stat(entryPath);\n totalSize += stat.size;\n }\n }\n }\n\n await processDir(dirPath);\n\n return { fileCount, dirCount, totalSize };\n}\n\n/**\n * Walks through a directory hierarchy, calling a visitor function for each entry.\n *\n * @param {string} dirPath - Starting directory path.\n * @param {object} options - Options for walking the directory.\n * @param {(entry: { path: string, name: string, isDirectory: boolean, stats: fs.Stats }) => boolean | void | Promise<boolean | void>} options.visitorFn -\n * Function called for each file/directory. Return false to skip a directory.\n * @param {'pre' | 'post'} [options.traversalOrder='pre'] - Whether to visit directories before or after their contents.\n * @throws {Error} If directory cannot be read.\n */\nexport async function walkDir(\n dirPath: string,\n options: {\n visitorFn: (entry: {\n path: string;\n name: string;\n isDirectory: boolean;\n stats: fs.Stats;\n }) => boolean | void | Promise<boolean | void>;\n traversalOrder?: \"pre\" | \"post\";\n },\n): Promise<void> {\n const traversalOrder = options.traversalOrder || \"pre\";\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 const stats = await fsp.stat(entryPath);\n const entryInfo = {\n path: entryPath,\n name: entry.name,\n isDirectory: entry.isDirectory(),\n stats,\n };\n\n if (entry.isDirectory()) {\n // Pre-order: visit directory before its contents\n if (traversalOrder === \"pre\") {\n const shouldContinue = await options.visitorFn(entryInfo);\n // If the visitor returns false, don't recurse into this directory\n if (shouldContinue !== false) {\n await walkDir(entryPath, options);\n }\n } else {\n // Post-order: visit directory after its contents\n await walkDir(entryPath, options);\n await options.visitorFn(entryInfo);\n }\n } else {\n // Files are always visited when encountered\n await options.visitorFn(entryInfo);\n }\n }\n\n if (traversalOrder === \"post\") {\n // Only visit the root if this is the top-level call (not for subdirectories)\n // But since this function is always called recursively, always visit after children\n const stats = await fsp.stat(dirPath);\n const entryInfo = {\n path: dirPath,\n name: path.basename(dirPath),\n isDirectory: true,\n stats,\n };\n await options.visitorFn(entryInfo);\n }\n}\n"]}
1
+ {"version":3,"file":"dir.utils.js","sourceRoot":"","sources":["../../../src/utils/dir.utils.ts"],"names":[],"mappings":";;;;;AAcA,8BAEC;AAUD,8BAgBC;AASD,gDAEC;AAQD,kCAOC;AAUD,0BAcC;AAUD,0BAGC;AASD,4BAYC;AASD,gCAeC;AASD,4BASC;AAaD,gDAMC;AAUD,8CAUC;AASD,wCAcC;AAYD,sCAoCC;AAUD,wCAYC;AAUD,wCAYC;AAWD,8BAuBC;AAWD,8CAwDC;AASD,kCA2BC;AAYD,0BAwDC;AA/gBD,4CAAoB;AACpB,4CAAoB;AACpB,2DAA8B;AAC9B,gDAAwB;AACxB,+BAA4B;AAC5B,mCAAqC;AAErC;;;;;;GAMG;AACI,KAAK,UAAU,SAAS,CAAC,OAAe;IAC7C,MAAM,kBAAG,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;AAChD,CAAC;AAED;;;;;;;GAOG;AACI,KAAK,UAAU,SAAS,CAAC,OAAe,EAAE,SAAS,GAAG,KAAK;IAChE,MAAM,OAAO,GAAG,MAAM,kBAAG,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;IACpE,MAAM,KAAK,GAAa,EAAE,CAAC;IAE3B,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,QAAQ,GAAG,cAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QAEhD,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC;YACnB,KAAK,CAAC,IAAI,CAAC,QA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ChB,IAAI,EAAE,SAAS;YACf,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,WAAW,EAAE,KAAK,CAAC,WAAW,EAAE;YAChC,KAAK;SACN,CAAC;QAEF,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;YACxB,iDAAiD;YACjD,IAAI,cAAc,KAAK,KAAK,EAAE,CAAC;gBAC7B,MAAM,cAAc,GAAG,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;gBAC1D,kEAAkE;gBAClE,IAAI,cAAc,KAAK,KAAK,EAAE,CAAC;oBAC7B,MAAM,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;gBACpC,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,iDAAiD;gBACjD,MAAM,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;gBAClC,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;YACrC,CAAC;QACH,CAAC;aAAM,CAAC;YACN,4CAA4C;YAC5C,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;QACrC,CAAC;IACH,CAAC;IAED,IAAI,cAAc,KAAK,MAAM,EAAE,CAAC;QAC9B,6EAA6E;QAC7E,oFAAoF;QACpF,MAAM,KAAK,GAAG,MAAM,kBAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtC,MAAM,SAAS,GAAG;YAChB,IAAI,EAAE,OAAO;YACb,IAAI,EAAE,cAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;YAC5B,WAAW,EAAE,IAAI;YACjB,KAAK;SACN,CAAC;QACF,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IACrC,CAAC;AACH,CAAC","sourcesContent":["import os from 'os';\nimport fs from 'fs';\nimport fsp from 'fs/promises';\nimport path from 'path';\nimport { glob } from 'glob';\nimport { randomBytes } from 'crypto';\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(dirPath: string, recursive = false): 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\n/**\n * Finds files matching a glob pattern.\n *\n * @param {string} pattern - Glob pattern to match files.\n * @param {object} [options] - Options for glob pattern matching.\n * @param {string} [options.cwd] - Current working directory for relative patterns.\n * @param {boolean} [options.dot=false] - Include dotfiles in matches.\n * @param {boolean} [options.nodir=true] - Only match files, not directories.\n * @returns {Promise<string[]>} Array of matched file paths.\n * @throws {Error} If pattern matching fails.\n */\nexport async function findFilesByPattern(\n pattern: string,\n options: { cwd?: string; dot?: boolean; nodir?: boolean } = {}\n): Promise<string[]> {\n const defaultOptions = { nodir: true, ...options };\n return glob(pattern, defaultOptions);\n}\n\n/**\n * Gets all subdirectories in a directory.\n *\n * @param {string} dirPath - The directory to search in.\n * @param {boolean} [recursive=false] - Whether to include subdirectories recursively.\n * @returns {Promise<string[]>} Array of absolute subdirectory paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function getSubdirectories(dirPath: string, recursive = false): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const dirs = entries.filter(entry => entry.isDirectory()).map(entry => path.join(dirPath, entry.name));\n\n if (recursive && dirs.length > 0) {\n const nestedDirs = await Promise.all(dirs.map(dir => getSubdirectories(dir, true)));\n return [...dirs, ...nestedDirs.flat()];\n }\n\n return dirs;\n}\n\n/**\n * Ensures a directory exists and is empty.\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<void>} Resolves when the directory exists and is empty.\n * @throws {Error} If directory cannot be created or emptied.\n */\nexport async function ensureEmptyDir(dirPath: string): Promise<void> {\n if (await isDirectory(dirPath)) {\n await emptyDir(dirPath);\n } else {\n try {\n await fsp.unlink(dirPath);\n } catch (error) {\n // Ignore if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n await ensureDir(dirPath);\n }\n}\n\n/**\n * Creates a temporary directory with optional auto-cleanup.\n *\n * @param {object} [options] - Options for the temporary directory.\n * @param {string} [options.prefix='tmp-'] - Prefix for the directory name.\n * @param {string} [options.parentDir=os.tmpdir()] - Parent directory.\n * @param {boolean} [options.cleanup=false] - Whether to register cleanup on process exit.\n * @returns {Promise<{ path: string, cleanup: () => Promise<void> }>} Object with directory path and cleanup function.\n * @throws {Error} If directory cannot be created.\n */\nexport async function createTempDir(\n options: { prefix?: string; parentDir?: string; cleanup?: boolean } = {}\n): Promise<{ path: string; cleanup: () => Promise<void> }> {\n const prefix = options.prefix || 'tmp-';\n const parentDir = options.parentDir || os.tmpdir();\n const dirName = `${prefix}${randomBytes(6).toString('hex')}`;\n const tempDirPath = path.join(parentDir, dirName);\n\n await ensureDir(tempDirPath);\n\n const cleanup = async () => {\n try {\n await deleteDirRecursive(tempDirPath);\n } catch {\n // Ignore cleanup errors\n }\n };\n\n if (options.cleanup) {\n process.once('exit', () => {\n try {\n fs.rmSync(tempDirPath, { recursive: true, force: true });\n } catch {\n // Ignore cleanup errors on exit\n }\n });\n\n // Handle signals for better cleanup\n ['SIGINT', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'].forEach(signal => {\n process.once(signal as NodeJS.Signals, () => {\n cleanup().then(() => process.exit());\n });\n });\n }\n\n return { path: tempDirPath, cleanup };\n}\n\n/**\n * Finds the newest file in a directory.\n *\n * @param {string} dirPath - Directory to search.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string | null>} Path to the newest file or null if no files.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findNewestFile(dirPath: string, recursive = false): Promise<string | null> {\n const files = await listFiles(dirPath, recursive);\n if (files.length === 0) return null;\n\n const stats = await Promise.all(\n files.map(async file => ({\n path: file,\n mtime: (await fsp.stat(file)).mtime\n }))\n );\n\n return stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0].path;\n}\n\n/**\n * Finds the oldest file in a directory.\n *\n * @param {string} dirPath - Directory to search.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string | null>} Path to the oldest file or null if no files.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findOldestFile(dirPath: string, recursive = false): Promise<string | null> {\n const files = await listFiles(dirPath, recursive);\n if (files.length === 0) return null;\n\n const stats = await Promise.all(\n files.map(async file => ({\n path: file,\n mtime: (await fsp.stat(file)).mtime\n }))\n );\n\n return stats.sort((a, b) => a.mtime.getTime() - b.mtime.getTime())[0].path;\n}\n\n/**\n * Finds files or directories in a directory matching a predicate function.\n *\n * @param {string} dirPath - Directory to search.\n * @param {(path: string, stat: fs.Stats) => boolean | Promise<boolean>} predicate - Function to test each path.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string[]>} Array of matching paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findInDir(\n dirPath: string,\n predicate: (path: string, stat: fs.Stats) => boolean | Promise<boolean>,\n recursive = false\n): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const results: string[] = [];\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n const stat = await fsp.stat(entryPath);\n\n if (await predicate(entryPath, stat)) {\n results.push(entryPath);\n }\n\n if (recursive && entry.isDirectory()) {\n const nestedResults = await findInDir(entryPath, predicate, true);\n results.push(...nestedResults);\n }\n }\n\n return results;\n}\n\n/**\n * Watches a directory recursively for file changes.\n *\n * @param {string} dirPath - Base directory path to watch.\n * @param {(eventType: \"rename\" | \"change\", filename: string) => void} callback - Callback for each change event.\n * @param {boolean} [includeSubdirs=true] - Whether to watch subdirectories.\n * @returns {Promise<() => void>} A function to stop watching the directory.\n * @throws {Error} If directory cannot be watched.\n */\nexport async function watchDirRecursive(\n dirPath: string,\n callback: (eventType: 'rename' | 'change', filename: string) => void,\n includeSubdirs = true\n): Promise<() => void> {\n // Normalize the path to ensure consistent path separators\n const normalizedBasePath = path.normalize(dirPath);\n\n // Create watchers for the base dir and all subdirectories\n const watchers: fs.FSWatcher[] = [];\n\n // Helper function to add a watcher for a directory\n const addWatcher = (dir: string) => {\n try {\n const watcher = fs.watch(dir, (eventType, filename) => {\n if (!filename) return;\n\n const fullPath = path.join(dir, filename);\n // Make the path relative to the base directory\n const relativePath = path.relative(normalizedBasePath, fullPath);\n callback(eventType, relativePath);\n\n // If a new directory is created, we should watch it\n if (eventType === 'rename' && includeSubdirs) {\n setTimeout(async () => {\n try {\n if (await isDirectory(fullPath)) {\n addWatcher(fullPath);\n }\n } catch {\n // Ignore errors checking newly created items\n }\n }, 100);\n }\n });\n watchers.push(watcher);\n } catch {\n // Silently ignore directories we can't watch\n }\n };\n\n // Add watcher for the base directory\n addWatcher(normalizedBasePath);\n\n // If watching subdirectories, add watchers for all existing subdirectories\n if (includeSubdirs) {\n const subdirs = await getSubdirectories(normalizedBasePath, true);\n for (const subdir of subdirs) {\n addWatcher(subdir);\n }\n }\n\n // Return a function to close all watchers\n return () => {\n watchers.forEach(watcher => watcher.close());\n };\n}\n\n/**\n * Gets detailed directory statistics including file count, directory count, and size.\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<{ fileCount: number, dirCount: number, totalSize: number }>} Directory statistics.\n * @throws {Error} If directory cannot be read.\n */\nexport async function getDirStats(\n dirPath: string\n): Promise<{ fileCount: number; dirCount: number; totalSize: number }> {\n let fileCount = 0;\n let dirCount = 0;\n let totalSize = 0;\n\n async function processDir(currentPath: string): Promise<void> {\n const entries = await fsp.readdir(currentPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(currentPath, entry.name);\n\n if (entry.isDirectory()) {\n dirCount++;\n await processDir(entryPath);\n } else if (entry.isFile()) {\n fileCount++;\n const stat = await fsp.stat(entryPath);\n totalSize += stat.size;\n }\n }\n }\n\n await processDir(dirPath);\n\n return { fileCount, dirCount, totalSize };\n}\n\n/**\n * Walks through a directory hierarchy, calling a visitor function for each entry.\n *\n * @param {string} dirPath - Starting directory path.\n * @param {object} options - Options for walking the directory.\n * @param {(entry: { path: string, name: string, isDirectory: boolean, stats: fs.Stats }) => boolean | void | Promise<boolean | void>} options.visitorFn -\n * Function called for each file/directory. Return false to skip a directory.\n * @param {'pre' | 'post'} [options.traversalOrder='pre'] - Whether to visit directories before or after their contents.\n * @throws {Error} If directory cannot be read.\n */\nexport async function walkDir(\n dirPath: string,\n options: {\n visitorFn: (entry: {\n path: string;\n name: string;\n isDirectory: boolean;\n stats: fs.Stats;\n }) => boolean | void | Promise<boolean | void>;\n traversalOrder?: 'pre' | 'post';\n }\n): Promise<void> {\n const traversalOrder = options.traversalOrder || 'pre';\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 const stats = await fsp.stat(entryPath);\n const entryInfo = {\n path: entryPath,\n name: entry.name,\n isDirectory: entry.isDirectory(),\n stats\n };\n\n if (entry.isDirectory()) {\n // Pre-order: visit directory before its contents\n if (traversalOrder === 'pre') {\n const shouldContinue = await options.visitorFn(entryInfo);\n // If the visitor returns false, don't recurse into this directory\n if (shouldContinue !== false) {\n await walkDir(entryPath, options);\n }\n } else {\n // Post-order: visit directory after its contents\n await walkDir(entryPath, options);\n await options.visitorFn(entryInfo);\n }\n } else {\n // Files are always visited when encountered\n await options.visitorFn(entryInfo);\n }\n }\n\n if (traversalOrder === 'post') {\n // Only visit the root if this is the top-level call (not for subdirectories)\n // But since this function is always called recursively, always visit after children\n const stats = await fsp.stat(dirPath);\n const entryInfo = {\n path: dirPath,\n name: path.basename(dirPath),\n isDirectory: true,\n stats\n };\n await options.visitorFn(entryInfo);\n }\n}\n"]}
@@ -25,7 +25,7 @@ class Env {
25
25
  * @returns {boolean} `true` if NODE_ENV is 'development', else `false`.
26
26
  */
27
27
  static isDev() {
28
- return (Env.get("NODE_ENV", Environment.DEVELOPMENT) === Environment.DEVELOPMENT);
28
+ return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.DEVELOPMENT;
29
29
  }
30
30
  /**
31
31
  * Checks if the current NODE_ENV is 'production'.
@@ -33,7 +33,7 @@ class Env {
33
33
  * @returns {boolean} `true` if NODE_ENV is 'production', else `false`.
34
34
  */
35
35
  static isProd() {
36
- return Env.get("NODE_ENV") === Environment.PRODUCTION;
36
+ return Env.get('NODE_ENV') === Environment.PRODUCTION;
37
37
  }
38
38
  /**
39
39
  * Checks if the current NODE_ENV is 'testing'.
@@ -41,7 +41,7 @@ class Env {
41
41
  * @returns {boolean} `true` if NODE_ENV is 'testing', else `false`.
42
42
  */
43
43
  static isTest() {
44
- return Env.get("NODE_ENV") === Environment.TESTING;
44
+ return Env.get('NODE_ENV') === Environment.TESTING;
45
45
  }
46
46
  /**
47
47
  * Checks if the current NODE_ENV is 'staging'.
@@ -49,7 +49,7 @@ class Env {
49
49
  * @returns {boolean} `true` if NODE_ENV is 'staging', else `false`.
50
50
  */
51
51
  static isStaging() {
52
- return Env.get("NODE_ENV") === Environment.STAGING;
52
+ return Env.get('NODE_ENV') === Environment.STAGING;
53
53
  }
54
54
  /**
55
55
  * Sets an environment variable (only affects runtime memory).
@@ -140,9 +140,9 @@ class Env {
140
140
  static getBoolean(key, defaultValue = false) {
141
141
  var _a;
142
142
  const value = ((_a = process.env[key]) !== null && _a !== void 0 ? _a : defaultValue).toString().toLowerCase();
143
- if (["true", "1", "yes", "on"].includes(value))
143
+ if (['true', '1', 'yes', 'on'].includes(value))
144
144
  return true;
145
- if (["false", "0", "no", "off"].includes(value))
145
+ if (['false', '0', 'no', 'off'].includes(value))
146
146
  return false;
147
147
  throw new Error(`Env variable ${key} is not a boolean`);
148
148
  }
@@ -190,15 +190,15 @@ class Env {
190
190
  * @param {string} [splitter=','] - Delimiter to split on.
191
191
  * @returns {string[] | T[]} An array of strings.
192
192
  */
193
- static getArray(key, defaultValue = [], splitter = ",") {
193
+ static getArray(key, defaultValue = [], splitter = ',') {
194
194
  const value = process.env[key];
195
- if (!value || value.trim() === "") {
195
+ if (!value || value.trim() === '') {
196
196
  return defaultValue;
197
197
  }
198
198
  return value
199
199
  .split(splitter)
200
- .map((item) => item.trim())
201
- .filter((item) => item.length > 0);
200
+ .map(item => item.trim())
201
+ .filter(item => item.length > 0);
202
202
  }
203
203
  /**
204
204
  * Retrieves an enum-like environment variable value, validating against allowed values.
@@ -214,7 +214,7 @@ class Env {
214
214
  var _a;
215
215
  const value = (_a = process.env[key]) !== null && _a !== void 0 ? _a : defaultValue;
216
216
  if (!value || !allowedValues.includes(value)) {
217
- throw new Error(`Env ${key} must be one of ${allowedValues.join(", ")}. Received: ${value}`);
217
+ throw new Error(`Env ${key} must be one of ${allowedValues.join(', ')}. Received: ${value}`);
218
218
  }
219
219
  return value;
220
220
  }
@@ -242,19 +242,19 @@ class Env {
242
242
  throw new Error(`Env ${key} is not a valid URL`);
243
243
  }
244
244
  if (options.protocols && options.protocols.length > 0) {
245
- const protocol = url.protocol.replace(":", "");
245
+ const protocol = url.protocol.replace(':', '');
246
246
  if (!options.protocols.includes(protocol)) {
247
- throw new Error(`Env ${key} must use one of the protocols: ${options.protocols.join(", ")}`);
247
+ throw new Error(`Env ${key} must use one of the protocols: ${options.protocols.join(', ')}`);
248
248
  }
249
249
  }
250
250
  if (options.requireTld === true) {
251
251
  // Check if hostname has a TLD (contains at least one dot and doesn't end with a dot)
252
252
  // localhost, 127.0.0.1, etc. don't have TLDs
253
253
  const hostname = url.hostname;
254
- if (!hostname.includes(".") ||
255
- hostname === "localhost" ||
254
+ if (!hostname.includes('.') ||
255
+ hostname === 'localhost' ||
256
256
  /^[\d.]+$/.test(hostname) || // IP address
257
- hostname.endsWith(".")) {
257
+ hostname.endsWith('.')) {
258
258
  throw new Error(`Env ${key} must have a valid host with TLD`);
259
259
  }
260
260
  }
@@ -302,9 +302,7 @@ class Env {
302
302
  }
303
303
  return defaultValue;
304
304
  }
305
- const path = options.makeAbsolute !== false && !(0, path_1.isAbsolute)(value)
306
- ? (0, path_1.resolve)(process.cwd(), value)
307
- : value;
305
+ const path = options.makeAbsolute !== false && !(0, path_1.isAbsolute)(value) ? (0, path_1.resolve)(process.cwd(), value) : value;
308
306
  if (options.mustExist && !(0, fs_1.existsSync)(path)) {
309
307
  throw new Error(`Path in env ${key} does not exist: ${path}`);
310
308
  }
@@ -334,7 +332,7 @@ class Env {
334
332
  * @returns {number} The duration in milliseconds.
335
333
  * @throws {Error} If duration format is invalid.
336
334
  */
337
- static getDuration(key, defaultValue = "0") {
335
+ static getDuration(key, defaultValue = '0') {
338
336
  const value = Env.get(key, String(defaultValue));
339
337
  if (!value)
340
338
  return 0;
@@ -345,7 +343,7 @@ class Env {
345
343
  // Parse duration string like "1d2h30m15s"
346
344
  const durationRegex = /(\d+d)?(\d+h)?(\d+m)?(\d+s)?(\d+ms)?/;
347
345
  const matches = value.match(durationRegex);
348
- if (!matches || matches[0] === "") {
346
+ if (!matches || matches[0] === '') {
349
347
  throw new Error(`Env ${key} has invalid duration format. Use 1d, 2h, 30m, 45s, or 100ms.`);
350
348
  }
351
349
  let ms = 0;
@@ -367,13 +365,13 @@ class Env {
367
365
  * @param {string[]} [sensitiveKeys=['password', 'secret', 'key', 'token', 'auth']] - Keys to mask.
368
366
  * @returns {Record<string, string>} Environment variables with sensitive values masked.
369
367
  */
370
- static getSafeEnv(sensitiveKeys = ["password", "secret", "key", "token", "auth"]) {
368
+ static getSafeEnv(sensitiveKeys = ['password', 'secret', 'key', 'token', 'auth']) {
371
369
  const safeEnv = {};
372
370
  for (const [key, value] of Object.entries(process.env)) {
373
371
  if (!value)
374
372
  continue;
375
- const isSensitive = sensitiveKeys.some((sensitiveKey) => key.toLowerCase().includes(sensitiveKey.toLowerCase()));
376
- safeEnv[key] = isSensitive ? "******" : value;
373
+ const isSensitive = sensitiveKeys.some(sensitiveKey => key.toLowerCase().includes(sensitiveKey.toLowerCase()));
374
+ safeEnv[key] = isSensitive ? '******' : value;
377
375
  }
378
376
  return safeEnv;
379
377
  }
@@ -1 +1 @@
1
- {"version":3,"file":"env.utils.js","sourceRoot":"","sources":["../../../src/utils/env.utils.ts"],"names":[],"mappings":";;;AAAA,qCAAqC;AACrC,2BAAgC;AAChC,+BAA2C;AAC3C;;GAEG;AACH,IAAY,WAKX;AALD,W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AQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,eAAe;QAE/D,OAAO,EAAE,CAAC;IACZ,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,UAAU,CACf,gBAA0B,CAAC,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,CAAC;QAExE,MAAM,OAAO,GAA2B,EAAE,CAAC;QAE3C,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACvD,IAAI,CAAC,KAAK;gBAAE,SAAS;YAErB,MAAM,WAAW,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE,CACtD,GAAG,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,YAAY,CAAC,WAAW,EAAE,CAAC,CACvD,CAAC;YAEF,OAAO,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC;QAChD,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,GAAG,CAAC,GAAW;QACpB,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC;IACxC,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,MAAM,CAAC,GAAW;QACvB,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC1B,CAAC;CACF;AAvbD,kBAubC","sourcesContent":["/* eslint-disable n/no-process-env */\nimport { existsSync } from \"fs\";\nimport { isAbsolute, resolve } from \"path\";\n/**\n * Enum representing valid application environments.\n */\nexport enum Environment {\n PRODUCTION = \"production\",\n DEVELOPMENT = \"development\",\n STAGING = \"staging\",\n TESTING = \"testing\",\n}\n\n/**\n * Utility class for accessing and managing environment variables.\n * Provides typed getters with fallback defaults and validation.\n */\nexport class Env {\n /**\n * Checks if the current NODE_ENV is 'development'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'development', else `false`.\n */\n static isDev(): boolean {\n return (\n Env.get(\"NODE_ENV\", Environment.DEVELOPMENT) === Environment.DEVELOPMENT\n );\n }\n\n /**\n * Checks if the current NODE_ENV is 'production'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'production', else `false`.\n */\n static isProd(): boolean {\n return Env.get(\"NODE_ENV\") === Environment.PRODUCTION;\n }\n\n /**\n * Checks if the current NODE_ENV is 'testing'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'testing', else `false`.\n */\n static isTest(): boolean {\n return Env.get(\"NODE_ENV\") === Environment.TESTING;\n }\n\n /**\n * Checks if the current NODE_ENV is 'staging'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'staging', else `false`.\n */\n static isStaging(): boolean {\n return Env.get(\"NODE_ENV\") === Environment.STAGING;\n }\n\n /**\n * Sets an environment variable (only affects runtime memory).\n *\n * @param {string} key - The environment variable key.\n * @param {string} value - The value to set.\n */\n static set(key: string, value: string): void {\n process.env[key] = value;\n }\n\n /**\n * Returns all environment variables as an object.\n *\n * @returns {object} The current `process.env` object.\n */\n static getAll(): object {\n return process.env;\n }\n\n /**\n * Retrieves a string environment variable with a fallback default.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Value to return if the key is missing.\n * @returns {string | undefined} The env value or the fallback.\n */\n static get(key: string, defaultValue?: string): string | undefined {\n return process.env[key] ?? defaultValue;\n }\n\n /**\n * Retrieves a string environment variable and throws if it's missing.\n *\n * @param {string} key - The environment variable key.\n * @returns {string} The environment variable's value.\n * @throws {Error} If the variable is not defined.\n */\n static getRequired(key: string): string {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required env ${key} is missing`);\n }\n return value;\n }\n\n /**\n * Retrieves an environment variable as a number, or returns a default.\n *\n * @param {string} key - The environment variable key.\n * @param {number} defaultValue - Fallback number if key is not present.\n * @returns {number} Parsed numeric value or default.\n * @throws {Error} If the value is not a valid number.\n */\n static getNumber(key: string, defaultValue: number): number {\n const value = process.env[key] ?? defaultValue;\n const numberValue = Number(value);\n if (isNaN(numberValue)) {\n throw new Error(`Env ${key} is not a number`);\n }\n return numberValue;\n }\n\n /**\n * Retrieves a required environment variable as a number.\n *\n * @param {string} key - The environment variable key.\n * @returns {number} Parsed number.\n * @throws {Error} If the value is missing or not a number.\n */\n static getNumberRequired(key: string): number {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required env ${key} is missing`);\n }\n const numberValue = Number(value);\n if (isNaN(numberValue)) {\n throw new Error(`Required env ${key} is not a number`);\n }\n return numberValue;\n }\n\n /**\n * Retrieves an environment variable as a boolean.\n * Accepts `true`, `1`, `yes`, `on` as true; `false`, `0`, `no`, `off` as false.\n *\n * @param {string} key - The environment variable key.\n * @param {boolean} [defaultValue=false] - Optional fallback value if key is missing.\n * @returns {boolean} Parsed boolean.\n * @throws {Error} If the value is not a recognized boolean string.\n */\n static getBoolean(key: string, defaultValue = false): boolean {\n const value = (process.env[key] ?? defaultValue).toString().toLowerCase();\n if ([\"true\", \"1\", \"yes\", \"on\"].includes(value)) return true;\n if ([\"false\", \"0\", \"no\", \"off\"].includes(value)) return false;\n throw new Error(`Env variable ${key} is not a boolean`);\n }\n\n /**\n * Retrieves a required environment variable as a boolean.\n *\n * @param {string} key - The environment variable key.\n * @returns {boolean} Parsed boolean value.\n * @throws {Error} If missing or invalid.\n */\n static getBooleanRequired(key: string): boolean {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required env ${key} is missing`);\n }\n return this.getBoolean(key); // reuse logic\n }\n\n /**\n * Parses a stringified JSON object from an environment variable.\n *\n * @typeParam T - The type to parse as (defaults to `object`).\n * @param {string} key - The environment variable key.\n * @param {T} defaultValue - Value to return if key is missing.\n * @returns {T} Parsed object or default.\n * @throws {Error} If the value is not valid JSON.\n */\n static getJSON<T extends object = object>(key: string, defaultValue: T): T {\n const v = process.env[key];\n if (v !== undefined) {\n try {\n return JSON.parse(v);\n } catch {\n throw new Error(`Env variable ${key} is not a valid JSON string`);\n }\n }\n return defaultValue;\n }\n\n /**\n * Parses a comma-separated string as an array.\n *\n * @typeParam T - The item type (optional, defaults to string).\n * @param {string} key - The environment variable key.\n * @param {T[]} [defaultValue=[]] - Array to return if value is empty or missing.\n * @param {string} [splitter=','] - Delimiter to split on.\n * @returns {string[] | T[]} An array of strings.\n */\n static getArray<T = string>(\n key: string,\n defaultValue: T[] = [],\n splitter = \",\",\n ): string[] | T[] {\n const value = process.env[key];\n if (!value || value.trim() === \"\") {\n return defaultValue;\n }\n return value\n .split(splitter)\n .map((item) => item.trim())\n .filter((item) => item.length > 0);\n }\n\n /**\n * Retrieves an enum-like environment variable value, validating against allowed values.\n *\n * @typeParam T - The allowed value type (string literal types).\n * @param {string} key - The environment variable key.\n * @param {T[]} allowedValues - Array of accepted string values.\n * @param {T} [defaultValue] - Optional fallback value.\n * @returns {T} The validated environment value.\n * @throws {Error} If missing or invalid.\n */\n static getEnum<T extends string>(\n key: string,\n allowedValues: T[],\n defaultValue?: T,\n ): T {\n const value = process.env[key] ?? defaultValue;\n if (!value || !allowedValues.includes(value as T)) {\n throw new Error(\n `Env ${key} must be one of ${allowedValues.join(\", \")}. Received: ${value}`,\n );\n }\n return value as T;\n }\n\n /**\n * Retrieves a URL environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @param {object} [options] - Validation options.\n * @param {string[]} [options.protocols] - Allowed protocols.\n * @param {boolean} [options.requireTld=true] - Whether TLD is required.\n * @returns {string} The validated URL.\n * @throws {Error} If URL is invalid.\n */\n static getUrl(\n key: string,\n defaultValue?: string,\n options: { protocols?: string[]; requireTld?: boolean } = {},\n ): string {\n const value = Env.get(key, defaultValue);\n if (!value) {\n throw new Error(`Env ${key} is missing or empty`);\n }\n\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`Env ${key} is not a valid URL`);\n }\n\n if (options.protocols && options.protocols.length > 0) {\n const protocol = url.protocol.replace(\":\", \"\");\n if (!options.protocols.includes(protocol)) {\n throw new Error(\n `Env ${key} must use one of the protocols: ${options.protocols.join(\", \")}`,\n );\n }\n }\n\n if (options.requireTld === true) {\n // Check if hostname has a TLD (contains at least one dot and doesn't end with a dot)\n // localhost, 127.0.0.1, etc. don't have TLDs\n const hostname = url.hostname;\n if (\n !hostname.includes(\".\") ||\n hostname === \"localhost\" ||\n /^[\\d.]+$/.test(hostname) || // IP address\n hostname.endsWith(\".\")\n ) {\n throw new Error(`Env ${key} must have a valid host with TLD`);\n }\n }\n\n return value;\n }\n\n /**\n * Retrieves an email environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @returns {string} The validated email address.\n * @throws {Error} If email is invalid.\n */\n static getEmail(key: string, defaultValue?: string): string {\n const value = Env.get(key, defaultValue);\n\n if (!value) {\n if (defaultValue === undefined) {\n throw new Error(`Email env ${key} is missing`);\n }\n return defaultValue;\n }\n\n // Simple email validation regex\n const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\n if (!emailRegex.test(value)) {\n throw new Error(`Env ${key} is not a valid email address`);\n }\n\n return value;\n }\n\n /**\n * Retrieves a path environment variable and validates it exists.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @param {object} [options] - Validation options.\n * @param {boolean} [options.mustExist=false] - Whether path must exist.\n * @param {boolean} [options.makeAbsolute=true] - Convert relative paths to absolute.\n * @returns {string} The validated path.\n * @throws {Error} If path is invalid.\n */\n static getPath(\n key: string,\n defaultValue?: string,\n options: { mustExist?: boolean; makeAbsolute?: boolean } = {},\n ): string {\n const value = Env.get(key, defaultValue);\n\n if (!value) {\n if (defaultValue === undefined) {\n throw new Error(`Path env ${key} is missing`);\n }\n return defaultValue;\n }\n\n const path =\n options.makeAbsolute !== false && !isAbsolute(value)\n ? resolve(process.cwd(), value)\n : value;\n\n if (options.mustExist && !existsSync(path)) {\n throw new Error(`Path in env ${key} does not exist: ${path}`);\n }\n\n return path;\n }\n\n /**\n * Retrieves a port environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {number} [defaultValue=3000] - Optional fallback value.\n * @returns {number} The validated port number.\n * @throws {Error} If port is invalid.\n */\n static getPort(key: string, defaultValue: number = 3000): number {\n const port = Env.getNumber(key, defaultValue);\n\n if (port < 0 || port > 65535) {\n throw new Error(`Env ${key} must be a valid port number (0-65535)`);\n }\n\n return port;\n }\n\n /**\n * Retrieves a duration string and converts to milliseconds.\n * Supports formats like \"1d\", \"2h\", \"30m\", \"45s\", \"100ms\" or combinations like \"1h30m\".\n *\n * @param {string} key - The environment variable key.\n * @param {string|number} [defaultValue='0'] - Optional fallback value.\n * @returns {number} The duration in milliseconds.\n * @throws {Error} If duration format is invalid.\n */\n static getDuration(key: string, defaultValue: string | number = \"0\"): number {\n const value = Env.get(key, String(defaultValue));\n\n if (!value) return 0;\n\n // Handle plain number input (assume milliseconds)\n if (/^\\d+$/.test(value)) {\n return parseInt(value, 10);\n }\n\n // Parse duration string like \"1d2h30m15s\"\n const durationRegex = /(\\d+d)?(\\d+h)?(\\d+m)?(\\d+s)?(\\d+ms)?/;\n const matches = value.match(durationRegex);\n\n if (!matches || matches[0] === \"\") {\n throw new Error(\n `Env ${key} has invalid duration format. Use 1d, 2h, 30m, 45s, or 100ms.`,\n );\n }\n\n let ms = 0;\n\n if (matches[1]) ms += parseInt(matches[1], 10) * 86400000; // days\n if (matches[2]) ms += parseInt(matches[2], 10) * 3600000; // hours\n if (matches[3]) ms += parseInt(matches[3], 10) * 60000; // minutes\n if (matches[4]) ms += parseInt(matches[4], 10) * 1000; // seconds\n if (matches[5]) ms += parseInt(matches[5], 10); // milliseconds\n\n return ms;\n }\n\n /**\n * Gets all environment variables with sensitive values masked for safe logging.\n *\n * @param {string[]} [sensitiveKeys=['password', 'secret', 'key', 'token', 'auth']] - Keys to mask.\n * @returns {Record<string, string>} Environment variables with sensitive values masked.\n */\n static getSafeEnv(\n sensitiveKeys: string[] = [\"password\", \"secret\", \"key\", \"token\", \"auth\"],\n ): Record<string, string> {\n const safeEnv: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(process.env)) {\n if (!value) continue;\n\n const isSensitive = sensitiveKeys.some((sensitiveKey) =>\n key.toLowerCase().includes(sensitiveKey.toLowerCase()),\n );\n\n safeEnv[key] = isSensitive ? \"******\" : value;\n }\n\n return safeEnv;\n }\n\n /**\n * Checks whether the specified environment variable exists.\n *\n * @param {string} key - The environment variable key.\n * @returns {boolean} `true` if the variable is defined, otherwise `false`.\n */\n static has(key: string): boolean {\n return process.env[key] !== undefined;\n }\n\n /**\n * Deletes the given environment variable (useful in tests).\n *\n * @param {string} key - The environment variable key to delete.\n * @returns {void}\n */\n static delete(key: string): void {\n delete process.env[key];\n }\n}\n"]}
1
+ {"version":3,"file":"env.utils.js","sourceRoot":"","sources":["../../../src/utils/env.utils.ts"],"names":[],"mappings":";;;AAAA,qCAAqC;AACrC,2BAAgC;AAChC,+BAA2C;AAC3C;;GAEG;AACH,IAAY,WAKX;AALD,WAAY,WAAW;IACrB,wCAAyB,CAAA;IACzB,0CAA2B,CAAA;IAC3B,kCAAmB,CAAA;IACnB,kCAAmB,CAAA;AACrB,CAAC,EALW,WAAW,2BAAX,WAAW,QAKtB;AAED;;;GAGG;AACH,MAAa,GAAG;IACd;;;;OAIG;IACH,MAAM,CAAC,KAAK;QACV,OAAO,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC,WAAW,CAAC,KAAK,WAAW,CAAC,WAAW,CAAC;IAClF,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,MAAM;QACX,OAAO,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,UAAU,CAAC;IACxD,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,MAAM;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CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;YAE/G,OAAO,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC;QAChD,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,GAAG,CAAC,GAAW;QACpB,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC;IACxC,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,MAAM,CAAC,GAAW;QACvB,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC1B,CAAC;CACF;AAhaD,kBAgaC","sourcesContent":["/* eslint-disable n/no-process-env */\nimport { existsSync } from 'fs';\nimport { isAbsolute, resolve } from 'path';\n/**\n * Enum representing valid application environments.\n */\nexport enum Environment {\n PRODUCTION = 'production',\n DEVELOPMENT = 'development',\n STAGING = 'staging',\n TESTING = 'testing'\n}\n\n/**\n * Utility class for accessing and managing environment variables.\n * Provides typed getters with fallback defaults and validation.\n */\nexport class Env {\n /**\n * Checks if the current NODE_ENV is 'development'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'development', else `false`.\n */\n static isDev(): boolean {\n return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.DEVELOPMENT;\n }\n\n /**\n * Checks if the current NODE_ENV is 'production'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'production', else `false`.\n */\n static isProd(): boolean {\n return Env.get('NODE_ENV') === Environment.PRODUCTION;\n }\n\n /**\n * Checks if the current NODE_ENV is 'testing'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'testing', else `false`.\n */\n static isTest(): boolean {\n return Env.get('NODE_ENV') === Environment.TESTING;\n }\n\n /**\n * Checks if the current NODE_ENV is 'staging'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'staging', else `false`.\n */\n static isStaging(): boolean {\n return Env.get('NODE_ENV') === Environment.STAGING;\n }\n\n /**\n * Sets an environment variable (only affects runtime memory).\n *\n * @param {string} key - The environment variable key.\n * @param {string} value - The value to set.\n */\n static set(key: string, value: string): void {\n process.env[key] = value;\n }\n\n /**\n * Returns all environment variables as an object.\n *\n * @returns {object} The current `process.env` object.\n */\n static getAll(): object {\n return process.env;\n }\n\n /**\n * Retrieves a string environment variable with a fallback default.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Value to return if the key is missing.\n * @returns {string | undefined} The env value or the fallback.\n */\n static get(key: string, defaultValue?: string): string | undefined {\n return process.env[key] ?? defaultValue;\n }\n\n /**\n * Retrieves a string environment variable and throws if it's missing.\n *\n * @param {string} key - The environment variable key.\n * @returns {string} The environment variable's value.\n * @throws {Error} If the variable is not defined.\n */\n static getRequired(key: string): string {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required env ${key} is missing`);\n }\n return value;\n }\n\n /**\n * Retrieves an environment variable as a number, or returns a default.\n *\n * @param {string} key - The environment variable key.\n * @param {number} defaultValue - Fallback number if key is not present.\n * @returns {number} Parsed numeric value or default.\n * @throws {Error} If the value is not a valid number.\n */\n static getNumber(key: string, defaultValue: number): number {\n const value = process.env[key] ?? defaultValue;\n const numberValue = Number(value);\n if (isNaN(numberValue)) {\n throw new Error(`Env ${key} is not a number`);\n }\n return numberValue;\n }\n\n /**\n * Retrieves a required environment variable as a number.\n *\n * @param {string} key - The environment variable key.\n * @returns {number} Parsed number.\n * @throws {Error} If the value is missing or not a number.\n */\n static getNumberRequired(key: string): number {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required env ${key} is missing`);\n }\n const numberValue = Number(value);\n if (isNaN(numberValue)) {\n throw new Error(`Required env ${key} is not a number`);\n }\n return numberValue;\n }\n\n /**\n * Retrieves an environment variable as a boolean.\n * Accepts `true`, `1`, `yes`, `on` as true; `false`, `0`, `no`, `off` as false.\n *\n * @param {string} key - The environment variable key.\n * @param {boolean} [defaultValue=false] - Optional fallback value if key is missing.\n * @returns {boolean} Parsed boolean.\n * @throws {Error} If the value is not a recognized boolean string.\n */\n static getBoolean(key: string, defaultValue = false): boolean {\n const value = (process.env[key] ?? defaultValue).toString().toLowerCase();\n if (['true', '1', 'yes', 'on'].includes(value)) return true;\n if (['false', '0', 'no', 'off'].includes(value)) return false;\n throw new Error(`Env variable ${key} is not a boolean`);\n }\n\n /**\n * Retrieves a required environment variable as a boolean.\n *\n * @param {string} key - The environment variable key.\n * @returns {boolean} Parsed boolean value.\n * @throws {Error} If missing or invalid.\n */\n static getBooleanRequired(key: string): boolean {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required env ${key} is missing`);\n }\n return this.getBoolean(key); // reuse logic\n }\n\n /**\n * Parses a stringified JSON object from an environment variable.\n *\n * @typeParam T - The type to parse as (defaults to `object`).\n * @param {string} key - The environment variable key.\n * @param {T} defaultValue - Value to return if key is missing.\n * @returns {T} Parsed object or default.\n * @throws {Error} If the value is not valid JSON.\n */\n static getJSON<T extends object = object>(key: string, defaultValue: T): T {\n const v = process.env[key];\n if (v !== undefined) {\n try {\n return JSON.parse(v);\n } catch {\n throw new Error(`Env variable ${key} is not a valid JSON string`);\n }\n }\n return defaultValue;\n }\n\n /**\n * Parses a comma-separated string as an array.\n *\n * @typeParam T - The item type (optional, defaults to string).\n * @param {string} key - The environment variable key.\n * @param {T[]} [defaultValue=[]] - Array to return if value is empty or missing.\n * @param {string} [splitter=','] - Delimiter to split on.\n * @returns {string[] | T[]} An array of strings.\n */\n static getArray<T = string>(key: string, defaultValue: T[] = [], splitter = ','): string[] | T[] {\n const value = process.env[key];\n if (!value || value.trim() === '') {\n return defaultValue;\n }\n return value\n .split(splitter)\n .map(item => item.trim())\n .filter(item => item.length > 0);\n }\n\n /**\n * Retrieves an enum-like environment variable value, validating against allowed values.\n *\n * @typeParam T - The allowed value type (string literal types).\n * @param {string} key - The environment variable key.\n * @param {T[]} allowedValues - Array of accepted string values.\n * @param {T} [defaultValue] - Optional fallback value.\n * @returns {T} The validated environment value.\n * @throws {Error} If missing or invalid.\n */\n static getEnum<T extends string>(key: string, allowedValues: T[], defaultValue?: T): T {\n const value = process.env[key] ?? defaultValue;\n if (!value || !allowedValues.includes(value as T)) {\n throw new Error(`Env ${key} must be one of ${allowedValues.join(', ')}. Received: ${value}`);\n }\n return value as T;\n }\n\n /**\n * Retrieves a URL environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @param {object} [options] - Validation options.\n * @param {string[]} [options.protocols] - Allowed protocols.\n * @param {boolean} [options.requireTld=true] - Whether TLD is required.\n * @returns {string} The validated URL.\n * @throws {Error} If URL is invalid.\n */\n static getUrl(\n key: string,\n defaultValue?: string,\n options: { protocols?: string[]; requireTld?: boolean } = {}\n ): string {\n const value = Env.get(key, defaultValue);\n if (!value) {\n throw new Error(`Env ${key} is missing or empty`);\n }\n\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`Env ${key} is not a valid URL`);\n }\n\n if (options.protocols && options.protocols.length > 0) {\n const protocol = url.protocol.replace(':', '');\n if (!options.protocols.includes(protocol)) {\n throw new Error(`Env ${key} must use one of the protocols: ${options.protocols.join(', ')}`);\n }\n }\n\n if (options.requireTld === true) {\n // Check if hostname has a TLD (contains at least one dot and doesn't end with a dot)\n // localhost, 127.0.0.1, etc. don't have TLDs\n const hostname = url.hostname;\n if (\n !hostname.includes('.') ||\n hostname === 'localhost' ||\n /^[\\d.]+$/.test(hostname) || // IP address\n hostname.endsWith('.')\n ) {\n throw new Error(`Env ${key} must have a valid host with TLD`);\n }\n }\n\n return value;\n }\n\n /**\n * Retrieves an email environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @returns {string} The validated email address.\n * @throws {Error} If email is invalid.\n */\n static getEmail(key: string, defaultValue?: string): string {\n const value = Env.get(key, defaultValue);\n\n if (!value) {\n if (defaultValue === undefined) {\n throw new Error(`Email env ${key} is missing`);\n }\n return defaultValue;\n }\n\n // Simple email validation regex\n const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\n if (!emailRegex.test(value)) {\n throw new Error(`Env ${key} is not a valid email address`);\n }\n\n return value;\n }\n\n /**\n * Retrieves a path environment variable and validates it exists.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @param {object} [options] - Validation options.\n * @param {boolean} [options.mustExist=false] - Whether path must exist.\n * @param {boolean} [options.makeAbsolute=true] - Convert relative paths to absolute.\n * @returns {string} The validated path.\n * @throws {Error} If path is invalid.\n */\n static getPath(\n key: string,\n defaultValue?: string,\n options: { mustExist?: boolean; makeAbsolute?: boolean } = {}\n ): string {\n const value = Env.get(key, defaultValue);\n\n if (!value) {\n if (defaultValue === undefined) {\n throw new Error(`Path env ${key} is missing`);\n }\n return defaultValue;\n }\n\n const path = options.makeAbsolute !== false && !isAbsolute(value) ? resolve(process.cwd(), value) : value;\n\n if (options.mustExist && !existsSync(path)) {\n throw new Error(`Path in env ${key} does not exist: ${path}`);\n }\n\n return path;\n }\n\n /**\n * Retrieves a port environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {number} [defaultValue=3000] - Optional fallback value.\n * @returns {number} The validated port number.\n * @throws {Error} If port is invalid.\n */\n static getPort(key: string, defaultValue: number = 3000): number {\n const port = Env.getNumber(key, defaultValue);\n\n if (port < 0 || port > 65535) {\n throw new Error(`Env ${key} must be a valid port number (0-65535)`);\n }\n\n return port;\n }\n\n /**\n * Retrieves a duration string and converts to milliseconds.\n * Supports formats like \"1d\", \"2h\", \"30m\", \"45s\", \"100ms\" or combinations like \"1h30m\".\n *\n * @param {string} key - The environment variable key.\n * @param {string|number} [defaultValue='0'] - Optional fallback value.\n * @returns {number} The duration in milliseconds.\n * @throws {Error} If duration format is invalid.\n */\n static getDuration(key: string, defaultValue: string | number = '0'): number {\n const value = Env.get(key, String(defaultValue));\n\n if (!value) return 0;\n\n // Handle plain number input (assume milliseconds)\n if (/^\\d+$/.test(value)) {\n return parseInt(value, 10);\n }\n\n // Parse duration string like \"1d2h30m15s\"\n const durationRegex = /(\\d+d)?(\\d+h)?(\\d+m)?(\\d+s)?(\\d+ms)?/;\n const matches = value.match(durationRegex);\n\n if (!matches || matches[0] === '') {\n throw new Error(`Env ${key} has invalid duration format. Use 1d, 2h, 30m, 45s, or 100ms.`);\n }\n\n let ms = 0;\n\n if (matches[1]) ms += parseInt(matches[1], 10) * 86400000; // days\n if (matches[2]) ms += parseInt(matches[2], 10) * 3600000; // hours\n if (matches[3]) ms += parseInt(matches[3], 10) * 60000; // minutes\n if (matches[4]) ms += parseInt(matches[4], 10) * 1000; // seconds\n if (matches[5]) ms += parseInt(matches[5], 10); // milliseconds\n\n return ms;\n }\n\n /**\n * Gets all environment variables with sensitive values masked for safe logging.\n *\n * @param {string[]} [sensitiveKeys=['password', 'secret', 'key', 'token', 'auth']] - Keys to mask.\n * @returns {Record<string, string>} Environment variables with sensitive values masked.\n */\n static getSafeEnv(sensitiveKeys: string[] = ['password', 'secret', 'key', 'token', 'auth']): Record<string, string> {\n const safeEnv: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(process.env)) {\n if (!value) continue;\n\n const isSensitive = sensitiveKeys.some(sensitiveKey => key.toLowerCase().includes(sensitiveKey.toLowerCase()));\n\n safeEnv[key] = isSensitive ? '******' : value;\n }\n\n return safeEnv;\n }\n\n /**\n * Checks whether the specified environment variable exists.\n *\n * @param {string} key - The environment variable key.\n * @returns {boolean} `true` if the variable is defined, otherwise `false`.\n */\n static has(key: string): boolean {\n return process.env[key] !== undefined;\n }\n\n /**\n * Deletes the given environment variable (useful in tests).\n *\n * @param {string} key - The environment variable key to delete.\n * @returns {void}\n */\n static delete(key: string): void {\n delete process.env[key];\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { ErrorResponse } from "./response.utils";
1
+ import { ErrorResponse } from './response.utils';
2
2
  /**
3
3
  * Generic HTTP error class used for custom exceptions with any status code.
4
4
  * Inherit this when you need to throw errors dynamically at runtime.
@@ -33,7 +33,7 @@ class InternalServerErrorException extends response_utils_1.ErrorResponse {
33
33
  /**
34
34
  * @param message - Optional custom message. Defaults to "Internal server error".
35
35
  */
36
- constructor(message = "Internal server error") {
36
+ constructor(message = 'Internal server error') {
37
37
  super(message);
38
38
  this.status = http_status_codes_1.HttpStatusCodes.INTERNAL_SERVER_ERROR;
39
39
  }
@@ -47,7 +47,7 @@ class UnauthorizedException extends response_utils_1.ErrorResponse {
47
47
  /**
48
48
  * @param message - Optional custom message. Defaults to "Unauthorized".
49
49
  */
50
- constructor(message = "Unauthorized") {
50
+ constructor(message = 'Unauthorized') {
51
51
  super(message);
52
52
  this.status = http_status_codes_1.HttpStatusCodes.UNAUTHORIZED;
53
53
  }
@@ -61,7 +61,7 @@ class BadRequestException extends response_utils_1.ErrorResponse {
61
61
  /**
62
62
  * @param message - Optional custom message. Defaults to "Bad request".
63
63
  */
64
- constructor(message = "Bad request") {
64
+ constructor(message = 'Bad request') {
65
65
  super(message);
66
66
  this.status = http_status_codes_1.HttpStatusCodes.BAD_REQUEST;
67
67
  }
@@ -75,7 +75,7 @@ class NotFoundException extends response_utils_1.ErrorResponse {
75
75
  /**
76
76
  * @param message - Optional custom message. Defaults to "Resource not found".
77
77
  */
78
- constructor(message = "Resource not found") {
78
+ constructor(message = 'Resource not found') {
79
79
  super(message);
80
80
  this.status = http_status_codes_1.HttpStatusCodes.NOT_FOUND;
81
81
  }
@@ -89,7 +89,7 @@ class ForbiddenException extends response_utils_1.ErrorResponse {
89
89
  /**
90
90
  * @param message - Optional custom message. Defaults to "Forbidden".
91
91
  */
92
- constructor(message = "Forbidden") {
92
+ constructor(message = 'Forbidden') {
93
93
  super(message);
94
94
  this.status = http_status_codes_1.HttpStatusCodes.FORBIDDEN;
95
95
  }
@@ -103,7 +103,7 @@ class ConflictException extends response_utils_1.ErrorResponse {
103
103
  /**
104
104
  * @param message - Optional custom message. Defaults to "Conflict".
105
105
  */
106
- constructor(message = "Conflict") {
106
+ constructor(message = 'Conflict') {
107
107
  super(message);
108
108
  this.status = http_status_codes_1.HttpStatusCodes.CONFLICT;
109
109
  }
@@ -117,7 +117,7 @@ class BadGatewayException extends response_utils_1.ErrorResponse {
117
117
  /**
118
118
  * @param message - Optional custom message. Defaults to "Bad Gateway".
119
119
  */
120
- constructor(message = "Bad Gateway") {
120
+ constructor(message = 'Bad Gateway') {
121
121
  super(message);
122
122
  this.status = http_status_codes_1.HttpStatusCodes.BAD_GATEWAY;
123
123
  }
@@ -131,7 +131,7 @@ class TooManyRequestsException extends response_utils_1.ErrorResponse {
131
131
  /**
132
132
  * @param message - Optional custom message. Defaults to "Too many requests".
133
133
  */
134
- constructor(message = "Too many requests") {
134
+ constructor(message = 'Too many requests') {
135
135
  super(message);
136
136
  this.status = http_status_codes_1.HttpStatusCodes.TOO_MANY_REQUESTS;
137
137
  }
@@ -145,7 +145,7 @@ class ServiceUnavailableException extends response_utils_1.ErrorResponse {
145
145
  /**
146
146
  * @param message - Optional custom message. Defaults to "Service Unavailable".
147
147
  */
148
- constructor(message = "Service Unavailable") {
148
+ constructor(message = 'Service Unavailable') {
149
149
  super(message);
150
150
  this.status = http_status_codes_1.HttpStatusCodes.SERVICE_UNAVAILABLE;
151
151
  }
@@ -159,7 +159,7 @@ class GatewayTimeoutException extends response_utils_1.ErrorResponse {
159
159
  /**
160
160
  * @param message - Optional custom message. Defaults to "Gateway Timeout".
161
161
  */
162
- constructor(message = "Gateway Timeout") {
162
+ constructor(message = 'Gateway Timeout') {
163
163
  super(message);
164
164
  this.status = http_status_codes_1.HttpStatusCodes.GATEWAY_TIMEOUT;
165
165
  }
@@ -174,7 +174,7 @@ class UnprocessableEntityException extends response_utils_1.ErrorResponse {
174
174
  * @param message - Optional custom message. Defaults to "Unprocessable Entity".
175
175
  * @param details - Optional validation details or additional error context.
176
176
  */
177
- constructor(message = "Unprocessable Entity", details) {
177
+ constructor(message = 'Unprocessable Entity', details) {
178
178
  super(message);
179
179
  this.details = details;
180
180
  this.status = http_status_codes_1.HttpStatusCodes.UNPROCESSABLE_ENTITY;
@@ -190,7 +190,7 @@ class MethodNotAllowedException extends response_utils_1.ErrorResponse {
190
190
  * @param message - Optional custom message. Defaults to "Method Not Allowed".
191
191
  * @param allowedMethods - Optional array of allowed HTTP methods.
192
192
  */
193
- constructor(message = "Method Not Allowed", allowedMethods) {
193
+ constructor(message = 'Method Not Allowed', allowedMethods) {
194
194
  super(message);
195
195
  this.allowedMethods = allowedMethods;
196
196
  this.status = http_status_codes_1.HttpStatusCodes.METHOD_NOT_ALLOWED;
@@ -205,7 +205,7 @@ class NotAcceptableException extends response_utils_1.ErrorResponse {
205
205
  /**
206
206
  * @param message - Optional custom message. Defaults to "Not Acceptable".
207
207
  */
208
- constructor(message = "Not Acceptable") {
208
+ constructor(message = 'Not Acceptable') {
209
209
  super(message);
210
210
  this.status = http_status_codes_1.HttpStatusCodes.NOT_ACCEPTABLE;
211
211
  }
@@ -219,7 +219,7 @@ class RequestTimeoutException extends response_utils_1.ErrorResponse {
219
219
  /**
220
220
  * @param message - Optional custom message. Defaults to "Request Timeout".
221
221
  */
222
- constructor(message = "Request Timeout") {
222
+ constructor(message = 'Request Timeout') {
223
223
  super(message);
224
224
  this.status = http_status_codes_1.HttpStatusCodes.REQUEST_TIMEOUT;
225
225
  }
@@ -233,7 +233,7 @@ class UnsupportedMediaTypeException extends response_utils_1.ErrorResponse {
233
233
  /**
234
234
  * @param message - Optional custom message. Defaults to "Unsupported Media Type".
235
235
  */
236
- constructor(message = "Unsupported Media Type") {
236
+ constructor(message = 'Unsupported Media Type') {
237
237
  super(message);
238
238
  this.status = http_status_codes_1.HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE;
239
239
  }
@@ -247,7 +247,7 @@ class PayloadTooLargeException extends response_utils_1.ErrorResponse {
247
247
  /**
248
248
  * @param message - Optional custom message. Defaults to "Payload Too Large".
249
249
  */
250
- constructor(message = "Payload Too Large") {
250
+ constructor(message = 'Payload Too Large') {
251
251
  super(message);
252
252
  this.status = http_status_codes_1.HttpStatusCodes.PAYLOAD_TOO_LARGE;
253
253
  }
@@ -261,7 +261,7 @@ class InsufficientStorageException extends response_utils_1.ErrorResponse {
261
261
  /**
262
262
  * @param message - Optional custom message. Defaults to "Insufficient Storage".
263
263
  */
264
- constructor(message = "Insufficient Storage") {
264
+ constructor(message = 'Insufficient Storage') {
265
265
  super(message);
266
266
  this.status = http_status_codes_1.HttpStatusCodes.INSUFFICIENT_STORAGE;
267
267
  }
@@ -303,7 +303,7 @@ function createHttpError(status, message) {
303
303
  case http_status_codes_1.HttpStatusCodes.CONFLICT:
304
304
  return new ConflictException(message);
305
305
  case http_status_codes_1.HttpStatusCodes.GONE:
306
- return new HttpError(http_status_codes_1.HttpStatusCodes.GONE, message || "Gone");
306
+ return new HttpError(http_status_codes_1.HttpStatusCodes.GONE, message || 'Gone');
307
307
  case http_status_codes_1.HttpStatusCodes.PAYLOAD_TOO_LARGE:
308
308
  return new PayloadTooLargeException(message);
309
309
  case http_status_codes_1.HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE:
@@ -333,10 +333,7 @@ function createHttpError(status, message) {
333
333
  * @returns True if object has error-like structure.
334
334
  */
335
335
  function hasErrorShape(error) {
336
- return (typeof error === "object" &&
337
- error !== null &&
338
- "message" in error &&
339
- typeof error.message === "string");
336
+ return (typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string');
340
337
  }
341
338
  /**
342
339
  * Safely extracts message from any error type.
@@ -345,7 +342,7 @@ function hasErrorShape(error) {
345
342
  * @returns A string error message.
346
343
  */
347
344
  function getErrorMessage(error) {
348
- if (typeof error === "string") {
345
+ if (typeof error === 'string') {
349
346
  return error;
350
347
  }
351
348
  if (error instanceof Error) {
@@ -354,7 +351,7 @@ function getErrorMessage(error) {
354
351
  if (hasErrorShape(error)) {
355
352
  return error.message;
356
353
  }
357
- return "Unknown error occurred";
354
+ return 'Unknown error occurred';
358
355
  }
359
356
  /**
360
357
  * Wraps a function and transforms any errors into HTTP errors.
@@ -373,10 +370,10 @@ function withErrorHandling(handler) {
373
370
  throw error;
374
371
  }
375
372
  // Log the original error (consider using a proper logger)
376
- (0, logger_utils_1.getLogger)().error("Caught error in handler:", error);
373
+ (0, logger_utils_1.getLogger)().error({ error }, 'Caught error in handler');
377
374
  // Extract status code if it exists, otherwise use 500
378
375
  let status = http_status_codes_1.HttpStatusCodes.INTERNAL_SERVER_ERROR;
379
- if (hasErrorShape(error) && typeof error.status === "number") {
376
+ if (hasErrorShape(error) && typeof error.status === 'number') {
380
377
  status = error.status;
381
378
  }
382
379
  // Create appropriate HTTP error