@catbee/utils 0.0.8-rc.3 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +3 -2
  2. package/build/index.cjs +6912 -0
  3. package/build/index.d.ts +5284 -0
  4. package/build/index.mjs +6635 -0
  5. package/package.json +13 -292
  6. package/build/cjs/config.d.ts +0 -121
  7. package/build/cjs/config.js +0 -137
  8. package/build/cjs/index.d.ts +0 -26
  9. package/build/cjs/index.js +0 -68
  10. package/build/cjs/servers/server.builder.d.ts +0 -507
  11. package/build/cjs/servers/server.builder.js +0 -658
  12. package/build/cjs/servers/server.d.ts +0 -255
  13. package/build/cjs/servers/server.js +0 -970
  14. package/build/cjs/types/api-response.d.ts +0 -151
  15. package/build/cjs/types/api-response.js +0 -36
  16. package/build/cjs/types/index.d.ts +0 -124
  17. package/build/cjs/types/index.js +0 -25
  18. package/build/cjs/types/server.d.ts +0 -267
  19. package/build/cjs/types/server.js +0 -25
  20. package/build/cjs/utils/array.utils.d.ts +0 -167
  21. package/build/cjs/utils/array.utils.js +0 -363
  22. package/build/cjs/utils/async.utils.d.ts +0 -264
  23. package/build/cjs/utils/async.utils.js +0 -640
  24. package/build/cjs/utils/cache.utils.d.ts +0 -152
  25. package/build/cjs/utils/cache.utils.js +0 -298
  26. package/build/cjs/utils/context-store.utils.d.ts +0 -188
  27. package/build/cjs/utils/context-store.utils.js +0 -297
  28. package/build/cjs/utils/crypto.utils.d.ts +0 -159
  29. package/build/cjs/utils/crypto.utils.js +0 -295
  30. package/build/cjs/utils/date.utils.d.ts +0 -158
  31. package/build/cjs/utils/date.utils.js +0 -395
  32. package/build/cjs/utils/decorators.utils.d.ts +0 -511
  33. package/build/cjs/utils/decorators.utils.js +0 -1035
  34. package/build/cjs/utils/dir.utils.d.ts +0 -195
  35. package/build/cjs/utils/dir.utils.js +0 -500
  36. package/build/cjs/utils/env.utils.d.ts +0 -376
  37. package/build/cjs/utils/env.utils.js +0 -786
  38. package/build/cjs/utils/exception.utils.d.ts +0 -229
  39. package/build/cjs/utils/exception.utils.js +0 -408
  40. package/build/cjs/utils/fs.utils.d.ts +0 -163
  41. package/build/cjs/utils/fs.utils.js +0 -371
  42. package/build/cjs/utils/http-status-codes.d.ts +0 -265
  43. package/build/cjs/utils/http-status-codes.js +0 -297
  44. package/build/cjs/utils/id.utils.d.ts +0 -35
  45. package/build/cjs/utils/id.utils.js +0 -90
  46. package/build/cjs/utils/logger.utils.d.ts +0 -159
  47. package/build/cjs/utils/logger.utils.js +0 -350
  48. package/build/cjs/utils/middleware.utils.d.ts +0 -99
  49. package/build/cjs/utils/middleware.utils.js +0 -243
  50. package/build/cjs/utils/obj.utils.d.ts +0 -123
  51. package/build/cjs/utils/obj.utils.js +0 -428
  52. package/build/cjs/utils/performance.utils.d.ts +0 -135
  53. package/build/cjs/utils/performance.utils.js +0 -280
  54. package/build/cjs/utils/request.utils.d.ts +0 -85
  55. package/build/cjs/utils/request.utils.js +0 -199
  56. package/build/cjs/utils/response.utils.d.ts +0 -162
  57. package/build/cjs/utils/response.utils.js +0 -274
  58. package/build/cjs/utils/stream.utils.d.ts +0 -87
  59. package/build/cjs/utils/stream.utils.js +0 -217
  60. package/build/cjs/utils/string.utils.d.ts +0 -92
  61. package/build/cjs/utils/string.utils.js +0 -178
  62. package/build/cjs/utils/type.utils.d.ts +0 -89
  63. package/build/cjs/utils/type.utils.js +0 -195
  64. package/build/cjs/utils/url.utils.d.ts +0 -140
  65. package/build/cjs/utils/url.utils.js +0 -316
  66. package/build/cjs/utils/validate.utils.d.ts +0 -176
  67. package/build/cjs/utils/validate.utils.js +0 -344
  68. package/build/esm/config.d.ts +0 -121
  69. package/build/esm/config.js +0 -132
  70. package/build/esm/index.d.ts +0 -26
  71. package/build/esm/index.js +0 -49
  72. package/build/esm/servers/server.builder.d.ts +0 -507
  73. package/build/esm/servers/server.builder.js +0 -654
  74. package/build/esm/servers/server.d.ts +0 -255
  75. package/build/esm/servers/server.js +0 -963
  76. package/build/esm/types/api-response.d.ts +0 -151
  77. package/build/esm/types/api-response.js +0 -33
  78. package/build/esm/types/index.d.ts +0 -124
  79. package/build/esm/types/index.js +0 -24
  80. package/build/esm/types/server.d.ts +0 -267
  81. package/build/esm/types/server.js +0 -24
  82. package/build/esm/utils/array.utils.d.ts +0 -167
  83. package/build/esm/utils/array.utils.js +0 -344
  84. package/build/esm/utils/async.utils.d.ts +0 -264
  85. package/build/esm/utils/async.utils.js +0 -619
  86. package/build/esm/utils/cache.utils.d.ts +0 -152
  87. package/build/esm/utils/cache.utils.js +0 -294
  88. package/build/esm/utils/context-store.utils.d.ts +0 -188
  89. package/build/esm/utils/context-store.utils.js +0 -290
  90. package/build/esm/utils/crypto.utils.d.ts +0 -159
  91. package/build/esm/utils/crypto.utils.js +0 -278
  92. package/build/esm/utils/date.utils.d.ts +0 -158
  93. package/build/esm/utils/date.utils.js +0 -383
  94. package/build/esm/utils/decorators.utils.d.ts +0 -511
  95. package/build/esm/utils/decorators.utils.js +0 -1013
  96. package/build/esm/utils/dir.utils.d.ts +0 -195
  97. package/build/esm/utils/dir.utils.js +0 -476
  98. package/build/esm/utils/env.utils.d.ts +0 -376
  99. package/build/esm/utils/env.utils.js +0 -782
  100. package/build/esm/utils/exception.utils.d.ts +0 -229
  101. package/build/esm/utils/exception.utils.js +0 -382
  102. package/build/esm/utils/fs.utils.d.ts +0 -163
  103. package/build/esm/utils/fs.utils.js +0 -348
  104. package/build/esm/utils/http-status-codes.d.ts +0 -265
  105. package/build/esm/utils/http-status-codes.js +0 -294
  106. package/build/esm/utils/id.utils.d.ts +0 -35
  107. package/build/esm/utils/id.utils.js +0 -83
  108. package/build/esm/utils/logger.utils.d.ts +0 -159
  109. package/build/esm/utils/logger.utils.js +0 -304
  110. package/build/esm/utils/middleware.utils.d.ts +0 -99
  111. package/build/esm/utils/middleware.utils.js +0 -235
  112. package/build/esm/utils/obj.utils.d.ts +0 -123
  113. package/build/esm/utils/obj.utils.js +0 -412
  114. package/build/esm/utils/performance.utils.d.ts +0 -135
  115. package/build/esm/utils/performance.utils.js +0 -273
  116. package/build/esm/utils/request.utils.d.ts +0 -85
  117. package/build/esm/utils/request.utils.js +0 -190
  118. package/build/esm/utils/response.utils.d.ts +0 -162
  119. package/build/esm/utils/response.utils.js +0 -261
  120. package/build/esm/utils/stream.utils.d.ts +0 -87
  121. package/build/esm/utils/stream.utils.js +0 -209
  122. package/build/esm/utils/string.utils.d.ts +0 -92
  123. package/build/esm/utils/string.utils.js +0 -164
  124. package/build/esm/utils/type.utils.d.ts +0 -89
  125. package/build/esm/utils/type.utils.js +0 -186
  126. package/build/esm/utils/url.utils.d.ts +0 -140
  127. package/build/esm/utils/url.utils.js +0 -303
  128. package/build/esm/utils/validate.utils.d.ts +0 -176
  129. package/build/esm/utils/validate.utils.js +0 -319
