@balena/env-parsing 1.0.0-multi-var-1a4340c1f5dc04e6b2ff27cf9a9f26c92a6cc8d2

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/.editorconfig ADDED
@@ -0,0 +1,16 @@
1
+ # editorconfig.org
2
+ root = true
3
+
4
+ [*]
5
+ indent_style = tab
6
+ end_of_line = lf
7
+ charset = utf-8
8
+ trim_trailing_whitespace = true
9
+ insert_final_newline = true
10
+
11
+ [*.md]
12
+ trim_trailing_whitespace = false
13
+
14
+ [package.json]
15
+ indent_style = space
16
+ indent_size = 2
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file
4
+ automatically by Versionist. DO NOT EDIT THIS FILE MANUALLY!
5
+ This project adheres to [Semantic Versioning](http://semver.org/).
6
+
7
+ # v1.0.0
8
+ ## (2022-08-12)
9
+
10
+ * Add support for passing an array of vars as well as a single one [Pagan Gazzard]
11
+ * Initial version [Pagan Gazzard]
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # @balena/env-parsing
2
+
3
+ A collection of utilities to simplify/standardize env var parsing
@@ -0,0 +1,41 @@
1
+ export declare const SECONDS = 1000;
2
+ export declare const SECONDS_PER_HOUR: number;
3
+ export declare const MINUTES: number;
4
+ export declare const HOURS: number;
5
+ export declare const DAYS: number;
6
+ /**
7
+ * Ensure an env var exists and return the contents if it does
8
+ */
9
+ export declare const requiredVar: (varName: string | string[]) => string;
10
+ /**
11
+ * Fetches the contents of an env var if it exists and is not empty, otherwise returning the specified default value,
12
+ * this means that if no default is specified then `''` will be normalized to `undefined`
13
+ */
14
+ export declare function optionalVar<R>(varName: string | string[] | string[], defaultValue: R): string | R;
15
+ export declare function optionalVar<R>(varName: string | string[] | string[], defaultValue?: undefined): string | undefined;
16
+ /**
17
+ * Checks that a string is a valid int and returns the number if so
18
+ */
19
+ export declare const checkInt: (s: string) => number | undefined;
20
+ /**
21
+ * Fetches the contents of an env var, ensuring it is a valid integer if set,
22
+ * if it is not set then instead it returns the specified default value
23
+ */
24
+ export declare function intVar(varName: string | string[]): number;
25
+ export declare function intVar<R>(varName: string | string[], defaultValue: R): number | R;
26
+ /**
27
+ * Fetches the contents of an env var, ensuring it is a valid boolean (`'true'`/`'false'`) if set,
28
+ * if it is not set then instead it returns the specified default value
29
+ */
30
+ export declare function boolVar(varName: string | string[]): boolean;
31
+ export declare function boolVar<R>(varName: string | string[], defaultValue: R): boolean | R;
32
+ export declare type HostPort = {
33
+ host: string;
34
+ port: number;
35
+ };
36
+ /**
37
+ * Splits an env var in the format of `${host1}:${port1}, ${host2}:${port2}, ...`
38
+ * into an array of individual host/port pairings
39
+ */
40
+ export declare const splitHostPort: (varName: string | string[], defaultHosts?: HostPort[]) => HostPort[];
41
+ export declare const trustProxyVar: (varName: string | string[], defaultValue?: string) => boolean | string | number;
package/build/index.js ADDED
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.trustProxyVar = exports.splitHostPort = exports.boolVar = exports.intVar = exports.checkInt = exports.optionalVar = exports.requiredVar = exports.DAYS = exports.HOURS = exports.MINUTES = exports.SECONDS_PER_HOUR = exports.SECONDS = void 0;
4
+ exports.SECONDS = 1000;
5
+ exports.SECONDS_PER_HOUR = 60 * 60;
6
+ exports.MINUTES = 60 * exports.SECONDS;
7
+ exports.HOURS = 60 * exports.MINUTES;
8
+ exports.DAYS = 24 * exports.HOURS;
9
+ /**
10
+ * Ensure an env var exists and return the contents if it does
11
+ */
12
+ const requiredVar = (varName) => {
13
+ const s = optionalVar(varName);
14
+ if (s == null) {
15
+ throw new Error(`Missing environment variable: ${varName}`);
16
+ }
17
+ return s;
18
+ };
19
+ exports.requiredVar = requiredVar;
20
+ function optionalVar(varName, defaultValue) {
21
+ // If there's a single string var name then fetch it directly from process.env, returning the default as necessary
22
+ if (typeof varName === 'string') {
23
+ const s = process.env[varName];
24
+ if (s == null || s === '') {
25
+ return defaultValue;
26
+ }
27
+ return s;
28
+ }
29
+ // Otherwise for a list then we loop through and return the first valid one, otherwise we return the default value
30
+ for (const name of varName) {
31
+ const s = optionalVar(name);
32
+ if (s != null) {
33
+ return s;
34
+ }
35
+ }
36
+ return defaultValue;
37
+ }
38
+ exports.optionalVar = optionalVar;
39
+ /**
40
+ * Checks that a string is a valid int and returns the number if so
41
+ */
42
+ const checkInt = (s) => {
43
+ s = s.trim();
44
+ if (/[^0-9]/.test(s)) {
45
+ return;
46
+ }
47
+ const i = parseInt(s, 10);
48
+ if (!Number.isFinite(i)) {
49
+ return;
50
+ }
51
+ return i;
52
+ };
53
+ exports.checkInt = checkInt;
54
+ function intVar(varName, defaultValue) {
55
+ if (arguments.length === 1) {
56
+ (0, exports.requiredVar)(varName);
57
+ }
58
+ const s = optionalVar(varName);
59
+ if (s == null) {
60
+ return defaultValue;
61
+ }
62
+ const i = (0, exports.checkInt)(s);
63
+ if (i === undefined) {
64
+ throw new Error(`${varName} must be a valid number if set`);
65
+ }
66
+ return i;
67
+ }
68
+ exports.intVar = intVar;
69
+ function boolVar(varName, defaultValue) {
70
+ if (arguments.length === 1) {
71
+ (0, exports.requiredVar)(varName);
72
+ }
73
+ const s = optionalVar(varName);
74
+ if (s == null) {
75
+ return defaultValue;
76
+ }
77
+ if (s === 'false') {
78
+ return false;
79
+ }
80
+ if (s === 'true') {
81
+ return true;
82
+ }
83
+ throw new Error(`Invalid value for boolean var '${varName}', got '${s}', expected 'true' or 'false'`);
84
+ }
85
+ exports.boolVar = boolVar;
86
+ /**
87
+ * Splits an env var in the format of `${host1}:${port1}, ${host2}:${port2}, ...`
88
+ * into an array of individual host/port pairings
89
+ */
90
+ const splitHostPort = (varName, defaultHosts) => {
91
+ const hostPairs = optionalVar(varName);
92
+ if (hostPairs == null) {
93
+ if (defaultHosts == null) {
94
+ throw new Error(`Missing environment variable: ${varName}`);
95
+ }
96
+ return defaultHosts;
97
+ }
98
+ return hostPairs.split(',').map((hostPair) => {
99
+ const [host, maybePort] = hostPair.trim().split(':');
100
+ const port = (0, exports.checkInt)(maybePort);
101
+ if (port == null) {
102
+ throw new Error(`Invalid port for '${varName}': ${maybePort}`);
103
+ }
104
+ return { host, port };
105
+ });
106
+ };
107
+ exports.splitHostPort = splitHostPort;
108
+ const trustProxyVar = (varName, defaultValue) => {
109
+ const trustProxy = optionalVar(varName, defaultValue);
110
+ if (trustProxy == null) {
111
+ throw new Error(`Missing environment variable: ${varName}`);
112
+ }
113
+ if (trustProxy === 'true') {
114
+ // If it's 'true' enable it
115
+ return true;
116
+ }
117
+ if (trustProxy === 'false') {
118
+ // If it's 'false' disable it
119
+ return false;
120
+ }
121
+ if (trustProxy.includes('.') || trustProxy.includes(':')) {
122
+ // If it looks like an ip use as-is
123
+ return trustProxy;
124
+ }
125
+ const trustProxyNum = (0, exports.checkInt)(trustProxy);
126
+ if (trustProxyNum != null) {
127
+ // If it's a number use the number
128
+ return trustProxyNum;
129
+ }
130
+ if (trustProxy === defaultValue) {
131
+ throw new Error(`Invalid default value for '${varName}' of '${trustProxy}'`);
132
+ }
133
+ throw new Error(`Invalid value for '${varName}' of '${trustProxy}'`);
134
+ };
135
+ exports.trustProxyVar = trustProxyVar;
136
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAa,QAAA,OAAO,GAAG,IAAI,CAAC;AACf,QAAA,gBAAgB,GAAG,EAAE,GAAG,EAAE,CAAC;AAC3B,QAAA,OAAO,GAAG,EAAE,GAAG,eAAO,CAAC;AACvB,QAAA,KAAK,GAAG,EAAE,GAAG,eAAO,CAAC;AACrB,QAAA,IAAI,GAAG,EAAE,GAAG,aAAK,CAAC;AAE/B;;GAEG;AACI,MAAM,WAAW,GAAG,CAAC,OAA0B,EAAU,EAAE;IACjE,MAAM,CAAC,GAAG,WAAW,CAAC,OAAO,CAAC,CA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OAAO,SAAS,UAAU,GAAG,CAAC,CAAC;AACtE,CAAC,CAAC;AAjCW,QAAA,aAAa,iBAiCxB"}
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@balena/env-parsing",
3
+ "version": "1.0.0-multi-var-1a4340c1f5dc04e6b2ff27cf9a9f26c92a6cc8d2",
4
+ "description": "A collection of utilities to simplify/standardize env var parsing",
5
+ "main": "build/index.js",
6
+ "types": "build/index.d.ts",
7
+ "scripts": {
8
+ "clean": "rimraf build",
9
+ "build": "npm run clean && tsc",
10
+ "lint": "balena-lint --typescript src test",
11
+ "lint-fix": "balena-lint --typescript --fix src test",
12
+ "test": "mocha && npm run lint",
13
+ "prepack": "npm run build",
14
+ "prepare": "husky install"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/balena-io-modules/balena-env-parsing.git"
19
+ },
20
+ "license": "Apache-2.0",
21
+ "bugs": {
22
+ "url": "https://github.com/balena-io-modules/balena-env-parsing/issues"
23
+ },
24
+ "homepage": "https://github.com/balena-io-modules/balena-env-parsing",
25
+ "devDependencies": {
26
+ "@balena/lint": "^6.2.0",
27
+ "@types/chai": "^4.3.3",
28
+ "@types/mocha": "^9.1.1",
29
+ "@types/node": "^16.11.48",
30
+ "chai": "^4.3.6",
31
+ "husky": "^8.0.0",
32
+ "mocha": "^10.0.0",
33
+ "rimraf": "^3.0.2",
34
+ "ts-node": "^10.9.1",
35
+ "typescript": "^4.7.4"
36
+ },
37
+ "mocha": {
38
+ "reporter": "spec",
39
+ "recursive": true,
40
+ "require": "ts-node/register/transpile-only",
41
+ "extension": ".ts"
42
+ },
43
+ "husky": {
44
+ "hooks": {
45
+ "pre-commit": "lint-staged"
46
+ }
47
+ },
48
+ "lint-staged": {
49
+ "*.ts": [
50
+ "balena-lint --fix"
51
+ ]
52
+ },
53
+ "versionist": {
54
+ "publishedAt": "2022-08-12T16:04:06.520Z"
55
+ }
56
+ }
package/src/index.ts ADDED
@@ -0,0 +1,176 @@
1
+ export const SECONDS = 1000;
2
+ export const SECONDS_PER_HOUR = 60 * 60;
3
+ export const MINUTES = 60 * SECONDS;
4
+ export const HOURS = 60 * MINUTES;
5
+ export const DAYS = 24 * HOURS;
6
+
7
+ /**
8
+ * Ensure an env var exists and return the contents if it does
9
+ */
10
+ export const requiredVar = (varName: string | string[]): string => {
11
+ const s = optionalVar(varName);
12
+ if (s == null) {
13
+ throw new Error(`Missing environment variable: ${varName}`);
14
+ }
15
+ return s;
16
+ };
17
+
18
+ /**
19
+ * Fetches the contents of an env var if it exists and is not empty, otherwise returning the specified default value,
20
+ * this means that if no default is specified then `''` will be normalized to `undefined`
21
+ */
22
+ export function optionalVar<R>(
23
+ varName: string | string[] | string[],
24
+ defaultValue: R,
25
+ ): string | R;
26
+ export function optionalVar<R>(
27
+ varName: string | string[] | string[],
28
+ defaultValue?: undefined,
29
+ ): string | undefined;
30
+ export function optionalVar<R>(
31
+ varName: string | string[] | string[],
32
+ defaultValue?: R,
33
+ ): string | R | undefined {
34
+ // If there's a single string var name then fetch it directly from process.env, returning the default as necessary
35
+ if (typeof varName === 'string') {
36
+ const s = process.env[varName];
37
+ if (s == null || s === '') {
38
+ return defaultValue;
39
+ }
40
+ return s;
41
+ }
42
+
43
+ // Otherwise for a list then we loop through and return the first valid one, otherwise we return the default value
44
+ for (const name of varName) {
45
+ const s = optionalVar(name);
46
+ if (s != null) {
47
+ return s;
48
+ }
49
+ }
50
+ return defaultValue;
51
+ }
52
+
53
+ /**
54
+ * Checks that a string is a valid int and returns the number if so
55
+ */
56
+ export const checkInt = (s: string): number | undefined => {
57
+ s = s.trim();
58
+ if (/[^0-9]/.test(s)) {
59
+ return;
60
+ }
61
+ const i = parseInt(s, 10);
62
+ if (!Number.isFinite(i)) {
63
+ return;
64
+ }
65
+ return i;
66
+ };
67
+
68
+ /**
69
+ * Fetches the contents of an env var, ensuring it is a valid integer if set,
70
+ * if it is not set then instead it returns the specified default value
71
+ */
72
+ export function intVar(varName: string | string[]): number;
73
+ export function intVar<R>(varName: string | string[], defaultValue: R): number | R;
74
+ export function intVar<R>(varName: string | string[], defaultValue?: R): number | R {
75
+ if (arguments.length === 1) {
76
+ requiredVar(varName);
77
+ }
78
+
79
+ const s = optionalVar(varName);
80
+ if (s == null) {
81
+ return defaultValue!;
82
+ }
83
+
84
+ const i = checkInt(s);
85
+ if (i === undefined) {
86
+ throw new Error(`${varName} must be a valid number if set`);
87
+ }
88
+ return i;
89
+ }
90
+
91
+ /**
92
+ * Fetches the contents of an env var, ensuring it is a valid boolean (`'true'`/`'false'`) if set,
93
+ * if it is not set then instead it returns the specified default value
94
+ */
95
+ export function boolVar(varName: string | string[]): boolean;
96
+ export function boolVar<R>(varName: string | string[], defaultValue: R): boolean | R;
97
+ export function boolVar<R>(varName: string | string[], defaultValue?: R): boolean | R {
98
+ if (arguments.length === 1) {
99
+ requiredVar(varName);
100
+ }
101
+
102
+ const s = optionalVar(varName);
103
+ if (s == null) {
104
+ return defaultValue!;
105
+ }
106
+ if (s === 'false') {
107
+ return false;
108
+ }
109
+ if (s === 'true') {
110
+ return true;
111
+ }
112
+ throw new Error(
113
+ `Invalid value for boolean var '${varName}', got '${s}', expected 'true' or 'false'`,
114
+ );
115
+ }
116
+
117
+ export type HostPort = { host: string; port: number };
118
+ /**
119
+ * Splits an env var in the format of `${host1}:${port1}, ${host2}:${port2}, ...`
120
+ * into an array of individual host/port pairings
121
+ */
122
+ export const splitHostPort = (
123
+ varName: string | string[],
124
+ defaultHosts?: HostPort[],
125
+ ): HostPort[] => {
126
+ const hostPairs = optionalVar(varName);
127
+ if (hostPairs == null) {
128
+ if (defaultHosts == null) {
129
+ throw new Error(`Missing environment variable: ${varName}`);
130
+ }
131
+ return defaultHosts;
132
+ }
133
+ return hostPairs.split(',').map((hostPair): HostPort => {
134
+ const [host, maybePort] = hostPair.trim().split(':');
135
+ const port = checkInt(maybePort);
136
+ if (port == null) {
137
+ throw new Error(`Invalid port for '${varName}': ${maybePort}`);
138
+ }
139
+ return { host, port };
140
+ });
141
+ };
142
+
143
+ export const trustProxyVar = (
144
+ varName: string | string[],
145
+ defaultValue?: string,
146
+ ): boolean | string | number => {
147
+ const trustProxy = optionalVar(varName, defaultValue);
148
+ if (trustProxy == null) {
149
+ throw new Error(`Missing environment variable: ${varName}`);
150
+ }
151
+ if (trustProxy === 'true') {
152
+ // If it's 'true' enable it
153
+ return true;
154
+ }
155
+ if (trustProxy === 'false') {
156
+ // If it's 'false' disable it
157
+ return false;
158
+ }
159
+ if (trustProxy.includes('.') || trustProxy.includes(':')) {
160
+ // If it looks like an ip use as-is
161
+ return trustProxy;
162
+ }
163
+
164
+ const trustProxyNum = checkInt(trustProxy);
165
+ if (trustProxyNum != null) {
166
+ // If it's a number use the number
167
+ return trustProxyNum;
168
+ }
169
+
170
+ if (trustProxy === defaultValue) {
171
+ throw new Error(
172
+ `Invalid default value for '${varName}' of '${trustProxy}'`,
173
+ );
174
+ }
175
+ throw new Error(`Invalid value for '${varName}' of '${trustProxy}'`);
176
+ };
package/test/index.ts ADDED
@@ -0,0 +1,210 @@
1
+ import { expect } from 'chai';
2
+ import {
3
+ boolVar,
4
+ checkInt,
5
+ intVar,
6
+ optionalVar,
7
+ requiredVar,
8
+ splitHostPort,
9
+ trustProxyVar,
10
+ } from '../src';
11
+
12
+ const varName = 'fruit';
13
+ const varNames = ['vegetable', 'fruit'];
14
+ const varTests = [
15
+ ['single var name', varName],
16
+ ['multi var name', varNames],
17
+ ] as const;
18
+ const clearVar = () => {
19
+ delete process.env[varName];
20
+ };
21
+ const setVar = (v: string) => {
22
+ process.env[varName] = v;
23
+ };
24
+
25
+ beforeEach(() => {
26
+ clearVar();
27
+ });
28
+
29
+ for (const [testType, varTest] of varTests) {
30
+ describe(testType, () => {
31
+ describe('requiredVar', () => {
32
+ it('should throw when the env var is missing', () => {
33
+ expect(() => requiredVar(varTest)).to.throw;
34
+ });
35
+ it('should return the value when the env var exists', () => {
36
+ const value = 'apple';
37
+ setVar(value);
38
+ expect(requiredVar(varTest)).to.equal(value);
39
+ });
40
+ });
41
+
42
+ describe('optionalVar', () => {
43
+ const defaultValue = 'banana';
44
+ it('should return undefined when the env var is missing', () => {
45
+ expect(optionalVar(varTest)).to.be.undefined;
46
+ });
47
+ it('should return undefined when the env var is empty', () => {
48
+ expect(optionalVar(varTest)).to.be.undefined;
49
+ });
50
+ it('should return the default value when the env var is missing', () => {
51
+ expect(optionalVar(varTest, defaultValue)).to.equal(defaultValue);
52
+ });
53
+ it('should return the default value when the env var is empty', () => {
54
+ setVar('');
55
+ expect(optionalVar(varTest, defaultValue)).to.equal(defaultValue);
56
+ });
57
+ it('should return the value when the env var exists', () => {
58
+ const value = 'coconut';
59
+ setVar(value);
60
+ expect(optionalVar(varTest)).to.equal(value);
61
+ expect(optionalVar(varTest, defaultValue)).to.equal(value);
62
+ });
63
+ });
64
+
65
+ describe('intVar', () => {
66
+ const defaultValue = 'banana';
67
+ it('should throw when the env var is missing', () => {
68
+ expect(() => intVar(varTest)).to.throw;
69
+ });
70
+ it('should throw when the env var is invalid', () => {
71
+ setVar('date');
72
+ expect(() => intVar(varTest)).to.throw;
73
+ });
74
+ it('should return the default value when the env var is missing', () => {
75
+ expect(intVar(varTest, defaultValue)).to.equal(defaultValue);
76
+ });
77
+ it('should return the default value when the env var is empty', () => {
78
+ setVar('');
79
+ expect(intVar(varTest, defaultValue)).to.equal(defaultValue);
80
+ });
81
+ it('should return the value when the env var is a valid number', () => {
82
+ const value = 123;
83
+ setVar(`${value}`);
84
+ expect(intVar(varTest)).to.equal(value);
85
+ expect(intVar(varTest, defaultValue)).to.equal(value);
86
+ });
87
+ });
88
+
89
+ describe('boolVar', () => {
90
+ const defaultValue = 'banana';
91
+ it('should throw when the env var is missing', () => {
92
+ expect(() => boolVar(varTest)).to.throw;
93
+ });
94
+ it('should throw when the env var is invalid', () => {
95
+ setVar('date');
96
+ expect(() => boolVar(varTest)).to.throw;
97
+ });
98
+ it('should return the default value when the env var is missing', () => {
99
+ expect(boolVar(varTest, defaultValue)).to.equal(defaultValue);
100
+ });
101
+ it('should return the default value when the env var is empty', () => {
102
+ setVar('');
103
+ expect(boolVar(varTest, defaultValue)).to.equal(defaultValue);
104
+ });
105
+ it('should return the value when the env var is true', () => {
106
+ const value = true;
107
+ setVar(`${value}`);
108
+ expect(boolVar(varTest)).to.equal(value);
109
+ expect(boolVar(varTest, defaultValue)).to.equal(value);
110
+ });
111
+ it('should return the value when the env var is false', () => {
112
+ const value = false;
113
+ setVar(`${value}`);
114
+ expect(boolVar(varTest)).to.equal(value);
115
+ expect(boolVar(varTest, defaultValue)).to.equal(value);
116
+ });
117
+ });
118
+
119
+ describe('splitHostPort', () => {
120
+ const defaultValue = [];
121
+ it('should throw when the env var is missing', () => {
122
+ expect(() => splitHostPort(varTest)).to.throw;
123
+ });
124
+ it('should throw when the env var is invalid', () => {
125
+ setVar('date');
126
+ expect(() => splitHostPort(varTest)).to.throw;
127
+ });
128
+ it('should return the default value when the env var is missing', () => {
129
+ expect(splitHostPort(varTest, defaultValue)).to.equal(defaultValue);
130
+ });
131
+ it('should return the default value when the env var is empty', () => {
132
+ setVar('');
133
+ expect(splitHostPort(varTest, defaultValue)).to.equal(defaultValue);
134
+ });
135
+ it('should return the value when the env var is valid', () => {
136
+ const value = [
137
+ { host: '127.0.0.1', port: 8080 },
138
+ { host: '10.0.0.1', port: 80 },
139
+ ];
140
+ setVar('127.0.0.1:8080, 10.0.0.1:80');
141
+ expect(splitHostPort(varTest)).to.deep.equal(value);
142
+ expect(splitHostPort(varTest, defaultValue)).to.deep.equal(value);
143
+ });
144
+ });
145
+
146
+ describe('trustProxyVar', () => {
147
+ const defaultValue = '127.0.0.1';
148
+ it('should throw when the env var is missing', () => {
149
+ expect(() => trustProxyVar(varTest)).to.throw;
150
+ });
151
+ it('should throw when the env var is invalid', () => {
152
+ setVar('date');
153
+ expect(() => trustProxyVar(varTest)).to.throw;
154
+ });
155
+ it('should return the default value when the env var is missing', () => {
156
+ expect(trustProxyVar(varTest, defaultValue)).to.equal(defaultValue);
157
+ });
158
+ it('should throw when the default var is invalid', () => {
159
+ setVar('date');
160
+ expect(() => trustProxyVar(varTest, '')).to.throw;
161
+ });
162
+ it('should return the default value when the env var is empty', () => {
163
+ setVar('');
164
+ expect(trustProxyVar(varTest, defaultValue)).to.equal(defaultValue);
165
+ });
166
+ it('should return the value when the env var is a valid number', () => {
167
+ const value = 123;
168
+ setVar(`${value}`);
169
+ expect(trustProxyVar(varTest)).to.equal(value);
170
+ expect(trustProxyVar(varTest, defaultValue)).to.equal(value);
171
+ });
172
+ it('should return the value when the env var is true', () => {
173
+ const value = true;
174
+ setVar(`${value}`);
175
+ expect(trustProxyVar(varTest)).to.equal(value);
176
+ expect(trustProxyVar(varTest, defaultValue)).to.equal(value);
177
+ });
178
+ it('should return the value when the env var is false', () => {
179
+ const value = false;
180
+ setVar(`${value}`);
181
+ expect(trustProxyVar(varTest)).to.equal(value);
182
+ expect(trustProxyVar(varTest, defaultValue)).to.equal(value);
183
+ });
184
+ it('should return the value when the env var is valid', () => {
185
+ const value = '127.0.0.1, 10.0.0.1';
186
+ setVar(value);
187
+ expect(trustProxyVar(varTest)).to.deep.equal(value);
188
+ expect(trustProxyVar(varTest, defaultValue)).to.deep.equal(value);
189
+ });
190
+ });
191
+
192
+ describe('checkInt', () => {
193
+ it('should fail on an empty value', () => {
194
+ expect(checkInt('')).to.be.undefined;
195
+ });
196
+ it('should fail on a float', () => {
197
+ expect(checkInt('123.456')).to.be.undefined;
198
+ });
199
+ it('should fail on an exponent', () => {
200
+ expect(checkInt('1e3')).to.be.undefined;
201
+ });
202
+ it('should return the value on a valid integer', () => {
203
+ expect(checkInt('1000')).to.equal(1000);
204
+ });
205
+ it('should return the value on a valid integer with leading/trailing spaces', () => {
206
+ expect(checkInt(' 1000 ')).to.equal(1000);
207
+ });
208
+ });
209
+ });
210
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "commonjs",
4
+ "outDir": "build",
5
+ "noUnusedParameters": true,
6
+ "noUnusedLocals": true,
7
+ "sourceMap": true,
8
+ "strict": true,
9
+ "target": "es2019",
10
+ "declaration": true,
11
+ "skipLibCheck": true
12
+ },
13
+ "include": [
14
+ "src/**/*.ts"
15
+ ]
16
+ }