@adonisjs/env 4.2.0-2 → 4.2.0-3

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,7 +1,7 @@
1
1
  # @adonisjs/env
2
2
  > Environment variables parser and validator used by the AdonisJS.
3
3
 
4
- [![gh-workflow-image]][gh-workflow-url] [![typescript-image]][typescript-url] [![npm-image]][npm-url] [![license-image]][license-url] [![synk-image]][synk-url]
4
+ [![gh-workflow-image]][gh-workflow-url] [![typescript-image]][typescript-url] [![npm-image]][npm-url] [![license-image]][license-url]
5
5
 
6
6
  > **Note:** This package is framework agnostic and can also be used outside of AdonisJS.
7
7
 
@@ -135,8 +135,8 @@ try {
135
135
  }
136
136
  ```
137
137
 
138
- [gh-workflow-image]: https://img.shields.io/github/actions/workflow/status/adonisjs/env/test.yml?style=for-the-badge
139
- [gh-workflow-url]: https://github.com/adonisjs/env/actions/workflows/test.yml "Github action"
138
+ [gh-workflow-image]: https://img.shields.io/github/actions/workflow/status/adonisjs/env/checks.yml?style=for-the-badge
139
+ [gh-workflow-url]: https://github.com/adonisjs/env/actions/workflows/checks.yml "Github action"
140
140
 
141
141
  [typescript-image]: https://img.shields.io/badge/Typescript-294E80.svg?style=for-the-badge&logo=typescript
142
142
  [typescript-url]: "typescript"
@@ -146,6 +146,3 @@ try {
146
146
 
147
147
  [license-image]: https://img.shields.io/npm/l/@adonisjs/env?color=blueviolet&style=for-the-badge
148
148
  [license-url]: LICENSE.md "license"
149
-
150
- [synk-image]: https://img.shields.io/snyk/vulnerabilities/github/adonisjs/env?label=Synk%20Vulnerabilities&style=for-the-badge
151
- [synk-url]: https://snyk.io/test/github/adonisjs/env?targetFile=package.json "synk"
package/build/index.d.ts CHANGED
@@ -4,4 +4,3 @@ export { EnvLoader } from './src/loader.js';
4
4
  export { EnvEditor } from './src/editor.js';
5
5
  export * as errors from './src/exceptions.js';
6
6
  export { EnvProcessor } from './src/processor.js';
7
- //# sourceMappingURL=index.d.ts.map
package/build/index.js CHANGED
@@ -1,3 +1,11 @@
1
+ /*
2
+ * @adonisjs/env
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
1
9
  export { Env } from './src/env.js';
2
10
  export { EnvParser } from './src/parser.js';
3
11
  export { EnvLoader } from './src/loader.js';
@@ -1,4 +1,3 @@
1
- /// <reference types="node" resolution-mode="require"/>
1
+ /// <reference types="@types/node" resolution-mode="require"/>
2
2
  declare const _default: import("util").DebugLogger;
3
3
  export default _default;
4
- //# sourceMappingURL=debug.d.ts.map
@@ -1,2 +1,10 @@
1
+ /*
2
+ * @adonisjs/env
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
1
9
  import { debuglog } from 'node:util';
2
10
  export default debuglog('adonisjs:env');
@@ -1,14 +1,27 @@
1
- /// <reference types="node" resolution-mode="require"/>
1
+ /// <reference types="@types/node" resolution-mode="require"/>
2
2
  export declare class EnvEditor {
3
3
  #private;
4
+ /**
5
+ * Creates an instance of env editor and loads .env files
6
+ * contents.
7
+ */
4
8
  static create(appRoot: URL): Promise<EnvEditor>;
5
9
  constructor(appRoot: URL);
10
+ /**
11
+ * Loads .env files for editing. Only ".env" and ".env.example"
12
+ * files are picked for editing.
13
+ */
6
14
  load(): Promise<void>;
15
+ /**
16
+ * Add key-value pair to the dot-env files.
17
+ */
7
18
  add(key: string, value: string | number | boolean): void;
8
19
  toJSON(): {
9
20
  contents: string[];
10
21
  path: string;
11
22
  }[];
23
+ /**
24
+ * Save changes to the disk
25
+ */
12
26
  save(): Promise<void>;
13
27
  }
14
- //# sourceMappingURL=editor.d.ts.map
@@ -1,3 +1,11 @@
1
+ /*
2
+ * @adonisjs/env
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
1
9
  import splitLines from 'split-lines';
2
10
  import lodash from '@poppinss/utils/lodash';
3
11
  import { writeFile } from 'node:fs/promises';
@@ -6,6 +14,10 @@ export class EnvEditor {
6
14
  #appRoot;
7
15
  #loader;
8
16
  #files = [];
17
+ /**
18
+ * Creates an instance of env editor and loads .env files
19
+ * contents.
20
+ */
9
21
  static async create(appRoot) {
10
22
  const editor = new EnvEditor(appRoot);
11
23
  await editor.load();
@@ -15,6 +27,10 @@ export class EnvEditor {
15
27
  this.#appRoot = appRoot;
16
28
  this.#loader = new EnvLoader(this.#appRoot, true);
17
29
  }
30
+ /**
31
+ * Loads .env files for editing. Only ".env" and ".env.example"
32
+ * files are picked for editing.
33
+ */
18
34
  async load() {
19
35
  const envFiles = await this.#loader.load();
20
36
  this.#files = envFiles
@@ -27,6 +43,9 @@ export class EnvEditor {
27
43
  };
28
44
  });
29
45
  }
46
+ /**
47
+ * Add key-value pair to the dot-env files.
48
+ */
30
49
  add(key, value) {
31
50
  this.#files.forEach((file) => {
32
51
  let entryIndex = file.contents.findIndex((line) => line.startsWith(`${key}=`));
@@ -37,6 +56,9 @@ export class EnvEditor {
37
56
  toJSON() {
38
57
  return this.#files;
39
58
  }
59
+ /**
60
+ * Save changes to the disk
61
+ */
40
62
  async save() {
41
63
  await Promise.all(this.#files.map((file) => {
42
64
  return writeFile(file.path, file.contents.join('\n'));
@@ -1,28 +1,82 @@
1
- /// <reference types="node" resolution-mode="require"/>
1
+ /// <reference types="@types/node" resolution-mode="require"/>
2
2
  import { type ValidateFn } from '@poppinss/validator-lite';
3
3
  import { EnvValidator } from './validator.js';
4
+ /**
5
+ * A wrapper over "process.env" with types information.
6
+ *
7
+ * ```ts
8
+ * const validate = Env.rules({
9
+ * PORT: Env.schema.number()
10
+ * })
11
+ *
12
+ * const validatedEnvVars = validate(process.env)
13
+ *
14
+ * const env = new EnvValues(validatedEnvVars)
15
+ * env.get('PORT') // type === number
16
+ * ```
17
+ */
4
18
  export declare class Env<EnvValues extends Record<string, any>> {
5
19
  #private;
6
20
  constructor(values: EnvValues);
21
+ /**
22
+ * Create an instance of the env class by validating the
23
+ * environment variables. Also, the `.env` files are
24
+ * loaded from the appRoot
25
+ */
7
26
  static create<Schema extends {
8
27
  [key: string]: ValidateFn<unknown>;
9
28
  }>(appRoot: URL, schema: Schema): Promise<Env<{
10
29
  [K in keyof Schema]: ReturnType<Schema[K]>;
11
30
  }>>;
31
+ /**
32
+ * The schema builder for defining validation rules
33
+ */
12
34
  static schema: {
13
35
  number: typeof import("@poppinss/validator-lite/build/src/schema/number.js").number;
14
36
  string: typeof import("@poppinss/validator-lite/build/src/schema/string.js").string;
15
37
  boolean: typeof import("@poppinss/validator-lite/build/src/schema/boolean.js").boolean;
16
38
  enum: typeof import("@poppinss/validator-lite/build/src/schema/oneOf.js").oneOf;
17
39
  };
40
+ /**
41
+ * Define the validation rules for validating environment
42
+ * variables. The return value is an instance of the
43
+ * env validator
44
+ */
18
45
  static rules<T extends {
19
46
  [key: string]: ValidateFn<unknown>;
20
47
  }>(schema: T): EnvValidator<T>;
48
+ /**
49
+ * Get the value of an environment variable by key. The values are
50
+ * lookedup inside the validated environment and "process.env"
51
+ * is used as a fallback.
52
+ *
53
+ * The second param is the default value, which is returned when
54
+ * the environment variable does not exist.
55
+ *
56
+ * ```ts
57
+ * Env.get('PORT')
58
+ *
59
+ * // With default value
60
+ * Env.get('PORT', 3000)
61
+ * ```
62
+ */
21
63
  get<K extends keyof EnvValues>(key: K): EnvValues[K];
22
64
  get<K extends keyof EnvValues>(key: K, defaultValue: Exclude<EnvValues[K], undefined>): Exclude<EnvValues[K], undefined>;
23
65
  get(key: string): string | undefined;
24
66
  get(key: string, defaultValue: string): string;
67
+ /**
68
+ * Update/set value of an environment variable.
69
+ *
70
+ * The value is not casted/validated using the validator, so make sure
71
+ * to set the correct data type.
72
+ *
73
+ * ```ts
74
+ * Env.set('PORT', 3000)
75
+ *
76
+ * Env.get('PORT') === 3000 // true
77
+ * process.env.PORT === '3000' // true
78
+ * ```
79
+ */
25
80
  set<K extends keyof EnvValues>(key: K, value: EnvValues[K]): void;
26
81
  set(key: string, value: string): void;
27
82
  }
28
- //# sourceMappingURL=env.d.ts.map
package/build/src/env.js CHANGED
@@ -1,29 +1,76 @@
1
+ /*
2
+ * @adonisjs/env
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
1
9
  import { schema as envSchema } from '@poppinss/validator-lite';
2
10
  import { EnvValidator } from './validator.js';
3
11
  import { EnvProcessor } from './processor.js';
4
- class Env {
12
+ /**
13
+ * A wrapper over "process.env" with types information.
14
+ *
15
+ * ```ts
16
+ * const validate = Env.rules({
17
+ * PORT: Env.schema.number()
18
+ * })
19
+ *
20
+ * const validatedEnvVars = validate(process.env)
21
+ *
22
+ * const env = new EnvValues(validatedEnvVars)
23
+ * env.get('PORT') // type === number
24
+ * ```
25
+ */
26
+ export class Env {
27
+ /**
28
+ * A cache of env values
29
+ */
5
30
  #values;
6
31
  constructor(values) {
7
32
  this.#values = values;
8
33
  }
34
+ /**
35
+ * Create an instance of the env class by validating the
36
+ * environment variables. Also, the `.env` files are
37
+ * loaded from the appRoot
38
+ */
9
39
  static async create(appRoot, schema) {
10
40
  const values = await new EnvProcessor(appRoot).process();
11
41
  const validator = this.rules(schema);
12
42
  return new Env(validator.validate(values));
13
43
  }
44
+ /**
45
+ * The schema builder for defining validation rules
46
+ */
14
47
  static schema = envSchema;
48
+ /**
49
+ * Define the validation rules for validating environment
50
+ * variables. The return value is an instance of the
51
+ * env validator
52
+ */
15
53
  static rules(schema) {
16
54
  const validator = new EnvValidator(schema);
17
55
  return validator;
18
56
  }
19
57
  get(key, defaultValue) {
58
+ /**
59
+ * Return cached value
60
+ */
20
61
  if (this.#values[key] !== undefined) {
21
62
  return this.#values[key];
22
63
  }
64
+ /**
65
+ * Get value from "process.env" and update the cache
66
+ */
23
67
  const envValue = process.env[key];
24
68
  if (envValue) {
25
69
  return envValue;
26
70
  }
71
+ /**
72
+ * Return default value when unable to lookup any other value
73
+ */
27
74
  return defaultValue;
28
75
  }
29
76
  set(key, value) {
@@ -31,4 +78,3 @@ class Env {
31
78
  process.env[key] = value;
32
79
  }
33
80
  }
34
- export { Env };
@@ -1,4 +1,8 @@
1
- /// <reference types="node" resolution-mode="require"/>
1
+ /// <reference types="@types/node" resolution-mode="require"/>
2
+ /**
3
+ * Exception raised when one or more env variables
4
+ * are invalid
5
+ */
2
6
  export declare const E_INVALID_ENV_VARIABLES: {
3
7
  new (message?: string | undefined, options?: (ErrorOptions & {
4
8
  code?: string | undefined;
@@ -22,4 +26,3 @@ export declare const E_INVALID_ENV_VARIABLES: {
22
26
  prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
23
27
  stackTraceLimit: number;
24
28
  };
25
- //# sourceMappingURL=exceptions.d.ts.map
@@ -1,4 +1,16 @@
1
+ /*
2
+ * @adonisjs/env
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
1
9
  import { Exception } from '@poppinss/utils';
10
+ /**
11
+ * Exception raised when one or more env variables
12
+ * are invalid
13
+ */
2
14
  export const E_INVALID_ENV_VARIABLES = class EnvValidationException extends Exception {
3
15
  static message = 'Validation failed for one or more environment variables';
4
16
  static code = 'E_INVALID_ENV_VARIABLES';
@@ -1,11 +1,36 @@
1
- /// <reference types="node" resolution-mode="require"/>
1
+ /// <reference types="@types/node" resolution-mode="require"/>
2
+ /**
3
+ * Read the contents of one or more dot-env files. Following is how the files
4
+ * are read.
5
+ *
6
+ * - Load file from the "ENV_PATH" environment file.
7
+ * (Raise error if file is missing)
8
+ *
9
+ * - If "ENV_PATH" is not defined, then find ".env" file in the app root.
10
+ * (Ignore if file is missing)
11
+ *
12
+ * - Find ".env.[NODE_ENV]" file in the app root.
13
+ * (Ignore if file is missing)
14
+ *
15
+ * ```ts
16
+ * const loader = new EnvLoader(new URL('./', import.meta.url))
17
+ *
18
+ * const { envContents, currentEnvContents } = await loader.load()
19
+ *
20
+ * // envContents: Contents of .env or file specified via ENV_PATH
21
+ * // currentEnvContents: Contents of .env.[NODE_ENV] file
22
+ * ```
23
+ */
2
24
  export declare class EnvLoader {
3
25
  #private;
4
26
  constructor(appRoot: string | URL, loadExampleFile?: boolean);
27
+ /**
28
+ * Load contents of the main dot-env file and the current
29
+ * environment dot-env file
30
+ */
5
31
  load(): Promise<{
6
32
  contents: string;
7
33
  path: string;
8
34
  fileExists: boolean;
9
35
  }[]>;
10
36
  }
11
- //# sourceMappingURL=loader.d.ts.map
@@ -1,7 +1,37 @@
1
+ /*
2
+ * @adonisjs/env
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
1
9
  import { fileURLToPath } from 'node:url';
2
10
  import { readFile } from 'node:fs/promises';
3
11
  import { isAbsolute, join } from 'node:path';
4
12
  import debug from './debug.js';
13
+ /**
14
+ * Read the contents of one or more dot-env files. Following is how the files
15
+ * are read.
16
+ *
17
+ * - Load file from the "ENV_PATH" environment file.
18
+ * (Raise error if file is missing)
19
+ *
20
+ * - If "ENV_PATH" is not defined, then find ".env" file in the app root.
21
+ * (Ignore if file is missing)
22
+ *
23
+ * - Find ".env.[NODE_ENV]" file in the app root.
24
+ * (Ignore if file is missing)
25
+ *
26
+ * ```ts
27
+ * const loader = new EnvLoader(new URL('./', import.meta.url))
28
+ *
29
+ * const { envContents, currentEnvContents } = await loader.load()
30
+ *
31
+ * // envContents: Contents of .env or file specified via ENV_PATH
32
+ * // currentEnvContents: Contents of .env.[NODE_ENV] file
33
+ * ```
34
+ */
5
35
  export class EnvLoader {
6
36
  #appRoot;
7
37
  #loadExampleFile;
@@ -9,18 +39,26 @@ export class EnvLoader {
9
39
  this.#appRoot = typeof appRoot === 'string' ? appRoot : fileURLToPath(appRoot);
10
40
  this.#loadExampleFile = loadExampleFile;
11
41
  }
42
+ /**
43
+ * Optionally read a file from the disk
44
+ */
12
45
  async #loadFile(filePath) {
13
46
  try {
14
47
  const contents = await readFile(filePath, 'utf-8');
15
48
  return { contents, fileExists: true };
16
49
  }
17
50
  catch (error) {
51
+ /* c8 ignore next 3 */
18
52
  if (error.code !== 'ENOENT') {
19
53
  throw error;
20
54
  }
21
55
  return { contents: '', fileExists: false };
22
56
  }
23
57
  }
58
+ /**
59
+ * Load contents of the main dot-env file and the current
60
+ * environment dot-env file
61
+ */
24
62
  async load() {
25
63
  const ENV_PATH = process.env.ENV_PATH;
26
64
  const NODE_ENV = process.env.NODE_ENV;
@@ -29,6 +67,9 @@ export class EnvLoader {
29
67
  debug('ENV_PATH variable is %s', ENV_PATH ? 'set' : 'not set');
30
68
  debug('NODE_ENV variable is %s', NODE_ENV ? 'set' : 'not set');
31
69
  }
70
+ /**
71
+ * Base path to load .env files from
72
+ */
32
73
  const baseEnvPath = ENV_PATH
33
74
  ? isAbsolute(ENV_PATH)
34
75
  ? ENV_PATH
@@ -37,6 +78,10 @@ export class EnvLoader {
37
78
  if (debug.enabled) {
38
79
  debug('dot-env files base path "%s"', baseEnvPath);
39
80
  }
81
+ /**
82
+ * 1st
83
+ * The top most priority is given to the ".env.[NODE_ENV].local" file
84
+ */
40
85
  if (NODE_ENV) {
41
86
  const nodeEnvLocalFile = join(baseEnvPath, `.env.${NODE_ENV}.local`);
42
87
  envFiles.push({
@@ -44,6 +89,10 @@ export class EnvLoader {
44
89
  ...(await this.#loadFile(nodeEnvLocalFile)),
45
90
  });
46
91
  }
92
+ /**
93
+ * 2nd
94
+ * Next, we give priority to the ".env.local" file
95
+ */
47
96
  if (!NODE_ENV || !['test', 'testing'].includes(NODE_ENV)) {
48
97
  const envLocalFile = join(baseEnvPath, '.env.local');
49
98
  envFiles.push({
@@ -51,6 +100,10 @@ export class EnvLoader {
51
100
  ...(await this.#loadFile(envLocalFile)),
52
101
  });
53
102
  }
103
+ /**
104
+ * 3rd
105
+ * Next, we give priority to the ".env.[NODE_ENV]" file
106
+ */
54
107
  if (NODE_ENV) {
55
108
  const nodeEnvFile = join(baseEnvPath, `.env.${NODE_ENV}`);
56
109
  envFiles.push({
@@ -58,11 +111,17 @@ export class EnvLoader {
58
111
  ...(await this.#loadFile(nodeEnvFile)),
59
112
  });
60
113
  }
114
+ /**
115
+ * Finally, we push the contents of the ".env" file.
116
+ */
61
117
  const envFile = join(baseEnvPath, '.env');
62
118
  envFiles.push({
63
119
  path: envFile,
64
120
  ...(await this.#loadFile(envFile)),
65
121
  });
122
+ /**
123
+ * Load example file
124
+ */
66
125
  if (this.#loadExampleFile) {
67
126
  const envExampleFile = join(baseEnvPath, '.env.example');
68
127
  envFiles.push({
@@ -1,9 +1,51 @@
1
1
  import { DotenvParseOutput } from 'dotenv';
2
+ /**
3
+ * Env parser parses the environment variables from a string formatted
4
+ * as a key-value pair seperated using an `=`. For example:
5
+ *
6
+ * ```dotenv
7
+ * PORT=3333
8
+ * HOST=127.0.0.1
9
+ * ```
10
+ *
11
+ * The variables can reference other environment variables as well using `$`.
12
+ * For example:
13
+ *
14
+ * ```dotenv
15
+ * PORT=3333
16
+ * REDIS_PORT=$PORT
17
+ * ```
18
+ *
19
+ * The variables using characters other than letters can wrap variable
20
+ * named inside a curly brace.
21
+ *
22
+ * ```dotenv
23
+ * APP-PORT=3333
24
+ * REDIS_PORT=${APP-PORT}
25
+ * ```
26
+ *
27
+ * You can escape the `$` sign with a backtick.
28
+ *
29
+ * ```dotenv
30
+ * REDIS_PASSWORD=foo\$123
31
+ * ```
32
+ *
33
+ * ## Usage
34
+ *
35
+ * ```ts
36
+ * const parser = new EnvParser(envContents)
37
+ * const output = parser.parse()
38
+ *
39
+ * // The output is a key-value pair
40
+ * ```
41
+ */
2
42
  export declare class EnvParser {
3
43
  #private;
4
44
  constructor(envContents: string, options?: {
5
45
  ignoreProcessEnv: boolean;
6
46
  });
47
+ /**
48
+ * Parse the env string to an object of environment variables.
49
+ */
7
50
  parse(): DotenvParseOutput;
8
51
  }
9
- //# sourceMappingURL=parser.d.ts.map
@@ -1,4 +1,52 @@
1
+ /*
2
+ * @adonisjs/env
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
1
9
  import dotenv from 'dotenv';
10
+ /**
11
+ * Env parser parses the environment variables from a string formatted
12
+ * as a key-value pair seperated using an `=`. For example:
13
+ *
14
+ * ```dotenv
15
+ * PORT=3333
16
+ * HOST=127.0.0.1
17
+ * ```
18
+ *
19
+ * The variables can reference other environment variables as well using `$`.
20
+ * For example:
21
+ *
22
+ * ```dotenv
23
+ * PORT=3333
24
+ * REDIS_PORT=$PORT
25
+ * ```
26
+ *
27
+ * The variables using characters other than letters can wrap variable
28
+ * named inside a curly brace.
29
+ *
30
+ * ```dotenv
31
+ * APP-PORT=3333
32
+ * REDIS_PORT=${APP-PORT}
33
+ * ```
34
+ *
35
+ * You can escape the `$` sign with a backtick.
36
+ *
37
+ * ```dotenv
38
+ * REDIS_PASSWORD=foo\$123
39
+ * ```
40
+ *
41
+ * ## Usage
42
+ *
43
+ * ```ts
44
+ * const parser = new EnvParser(envContents)
45
+ * const output = parser.parse()
46
+ *
47
+ * // The output is a key-value pair
48
+ * ```
49
+ */
2
50
  export class EnvParser {
3
51
  #envContents;
4
52
  #preferProcessEnv = true;
@@ -8,6 +56,9 @@ export class EnvParser {
8
56
  }
9
57
  this.#envContents = envContents;
10
58
  }
59
+ /**
60
+ * Returns the value from the parsed object
61
+ */
11
62
  #getValue(key, parsed) {
12
63
  if (this.#preferProcessEnv && process.env[key]) {
13
64
  return process.env[key];
@@ -17,46 +68,94 @@ export class EnvParser {
17
68
  }
18
69
  return process.env[key] || '';
19
70
  }
71
+ /**
72
+ * Interpolating the token wrapped inside the mustache braces.
73
+ */
20
74
  #interpolateMustache(token, parsed) {
75
+ /**
76
+ * Finding the closing brace. If closing brace is missing, we
77
+ * consider the block as a normal string
78
+ */
21
79
  const closingBrace = token.indexOf('}');
22
80
  if (closingBrace === -1) {
23
81
  return token;
24
82
  }
83
+ /**
84
+ * Then we pull everything until the closing brace, except
85
+ * the opening brace and trim off all white spaces.
86
+ */
25
87
  const varReference = token.slice(1, closingBrace).trim();
88
+ /**
89
+ * Getting the value of the reference inside the braces
90
+ */
26
91
  return `${this.#getValue(varReference, parsed)}${token.slice(closingBrace + 1)}`;
27
92
  }
