devguard-env 0.0.0-stage → 1.0.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 +21 -0
- package/README.md +246 -2
- package/bin/devguard.js +133 -0
- package/package.json +42 -4
- package/src/env-loader.js +96 -0
- package/src/errors.js +30 -0
- package/src/index.js +20 -0
- package/src/validator.js +264 -0
- package/types/index.d.ts +52 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 OJAL AKASH
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,247 @@
|
|
|
1
|
-
#
|
|
1
|
+
# DevGuard Env
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**A lightweight environment variable validation toolkit for Node.js applications.**
|
|
4
|
+
|
|
5
|
+
DevGuard Env helps developers validate environment variables, convert values to the correct types, apply default values, and catch configuration errors before they cause problems in an application.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- Validate required environment variables.
|
|
10
|
+
- Convert strings into numbers and booleans.
|
|
11
|
+
- Validate URLs and email addresses.
|
|
12
|
+
- Set default values.
|
|
13
|
+
- Define minimum and maximum values.
|
|
14
|
+
- Validate allowed values using enums.
|
|
15
|
+
- Add custom validation rules.
|
|
16
|
+
- Load variables from `.env` files.
|
|
17
|
+
- Strict mode to detect unexpected variables.
|
|
18
|
+
- Simple command-line interface.
|
|
19
|
+
- Zero external runtime dependencies.
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install devguard-env
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Quick Start
|
|
28
|
+
|
|
29
|
+
Create a `devguard.config.js` file in your project root:
|
|
30
|
+
|
|
31
|
+
```javascript
|
|
32
|
+
const { validateEnv } = require("devguard-env");
|
|
33
|
+
|
|
34
|
+
const config = validateEnv({
|
|
35
|
+
PORT: {
|
|
36
|
+
type: "number",
|
|
37
|
+
required: true,
|
|
38
|
+
default: 3000
|
|
39
|
+
},
|
|
40
|
+
DATABASE_URL: {
|
|
41
|
+
type: "url",
|
|
42
|
+
required: true
|
|
43
|
+
},
|
|
44
|
+
DEBUG: {
|
|
45
|
+
type: "boolean",
|
|
46
|
+
default: false
|
|
47
|
+
},
|
|
48
|
+
NODE_ENV: {
|
|
49
|
+
type: "string",
|
|
50
|
+
enum: ["development", "production", "test"]
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
module.exports = config;
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Then load your environment variables before running your application:
|
|
58
|
+
|
|
59
|
+
```javascript
|
|
60
|
+
require("devguard-env").loadEnv();
|
|
61
|
+
|
|
62
|
+
const config = require("./devguard.config");
|
|
63
|
+
|
|
64
|
+
console.log(config);
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Supported Validation Rules
|
|
68
|
+
|
|
69
|
+
| Rule | Description |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `type` | `string`, `number`, `boolean`, or `url` |
|
|
72
|
+
| `required` | Requires the variable to be present |
|
|
73
|
+
| `default` | Supplies a default value |
|
|
74
|
+
| `min` | Minimum numeric value |
|
|
75
|
+
| `max` | Maximum numeric value |
|
|
76
|
+
| `minLength` | Minimum string length |
|
|
77
|
+
| `maxLength` | Maximum string length |
|
|
78
|
+
| `email` | Checks whether a string is a valid email |
|
|
79
|
+
| `enum` | Restricts values to an allowed list |
|
|
80
|
+
| `custom` | Accepts a custom validation function |
|
|
81
|
+
|
|
82
|
+
### Example
|
|
83
|
+
|
|
84
|
+
```javascript
|
|
85
|
+
const { validateEnv } = require("devguard-env");
|
|
86
|
+
|
|
87
|
+
const config = validateEnv({
|
|
88
|
+
PORT: {
|
|
89
|
+
type: "number",
|
|
90
|
+
min: 1,
|
|
91
|
+
max: 65535,
|
|
92
|
+
required: true
|
|
93
|
+
},
|
|
94
|
+
ADMIN_EMAIL: {
|
|
95
|
+
type: "string",
|
|
96
|
+
email: true,
|
|
97
|
+
required: true
|
|
98
|
+
},
|
|
99
|
+
NODE_ENV: {
|
|
100
|
+
type: "string",
|
|
101
|
+
enum: ["development", "production", "test"]
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## API Reference
|
|
107
|
+
|
|
108
|
+
### `validateEnv(schema, options)`
|
|
109
|
+
|
|
110
|
+
Validates environment variables against a schema and returns a configuration object containing converted values.
|
|
111
|
+
|
|
112
|
+
Options:
|
|
113
|
+
|
|
114
|
+
- `env`: Environment object to validate. Defaults to `process.env`.
|
|
115
|
+
- `strict`: Rejects variables that are not defined in the schema.
|
|
116
|
+
- `log`: Set to `false` to suppress success messages.
|
|
117
|
+
|
|
118
|
+
Example:
|
|
119
|
+
|
|
120
|
+
```javascript
|
|
121
|
+
const { validateEnv } = require("devguard-env");
|
|
122
|
+
|
|
123
|
+
const config = validateEnv(
|
|
124
|
+
{
|
|
125
|
+
PORT: { type: "number", required: true },
|
|
126
|
+
DEBUG: { type: "boolean", default: false }
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
env: process.env,
|
|
130
|
+
strict: false,
|
|
131
|
+
log: false
|
|
132
|
+
}
|
|
133
|
+
);
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### `loadEnv(filePath, options)`
|
|
137
|
+
|
|
138
|
+
Reads and parses an environment file.
|
|
139
|
+
|
|
140
|
+
```javascript
|
|
141
|
+
const { loadEnv } = require("devguard-env");
|
|
142
|
+
|
|
143
|
+
const env = loadEnv(".env");
|
|
144
|
+
console.log(env);
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
To also populate `process.env`:
|
|
148
|
+
|
|
149
|
+
```javascript
|
|
150
|
+
loadEnv(".env", {
|
|
151
|
+
populateProcessEnv: true
|
|
152
|
+
});
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Existing process variables are preserved by default. Set `override: true` to overwrite them.
|
|
156
|
+
|
|
157
|
+
### `parseEnv(content)`
|
|
158
|
+
|
|
159
|
+
Parses environment variable text directly.
|
|
160
|
+
|
|
161
|
+
```javascript
|
|
162
|
+
const { parseEnv } = require("devguard-env");
|
|
163
|
+
|
|
164
|
+
const env = parseEnv(`
|
|
165
|
+
PORT=3000
|
|
166
|
+
DEBUG=true
|
|
167
|
+
`);
|
|
168
|
+
|
|
169
|
+
console.log(env);
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
### `DevGuardError`
|
|
173
|
+
|
|
174
|
+
Validation failures throw a `DevGuardError` containing detailed information about the invalid variables.
|
|
175
|
+
|
|
176
|
+
```javascript
|
|
177
|
+
const { validateEnv, DevGuardError } = require("devguard-env");
|
|
178
|
+
|
|
179
|
+
try {
|
|
180
|
+
validateEnv({
|
|
181
|
+
PORT: { type: "number", required: true }
|
|
182
|
+
});
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (error instanceof DevGuardError) {
|
|
185
|
+
console.error(error.message);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## Command-Line Usage
|
|
191
|
+
|
|
192
|
+
DevGuard also provides a command-line interface.
|
|
193
|
+
|
|
194
|
+
Create a `devguard.config.js` file that exports a schema:
|
|
195
|
+
|
|
196
|
+
```javascript
|
|
197
|
+
module.exports = {
|
|
198
|
+
schema: {
|
|
199
|
+
PORT: {
|
|
200
|
+
type: "number",
|
|
201
|
+
required: true
|
|
202
|
+
},
|
|
203
|
+
DATABASE_URL: {
|
|
204
|
+
type: "url",
|
|
205
|
+
required: true
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Run:
|
|
212
|
+
|
|
213
|
+
```bash
|
|
214
|
+
npx devguard-env
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
Available options:
|
|
218
|
+
|
|
219
|
+
| Command | Description |
|
|
220
|
+
|---|---|
|
|
221
|
+
| `--help` | Display help |
|
|
222
|
+
| `--env <path>` | Specify an environment file |
|
|
223
|
+
| `--config <path>` | Specify a configuration file |
|
|
224
|
+
| `--strict` | Reject unexpected variables |
|
|
225
|
+
| `--quiet` | Suppress success messages |
|
|
226
|
+
|
|
227
|
+
## Error Handling
|
|
228
|
+
|
|
229
|
+
DevGuard reports validation errors with the variable name and the reason for failure.
|
|
230
|
+
|
|
231
|
+
Example:
|
|
232
|
+
|
|
233
|
+
```text
|
|
234
|
+
DevGuard Validation Failed
|
|
235
|
+
|
|
236
|
+
✖ PORT: Must be a valid number.
|
|
237
|
+
|
|
238
|
+
1 configuration error(s) found.
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
## Requirements
|
|
242
|
+
|
|
243
|
+
- Node.js 18 or higher.
|
|
244
|
+
|
|
245
|
+
## License
|
|
246
|
+
|
|
247
|
+
MIT
|
package/bin/devguard.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
"use strict";
|
|
4
|
+
|
|
5
|
+
const path = require("node:path");
|
|
6
|
+
const {
|
|
7
|
+
validateEnv,
|
|
8
|
+
loadEnv,
|
|
9
|
+
DevGuardError
|
|
10
|
+
} = require("../src");
|
|
11
|
+
|
|
12
|
+
function printHelp() {
|
|
13
|
+
console.log(`
|
|
14
|
+
DevGuard - Environment Variable Validator
|
|
15
|
+
|
|
16
|
+
Usage:
|
|
17
|
+
devguard-env [options]
|
|
18
|
+
|
|
19
|
+
Options:
|
|
20
|
+
--env <path> Environment file (default: .env)
|
|
21
|
+
--config <path> Configuration file (default: devguard.config.js)
|
|
22
|
+
--strict Reject unexpected environment variables
|
|
23
|
+
--quiet Suppress success messages
|
|
24
|
+
--help Show this help message
|
|
25
|
+
|
|
26
|
+
Examples:
|
|
27
|
+
devguard-env
|
|
28
|
+
devguard-env --env .env.production
|
|
29
|
+
devguard-env --strict
|
|
30
|
+
devguard-env --config config/devguard.config.js
|
|
31
|
+
`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function parseArguments(args) {
|
|
35
|
+
const options = {
|
|
36
|
+
env: ".env",
|
|
37
|
+
config: "devguard.config.js",
|
|
38
|
+
strict: false,
|
|
39
|
+
quiet: false
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
for (let i = 0; i < args.length; i++) {
|
|
43
|
+
const arg = args[i];
|
|
44
|
+
|
|
45
|
+
if (arg === "--help" || arg === "-h") {
|
|
46
|
+
options.help = true;
|
|
47
|
+
} else if (arg === "--strict") {
|
|
48
|
+
options.strict = true;
|
|
49
|
+
} else if (arg === "--quiet" || arg === "-q") {
|
|
50
|
+
options.quiet = true;
|
|
51
|
+
} else if (arg === "--env" || arg === "--config") {
|
|
52
|
+
const value = args[++i];
|
|
53
|
+
|
|
54
|
+
if (!value || value.startsWith("--")) {
|
|
55
|
+
throw new Error(`Missing value for ${arg}.`);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
options[arg === "--env" ? "env" : "config"] = value;
|
|
59
|
+
} else {
|
|
60
|
+
throw new Error(`Unknown option: ${arg}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return options;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function main() {
|
|
68
|
+
try {
|
|
69
|
+
const options = parseArguments(process.argv.slice(2));
|
|
70
|
+
|
|
71
|
+
if (options.help) {
|
|
72
|
+
printHelp();
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const configPath = path.resolve(options.config);
|
|
77
|
+
const envPath = path.resolve(options.env);
|
|
78
|
+
|
|
79
|
+
let userConfig;
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
userConfig = require(configPath);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (error.code === "MODULE_NOT_FOUND") {
|
|
85
|
+
throw new Error(
|
|
86
|
+
`Configuration file not found: ${configPath}`
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (
|
|
94
|
+
!userConfig ||
|
|
95
|
+
typeof userConfig !== "object" ||
|
|
96
|
+
!userConfig.schema
|
|
97
|
+
) {
|
|
98
|
+
throw new Error(
|
|
99
|
+
"Invalid configuration. Export an object containing a schema property."
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const env = loadEnv(envPath);
|
|
104
|
+
|
|
105
|
+
const validated = validateEnv(
|
|
106
|
+
userConfig.schema,
|
|
107
|
+
{
|
|
108
|
+
env,
|
|
109
|
+
strict: options.strict,
|
|
110
|
+
log: false
|
|
111
|
+
}
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
if (!options.quiet) {
|
|
115
|
+
console.log("\n✓ DevGuard: Environment validation successful!");
|
|
116
|
+
console.log(
|
|
117
|
+
`✓ ${Object.keys(validated).length} environment variable(s) validated.`
|
|
118
|
+
);
|
|
119
|
+
console.log(`✓ Environment file: ${envPath}`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (error instanceof DevGuardError) {
|
|
124
|
+
console.error("\n" + error.message);
|
|
125
|
+
} else {
|
|
126
|
+
console.error("\n✖ DevGuard:", error.message);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
process.exitCode = 1;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
main();
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
|
+
|
|
1
2
|
{
|
|
2
3
|
"name": "devguard-env",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
4
|
+
"version": "1.0.0",
|
|
5
|
+
"description": "A lightweight and powerful environment variable validation toolkit for Node.js applications.",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"types": "types/index.d.ts",
|
|
8
|
+
"bin": {
|
|
9
|
+
"devguard": "bin/devguard.js"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./types/index.d.ts",
|
|
14
|
+
"require": "./src/index.js",
|
|
15
|
+
"default": "./src/index.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"src",
|
|
20
|
+
"bin",
|
|
21
|
+
"types",
|
|
22
|
+
"README.md",
|
|
23
|
+
"LICENSE"
|
|
24
|
+
],
|
|
25
|
+
"scripts": {
|
|
26
|
+
"test": "node --test",
|
|
27
|
+
"test:watch": "node --test --watch"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"environment-variables",
|
|
31
|
+
"env-validator",
|
|
32
|
+
"dotenv",
|
|
33
|
+
"configuration",
|
|
34
|
+
"validation",
|
|
35
|
+
"nodejs",
|
|
36
|
+
"developer-tools"
|
|
37
|
+
],
|
|
38
|
+
"author": "OJAL AKASH",
|
|
39
|
+
"license": "MIT",
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=18"
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
const fs = require("node:fs");
|
|
5
|
+
const path = require("node:path");
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Parses environment variable content.
|
|
9
|
+
*/
|
|
10
|
+
function parseEnv(content) {
|
|
11
|
+
const result = {};
|
|
12
|
+
|
|
13
|
+
const lines = content.split(/\r?\n/);
|
|
14
|
+
|
|
15
|
+
for (const line of lines) {
|
|
16
|
+
const trimmed = line.trim();
|
|
17
|
+
|
|
18
|
+
if (!trimmed || trimmed.startsWith("#")) {
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const match = trimmed.match(
|
|
23
|
+
/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
if (!match) {
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const key = match[1];
|
|
31
|
+
let value = match[2].trim();
|
|
32
|
+
|
|
33
|
+
if (
|
|
34
|
+
(value.startsWith('"') && value.endsWith('"')) ||
|
|
35
|
+
(value.startsWith("'") && value.endsWith("'")) ||
|
|
36
|
+
(value.startsWith("`") && value.endsWith("`"))
|
|
37
|
+
) {
|
|
38
|
+
value = value.slice(1, -1);
|
|
39
|
+
|
|
40
|
+
if (value.startsWith('"')) {
|
|
41
|
+
value = value
|
|
42
|
+
.replace(/\\n/g, "\n")
|
|
43
|
+
.replace(/\\r/g, "\r");
|
|
44
|
+
}
|
|
45
|
+
} else {
|
|
46
|
+
value = value.replace(/\s+#.*$/, "").trim();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
result[key] = value;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return result;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Loads environment variables from a file.
|
|
57
|
+
*
|
|
58
|
+
* @param {string} filePath Path to the environment file.
|
|
59
|
+
* @param {Object} options Loader options.
|
|
60
|
+
* @returns {Object} Parsed environment variables.
|
|
61
|
+
*/
|
|
62
|
+
function loadEnv(filePath = ".env", options = {}) {
|
|
63
|
+
if (typeof filePath !== "string" || !filePath.trim()) {
|
|
64
|
+
throw new TypeError("Environment file path must be a non-empty string.");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const resolvedPath = path.resolve(filePath);
|
|
68
|
+
|
|
69
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`DevGuard: Environment file not found: ${resolvedPath}`
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const content = fs.readFileSync(resolvedPath, "utf8");
|
|
76
|
+
|
|
77
|
+
const parsed = parseEnv(content);
|
|
78
|
+
|
|
79
|
+
if (options.populateProcessEnv === true) {
|
|
80
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
81
|
+
if (
|
|
82
|
+
options.override === true ||
|
|
83
|
+
process.env[key] === undefined
|
|
84
|
+
) {
|
|
85
|
+
process.env[key] = value;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return parsed;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
module.exports = {
|
|
94
|
+
loadEnv,
|
|
95
|
+
parseEnv
|
|
96
|
+
};
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Represents an environment validation error.
|
|
6
|
+
*/
|
|
7
|
+
class DevGuardError extends Error {
|
|
8
|
+
constructor(errors) {
|
|
9
|
+
const message = [
|
|
10
|
+
"DevGuard Validation Failed",
|
|
11
|
+
"",
|
|
12
|
+
...errors.map(
|
|
13
|
+
(error) => `✖ ${error.variable}: ${error.message}`
|
|
14
|
+
),
|
|
15
|
+
"",
|
|
16
|
+
`${errors.length} configuration error(s) found.`
|
|
17
|
+
].join("\n");
|
|
18
|
+
|
|
19
|
+
super(message);
|
|
20
|
+
|
|
21
|
+
this.name = "DevGuardError";
|
|
22
|
+
this.errors = errors;
|
|
23
|
+
|
|
24
|
+
Error.captureStackTrace?.(this, DevGuardError);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
module.exports = {
|
|
29
|
+
DevGuardError
|
|
30
|
+
};
|
package/src/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const {
|
|
4
|
+
validateEnv,
|
|
5
|
+
isValidEmail,
|
|
6
|
+
isValidUrl
|
|
7
|
+
} = require("./validator");
|
|
8
|
+
|
|
9
|
+
const { DevGuardError } = require("./errors");
|
|
10
|
+
|
|
11
|
+
const { loadEnv, parseEnv } = require("./env-loader");
|
|
12
|
+
|
|
13
|
+
module.exports = {
|
|
14
|
+
validateEnv,
|
|
15
|
+
DevGuardError,
|
|
16
|
+
loadEnv,
|
|
17
|
+
parseEnv,
|
|
18
|
+
isValidEmail,
|
|
19
|
+
isValidUrl
|
|
20
|
+
};
|
package/src/validator.js
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
const { DevGuardError } = require("./errors");
|
|
5
|
+
|
|
6
|
+
const SUPPORTED_TYPES = ["string", "number", "boolean", "url"];
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Checks whether a value is a valid email address.
|
|
10
|
+
*/
|
|
11
|
+
function isValidEmail(value) {
|
|
12
|
+
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Converts environment strings into appropriate JavaScript values.
|
|
17
|
+
*/
|
|
18
|
+
function convertValue(value, type) {
|
|
19
|
+
if (type === "number") {
|
|
20
|
+
const number = Number(value);
|
|
21
|
+
return Number.isFinite(number) ? number : NaN;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (type === "boolean") {
|
|
25
|
+
if (value === true || value === "true") return true;
|
|
26
|
+
if (value === false || value === "false") return false;
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
if (type === "string") {
|
|
31
|
+
return String(value);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Validates a URL.
|
|
39
|
+
*/
|
|
40
|
+
function isValidUrl(value) {
|
|
41
|
+
try {
|
|
42
|
+
const parsed = new URL(value);
|
|
43
|
+
|
|
44
|
+
return ["http:", "https:"].includes(parsed.protocol);
|
|
45
|
+
} catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Validates one environment variable.
|
|
52
|
+
*/
|
|
53
|
+
function validateVariable(name, value, rules) {
|
|
54
|
+
const errors = [];
|
|
55
|
+
|
|
56
|
+
const addError = (message) => {
|
|
57
|
+
errors.push({ variable: name, message });
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const exists = value !== undefined && value !== null;
|
|
61
|
+
const empty = value === "";
|
|
62
|
+
|
|
63
|
+
if (!exists || empty) {
|
|
64
|
+
if (rules.default !== undefined) {
|
|
65
|
+
value = rules.default;
|
|
66
|
+
} else if (rules.required) {
|
|
67
|
+
addError("Required environment variable is missing.");
|
|
68
|
+
return { value, errors };
|
|
69
|
+
} else {
|
|
70
|
+
return { value: undefined, errors };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const type = rules.type || "string";
|
|
75
|
+
|
|
76
|
+
if (!SUPPORTED_TYPES.includes(type)) {
|
|
77
|
+
throw new TypeError(
|
|
78
|
+
`Unsupported type "${type}" for ${name}. Supported types: ${SUPPORTED_TYPES.join(", ")}.`
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (type === "url") {
|
|
83
|
+
if (typeof value !== "string" || !isValidUrl(value)) {
|
|
84
|
+
addError("Must be a valid HTTP or HTTPS URL.");
|
|
85
|
+
return { value, errors };
|
|
86
|
+
}
|
|
87
|
+
} else {
|
|
88
|
+
value = convertValue(value, type);
|
|
89
|
+
|
|
90
|
+
if (
|
|
91
|
+
(type === "number" && !Number.isFinite(value)) ||
|
|
92
|
+
(type === "boolean" && value === null)
|
|
93
|
+
) {
|
|
94
|
+
addError(`Must be a valid ${type}.`);
|
|
95
|
+
return { value, errors };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (type === "string") {
|
|
100
|
+
if (
|
|
101
|
+
rules.minLength !== undefined &&
|
|
102
|
+
value.length < rules.minLength
|
|
103
|
+
) {
|
|
104
|
+
addError(
|
|
105
|
+
`Must be at least ${rules.minLength} characters long.`
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (
|
|
110
|
+
rules.maxLength !== undefined &&
|
|
111
|
+
value.length > rules.maxLength
|
|
112
|
+
) {
|
|
113
|
+
addError(
|
|
114
|
+
`Must not exceed ${rules.maxLength} characters.`
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (rules.email && !isValidEmail(value)) {
|
|
119
|
+
addError("Must be a valid email address.");
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (type === "number") {
|
|
124
|
+
if (rules.min !== undefined && value < rules.min) {
|
|
125
|
+
addError(`Must be greater than or equal to ${rules.min}.`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (rules.max !== undefined && value > rules.max) {
|
|
129
|
+
addError(`Must be less than or equal to ${rules.max}.`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (rules.enum !== undefined) {
|
|
134
|
+
if (!Array.isArray(rules.enum) || rules.enum.length === 0) {
|
|
135
|
+
throw new TypeError(
|
|
136
|
+
`The enum rule for ${name} must be a non-empty array.`
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (!rules.enum.includes(value)) {
|
|
141
|
+
addError(
|
|
142
|
+
`Must be one of: ${rules.enum.join(", ")}.`
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (rules.custom !== undefined) {
|
|
148
|
+
if (typeof rules.custom !== "function") {
|
|
149
|
+
throw new TypeError(
|
|
150
|
+
`The custom rule for ${name} must be a function.`
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
try {
|
|
155
|
+
const result = rules.custom(value);
|
|
156
|
+
|
|
157
|
+
if (result !== true) {
|
|
158
|
+
addError(
|
|
159
|
+
typeof result === "string"
|
|
160
|
+
? result
|
|
161
|
+
: "Failed custom validation."
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
} catch {
|
|
165
|
+
addError("Custom validation threw an unexpected error.");
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return { value, errors };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Validates an environment configuration against a schema.
|
|
174
|
+
*
|
|
175
|
+
* @param {Object} schema Validation rules.
|
|
176
|
+
* @param {Object} options Configuration options.
|
|
177
|
+
* @returns {Object} Validated configuration.
|
|
178
|
+
*/
|
|
179
|
+
function validateEnv(schema, options = {}) {
|
|
180
|
+
if (
|
|
181
|
+
schema === null ||
|
|
182
|
+
typeof schema !== "object" ||
|
|
183
|
+
Array.isArray(schema)
|
|
184
|
+
) {
|
|
185
|
+
throw new TypeError("DevGuard schema must be an object.");
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (
|
|
189
|
+
options === null ||
|
|
190
|
+
typeof options !== "object" ||
|
|
191
|
+
Array.isArray(options)
|
|
192
|
+
) {
|
|
193
|
+
throw new TypeError("DevGuard options must be an object.");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const source = options.env || process.env;
|
|
197
|
+
|
|
198
|
+
if (
|
|
199
|
+
source === null ||
|
|
200
|
+
typeof source !== "object" ||
|
|
201
|
+
Array.isArray(source)
|
|
202
|
+
) {
|
|
203
|
+
throw new TypeError("The env option must be an object.");
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const config = {};
|
|
207
|
+
const allErrors = [];
|
|
208
|
+
|
|
209
|
+
for (const [name, rules] of Object.entries(schema)) {
|
|
210
|
+
if (
|
|
211
|
+
rules === null ||
|
|
212
|
+
typeof rules !== "object" ||
|
|
213
|
+
Array.isArray(rules)
|
|
214
|
+
) {
|
|
215
|
+
throw new TypeError(
|
|
216
|
+
`Validation rules for ${name} must be an object.`
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const result = validateVariable(
|
|
221
|
+
name,
|
|
222
|
+
source[name],
|
|
223
|
+
rules
|
|
224
|
+
);
|
|
225
|
+
|
|
226
|
+
if (result.value !== undefined) {
|
|
227
|
+
config[name] = result.value;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
allErrors.push(...result.errors);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
if (options.strict === true) {
|
|
234
|
+
for (const name of Object.keys(source)) {
|
|
235
|
+
if (!Object.prototype.hasOwnProperty.call(schema, name)) {
|
|
236
|
+
allErrors.push({
|
|
237
|
+
variable: name,
|
|
238
|
+
message: "Unexpected environment variable."
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (allErrors.length > 0) {
|
|
245
|
+
throw new DevGuardError(allErrors);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (options.log !== false) {
|
|
249
|
+
console.log(
|
|
250
|
+
`✓ DevGuard: Environment validation successful!`
|
|
251
|
+
);
|
|
252
|
+
console.log(
|
|
253
|
+
`✓ ${Object.keys(config).length} environment variable(s) validated.`
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return config;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
module.exports = {
|
|
261
|
+
validateEnv,
|
|
262
|
+
isValidEmail,
|
|
263
|
+
isValidUrl
|
|
264
|
+
};
|
package/types/index.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
|
|
2
|
+
export type EnvValueType = "string" | "number" | "boolean" | "url";
|
|
3
|
+
|
|
4
|
+
export interface ValidationRules {
|
|
5
|
+
type?: EnvValueType;
|
|
6
|
+
required?: boolean;
|
|
7
|
+
default?: unknown;
|
|
8
|
+
min?: number;
|
|
9
|
+
max?: number;
|
|
10
|
+
minLength?: number;
|
|
11
|
+
maxLength?: number;
|
|
12
|
+
email?: boolean;
|
|
13
|
+
enum?: readonly unknown[];
|
|
14
|
+
custom?: (value: unknown) => boolean | string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ValidateOptions {
|
|
18
|
+
env?: Record<string, unknown>;
|
|
19
|
+
strict?: boolean;
|
|
20
|
+
log?: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface LoadEnvOptions {
|
|
24
|
+
populateProcessEnv?: boolean;
|
|
25
|
+
override?: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface DevGuardValidationError {
|
|
29
|
+
variable: string;
|
|
30
|
+
message: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class DevGuardError extends Error {
|
|
34
|
+
errors: DevGuardValidationError[];
|
|
35
|
+
constructor(errors: DevGuardValidationError[]);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function validateEnv<T extends Record<string, ValidationRules>>(
|
|
39
|
+
schema: T,
|
|
40
|
+
options?: ValidateOptions
|
|
41
|
+
): Record<string, unknown>;
|
|
42
|
+
|
|
43
|
+
export function loadEnv(
|
|
44
|
+
filePath?: string,
|
|
45
|
+
options?: LoadEnvOptions
|
|
46
|
+
): Record<string, string>;
|
|
47
|
+
|
|
48
|
+
export function parseEnv(content: string): Record<string, string>;
|
|
49
|
+
|
|
50
|
+
export function isValidEmail(value: string): boolean;
|
|
51
|
+
|
|
52
|
+
export function isValidUrl(value: string): boolean;
|