First upload version 0.0.1

This commit is contained in:
Neyra
2026-02-05 15:27:49 +08:00
commit 8e9b7201ed
4182 changed files with 593136 additions and 0 deletions

191
node_modules/env-var/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,191 @@
## 7.5.0 (20/05/2024)
* Add `AsSet()` accessor (#173)
## 7.4.2 (10/05/2024)
* Fix docstrings for positive/negative int/float validators (#172)
## 7.4.1 (29/08/2023)
* Fix 7.4.0 issues with `create-react-app` polyfill (#168)
## 7.4.0 (21/08/2023)
* Do not use `process.env` by default in non-Node.js environments (#155)
## 7.3.1 (24/04/2023)
* Fix parsing even floating point numbers (#166)
## 7.3.0 (06/09/2022)
* Add missing `asEmailString()` typings (#160)
## 7.2.0 (01/09/2022)
* Add `asEmailString()` accessor (#146)
## 7.1.1 (28/10/2021)
* Fix duplicate identifier error for TypeScript builds (#151)
## 7.1.0 (28/10/2021)
* Support type narrowed `process.env`/record and remove unused type (#148)
* Add support for `readonly T[]` generic use with `asEnum()`
## 7.0.1
* Fix loose float and int parsing (PR #144)
## 7.0.0 (11/11/2020)
* Drop support for Node.js 8 and 13 (support only current, active, and maintenance versions)
* Improve support for browser usage (#138)
* Fix documentation errors (#139)
## 6.3.0 (27/07/2020)
* Add `asRegExp` accessor (#136)
* Add better TypeScript example for custom accessors (#133)
## 6.2.0 (12/06/2020)
* Add `accessors` property to the public API for use in building `extraAccessors` (#121)
* Add support for logging with a built-in or custom logger (#112)
* Add Node.js v14 to CI builds
* Add single quote rule to `.editorconfig` (#129)
* Add JavaScript example for `extraAccesors` (#129)
* Fix `extraAccessors` args type error (#131)
* Fix types and docs for `asUrlString()` and `asUrlObject()` (#132)
* Update README for `asUrlString()` to mention WHATWG URL behaviour (#126, #129)
## 6.1.1 (22/04/2020)
* Fix TS error with *ExtenderTypeOptional* and *ExtenderType* typings (#119)
## 6.1.0 (20/04/2020)
* Fix TS error with *extraAccessor* typings (#114)
* Add support for generic types in *asEnum* (#116)
## 6.0.4 (04/03/2020)
* Fix compilation error caused by typings generic issue.
## 6.0.3 (03/03/2020)
* Fix typings to support `required()`, `convertFromBase64()`, etc. with `ExtensionFn`.
## 6.0.2 (29/02/2020)
* Fix `default()` so that it correctly returns an empty string value if provided.
* README improvement by @joh-klein for positive/negative number parsing rules.
## 6.0.1 (12/02/2020)
* Fix typings for the `default(value)` function.
## 6.0.0 (12/02/2020)
* Add support for setting an example value via the `example(string)` function.
* Passing default values is now performed using the `default(string)` function.
* Defer checks for `required()` until an accessor such as `asString()` is invoked.
* Fix typings issue where `required()` was undefined on a `IPresentVariable`.
* Improve error message output.
Migration from 5.x to 6.0.0 should be smooth. Change any instance of
`env.get(target, default)` to `env.get(target).default(default)`. For example:
```js
// Old 5.x code
const emailAddr = env.get('EMAIL_ADDR', 'admin@example.com').asString()
// New 6.x compatible code
const emailAddr = env.get('EMAIL_ADDR').default('admin@example.com').asString()
```
## 5.2.0 (22/11/2019)
* The `required()` function now verifies the variable is not an empty string
## 5.1.0 (09/09/2019)
* Ability to add custom accessors in PR #72 (thanks @todofixthis)
* Improved TypeScript tests
* Fixed warning generated by husky
## 5.0.0 (14/06/2019)
* Return values from `asArray()` are now more intuitive & consitent
* `asUrlString()` and `asUrlObject`now use the built-in `URL` class in Node.js
to perform validation
* README updated in accordance with changes listed above
## 4.1.0 (14/06/2019)
* Add `asPortNumber()` function
* Update documentation structure
## 4.0.1 (24/05/2019)
* Add node `process.env` typings to `env.from`
## 4.0.0 (09/04/2019)
* Rename `.env.mock()` to `env.from()`
* Change module internals per issue #39
* Update docs related to `env.mock`
## 3.5.0 (02/29/2019)
* Update `required()` to support boolean paramter to bypass the check
## 3.4.2 (06/11/2018)
* Fix README badge copy/paste error
## 3.4.1 (06/11/2018)
* Fix TypeScript definition for "asBoolStrict" function name
## 3.4.0 (24/10/2018)
* Add `convertFromBase64()` function
* Enable Greenkeeper
## 3.3.0 (26/06/2018)
* Add `asEnum` functionality
## 3.2.0 (15/06/2018)
* Remove @types/node dependency
## 3.1.0 (11/12/2017)
* Update typings to correctly handle default values for numeric types.
* Ensure an error is thrown when `asArray` does not detect at least a single non-empty value.
## 3.0.2 (19/10/2017)
* Restore support for use in browser based applications
## 3.0.1 (19/10/2017)
* Fix bug that caused default values to be ignored
## 3.0.0 (13/10/2017)
* Public API no longer is a function, instead exposes two functions, `mock` and `get`
* Drop support for Node.js versions less than 4.0
* Rename `asPositiveInt` to `asIntPositive`
* Rename `asNegativeInt` to `asIntNegative`
* Rename `asStrictBool` to `asBoolStrict`
* Add `asFloatPositive` and `asFloatNegative`
* Add `asUrlString` and `asUrlObject`
* Refactor code with consistent errors and structure
* Use `standard` for code quality and formatting
## 2.4.3 (5/04/2017)
* Update with build, coverage, and version information badges
## 2.4.2 (19/12/2016)
* Fix TypeScript definition file
## 2.4.1 (15/12/2016)
* Remove unnecessary code path
## 2.4.0 (15/12/2016)
* Add `asArray([delimeter])` to read environment variables as an array by splitting
the varible string on each instance of _delimeter_;
* Add `asJsonArray()` to read in an environment variable that contains a JSON
Array. Similar to `asJson()`, but ensures the variable is an Array.
* Add `asJsonObject()` to read in an environment variable that contains a JSON
Object. Similar to `asJson()`, but ensures the variable is an Object.
## 2.3.0 & 2.3.1 (12/12/2016)
* Add typings support for TypeScript
## 2.2.0 (28/10/2016)
* Thanks to @itavy for a patch for our _asBool_ parsing and adding the new
_asStrictBool_ function
## 2.1.0 (25/10/2016)
* Added _env.mock_ PR from @MikeyBurkman to improve testability
## 2.0.0 (27/07/2016)
* Add CI process for node 6, 5, 4, and 0.10
* Add chained functions for variable validations
* Add assertions for _required()_ and various type checks, e.g _asPositiveInt(_)
* Remove node 0.8.x support
* Remove old pattern of returning variables directly
* Continue support for defaults from 1.X
## <2.0.0
* Venture forth at thine own risk, for here be dragons

21
node_modules/env-var/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016, 2024 Evan Shortiss
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

169
node_modules/env-var/README.md generated vendored Normal file
View File

@@ -0,0 +1,169 @@
# env-var
<div align="center">
[![NPM version](https://img.shields.io/npm/v/env-var.svg?style=flat)](https://www.npmjs.com/package/env-var)
[![TypeScript](https://badgen.net/npm/types/env-var)](http://www.typescriptlang.org/)
[![License](https://badgen.net/npm/license/env-var)](https://opensource.org/licenses/MIT)
[![Coverage Status](https://coveralls.io/repos/github/evanshortiss/env-var/badge.svg?branch=master)](https://coveralls.io/github/evanshortiss/env-var?branch=master)
[![npm downloads](https://img.shields.io/npm/dm/env-var.svg?style=flat)](https://www.npmjs.com/package/env-var)
[![Known Vulnerabilities](https://snyk.io//test/github/evanshortiss/env-var/badge.svg?targetFile=package.json)](https://snyk.io//test/github/evanshortiss/env-var?targetFile=package.json)
Verification, sanitization, and type coercion for environment variables in Node.js and web applications. Supports TypeScript!
<br>
<br>
</div>
* 🏋 Lightweight. Zero dependencies and just ~4.7kB when minified!
* 🧹 Clean and simple code, as [shown here](https://gist.github.com/evanshortiss/0cb049bf676b6138d13384671dad750d).
* 🚫 [Fails fast](https://en.wikipedia.org/wiki/Fail-fast) if your environment is misconfigured.
* 👩‍💻 Friendly error messages and example values for better debugging experience.
* 🎉 TypeScript support provides compile time safety and better developer experience.
* 📦 Support for frontend projects, e.g in React, React Native, Angular, etc.
## Contents
- [API](API.md): The full API set for `env-var`
- [Changelog](CHANGELOG.md)
- [Code of Conduct](CODE_OF_CONDUCT.md)
- [Contributing](CONTRIBUTING.md)
- [Examples](EXAMPLE.md): Example usage of `env-var`
## Install
### npm
```shell
npm install env-var
```
### yarn
```shell
yarn add env-var
```
## Getting started
You can use `env-var` in both JavaScript and TypeScript!
### Node.js Javascript example
```js
const env = require('env-var');
// Or using module import syntax:
// import env from 'env-var'
const PASSWORD = env.get('DB_PASSWORD')
// Throws an error if the DB_PASSWORD variable is not set (optional)
.required()
// Decode DB_PASSWORD from base64 to a utf8 string (optional)
.convertFromBase64()
// Call asString (or other APIs) to get the variable value (required)
.asString();
// Read in a port (checks that PORT is in the range 0 to 65535)
// Alternatively, use a default value of 5432 if PORT is not defined
const PORT = env.get('PORT').default('5432').asPortNumber()
```
### Node.js TypeScript example
```ts
import * as env from 'env-var';
// Read a PORT environment variable and ensure it's a positive integer.
// An EnvVarError will be thrown if the variable is not set, or if it
// is not a positive integer.
const PORT: number = env.get('PORT').required().asIntPositive();
```
### WebApp Example
When using environment variables in a web application, usually your tooling
such as `vite` imposes special conventions and doesn't expose `process.env`.
Use `from` function to workaround this, and create an `env` object like so:
```ts
import { from } from 'env-var'
const env = from({
BASE_URL: import.meta.env.BASE_URL,
VITE_CUSTOM_VARIABLE: import.meta.env.CUSTOM_VARIABLE
})
```
For more examples, refer to the `/example` directory and [EXAMPLE.md](EXAMPLE.md). A summary of the examples available in `/example` is written in the ['Other examples' section of EXAMPLE.md](EXAMPLE.md#other-examples).
## API
The examples above only cover a very small set of `env-var` API calls. There are many others such as `asFloatPositive()`, `asJson()` and `asRegExp()`. For a full list of `env-var` API calls, check out [API.md](API.md).
You can also create your own custom accessor; refer to the ['extraAccessors' section of API.md](API.md#extraAccessors).
## Logging
Logging is disabled by default in `env-var` to prevent accidental logging of secrets.
To enable logging, you need to create an `env-var` instance using the `from()` function that the API provides and pass in a logger.
- A built-in logger is available, but a custom logger is also supported.
- Always exercise caution when logging environment variables!
### Using the Built-in Logger
The built-in logger will print logs only when `NODE_ENV` is **not** set to either `prod` or `production`.
```js
const { from, logger } = require('env-var')
const env = from(process.env, {}, logger)
const API_KEY = env.get('API_KEY').required().asString()
```
This is an example output from the built-in logger generated by running [example/logging.js](example/logging.js):
![logging example output](screenshots/logging.png)
### Using a Custom Logger
If you need to filter `env-var` logs based on log levels (e.g. trace logging only) or have your own preferred logger, you can use a custom logging solution such as `pino` easily.
See the ['Custom logging' section of EXAMPLE.md](EXAMPLE.md#custom-logging) for more information.
## Optional integration with dotenv
You can optionally use [dotenv](https://www.npmjs.com/package/dotenv) with [env-var](https://www.npmjs.com/package/env-var).
There is no coupling between `dotenv` and `env-var`, but you can easily use them both together. This loose coupling reduces package bloat and allows you to start or stop using one without being forced to do the same for the other.
See the ['dotenv' section of EXAMPLE.md](EXAMPLE.md#dotenv) for more information.
## Contributing
Contributions are welcomed and discussed in [CONTRIBUTING.md](CONTRIBUTING.md). If you would like to discuss an idea, open an issue or a PR with an initial implementation.
## Contributors
* @aautio
* @avocadomaster
* @caccialdo
* @ChibiBlasphem
* @DigiPie
* @dror-weiss
* @evanshortiss
* @gabrieloczkowski
* @hhravn
* @ineentho
* @itavy
* @jerome-fox
* @joh-klein
* @Lioness100
* @MikeyBurkman
* @pepakriz
* @rmblstrp
* @shawnmclean
* @todofixthis
* @xuo

335
node_modules/env-var/env-var.d.ts generated vendored Normal file
View File

@@ -0,0 +1,335 @@
/// <reference types="node" />
import { URL } from 'url';
type PublicAccessors = {
/**
* Converts a number to an integer and verifies it's in port ranges 0-65535
*/
asPortNumber: (input: string) => number
/**
* Attempt to parse the variable to a float. Throws an exception if parsing fails.
*/
asFloat: (input: string) => number;
/**
* Performs the same task as asFloat(), but also verifies that the number is positive (greater than or equal to zero).
*/
asFloatPositive: (input: string) => number;
/**
* Performs the same task as asFloat(), but also verifies that the number is negative (less than or equal to zero).
*/
asFloatNegative: (input: string) => number;
/**
* Attempt to parse the variable to an integer. Throws an exception if parsing fails.
* This is a strict check, meaning that if the process.env value is 1.2, an exception will be raised rather than rounding up/down.
*/
asInt: (input: string) => number;
/**
* Performs the same task as asInt(), but also verifies that the number is positive (greater than or equal to zero).
*/
asIntPositive: (input: string) => number;
/**
* Performs the same task as asInt(), but also verifies that the number is negative (less than or equal to zero).
*/
asIntNegative: (input: string) => number;
/**
* Return the variable value as a String. Throws an exception if value is not a String.
* It's highly unlikely that a variable will not be a String since all process.env entries you set in bash are Strings by default.
*/
asString: (input: string) => string;
/**
* Return the variable value as an Email. Throws an exception if value is not an Email.
*/
asEmailString: (input: string) => string;
/**
* Attempt to parse the variable to a JSON Object or Array. Throws an exception if parsing fails.
*/
asJson: (input: string) => Object|Array<any>;
/**
* The same as asJson but checks that the data is a JSON Array, e.g [1,2].
*/
asJsonArray: (input: string) => Array<any>;
/**
* The same as asJson but checks that the data is a JSON Object, e.g {a: 1}.
*/
asJsonObject: (input: string) => Object;
/**
* Reads an environment variable as a string, then splits it on each occurrence of the specified delimiter.
* By default a comma is used as the delimiter. For example a var set to "1,2,3" would become ['1', '2', '3'].
*/
asArray: (input: string, delimiter?: string) => Array<string>;
/**
* Reads an environment variable as a string, then splits it on each occurrence of the specified delimiter.
* By default a comma is used as the delimiter. For example a var set to "1,2,3" would become new Set(['1', '2', '3']).
*/
asSet: (input: string, delimiter?: string) => Set<string>;
/**
* Attempt to parse the variable to a Boolean. Throws an exception if parsing fails.
* The var must be set to either "true", "false" (upper or lowercase), 0 or 1 to succeed.
*/
asBool: (input: string) => boolean;
/**
* Attempt to parse the variable to a Boolean. Throws an exception if parsing fails.
* The var must be set to either "true" or "false" (upper or lowercase) to succeed.
*/
asBoolStrict: (input: string) => boolean;
/**
* Verifies that the variable is a valid URL string and returns the validated
* string. The validation is performed by passing the URL string to the
* Node.js URL constructor.
*
* Note that URLs without paths will have a default path `/` appended when read, e.g.
* `https://api.acme.org` would become `https://api.acme.org/`. Always use URL
* safe utilities included in the Node.js URL module to create
* valid URL strings, instead of error prone string concatenation.
*/
asUrlString: (input: string) => string;
/**
* Verifies that the variable is a valid URL string using the same method as
* `asUrlString()`, but instead returns the resulting URL instance.
*/
asUrlObject: (input: string) => URL;
/**
* Verifies that the var being accessed is one of the given values
*/
asEnum: <T extends string>(input: string, validValues: readonly T[]|T[]) => T;
}
interface VariableAccessors <AlternateType = unknown> {
/**
* Converts a number to an integer and verifies it's in port ranges 0-65535
*/
asPortNumber: () => AlternateType extends undefined ? undefined|number : number
/**
* Attempt to parse the variable to a float. Throws an exception if parsing fails.
*/
asFloat: () => AlternateType extends undefined ? undefined|number : number;
/**
* Performs the same task as asFloat(), but also verifies that the number is positive (greater than or equal to zero).
*/
asFloatPositive: () => AlternateType extends undefined ? undefined|number : number;
/**
* Performs the same task as asFloat(), but also verifies that the number is negative (less than or equal to zero).
*/
asFloatNegative: () => AlternateType extends undefined ? undefined|number : number;
/**
* Attempt to parse the variable to an integer. Throws an exception if parsing fails.
* This is a strict check, meaning that if the process.env value is 1.2, an exception will be raised rather than rounding up/down.
*/
asInt: () => AlternateType extends undefined ? undefined|number : number;
/**
* Performs the same task as asInt(), but also verifies that the number is positive (greater than or equal to zero).
*/
asIntPositive: () => AlternateType extends undefined ? undefined|number : number;
/**
* Performs the same task as asInt(), but also verifies that the number is negative (less than or equal to zero).
*/
asIntNegative: () => AlternateType extends undefined ? undefined|number : number;
/**
* Return the variable value as a String. Throws an exception if value is not a String.
* It's highly unlikely that a variable will not be a String since all process.env entries you set in bash are Strings by default.
*/
asString: () => AlternateType extends undefined ? undefined|string : string;
/**
* Return the variable value as an Email. Throws an exception if value is not an Email.
*/
asEmailString: () => AlternateType extends undefined ? undefined|string : string;
/**
* Attempt to parse the variable to a JSON Object or Array. Throws an exception if parsing fails.
*/
asJson: () => AlternateType extends undefined ? undefined|Object|Array<any> : Object|Array<any>;
/**
* The same as asJson but checks that the data is a JSON Array, e.g [1,2].
*/
asJsonArray: () => AlternateType extends undefined ? undefined|Array<any> : Array<any>;
/**
* The same as asJson but checks that the data is a JSON Object, e.g {a: 1}.
*/
asJsonObject: () => AlternateType extends undefined ? undefined|Object : Object;
/**
* Reads an environment variable as a string, then splits it on each occurrence of the specified delimiter.
* By default a comma is used as the delimiter. For example a var set to "1,2,3" would become ['1', '2', '3'].
*/
asArray: (delimiter?: string) => AlternateType extends undefined ? undefined|Array<string> : Array<string>;
/**
* Reads an environment variable as a string, then splits it on each occurrence of the specified delimiter.
* By default a comma is used as the delimiter. For example a var set to "1,2,3" would become new Set(['1', '2', '3']).
*/
asSet: (delimiter?: string) => AlternateType extends undefined ? undefined|Set<string> : Set<string>;
/**
* Attempt to parse the variable to a Boolean. Throws an exception if parsing fails.
* The var must be set to either "true", "false" (upper or lowercase), 0 or 1 to succeed.
*/
asBool: () => AlternateType extends undefined ? undefined|boolean : boolean;
/**
* Attempt to parse the variable to a Boolean. Throws an exception if parsing fails.
* The var must be set to either "true" or "false" (upper or lowercase) to succeed.
*/
asBoolStrict: () => AlternateType extends undefined ? undefined|boolean : boolean;
/**
* Verifies that the variable is a valid URL string and returns the validated
* string. The validation is performed by passing the URL string to the
* Node.js URL constructor.
*
* Note that URLs without paths will have a default path `/` appended when read, e.g.
* `https://api.acme.org` would become `https://api.acme.org/`. Always use URL
* safe utilities included in the Node.js URL module to create
* valid URL strings, instead of error prone string concatenation.
*/
asUrlString: () => AlternateType extends undefined ? undefined|string : string;
/**
* Verifies that the variable is a valid URL string using the same method as
* `asUrlString()`, but instead returns the resulting URL instance.
*/
asUrlObject: () => AlternateType extends undefined ? undefined|URL : URL;
/**
* Verifies that the var being accessed is one of the given values
*/
asEnum: <T extends string>(validValues: readonly T[]|T[]) => AlternateType extends undefined ? undefined|T : T;
/**
* Verifies that the variable is a valid regular expression and returns the
* validated expression as a RegExp instance.
*/
asRegExp: (flags?: string) => AlternateType extends undefined ? undefined|RegExp : RegExp;
}
interface IPresentVariable<Exs extends Extensions = {}> extends VariableAccessors {
/**
* Converts a bas64 environment variable to ut8
*/
convertFromBase64: () => IPresentVariable<Exs> & ExtenderType<Exs>
/**
* Provide an example value that can be used in error output if the variable
* is not set, or is set to an invalid value
*/
example: (example: string) => IPresentVariable<Exs> & ExtenderType<Exs>
/**
* Set a default value for this variable. This will be used if a value is not
* set in the process environment
*/
default: (value: string|number|Record<string, any>|Array<any>) => IPresentVariable<Exs> & ExtenderType<Exs>;
/**
* Ensures the variable is set on process.env. If it's not set an exception
* will be thrown. Can pass false to bypass the check.
*/
required: (isRequired?: boolean) => IPresentVariable & ExtenderType<Exs>;
}
interface IOptionalVariable<Exs extends Extensions = {}> extends VariableAccessors<undefined> {
/**
* Decodes a base64-encoded environment variable
*/
convertFromBase64: () => IOptionalVariable<Exs> & ExtenderTypeOptional<Exs>;
/**
* Provide an example value that can be used in error output if the variable
* is not set, or is set to an invalid value
*/
example: (value: string) => IOptionalVariable<Exs> & ExtenderTypeOptional<Exs>;
/**
* Set a default value for this variable. This will be used if a value is not
* set in the process environment
*/
default: (value: string|number|Record<string, any>|Array<any>) => IPresentVariable<Exs> & ExtenderType<Exs>;
/**
* Ensures the variable is set on process.env. If it's not set an exception will be thrown.
* Can pass false to bypass the check
*/
required: (isRequired?: boolean) => IPresentVariable & ExtenderType<Exs>;
}
export class EnvVarError extends Error {}
interface IEnv<OptionalVariable, Container> {
/**
* Returns an object containing all current environment variables
*/
get (): Container,
/**
* Gets an environment variable that is possibly not set to a value
*/
get (varName: keyof Container): OptionalVariable;
/**
* Returns a new env-var instance, where the given object is used for the environment variable mapping.
* Use this when writing unit tests or in environments outside node.js.
*/
from<V, T extends Extensions>(values: V, extensions?: T, logger?: LoggerFn): IEnv<
IOptionalVariable<T> & ExtenderTypeOptional<T>,
V
>;
accessors: PublicAccessors
/**
* This is the error type used to represent error returned by this module.
* Useful for filtering errors and responding appropriately.
*/
EnvVarError: EnvVarError
}
// Used internally only to support extension fns
type RestParams<F extends (...args: any[]) => any> = F extends (value: string, ...args: infer P) => any ? P : any[];
type ExtenderType<T extends Extensions> = { [P in keyof T]: (...args: RestParams<T[P]>) => ReturnType<T[P]> }
type ExtenderTypeOptional<T extends Extensions> = { [P in keyof T]: (...args: RestParams<T[P]>) => ReturnType<T[P]>|undefined }
export type Extensions = {
[key: string]: ExtensionFn<any>
}
export type LoggerFn = (varname: string, str: string) => void
export type RaiseErrorFn = (error: string) => void
export type ExtensionFn<T> = (value: string, ...args: any[]) => T
export const accessors: PublicAccessors
export function logger (varname: string, str: string): void
type IDefaultEnv = IEnv<IOptionalVariable, NodeJS.ProcessEnv>
export const get: IDefaultEnv['get']
export const from: IDefaultEnv['from']

70
node_modules/env-var/env-var.js generated vendored Normal file
View File

@@ -0,0 +1,70 @@
'use strict'
const variable = require('./lib/variable')
const EnvVarError = require('./lib/env-error')
/**
* Returns an "env-var" instance that reads from the given container of values.
* By default, we export an instance that reads from process.env
* @param {Object} container target container to read values from
* @param {Object} extraAccessors additional accessors to attach to the
* resulting object
* @return {Object} a new module instance
*/
const from = (container, extraAccessors, logger) => {
return {
from: from,
/**
* This is the Error class used to generate exceptions. Can be used to identify
* exceptions and handle them appropriately.
*/
EnvVarError: require('./lib/env-error'),
/**
* Returns a variable instance with helper functions, or process.env
* @param {String} variableName Name of the environment variable requested
* @return {Object}
*/
get: function (variableName) {
if (!variableName) {
return container
}
if (arguments.length > 1) {
throw new EnvVarError('It looks like you passed more than one argument to env.get(). Since env-var@6.0.0 this is no longer supported. To set a default value use env.get(TARGET).default(DEFAULT)')
}
return variable(container, variableName, extraAccessors || {}, logger || function noopLogger () {})
},
/**
* Provides access to the functions that env-var uses to parse
* process.env strings into valid types requested by the API
*/
accessors: require('./lib/accessors/index'),
/**
* Provides a default logger that can be used to print logs.
* This will not print logs in a production environment (checks process.env.NODE_ENV)
*/
logger: require('./lib/logger')(console.log, container.NODE_ENV)
}
}
/**
* Makes a best-effort attempt to load environment variables in
* different environments, e.g create-react-app, vite, Node.js
* @returns Object
*/
function getProcessEnv () {
/* istanbul ignore next */
try {
return process.env
} catch (e) {
return {}
}
}
/* istanbul ignore next */
module.exports = from(getProcessEnv())

13
node_modules/env-var/lib/accessors/array.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
const asString = require('./string')
module.exports = function asArray (value, delimiter) {
delimiter = delimiter || ','
if (!value.length) {
return []
} else {
return asString(value).split(delimiter).filter(Boolean)
}
}

11
node_modules/env-var/lib/accessors/bool-strict.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
'use strict'
module.exports = function asBoolStrict (value) {
const val = value.toLowerCase()
if ((val !== 'false') && (val !== 'true')) {
throw new Error('should be either "true", "false", "TRUE", or "FALSE"')
}
return val !== 'false'
}

18
node_modules/env-var/lib/accessors/bool.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
'use strict'
module.exports = function asBool (value) {
const val = value.toLowerCase()
const allowedValues = [
'false',
'0',
'true',
'1'
]
if (allowedValues.indexOf(val) === -1) {
throw new Error('should be either "true", "false", "TRUE", "FALSE", 1, or 0')
}
return !(((val === '0') || (val === 'false')))
}

16
node_modules/env-var/lib/accessors/email-string.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
'use strict'
const asString = require('./string')
// eslint-disable-next-line no-control-regex
const EMAIL_REGEX = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021\u0023-\u005b\u005d-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021-\u005a\u0053-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])+)\])$/
module.exports = function asEmailString (value) {
const strValue = asString(value)
if (!EMAIL_REGEX.test(strValue)) {
throw new Error('should be a valid email address')
}
return strValue
}

13
node_modules/env-var/lib/accessors/enum.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
const asString = require('./string')
module.exports = function asEnum (value, validValues) {
const valueString = asString(value)
if (validValues.indexOf(valueString) < 0) {
throw new Error(`should be one of [${validValues.join(', ')}]`)
}
return valueString
}

13
node_modules/env-var/lib/accessors/float-negative.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
const asFloat = require('./float')
module.exports = function asFloatNegative (value) {
const ret = asFloat(value)
if (ret > 0) {
throw new Error('should be a negative float')
}
return ret
}

13
node_modules/env-var/lib/accessors/float-positive.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
const asFloat = require('./float')
module.exports = function asFloatPositive (value) {
const ret = asFloat(value)
if (ret < 0) {
throw new Error('should be a positive float')
}
return ret
}

13
node_modules/env-var/lib/accessors/float.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
module.exports = function asFloat (value) {
const n = parseFloat(value)
// Some values are parsed as valid floats despite being obviously invalid, e.g. "1.o" or "192.168.1.1".
// In these cases we would want to throw an error.
if (isNaN(n) || isNaN(value)) {
throw new Error('should be a valid float')
}
return n
}

31
node_modules/env-var/lib/accessors/index.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
module.exports = {
asArray: require('./array'),
asSet: require('./set'),
asBoolStrict: require('./bool-strict'),
asBool: require('./bool'),
asPortNumber: require('./port'),
asEnum: require('./enum'),
asFloatNegative: require('./float-negative'),
asFloatPositive: require('./float-positive'),
asFloat: require('./float'),
asIntNegative: require('./int-negative'),
asIntPositive: require('./int-positive'),
asInt: require('./int'),
asJsonArray: require('./json-array'),
asJsonObject: require('./json-object'),
asJson: require('./json'),
asRegExp: require('./regexp'),
asString: require('./string'),
asUrlObject: require('./url-object'),
asUrlString: require('./url-string'),
asEmailString: require('./email-string')
}

13
node_modules/env-var/lib/accessors/int-negative.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
const asInt = require('./int')
module.exports = function asIntNegative (value) {
const ret = asInt(value)
if (ret > 0) {
throw new Error('should be a negative integer')
}
return ret
}

13
node_modules/env-var/lib/accessors/int-positive.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
const asInt = require('./int')
module.exports = function asIntPositive (value) {
const ret = asInt(value)
if (ret < 0) {
throw new Error('should be a positive integer')
}
return ret
}

11
node_modules/env-var/lib/accessors/int.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
'use strict'
module.exports = function asInt (value) {
const n = parseInt(value, 10)
if (isNaN(n) || n.toString(10) !== value) {
throw new Error('should be a valid integer')
}
return n
}

13
node_modules/env-var/lib/accessors/json-array.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
const asJson = require('./json')
module.exports = function asJsonArray (value) {
var ret = asJson(value)
if (!Array.isArray(ret)) {
throw new Error('should be a parseable JSON Array')
}
return ret
}

13
node_modules/env-var/lib/accessors/json-object.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
const asJson = require('./json')
module.exports = function asJsonObject (value) {
var ret = asJson(value)
if (Array.isArray(ret)) {
throw new Error('should be a parseable JSON Object')
}
return ret
}

9
node_modules/env-var/lib/accessors/json.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
'use strict'
module.exports = function asJson (value) {
try {
return JSON.parse(value)
} catch (e) {
throw new Error('should be valid (parseable) JSON')
}
}

13
node_modules/env-var/lib/accessors/port.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
const asIntPositive = require('./int-positive')
module.exports = function asPortNumber (value) {
var ret = asIntPositive(value)
if (ret > 65535) {
throw new Error('cannot assign a port number greater than 65535')
}
return ret
}

21
node_modules/env-var/lib/accessors/regexp.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
'use strict'
module.exports = function asRegExp (value, flags) {
// We have to test the value and flags indivudally if we want to write our
// own error messages,as there is no way to differentiate between the two
// errors except by using string comparisons.
// Test the flags
try {
RegExp(undefined, flags)
} catch (err) {
throw new Error('invalid regexp flags')
}
try {
return new RegExp(value, flags)
} catch (err) {
// We know that the regexp is the issue because we tested the flags earlier
throw new Error('should be a valid regexp')
}
}

11
node_modules/env-var/lib/accessors/set.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
'use strict'
const asArray = require('./array')
module.exports = function asSet (value, delimiter) {
if (!value.length) {
return new Set()
} else {
return new Set(asArray(value, delimiter))
}
}

5
node_modules/env-var/lib/accessors/string.js generated vendored Normal file
View File

@@ -0,0 +1,5 @@
'use strict'
module.exports = function asString (value) {
return value
}

13
node_modules/env-var/lib/accessors/url-object.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
const asString = require('./string')
module.exports = function asUrlObject (value) {
const ret = asString(value)
try {
return new URL(ret)
} catch (e) {
throw new Error('should be a valid URL')
}
}

7
node_modules/env-var/lib/accessors/url-string.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
'use strict'
const urlObject = require('./url-object')
module.exports = function asUrlString (value) {
return urlObject(value).toString()
}

20
node_modules/env-var/lib/env-error.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
'use strict'
/**
* Custom error class that can be used to identify errors generated
* by the module
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error}
*/
class EnvVarError extends Error {
constructor (message, ...params) {
super(`env-var: ${message}`, ...params)
/* istanbul ignore else */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, EnvVarError)
}
this.name = 'EnvVarError'
}
}
module.exports = EnvVarError

13
node_modules/env-var/lib/logger.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
/**
* Default logger included with env-var.
* Will not log anything if NODE_ENV is set to production
*/
module.exports = function genLogger (out, prodFlag) {
return function envVarLogger (varname, str) {
if (!prodFlag || !prodFlag.match(/prod|production/)) {
out(`env-var (${varname}): ${str}`)
}
}
}

183
node_modules/env-var/lib/variable.js generated vendored Normal file
View File

@@ -0,0 +1,183 @@
'use strict'
const EnvVarError = require('./env-error')
const base64Regex = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/
/**
* Returns an Object that contains functions to read and specify the format of
* the variable you wish to have returned
* @param {Object} container Encapsulated container (e.g., `process.env`).
* @param {String} varName Name of the requested property from `container`.
* @param {*} defValue Default value to return if `varName` is invalid.
* @param {Object} extraAccessors Extra accessors to install.
* @return {Object}
*/
module.exports = function getVariableAccessors (container, varName, extraAccessors, logger) {
let isBase64 = false
let isRequired = false
let defValue
let example
const builtInAccessors = require('./accessors/index')
/**
* Logs the given string using the provided logger
* @param {String} str
* @param {String} str
*/
function log (str) {
logger(varName, str)
}
/**
* Throw an error with a consistent type/format.
* @param {String} value
*/
function raiseError (value, msg) {
let errMsg = `"${varName}" ${msg}`
if (value) {
errMsg = `${errMsg}`
}
if (example) {
errMsg = `${errMsg}. An example of a valid value would be: ${example}`
}
throw new EnvVarError(errMsg)
}
/**
* Returns an accessor wrapped by error handling and args passing logic
* @param {Function} accessor
*/
function generateAccessor (accessor) {
return function () {
let value = container[varName]
log(`will be read from the environment using "${accessor.name}" accessor`)
if (typeof value === 'undefined') {
if (typeof defValue === 'undefined' && isRequired) {
log('was not found in the environment, but is required to be set')
// Var is not set, nor is a default. Throw an error
raiseError(undefined, 'is a required variable, but it was not set')
} else if (typeof defValue !== 'undefined') {
log(`was not found in the environment, parsing default value "${defValue}" instead`)
value = defValue
} else {
log('was not found in the environment, but is not required. returning undefined')
// return undefined since variable is not required and
// there's no default value provided
return undefined
}
}
if (isRequired) {
log('verifying variable value is not an empty string')
// Need to verify that required variables aren't just whitespace
if (value.trim().length === 0) {
raiseError(undefined, 'is a required variable, but its value was empty')
}
}
if (isBase64) {
log('verifying variable is a valid base64 string')
if (!value.match(base64Regex)) {
raiseError(value, 'should be a valid base64 string if using convertFromBase64')
}
log('converting from base64 to utf8 string')
value = Buffer.from(value, 'base64').toString()
}
const args = [value].concat(Array.prototype.slice.call(arguments))
try {
log(`passing value "${value}" to "${accessor.name}" accessor`)
const result = accessor.apply(
accessor,
args
)
log(`parsed successfully, returning ${result}`)
return result
} catch (error) {
raiseError(value, error.message)
}
}
}
const accessors = {
/**
* Instructs env-var to first convert the value of the variable from base64
* when reading it using a function such as asString()
*/
convertFromBase64: function () {
log('marking for base64 conversion')
isBase64 = true
return accessors
},
/**
* Set a default value for the variable
* @param {String} value
*/
default: function (value) {
if (typeof value === 'number') {
defValue = value.toString()
} else if (Array.isArray(value) || (typeof value === 'object' && value !== null)) {
defValue = JSON.stringify(value)
} else if (typeof value !== 'string') {
throw new EnvVarError('values passed to default() must be of Number, String, Array, or Object type')
} else {
defValue = value
}
log(`setting default value to "${defValue}"`)
return accessors
},
/**
* Ensures a variable is set in the given environment container. Throws an
* EnvVarError if the variable is not set or a default is not provided
* @param {Boolean} required
*/
required: function (required) {
if (typeof required === 'undefined') {
log('marked as required')
// If no value is passed assume that developer means "true"
// This is to retain support legacy usage (and intuitive)
isRequired = true
} else {
log(`setting required flag to ${required}`)
isRequired = required
}
return accessors
},
/**
* Set an example value for this variable. If the variable value is not set
* or is set to an invalid value this example will be show in error output.
* @param {String} example
*/
example: function (ex) {
example = ex
return accessors
}
}
// Attach accessors, and extra accessors if provided.
Object.entries({
...builtInAccessors,
...extraAccessors
}).forEach(([name, accessor]) => {
accessors[name] = generateAccessor(accessor)
})
return accessors
}

70
node_modules/env-var/package.json generated vendored Normal file
View File

@@ -0,0 +1,70 @@
{
"name": "env-var",
"version": "7.5.0",
"description": "Verification, sanitization, and type coercion for environment variables in Node.js",
"main": "env-var.js",
"typings": "env-var.d.ts",
"scripts": {
"coverage": "nyc mocha test/*.js && nyc report --reporter=lcov",
"check-coverage": "nyc check-coverage --statements 100 --branches 100 --functions 100 --lines 100",
"unit": "mocha test/*.js",
"lint": "standard example/*.js *.js \"lib/**/*.js\" test/*.js --fix",
"test": "npm run unit && npm run coverage && npm run check-coverage && npm run lint && npm run ts-verify",
"ts-verify": "tsc && mocha test/types/*.js"
},
"husky": {
"hooks": {
"pre-commit": "npm run lint && npm run unit"
}
},
"repository": {
"type": "git",
"url": "https://github.com/evanshortiss/env-var.git"
},
"keywords": [
"dotenv",
"env",
"process.env",
"process",
"var",
"environment",
"variables",
"variable",
"loader",
"env-var",
"envvar",
"config",
"configuration",
"typescript",
"ts"
],
"author": "Evan Shortiss",
"license": "MIT",
"files": [
"lib/",
"env-var.js",
"env-var.d.ts"
],
"bugs": {
"url": "https://github.com/evanshortiss/env-var/issues"
},
"homepage": "https://github.com/evanshortiss/env-var",
"devDependencies": {
"@types/chai": "~4.2.10",
"@types/mocha": "~7.0.1",
"@types/node": "~13.13.0",
"bluebird": "~3.7.0",
"chai": "~4.2.0",
"conditional-type-checks": "1.0.5",
"coveralls": "~3.1.0",
"husky": "~4.2.2",
"mocha": "~8.2.0",
"mocha-lcov-reporter": "~1.3.0",
"nyc": "~15.1.0",
"standard": "~14.3.4",
"typescript": "~3.9.0"
},
"engines": {
"node": ">=10"
}
}