93
+ /**
94
+ * Interpolating the variable reference starting with a
95
+ * `$`. We only capture numbers,letter and underscore.
96
+ * For other characters, one can use the mustache
97
+ * braces.
98
+ */
28
99
  #interpolateVariable(token, parsed) {
29
100
  return token.replace(/[a-zA-Z0-9_]+/, (key) => {
30
101
  return this.#getValue(key, parsed);
31
102
  });
32
103
  }
104
+ /**
105
+ * Interpolates the referenced values
106
+ */
33
107
  #interpolate(value, parsed) {
34
108
  const tokens = value.split('$');
35
109
  let newValue = '';
36
110
  let skipNextToken = true;
37
111
  tokens.forEach((token) => {
112
+ /**
113
+ * If the value is an escaped sequence, then we replace it
114
+ * with a `$` and then skip the next token.
115
+ */
38
116
  if (token === '\\') {
39
117
  newValue += '$';
40
118
  skipNextToken = true;
41
119
  return;
42
120
  }
121
+ /**
122
+ * Use the value as it is when "skipNextToken" is set to true.
123
+ */
43
124
  if (skipNextToken) {
125
+ /**
126
+ * Replace the ending escape sequence with a $
127
+ */
44
128
  newValue += token.replace(/\\$/, '$');
129
+ /**
130
+ * and then skip the next token if it ends with escape sequence
131
+ */
45
132
  if (token.endsWith('\\')) {
46
133
  return;
47
134
  }
48
135
  }
49
136
  else {
137
+ /**
138
+ * Handle mustache block
139
+ */
50
140
  if (token.startsWith('{')) {
51
141
  newValue += this.#interpolateMustache(token, parsed);
52
142
  return;
53
143
  }
144
+ /**
145
+ * Process all words as variable
146
+ */
54
147
  newValue += this.#interpolateVariable(token, parsed);
55
148
  }
149
+ /**
150
+ * Process next token
151
+ */
56
152
  skipNextToken = false;
57
153
  });
