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