@@ -1,782 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- */
24
- /* eslint-disable n/no-process-env */
25
- import { existsSync, readFileSync } from 'fs';
26
- import { isAbsolute, resolve } from 'path';
27
- /**
28
- * Enum representing valid application environments.
29
- */
30
- export var Environment;
31
- (function (Environment) {
32
- Environment["PRODUCTION"] = "production";
33
- Environment["DEVELOPMENT"] = "development";
34
- Environment["STAGING"] = "staging";
35
- Environment["TESTING"] = "testing";
36
- })(Environment || (Environment = {}));
37
- /**
38
- * Utility class for accessing and managing environment variables.
39
- * Provides typed getters with fallback defaults and validation.
40
- */
41
- export class Env {
42
- // Cache for parsed values to avoid repeated parsing of complex values
43
- static cache = new Map();
44
- /**
45
- * Checks if the current NODE_ENV is 'development'.
46
- *
47
- * @returns {boolean} `true` if NODE_ENV is 'development', else `false`.
48
- */
49
- static isDev() {
50
- return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.DEVELOPMENT;
51
- }
52
- /**
53
- * Checks if the current NODE_ENV is 'production'.
54
- *
55
- * @returns {boolean} `true` if NODE_ENV is 'production', else `false`.
56
- */
57
- static isProd() {
58
- return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.PRODUCTION;
59
- }
60
- /**
61
- * Checks if the current NODE_ENV is 'testing'.
62
- *
63
- * @returns {boolean} `true` if NODE_ENV is 'testing', else `false`.
64
- */
65
- static isTest() {
66
- return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.TESTING;
67
- }
68
- /**
69
- * Checks if the current NODE_ENV is 'staging'.
70
- *
71
- * @returns {boolean} `true` if NODE_ENV is 'staging', else `false`.
72
- */
73
- static isStaging() {
74
- return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.STAGING;
75
- }
76
- /**
77
- * Sets an environment variable (only affects runtime memory).
78
- *
79
- * @param {string} key - The environment variable key.
80
- * @param {string} value - The value to set.
81
- */
82
- static set(key, value) {
83
- process.env[key] = value;
84
- // Clear all cached values for this key with any prefix
85
- this.cache.delete(key);
86
- for (const cacheKey of [...this.cache.keys()]) {
87
- if (cacheKey.includes(`:${key}`)) {
88
- this.cache.delete(cacheKey);
89
- }
90
- }
91
- }
92
- /**
93
- * Returns all environment variables as an object.
94
- *
95
- * @returns {object} The current `process.env` object.
96
- */
97
- static getAll() {
98
- return process.env;
99
- }
100
- /**
101
- * Retrieves a string environment variable with a fallback default.
102
- * Supports variable expansion with ${VAR_NAME} syntax.
103
- *
104
- * @param {string} key - The environment variable key.
105
- * @param {string} [defaultValue] - Value to return if the key is missing.
106
- * @returns {string} The env value or the fallback.
107
- *
108
- * @example
109
- * // If DATABASE_URL is "postgres://localhost:5432/${DB_NAME}"
110
- * // and DB_NAME is "myapp"
111
- * const url = Env.get('DATABASE_URL', ''); // "postgres://localhost:5432/myapp"
112
- */
113
- static get(key, defaultValue) {
114
- let value = process.env[key] ?? defaultValue;
115
- // Expand ${VAR} references
116
- if (value && value.includes('${')) {
117
- value = value.replace(/\${([A-Za-z0-9_]+)}/g, (_, varName) => {
118
- return process.env[varName] ?? '';
119
- });
120
- }
121
- return value;
122
- }
123
- /**
124
- * Retrieves a string environment variable and throws if it's missing.
125
- *
126
- * @param {string} key - The environment variable key.
127
- * @returns {string} The environment variable's value.
128
- * @throws {Error} If the variable is not defined.
129
- */
130
- static getRequired(key) {
131
- const value = process.env[key];
132
- if (value === undefined) {
133
- throw new Error(`Required environment variable '${key}' is missing`);
134
- }
135
- return Env.get(key, ''); // Use get to handle variable expansion
136
- }
137
- /**
138
- * Retrieves a value using a default generating function if the key doesn't exist.
139
- * Useful for expensive default calculations.
140
- *
141
- * @param {string} key - The environment variable key.
142
- * @param {() => string} defaultFn - Function that generates default value.
143
- * @returns {string} The environment value or generated default.
144
- *
145
- * @example
146
- * const hostname = Env.getWithDefault('HOSTNAME', () => {
147
- * // Only called if HOSTNAME is not set
148
- * return require('os').hostname();
149
- * });
150
- */
151
- static getWithDefault(key, defaultFn) {
152
- if (Env.has(key)) {
153
- return Env.get(key, '');
154
- }
155
- return defaultFn();
156
- }
157
- /**
158
- * Retrieves an environment variable as a number, or returns a default.
159
- *
160
- * @param {string} key - The environment variable key.
161
- * @param {number} defaultValue - Fallback number if key is not present.
162
- * @returns {number} Parsed numeric value or default.
163
- * @throws {Error} If the value is not a valid number.
164
- */
165
- static getNumber(key, defaultValue) {
166
- if (this.cache.has(`number:${key}`)) {
167
- return this.cache.get(`number:${key}`);
168
- }
169
- const value = process.env[key];
170
- if (value === undefined) {
171
- return defaultValue;
172
- }
173
- const numberValue = Number(value);
174
- if (isNaN(numberValue)) {
175
- throw new Error(`Environment variable '${key}' is not a valid number, got: "${value}"`);
176
- }
177
- this.cache.set(`number:${key}`, numberValue);
178
- return numberValue;
179
- }
180
- /**
181
- * Retrieves a required environment variable as a number.
182
- *
183
- * @param {string} key - The environment variable key.
184
- * @returns {number} Parsed number.
185
- * @throws {Error} If the value is missing or not a number.
186
- */
187
- static getNumberRequired(key) {
188
- const value = process.env[key];
189
- if (value === undefined) {
190
- throw new Error(`Required environment variable '${key}' is missing`);
191
- }
192
- return Env.getNumber(key, 0); // The default is ignored since we know the key exists
193
- }
194
- /**
195
- * Retrieves an integer environment variable and validates it.
196
- *
197
- * @param {string} key - The environment variable key.
198
- * @param {number} defaultValue - Fallback number if key is not present.
199
- * @param {object} [options] - Validation options.
200
- * @param {number} [options.min] - Minimum allowed value.
201
- * @param {number} [options.max] - Maximum allowed value.
202
- * @returns {number} The parsed integer.
203
- *
204
- * @example
205
- * // Require PORT to be between 1000 and 9999
206
- * const port = Env.getInteger('PORT', 3000, { min: 1000, max: 9999 });
207
- */
208
- static getInteger(key, defaultValue, options = {}) {
209
- const num = Env.getNumber(key, defaultValue);
210
- const intValue = Math.floor(num);
211
- if (intValue !== num) {
212
- throw new Error(`Environment variable '${key}' must be an integer, got: ${num}`);
213
- }
214
- if (options.min !== undefined && intValue < options.min) {
215
- throw new Error(`Environment variable '${key}' must be at least ${options.min}, got: ${intValue}`);
216
- }
217
- if (options.max !== undefined && intValue > options.max) {
218
- throw new Error(`Environment variable '${key}' must be at most ${options.max}, got: ${intValue}`);
219
- }
220
- return intValue;
221
- }
222
- /**
223
- * Retrieves an environment variable as a boolean.
224
- * Accepts `true`, `1`, `yes`, `on` as true; `false`, `0`, `no`, `off` as false.
225
- *
226
- * @param {string} key - The environment variable key.
227
- * @param {boolean} [defaultValue=false] - Optional fallback value if key is missing.
228
- * @returns {boolean} Parsed boolean.
229
- * @throws {Error} If the value is not a recognized boolean string.
230
- *
231
- * @example
232
- * // If DEBUG=yes
233
- * const isDebug = Env.getBoolean('DEBUG', false); // true
234
- */
235
- static getBoolean(key, defaultValue = false) {
236
- if (this.cache.has(`bool:${key}`)) {
237
- return this.cache.get(`bool:${key}`);
238
- }
239
- const value = process.env[key];
240
- if (value === undefined) {
241
- return defaultValue;
242
- }
243
- const lowerValue = value.toLowerCase();
244
- if (['true', '1', 'yes', 'on'].includes(lowerValue)) {
245
- this.cache.set(`bool:${key}`, true);
246
- return true;
247
- }
248
- if (['false', '0', 'no', 'off'].includes(lowerValue)) {
249
- this.cache.set(`bool:${key}`, false);
250
- return false;
251
- }
252
- throw new Error(`Environment variable '${key}' is not a valid boolean, got: "${value}". Use true/false, yes/no, 1/0, or on/off.`);
253
- }
254
- /**
255
- * Retrieves a required environment variable as a boolean.
256
- *
257
- * @param {string} key - The environment variable key.
258
- * @returns {boolean} Parsed boolean value.
259
- * @throws {Error} If missing or invalid.
260
- */
261
- static getBooleanRequired(key) {
262
- const value = process.env[key];
263
- if (value === undefined) {
264
- throw new Error(`Required environment variable '${key}' is missing`);
265
- }
266
- return Env.getBoolean(key);
267
- }
268
- /**
269
- * Parses a stringified JSON object from an environment variable.
270
- *
271
- * @typeParam T - The type to parse as (defaults to `object`).
272
- * @param {string} key - The environment variable key.
273
- * @param {T} defaultValue - Value to return if key is missing.
274
- * @returns {T} Parsed object or default.
275
- * @throws {Error} If the value is not valid JSON.
276
- *
277
- * @example
278
- * // If CONFIG='{"debug":true,"api":{"url":"https://api.example.com"}}'
279
- * const config = Env.getJSON('CONFIG', { debug: false });
280
- * // { debug: true, api: { url: "https://api.example.com" }}
281
- */
282
- static getJSON(key, defaultValue) {
283
- if (this.cache.has(`json:${key}`)) {
284
- return this.cache.get(`json:${key}`);
285
- }
286
- const v = process.env[key];
287
- if (v === undefined) {
288
- return defaultValue;
289
- }
290
- try {
291
- const parsed = JSON.parse(v);
292
- this.cache.set(`json:${key}`, parsed);
293
- return parsed;
294
- }
295
- catch (error) {
296
- throw new Error(`Environment variable '${key}' is not valid JSON: ${error.message}`);
297
- }
298
- }
299
- /**
300
- * Parses a comma-separated string as an array.
301
- *
302
- * @typeParam T - The item type (optional, defaults to string).
303
- * @param {string} key - The environment variable key.
304
- * @param {T[]} [defaultValue=[]] - Array to return if value is empty or missing.
305
- * @param {string} [splitter=','] - Delimiter to split on.
306
- * @param {(item: string) => T} [transform] - Optional function to transform each item.
307
- * @returns {T[]} An array of items.
308
- *
309
- * @example
310
- * // If ALLOWED_IPS=127.0.0.1,192.168.1.1,10.0.0.1
311
- * const ips = Env.getArray('ALLOWED_IPS');
312
- * // ["127.0.0.1", "192.168.1.1", "10.0.0.1"]
313
- *
314
- * // With transformation function
315
- * const ports = Env.getArray('PORTS', [], ',', (p) => parseInt(p, 10));
316
- */
317
- static getArray(key, defaultValue = [], splitter = ',', transform) {
318
- const cacheKey = `array:${key}:${splitter}:${transform ? 'transformed' : 'raw'}`;
319
- if (this.cache.has(cacheKey)) {
320
- return this.cache.get(cacheKey);
321
- }
322
- const value = process.env[key];
323
- if (!value || value.trim() === '') {
324
- return defaultValue;
325
- }
326
- const items = value
327
- .split(splitter)
328
- .map(item => item.trim())
329
- .filter(item => item.length > 0);
330
- if (transform) {
331
- try {
332
- const result = items.map(transform);
333
- this.cache.set(cacheKey, result);
334
- return result;
335
- }
336
- catch (error) {
337
- throw new Error(`Failed to transform items in '${key}': ${error.message}`);
338
- }
339
- }
340
- const result = items;
341
- this.cache.set(cacheKey, result);
342
- return result;
343
- }
344
- /**
345
- * Parses a comma-separated list of numbers.
346
- *
347
- * @param {string} key - The environment variable key.
348
- * @param {number[]} [defaultValue=[]] - Default value if not present.
349
- * @param {string} [splitter=','] - Delimiter to split on.
350
- * @returns {number[]} Array of parsed numbers.
351
- *
352
- * @example
353
- * // If ALLOWED_PORTS=80,443,3000,8080
354
- * const ports = Env.getNumberArray('ALLOWED_PORTS');
355
- * // [80, 443, 3000, 8080]
356
- */
357
- static getNumberArray(key, defaultValue = [], splitter = ',') {
358
- return Env.getArray(key, defaultValue, splitter, item => {
359
- const num = Number(item);
360
- if (isNaN(num)) {
361
- throw new Error(`Value "${item}" in array '${key}' is not a valid number`);
362
- }
363
- return num;
364
- });
365
- }
366
- /**
367
- * Retrieves an enum-like environment variable value, validating against allowed values.
368
- *
369
- * @typeParam T - The allowed value type (string literal types).
370
- * @param {string} key - The environment variable key.
371
- * @param {T[]} allowedValues - Array of accepted string values.
372
- * @param {T} [defaultValue] - Optional fallback value.
373
- * @returns {T} The validated environment value.
374
- * @throws {Error} If missing or invalid.
375
- *
376
- * @example
377
- * // If LOG_LEVEL=debug
378
- * const level = Env.getEnum('LOG_LEVEL', ['debug', 'info', 'warn', 'error'] as const, 'info');
379
- * // 'debug' (typed as 'debug' | 'info' | 'warn' | 'error')
380
- */
381
- static getEnum(key, allowedValues, defaultValue) {
382
- const value = process.env[key];
383
- if (!value) {
384
- return defaultValue;
385
- }
386
- if (!allowedValues.includes(value)) {
387
- throw new Error(`Environment variable '${key}' must be one of: ${allowedValues.join(', ')}. Received: "${value}"`);
388
- }
389
- return value;
390
- }
391
- /**
392
- * Retrieves an enum-like numeric environment variable.
393
- *
394
- * @param {string} key - The environment variable key.
395
- * @param {number[]} allowedValues - Array of accepted values.
396
- * @param {number} defaultValue - Default value if not present.
397
- * @returns {number} The validated value.
398
- *
399
- * @example
400
- * // If NODE_VERSION=16
401
- * const version = Env.getNumberEnum('NODE_VERSION', [14, 16, 18], 16);
402
- */
403
- static getNumberEnum(key, allowedValues, defaultValue) {
404
- const value = Env.getNumber(key, defaultValue);
405
- if (!allowedValues.includes(value)) {
406
- throw new Error(`Environment variable '${key}' must be one of: ${allowedValues.join(', ')}. Received: ${value}`);
407
- }
408
- return value;
409
- }
410
- /**
411
- * Retrieves a URL environment variable and validates it.
412
- *
413
- * @param {string} key - The environment variable key.
414
- * @param {string} [defaultValue] - Optional fallback value.
415
- * @param {UrlOptions} [options] - Validation options.
416
- * @returns {string} The validated URL.
417
- * @throws {Error} If URL is invalid.
418
- *
419
- * @example
420
- * // Validate API URL requires HTTPS
421
- * const apiUrl = Env.getUrl('API_URL', 'https://api.example.com', {
422
- * protocols: ['https'],
423
- * requireTld: true,
424
- * allowIp: false
425
- * });
426
- */
427
- static getUrl(key, defaultValue, options = {}) {
428
- const cacheKey = `url:${key}:${JSON.stringify(options)}`;
429
- if (this.cache.has(cacheKey)) {
430
- return this.cache.get(cacheKey);
431
- }
432
- const value = Env.get(key, defaultValue);
433
- if (!value) {
434
- throw new Error(`URL environment variable '${key}' is missing or empty`);
435
- }
436
- let url;
437
- try {
438
- url = new URL(value);
439
- }
440
- catch {
441
- throw new Error(`Environment variable '${key}' is not a valid URL: "${value}"`);
442
- }
443
- // Validate protocol
444
- if (options.protocols && options.protocols.length > 0) {
445
- const protocol = url.protocol.replace(':', '');
446
- if (!options.protocols.includes(protocol)) {
447
- throw new Error(`Environment variable '${key}' must use one of the protocols: ${options.protocols.join(', ')}. Got: ${protocol}`);
448
- }
449
- }
450
- // Validate hostname
451
- const { hostname } = url;
452
- const isIp = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/.test(hostname);
453
- const isLocalhost = hostname === 'localhost';
454
- // Check if hostname is an IP address when not allowed
455
- if (isIp && options.allowIp === false) {
456
- throw new Error(`Environment variable '${key}' cannot be an IP address: "${hostname}"`);
457
- }
458
- // Check if hostname is localhost when not allowed
459
- if (isLocalhost && options.allowLocalhost === false) {
460
- throw new Error(`Environment variable '${key}' cannot be localhost`);
461
- }
462
- // Check for TLD requirement - include localhost in check if requireTld is true and allowLocalhost is false
463
- if (options.requireTld === true) {
464
- if (isLocalhost && options.allowLocalhost !== false) {
465
- // Localhost is allowed, so no TLD check needed for it
466
- }
467
- else if (isIp && options.allowIp !== false) {
468
- // IP is allowed, so no TLD check needed for it
469
- }
470
- else if (!hostname.includes('.') || hostname.endsWith('.')) {
471
- throw new Error(`Environment variable '${key}' must have a valid host with TLD: "${hostname}"`);
472
- }
473
- }
474
- this.cache.set(cacheKey, value);
475
- return value;
476
- }
477
- /**
478
- * Retrieves an email environment variable and validates it.
479
- *
480
- * @param {string} key - The environment variable key.
481
- * @param {string} [defaultValue] - Optional fallback value.
482
- * @returns {string} The validated email address.
483
- * @throws {Error} If email is invalid.
484
- *
485
- * @example
486
- * const supportEmail = Env.getEmail('SUPPORT_EMAIL', 'support@example.com');
487
- */
488
- static getEmail(key, defaultValue) {
489
- if (this.cache.has(`email:${key}`)) {
490
- return this.cache.get(`email:${key}`);
491
- }
492
- const value = Env.get(key, defaultValue);
493
- if (!value) {
494
- if (defaultValue === undefined) {
495
- throw new Error(`Email environment variable '${key}' is missing`);
496
- }
497
- return defaultValue;
498
- }
499
- // More comprehensive email validation regex
500
- const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
501
- if (!emailRegex.test(value)) {
502
- throw new Error(`Environment variable '${key}' is not a valid email address: "${value}"`);
503
- }
504
- this.cache.set(`email:${key}`, value);
505
- return value;
506
- }
507
- /**
508
- * Retrieves a path environment variable and validates it exists.
509
- *
510
- * @param {string} key - The environment variable key.
511
- * @param {string} [defaultValue] - Optional fallback value.
512
- * @param {PathOptions} [options] - Validation options.
513
- * @returns {string} The validated path.
514
- * @throws {Error} If path is invalid.
515
- *
516
- * @example
517
- * // Require that the path exists and is a .json file
518
- * const configPath = Env.getPath('CONFIG_PATH', './config.json', {
519
- * mustExist: true,
520
- * allowedExtensions: ['.json', '.yaml']
521
- * });
522
- */
523
- static getPath(key, defaultValue, options = {}) {
524
- const cacheKey = `path:${key}:${JSON.stringify(options)}`;
525
- if (this.cache.has(cacheKey)) {
526
- return this.cache.get(cacheKey);
527
- }
528
- const value = Env.get(key, defaultValue);
529
- if (!value) {
530
- if (defaultValue === undefined) {
531
- throw new Error(`Path environment variable '${key}' is missing`);
532
- }
533
- return defaultValue;
534
- }
535
- const path = options.makeAbsolute !== false && !isAbsolute(value) ? resolve(process.cwd(), value) : value;
536
- // Validate path exists if required
537
- if (options.mustExist && !existsSync(path)) {
538
- throw new Error(`Path in environment variable '${key}' does not exist: "${path}"`);
539
- }
540
- // Validate file extension if specified
541
- if (options.allowedExtensions && options.allowedExtensions.length > 0) {
542
- const hasValidExtension = options.allowedExtensions.some(ext => path.toLowerCase().endsWith(ext.toLowerCase()));
543
- if (!hasValidExtension) {
544
- throw new Error(`Path in environment variable '${key}' must have one of these extensions: ${options.allowedExtensions.join(', ')}. Got: "${path}"`);
545
- }
546
- }
547
- this.cache.set(cacheKey, path);
548
- return path;
549
- }
550
- /**
551
- * Retrieves a port environment variable and validates it.
552
- *
553
- * @param {string} key - The environment variable key.
554
- * @param {number} [defaultValue] - Optional fallback value.
555
- * @returns {number} The validated port number.
556
- * @throws {Error} If port is invalid.
557
- *
558
- * @example
559
- * const serverPort = Env.getPort('PORT', 3000);
560
- */
561
- static getPort(key, defaultValue) {
562
- try {
563
- return Env.getInteger(key, defaultValue, { min: 0, max: 65535 });
564
- }
565
- catch (error) {
566
- // Rewrite the error message to match the expected pattern
567
- if (error.message.includes('must be at most 65535')) {
568
- throw new Error(`Environment variable '${key}' must be a valid port number (0-65535)`);
569
- }
570
- throw error;
571
- }
572
- }
573
- /**
574
- * Retrieves an ISO date string and converts it to a Date object.
575
- *
576
- * @param {string} key - The environment variable key.
577
- * @param {string|Date} [defaultValue] - Optional fallback value.
578
- * @returns {Date} The parsed Date object.
579
- *
580
- * @example
581
- * // If EXPIRY_DATE=2023-12-31T23:59:59Z
582
- * const expiryDate = Env.getDate('EXPIRY_DATE', new Date());
583
- */
584
- static getDate(key, defaultValue = new Date()) {
585
- const value = Env.get(key, defaultValue instanceof Date ? defaultValue.toISOString() : defaultValue);
586
- if (!value) {
587
- return defaultValue instanceof Date ? defaultValue : new Date();
588
- }
589
- const date = new Date(value);
590
- if (isNaN(date.getTime())) {
591
- throw new Error(`Environment variable '${key}' is not a valid date: "${value}"`);
592
- }
593
- return date;
594
- }
595
- /**
596
- * Retrieves a duration string and converts it to milliseconds.
597
- * Supports formats like "1d", "2h", "30m", "45s", "100ms" or combinations like "1h30m".
598
- *
599
- * @param {string} key - The environment variable key.
600
- * @param {string|number} [defaultValue='0'] - Optional fallback value.
601
- * @returns {number} The duration in milliseconds.
602
- * @throws {Error} If duration format is invalid.
603
- *
604
- * @example
605
- * // If CACHE_TTL=2h30m
606
- * const cacheTtlMs = Env.getDuration('CACHE_TTL', '1h');
607
- * // 9000000 (2.5 hours in milliseconds)
608
- */
609
- static getDuration(key, defaultValue = '0') {
610
- const cacheKey = `duration:${key}`;
611
- if (this.cache.has(cacheKey)) {
612
- return this.cache.get(cacheKey);
613
- }
614
- const value = Env.get(key, String(defaultValue));
615
- if (!value)
616
- return 0;
617
- // Handle plain number input (assume milliseconds)
618
- if (/^\d+$/.test(value)) {
619
- const ms = parseInt(value, 10);
620
- this.cache.set(cacheKey, ms);
621
- return ms;
622
- }
623
- // Enhanced duration parsing with more precise regex
624
- const durationRegex = /^(?:(\d+)y)?(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?(?:(\d+)ms)?$/;
625
- const matches = value.match(durationRegex);
626
- if (!matches || matches[0] === '') {
627
- throw new Error(`Environment variable '${key}' has invalid duration format: "${value}". ` +
628
- `Use formats like 1y, 2w, 3d, 4h, 5m, 6s, or 7ms.`);
629
- }
630
- let ms = 0;
631
- if (matches[1])
632
- ms += parseInt(matches[1], 10) * 31536000000; // years (approximate)
633
- if (matches[2])
634
- ms += parseInt(matches[2], 10) * 604800000; // weeks
635
- if (matches[3])
636
- ms += parseInt(matches[3], 10) * 86400000; // days
637
- if (matches[4])
638
- ms += parseInt(matches[4], 10) * 3600000; // hours
639
- if (matches[5])
640
- ms += parseInt(matches[5], 10) * 60000; // minutes
641
- if (matches[6])
642
- ms += parseInt(matches[6], 10) * 1000; // seconds
643
- if (matches[7])
644
- ms += parseInt(matches[7], 10); // milliseconds
645
- this.cache.set(cacheKey, ms);
646
- return ms;
647
- }
648
- /**
649
- * Gets all environment variables with sensitive values masked for safe logging.
650
- *
651
- * @param {string[]} [sensitiveKeys=['password', 'secret', 'key', 'token', 'auth']] - Keys to mask.
652
- * @returns {Record<string, string>} Environment variables with sensitive values masked.
653
- *
654
- * @example
655
- * console.log(Env.getSafeEnv(['password', 'secret', 'key']));
656
- * // { DATABASE_URL: "postgres://...", API_KEY: "******", ... }
657
- */
658
- static getSafeEnv(sensitiveKeys = ['password', 'secret', 'key', 'token', 'auth']) {
659
- const safeEnv = {};
660
- for (const [key, value] of Object.entries(process.env)) {
661
- if (!value)
662
- continue;
663
- const isSensitive = sensitiveKeys.some(sensitiveKey => key.toLowerCase().includes(sensitiveKey.toLowerCase()));
664
- safeEnv[key] = isSensitive ? '******' : value;
665
- }
666
- return safeEnv;
667
- }
668
- /**
669
- * Loads environment variables from a .env file.
670
- * Does not override existing variables.
671
- *
672
- * @param {string} [path='.env'] - Path to the .env file.
673
- * @returns {Record<string, string>} Loaded environment variables.
674
- *
675
- * @example
676
- * // Load variables from .env.development
677
- * Env.loadFromFile('.env.development');
678
- */
679
- static loadFromFile(path = '.env') {
680
- if (!existsSync(path)) {
681
- throw new Error(`Environment file not found: "${path}"`);
682
- }
683
- const content = readFileSync(path, 'utf8');
684
- const variables = {};
685
- const lines = content.split(/\r?\n/);
686
- let i = 0;
687
- while (i < lines.length) {
688
- let line = lines[i].trim();
689
- // Skip empty lines or comment-only lines
690
- if (!line || line.startsWith('#')) {
691
- i++;
692
- continue;
693
- }
694
- const match = line.match(/^([^=]+)=(.*)$/);
695
- if (!match) {
696
- i++;
697
- continue;
698
- }
699
- const key = match[1].trim();
700
- let value = match[2].trim();
701
- // Remove inline comment for unquoted values
702
- if (!/^['"]/.test(value)) {
703
- const hashIndex = value.indexOf(' #');
704
- if (hashIndex !== -1) {
705
- value = value.slice(0, hashIndex).trim();
706
- }
707
- }
708
- // Handle quoted values
709
- if ((value.startsWith('"') || value.startsWith("'")) && value.length > 1) {
710
- const quote = value[0];
711
- if (!value.endsWith(quote) || value.length === 1) {
712
- // multiline quoted
713
- let multilineValue = value.slice(1);
714
- i++;
715
- while (i < lines.length) {
716
- const nextLine = lines[i];
717
- if (nextLine.endsWith(quote)) {
718
- multilineValue += '\n' + nextLine.slice(0, -1);
719
- break;
720
- }
721
- else {
722
- multilineValue += '\n' + nextLine;
723
- }
724
- i++;
725
- }
726
- value = multilineValue;
727
- }
728
- else {
729
- // single-line quoted
730
- value = value.slice(1, -1);
731
- }
732
- }
733
- else {
734
- // Handle unquoted multiline: continue collecting until next key=value or empty line
735
- i++;
736
- while (i < lines.length && !lines[i].includes('=') && lines[i].trim() !== '') {
737
- value += '\n' + lines[i];
738
- i++;
739
- }
740
- i--; // adjust for outer loop
741
- }
742
- if (!process.env[key]) {
743
- process.env[key] = value;
744
- variables[key] = value;
745
- }
746
- i++;
747
- }
748
- return variables;
749
- }
750
- /**
751
- * Checks whether the specified environment variable exists.
752
- *
753
- * @param {string} key - The environment variable key.
754
- * @returns {boolean} `true` if the variable is defined, otherwise `false`.
755
- */
756
- static has(key) {
757
- return process.env[key] !== undefined;
758
- }
759
- /**
760
- * Deletes the given environment variable (useful in tests).
761
- *
762
- * @param {string} key - The environment variable key to delete.
763
- * @returns {void}
764
- */
765
- static delete(key) {
766
- delete process.env[key];
767
- this.cache.delete(key);
768
- // Also clear all cached variations of this key
769
- for (const cacheKey of this.cache.keys()) {
770
- if (cacheKey.includes(`:${key}`)) {
771
- this.cache.delete(cacheKey);
772
- }
773
- }
774
- }
775
- /**
776
- * Clears the internal cache of parsed environment values.
777
- * Useful for testing or when environment variables might change.
778
- */
779
- static clearCache() {
780
- this.cache.clear();
781
- }
782
- }