58
154
  return newValue;
59
155
  }
156
+ /**
157
+ * Parse the env string to an object of environment variables.
158
+ */
60
159
  parse() {
61
160
  const envCollection = dotenv.parse(this.#envContents.trim());
62
161
  return Object.keys(envCollection).reduce((result, key) => {
@@ -1,7 +1,12 @@
1
- /// <reference types="node" resolution-mode="require"/>
1
+ /// <reference types="@types/node" resolution-mode="require"/>
2
+ /**
3
+ * Env processors loads, parses and process environment variables.
4
+ */
2
5
  export declare class EnvProcessor {
3
6
  #private;
4
7
  constructor(appRoot: URL);
8
+ /**
9
+ * Process env variables
10
+ */
5
11
  process(): Promise<Record<string, any>>;
6
12
  }
7
- //# sourceMappingURL=processor.d.ts.map
@@ -1,12 +1,32 @@
1
+ /*
2
+ * @adonisjs/application
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
1
9
  import debug from './debug.js';
2
10
  import { EnvParser } from './parser.js';
3
11
  import { EnvLoader } from './loader.js';
12
+ /**
13
+ * Env processors loads, parses and process environment variables.
14
+ */
4
15
  export class EnvProcessor {
16
+ /**
17
+ * App root is needed to load files
18
+ */
5
19
  #appRoot;
6
20
  constructor(appRoot) {
7
21
  this.#appRoot = appRoot;
8
22
  }
23
+ /**
24
+ * Parse env variables from raw contents
25
+ */
9
26
  #processContents(envContents, store) {
27
+ /**
28
+ * Collected env variables
29
+ */
10
30
  if (!envContents.trim()) {
11
31
  return store;
12
32
  }
@@ -23,16 +43,25 @@ export class EnvProcessor {
23
43
  });
24
44
  return store;
25
45
  }
46
+ /**
47
+ * Parse env variables by loading dot files.
48
+ */
26
49
  async #loadAndProcessDotFiles() {
27
50
  const loader = new EnvLoader(this.#appRoot);
28
51
  const envFiles = await loader.load();
29
52
  if (debug.enabled) {
30
53
  debug('processing .env files (priority from top to bottom) %O', envFiles.map((file) => file.path));
31
54
  }
55
+ /**
56
+ * Collected env variables
57
+ */
32
58
  const envValues = {};
33
59
  envFiles.forEach(({ contents }) => this.#processContents(contents, envValues));
34
60
  return envValues;
35
61
  }
62
+ /**
63
+ * Process env variables
64
+ */
36
65
  async process() {
37
66
  return this.#loadAndProcessDotFiles();
38
67
  }
@@ -1,13 +1,25 @@
1
1
  import { ValidateFn } from '@poppinss/validator-lite';
2
+ /**
3
+ * Exposes the API to validate environment variables against a
4
+ * pre-defined schema.
5
+ *
6
+ * The class is not exported in the main API and used internally.
7
+ */
2
8
  export declare class EnvValidator<Schema extends {
3
9
  [key: string]: ValidateFn<unknown>;
4
10
  }> {
5
11
  #private;
6
12
  constructor(schema: Schema);
13
+ /**
14
+ * Accepts an object of values to validate against the pre-defined
15
+ * schema.
16
+ *
17
+ * The return value is a merged copy of the original object and the
18
+ * values mutated by the schema validator.
19
+ */
7
20
  validate(values: {
8
21
  [K: string]: string | undefined;
9
22
  }): {
10
23
  [K in keyof Schema]: ReturnType<Schema[K]>;
11
24
  };
12
25
  }
13
- //# sourceMappingURL=validator.d.ts.map
@@ -1,4 +1,18 @@
1
+ /*
2
+ * @adonisjs/env
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
1
9
  import { E_INVALID_ENV_VARIABLES } from './exceptions.js';
10
+ /**
11
+ * Exposes the API to validate environment variables against a
12
+ * pre-defined schema.
13
+ *
14
+ * The class is not exported in the main API and used internally.
15
+ */
2
16
  export class EnvValidator {
3
17
  #schema;
4
18
  #error;
@@ -6,6 +20,13 @@ export class EnvValidator {
6
20
  this.#schema = schema;
7
21
  this.#error = new E_INVALID_ENV_VARIABLES();
8
22
  }
23
+ /**
24
+ * Accepts an object of values to validate against the pre-defined
25
+ * schema.
26
+ *
27
+ * The return value is a merged copy of the original object and the
28
+ * values mutated by the schema validator.
29
+ */
9
30
  validate(values) {
10
31
  const help = [];
11
32
  const validated = Object.keys(this.#schema).reduce((result, key) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adonisjs/env",
3
- "version": "4.2.0-2",
3
+ "version": "4.2.0-3",
4
4
  "description": "Environment variable manager for Node.js",
5
5
  "main": "build/index.js",
6
6
  "type": "module",
@@ -15,10 +15,14 @@
15
15
  "exports": {
16
16
  ".": "./build/index.js"
17
17
  },
18
+ "engines": {
19
+ "node": ">=18.16.0"
20
+ },
18
21
  "scripts": {
19
22
  "pretest": "npm run lint",
20
- "test": "cross-env NODE_DEBUG=adonisjs:env c8 npm run vscode:test",
23
+ "test": "cross-env NODE_DEBUG=adonisjs:env c8 npm run quick:test",
21
24
  "clean": "del-cli build",
25
+ "typecheck": "tsc --noEmit",
22
26
  "compile": "npm run lint && npm run clean && tsc",
23
27
  "build": "npm run compile",
24
28
  "release": "np",
@@ -27,7 +31,7 @@
27
31
  "lint": "eslint . --ext=.ts",
28
32
  "format": "prettier --write .",
29
33
  "sync-labels": "github-label-sync --labels .github/labels.json adonisjs/env",
30
- "vscode:test": "node --loader=ts-node/esm bin/test.ts"
34
+ "quick:test": "node --loader=ts-node/esm bin/test.ts"
31
35
  },
32
36
  "keywords": [
33
37
  "env",
@@ -36,34 +40,32 @@
36
40
  "author": "virk,adonisjs",
37
41
  "license": "MIT",
38
42
  "devDependencies": {
39
- "@commitlint/cli": "^17.5.0",
40
- "@commitlint/config-conventional": "^17.4.4",
41
- "@japa/assert": "^1.4.1",
42
- "@japa/expect-type": "^1.0.3",
43
- "@japa/file-system": "^1.0.1",
44
- "@japa/run-failed-tests": "^1.1.1",
45
- "@japa/runner": "^2.5.1",
46
- "@japa/spec-reporter": "^1.3.3",
47
- "@swc/core": "^1.3.42",
48
- "@types/node": "^18.15.9",
49
- "c8": "^7.13.0",
43
+ "@adonisjs/eslint-config": "^1.1.7",
44
+ "@adonisjs/prettier-config": "^1.1.7",
45
+ "@adonisjs/tsconfig": "^1.1.7",
46
+ "@commitlint/cli": "^17.6.6",
47
+ "@commitlint/config-conventional": "^17.6.6",
48
+ "@japa/assert": "^2.0.0-1",
49
+ "@japa/expect-type": "^2.0.0-0",
50
+ "@japa/file-system": "^2.0.0-1",
51
+ "@japa/runner": "^3.0.0-3",
52
+ "@swc/core": "^1.3.67",
53
+ "@types/node": "^20.3.3",
54
+ "c8": "^8.0.0",
50
55
  "cross-env": "^7.0.3",
51
56
  "del-cli": "^5.0.0",
52
- "eslint": "^8.36.0",
53
- "eslint-config-prettier": "^8.8.0",
54
- "eslint-plugin-adonis": "^3.0.3",
55
- "eslint-plugin-prettier": "^4.2.1",
57
+ "eslint": "^8.44.0",
56
58
  "github-label-sync": "^2.3.1",
57
59
  "husky": "^8.0.3",
58
- "np": "^7.6.4",
59
- "prettier": "^2.8.7",
60
+ "np": "^8.0.4",
61
+ "prettier": "^2.8.8",
60
62
  "ts-node": "^10.9.1",
61
- "typescript": "^5.0.2"
63
+ "typescript": "^5.1.6"
62
64
  },
63
65
  "dependencies": {
64
- "@poppinss/utils": "^6.5.0-2",
66
+ "@poppinss/utils": "^6.5.0-3",
65
67
  "@poppinss/validator-lite": "^1.0.3",
66
- "dotenv": "^16.0.3",
68
+ "dotenv": "^16.3.1",
67
69
  "split-lines": "^3.0.0"
68
70
  },
69
71
  "repository": {
@@ -74,36 +76,6 @@
74
76
  "url": "https://github.com/adonisjs/env/issues"
75
77
  },
76
78
  "homepage": "https://github.com/adonisjs/env#readme",
77
- "eslintConfig": {
78
- "extends": [
79
- "plugin:adonis/typescriptPackage",
80
- "prettier"
81
- ],
82
- "plugins": [
83
- "prettier"
84
- ],
85
- "rules": {
86
- "prettier/prettier": [
87
- "error",
88
- {
89
- "endOfLine": "auto"
90
- }
91
- ]
92
- }
93
- },
94
- "eslintIgnore": [
95
- "build"
96
- ],
97
- "prettier": {
98
- "trailingComma": "es5",
99
- "semi": false,
100
- "singleQuote": true,
101
- "useTabs": false,
102
- "quoteProps": "consistent",
103
- "bracketSpacing": true,
104
- "arrowParens": "always",
105
- "printWidth": 100
106
- },
107
79
  "commitlint": {
108
80
  "extends": [
109
81
  "@commitlint/config-conventional"
@@ -127,5 +99,9 @@
127
99
  "exclude": [
128
100
  "tests/**"
129
101
  ]
130
- }
102
+ },
103
+ "eslintConfig": {
104
+ "extends": "@adonisjs/eslint-config/package"
105
+ },
106
+ "prettier": "@adonisjs/prettier-config"
131
107
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,qBAAqB,CAAA;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"debug.d.ts","sourceRoot":"","sources":["../../src/debug.ts"],"names":[],"mappings":";;AAUA,wBAAuC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"editor.d.ts","sourceRoot":"","sources":["../../src/editor.ts"],"names":[],"mappings":";AAeA,qBAAa,SAAS;;WASP,MAAM,CAAC,OAAO,EAAE,GAAG;gBAOpB,OAAO,EAAE,GAAG;IASlB,IAAI;IAoBV,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO;IASjD,MAAM;;;;IAOA,IAAI;CAOX"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"env.d.ts","sourceRoot":"","sources":["../../src/env.ts"],"names":[],"mappings":";AASA,OAAO,EAAuB,KAAK,UAAU,EAAE,MAAM,0BAA0B,CAAA;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAiB7C,qBAAa,GAAG,CAAC,SAAS,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;;gBAMxC,MAAM,EAAE,SAAS;WAShB,MAAM,CAAC,MAAM,SAAS;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,CAAA;KAAE,EACvE,OAAO,EAAE,GAAG,EACZ,MAAM,EAAE,MAAM,GACb,OAAO,CACR,GAAG,CAAC;SACD,CAAC,IAAI,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;KAC3C,CAAC,CACH;IASD,MAAM,CAAC,MAAM;;;;;MAAY;IAOzB,MAAM,CAAC,KAAK,CAAC,CAAC,SAAS;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,CAAA;KAAE,EAAE,MAAM,EAAE,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC;IAoB1F,GAAG,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC;IACpD,GAAG,CAAC,CAAC,SAAS,MAAM,SAAS,EAC3B,GAAG,EAAE,CAAC,EACN,YAAY,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,GAC7C,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC;IACnC,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IACpC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM;IAoC9C,GAAG,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,IAAI;IACjE,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;CAKtC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"exceptions.d.ts","sourceRoot":"","sources":["../../src/exceptions.ts"],"names":[],"mappings":";AAeA,eAAO,MAAM,uBAAuB;;;;;cAG5B,MAAM;;;;;;;;;;;;;;;;;CACb,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../../src/loader.ts"],"names":[],"mappings":";AAqCA,qBAAa,SAAS;;gBAIR,OAAO,EAAE,MAAM,GAAG,GAAG,EAAE,eAAe,GAAE,OAAe;IA0B7D,IAAI,IAAI,OAAO,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,OAAO,CAAA;KAAE,EAAE,CAAC;CAiFjF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../src/parser.ts"],"names":[],"mappings":"AASA,OAAe,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAA;AA0ClD,qBAAa,SAAS;;gBAIR,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,EAAE,OAAO,CAAA;KAAE;IAyHxE,KAAK,IAAI,iBAAiB;CAQ3B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"processor.d.ts","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":";AAgBA,qBAAa,YAAY;;gBAMX,OAAO,EAAE,GAAG;IAyDlB,OAAO;CAGd"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"validator.d.ts","sourceRoot":"","sources":["../../src/validator.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAA;AAUrD,qBAAa,YAAY,CAAC,MAAM,SAAS;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,CAAA;CAAE;;gBAIjE,MAAM,EAAE,MAAM;IAY1B,QAAQ,CAAC,MAAM,EAAE;QAAE,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAA;KAAE,GAAG;SACpD,CAAC,IAAI,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;KAC3C;CAwBF"}