@adonisjs/env 4.0.0-0 → 4.0.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.
package/README.md CHANGED
@@ -1,41 +1,141 @@
1
- <div align="center">
2
- <img src="https://res.cloudinary.com/adonisjs/image/upload/q_100/v1558612869/adonis-readme_zscycu.jpg" width="600px">
3
- </div>
4
-
5
- <br />
6
-
7
- <div align="center">
8
- <h3>AdonisJS Env Provider</h3>
9
- <p>Provider to parse and load environment variables from a local <code>.env</code> file. Comes with first class support for <strong>variables substitution</strong>.</p>
10
- </div>
11
-
12
- <br />
13
-
14
- <div align="center">
15
-
16
- [![gh-workflow-image]][gh-workflow-url] [![npm-image]][npm-url] ![][typescript-image] [![license-image]][license-url] [![synk-image]][synk-url]
17
-
18
- </div>
19
-
20
- <div align="center">
21
- <h3>
22
- <a href="https://adonisjs.com">
23
- Website
24
- </a>
25
- <span> | </span>
26
- <a href="https://docs.adonisjs.com/guides/environment-variables">
27
- Guides
28
- </a>
29
- <span> | </span>
30
- <a href="CONTRIBUTING.md">
31
- Contributing
32
- </a>
33
- </h3>
34
- </div>
35
-
36
- <div align="center">
37
- <sub>Built with ❤︎ by <a href="https://twitter.com/AmanVirk1">Harminder Virk</a>
38
- </div>
1
+ # @adonisjs/env
2
+ > Environment variables parser and validator used by the AdonisJS.
3
+
4
+ [![gh-workflow-image]][gh-workflow-url] [![typescript-image]][typescript-url] [![npm-image]][npm-url] [![license-image]][license-url] [![synk-image]][synk-url]
5
+
6
+ > **Note:** This package is framework agnostic and can also be used outside of AdonisJS.
7
+
8
+ The `@adonisjs/env` package encapsulates the workflow around loading, parsing, and validating environment variables.
9
+
10
+ ## Setup
11
+ Install the package from the npm packages registry as follows.
12
+
13
+ ```sh
14
+ npm i @adonisjs/env
15
+
16
+ yarn add @adonisjs/env
17
+ ```
18
+
19
+ ## EnvLoader
20
+ The `EnvLoader` class is responsible for loading the environment variable files from the disk and returning their contents as a string.
21
+
22
+ ```ts
23
+ import { EnvLoader } from '@adonisjs/env'
24
+
25
+ const lookupPath = new URL('./', import.meta.url)
26
+ const loader = new EnvLoader(lookupPath)
27
+
28
+ const { envContents, currentEnvContents } = loader.load()
29
+ ```
30
+
31
+ ### `envContents`
32
+
33
+ - The `envContents` is read from the `.env` file from the root of the `lookupPath`.
34
+ - No exceptions are raised if the `.env` file is missing. In brief, it is optional to have a `.env` file.
35
+ - If the `ENV_PATH` environment variable is set, the loader will use that instead of the `.env` file. This allows overwriting the location of the dot-env file.
36
+
37
+
38
+ ### `currentEnvContents`
39
+
40
+ - The `currentEnvContents` contents are read from the `.env.[NODE_ENV]` file.
41
+ - If the current `NODE_ENV = 'development'`, then the contents of this variable will be from the `.env.development` file and so on.
42
+ - The contents of this file should precede the `.env` file.
43
+
44
+ ## EnvParser
45
+ The `EnvParser` class is responsible for parsing the contents of the `.env` file(s) and converting them into an object.
46
+
47
+ ```ts
48
+ import { EnvLoader, EnvParser } from '@adonisjs/env'
49
+
50
+ const lookupPath = new URL('./', import.meta.url)
51
+ const loader = new EnvLoader(lookupPath)
52
+ const { envContents, currentEnvContents } = loader.load()
53
+
54
+ const envParser = new EnvParser(envContents)
55
+ const currentEnvParser = new EnvParser(currentEnvContents)
56
+
57
+ console.log(envParser.parse()) // { key: value }
58
+ console.log(currentEnvParser.parse()) // { key: value }
59
+ ```
60
+
61
+ The return value of `parser.parse` is an object with key-value pair. The parser also has support for interpolation.
62
+
63
+ ## Validating environment variables
64
+ Once you have the parsed objects, you can optionally validate them against a pre-defined schema. We recommend validation for the following reasons.
65
+
66
+ - Fail early if one or more environment variables are missing.
67
+ - Cast values to specific data types.
68
+ - Have type safety alongside runtime safety.
69
+
70
+ ```ts
71
+ import { Env } from '@adonisjs/env'
72
+
73
+ const validate = Env.rules({
74
+ PORT: Env.schema.number(),
75
+ HOST: Env.schema.string({ format: 'host' })
76
+ })
77
+ ```
78
+
79
+ The `Env.schema` is a reference to the [@poppinss/validator-lite](https://github.com/poppinss/validator-lite) `schema` object. Make sure to go through the package README to view all the available methods and options.
80
+
81
+ The `Env.rules` method returns a function to validate the environment variables. The return value is the validated object with type information inferred from the schema.
82
+
83
+ ```ts
84
+ validate(process.env)
85
+ ```
86
+
87
+ Following is a complete example of using the `EnvLoader`, `EnvParser`, and the validator to set up environment variables.
88
+
89
+ ```ts
90
+ import { EnvLoader, EnvParser, Env } from '@adonisjs/env'
91
+
92
+ const lookupPath = new URL('./', import.meta.url)
93
+ const loader = new EnvLoader(lookupPath)
94
+ const { envContents, currentEnvContents } = loader.load()
95
+
96
+ const envValues = new EnvParser(envContents).parse()
97
+ const currentEnvValues = new EnvParser(currentEnvContents).parse()
98
+
99
+ /**
100
+ * Loop over all the parsed env values and set
101
+ * them on "process.env"
102
+ *
103
+ * However, if the value already exists on "process.env", then
104
+ * do not overwrite it, instead update the envValues
105
+ * object.
106
+ */
107
+ Object.keys(envValues).forEach((key) => {
108
+ if (process.env[key]) {
109
+ envValues[key] = process.env[key]
110
+ } else {
111
+ process.env[key] = envValues[key]
112
+ }
113
+ })
114
+
115
+ /**
116
+ * Loop over all the current env parsed values and make
117
+ * them take precedence over the existing process.env
118
+ * values.
119
+ */
120
+ Object.keys(currentEnvValues).forEach((key) => {
121
+ process.env[key] = envValues[key]
122
+ })
123
+
124
+ // Now perform the validation
125
+ const validate = Env.rules({
126
+ PORT: Env.schema.number(),
127
+ HOST: Env.schema.string({ format: 'host' })
128
+ })
129
+
130
+ const validated = validate({ ...envValues, ...currentEnvValues })
131
+ const env = new Env(validated)
132
+
133
+ env.get('PORT') // is a number
134
+ env.get('HOST') // is a string
135
+ env.get('NODE_ENV') // is unknown, hence a string or undefined
136
+ ```
137
+
138
+ The above code may seem like a lot of work to set up environment variables. However, you have fine-grained control over each step. In the case of AdonisJS, all this boilerplate is hidden inside the framework's application bootstrapping logic.
39
139
 
40
140
  [gh-workflow-image]: https://img.shields.io/github/workflow/status/adonisjs/env/test?style=for-the-badge
41
141
  [gh-workflow-url]: https://github.com/adonisjs/env/actions/workflows/test.yml "Github action"
@@ -0,0 +1,6 @@
1
+ import { Exception } from '@poppinss/utils';
2
+ export declare class InvalidEnvVariablesException extends Exception {
3
+ static status: number;
4
+ static code: string;
5
+ static message: string;
6
+ }
@@ -0,0 +1,6 @@
1
+ import { Exception } from '@poppinss/utils';
2
+ export class InvalidEnvVariablesException extends Exception {
3
+ static status = 500;
4
+ static code = 'E_INVALID_ENV_VARIABLES';
5
+ static message = 'Validation failed for one or more environment variables';
6
+ }
@@ -1,12 +1,26 @@
1
+ import { InvalidEnvVariablesException } from './exceptions/invalid_env_variables.js';
1
2
  export class EnvValidator {
2
3
  #schema;
4
+ #error;
3
5
  constructor(schema) {
4
6
  this.#schema = schema;
7
+ this.#error = new InvalidEnvVariablesException();
5
8
  }
6
9
  validate(values) {
7
- return Object.keys(this.#schema).reduce((result, key) => {
8
- result[key] = this.#schema[key](key, values[key]);
10
+ const help = [];
11
+ const validated = Object.keys(this.#schema).reduce((result, key) => {
12
+ try {
13
+ result[key] = this.#schema[key](key, values[key]);
14
+ }
15
+ catch (error) {
16
+ help.push(`- ${error.message}`);
17
+ }
9
18
  return result;
10
19
  }, { ...values });
20
+ if (help.length) {
21
+ this.#error.help = help.join('\n');
22
+ throw this.#error;
23
+ }
24
+ return validated;
11
25
  }
12
26
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adonisjs/env",
3
- "version": "4.0.0-0",
3
+ "version": "4.0.0-1",
4
4
  "description": "Environment variable manager for Node.js",
5
5
  "main": "build/index.js",
6
6
  "type": "module",