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