@catbee/utils 0.0.3 → 0.0.5

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