Permalink
Browse files

Use prettier for style

  • Loading branch information...
SimenB committed Aug 22, 2017
1 parent 2af1e16 commit 3f8ed00568bcbf8b96c4656f7296c8aee4f3ec23
Showing with 290 additions and 221 deletions.
  1. +60 −83 .eslintrc.js
  2. +3 −3 example/env.js
  3. +41 −25 index.js
  4. +3 −1 lib/reporter.js
  5. +25 −23 lib/strictProxy.js
  6. +13 −14 lib/validators.js
  7. +4 −2 package.json
  8. +51 −25 tests/test_basics.js
  9. +14 −7 tests/test_dotenv.js
  10. +1 −2 tests/test_reporter.js
  11. +54 −24 tests/test_strict.js
  12. +19 −6 tests/test_types.js
  13. +2 −6 tests/test_typescript.js
View
@@ -1,105 +1,82 @@
const [OFF, WARN, ERR] = [0, 1, 2]
module.exports = {
extends: "eslint:recommended",
extends: 'eslint:recommended',
plugins: ['prettier'],
parserOptions: {
"impliedStrict": true,
"sourceType": "module",
"ecmaVersion": 7
impliedStrict: true,
sourceType: 'module',
ecmaVersion: 7
},
env: {
"es6": true,
"node": true,
"browser": true
es6: true,
node: true,
browser: true
},
globals: {},
rules: {
// Possible errors & best practices
"complexity": [WARN, 7],
//"consistent-return": ERR,
"curly": [ERR, "multi-line"],
"dot-notation": WARN,
"eqeqeq": [ERR, "allow-null"],
"linebreak-style": [ERR, "unix"],
"no-empty": WARN,
"no-else-return": OFF,
"no-extra-bind": ERR,
//"no-magic-numbers": [ERR, { "ignore": [0, 1, 2, -1] }],
"no-param-reassign": WARN,
"no-throw-literal": WARN,
"no-warning-comments": WARN,
"no-unexpected-multiline": ERR,
"radix": [WARN, "as-needed"],
"wrap-iife": [WARN, "outside"],
"yoda": ERR,
complexity: [WARN, 7],
// "consistent-return": ERR,
'dot-notation': WARN,
eqeqeq: [ERR, 'allow-null'],
'linebreak-style': [ERR, 'unix'],
'no-empty': WARN,
'no-else-return': OFF,
'no-extra-bind': ERR,
// "no-magic-numbers": [ERR, { "ignore": [0, 1, 2, -1] }],
'no-param-reassign': WARN,
'no-throw-literal': WARN,
'no-warning-comments': WARN,
'no-unexpected-multiline': ERR,
radix: [WARN, 'as-needed'],
'wrap-iife': [WARN, 'outside'],
yoda: ERR,
// Variables
"init-declarations": [WARN, "always"],
"no-redeclare": WARN,
"no-shadow": WARN,
"no-undef-init": ERR,
"no-use-before-define": WARN,
'init-declarations': [WARN, 'always'],
'no-redeclare': WARN,
'no-shadow': WARN,
'no-undef-init': ERR,
'no-use-before-define': WARN,
// Node/commonjs
"callback-return": WARN,
"handle-callback-err": ERR,
'callback-return': WARN,
'handle-callback-err': ERR,
// Style
"array-bracket-spacing": [ERR, "never"],
"block-spacing": ERR,
"brace-style": [WARN, "1tbs", { "allowSingleLine": true }],
"camelcase": [ERR, { "properties": "never" }],
"comma-dangle": OFF,
"comma-spacing": ERR,
"comma-style": ERR,
"eol-last": ERR,
"indent": [OFF, 4], // Definitely want to enable this later
//"key-spacing": ERR,
"keyword-spacing": ERR,
"max-depth": [ERR, 4],
"max-len": [WARN, 100, 4, { "ignoreUrls": true, "ignoreComments": true }],
"max-nested-callbacks": [WARN, 4],
"new-cap": OFF,
"no-bitwise": OFF, // Could enable later, but we do use bitwise ops in a few places
"no-case-declarations": OFF,
"no-console": WARN,
"no-lonely-if": WARN,
"no-multiple-empty-lines": [ERR, { "max": 3 }],
"no-new-object": ERR,
"no-restricted-syntax": [ERR, "WithStatement"],
"no-spaced-func": ERR,
"no-trailing-spaces": ERR,
"no-unneeded-ternary": ERR,
"no-unused-vars": [WARN, {"vars": "all", "args": "none"}], // Should be err, but can trigger on commented-out code
"object-curly-spacing": [OFF, "always"],
"one-var": [WARN, "never"],
"operator-linebreak": WARN,
"padded-blocks": [WARN, "never"],
"quotes": [ERR, "single"],
"quote-props": [WARN, "as-needed"],
"semi": [ERR, "never"],
"semi-spacing": ERR,
"space-before-blocks": ERR,
"space-before-function-paren": [ERR, "never"],
"space-in-parens": ERR,
"space-infix-ops": WARN,
"spaced-comment": [ERR, "always"],
camelcase: [ERR, { properties: 'never' }],
'comma-dangle': OFF,
'max-depth': [ERR, 4],
'max-nested-callbacks': [WARN, 4],
'new-cap': OFF,
'no-bitwise': OFF, // Could enable later, but we do use bitwise ops in a few places
'no-case-declarations': OFF,
'no-console': WARN,
'no-lonely-if': WARN,
'no-new-object': ERR,
'no-restricted-syntax': [ERR, 'WithStatement'],
'no-unneeded-ternary': ERR,
'no-unused-vars': [WARN, { vars: 'all', args: 'none' }], // Should be err, but can trigger on commented-out code
'object-curly-spacing': [OFF, 'always'],
'one-var': [WARN, 'never'],
'spaced-comment': [ERR, 'always'],
// ES6
// Any rules here set to OFF are things to turn on eventually
"arrow-spacing": ERR,
"no-confusing-arrow": ERR,
"no-const-assign": ERR,
"no-dupe-class-members": ERR,
"no-var": ERR,
"object-shorthand": OFF,
"prefer-arrow-callback": OFF,
"prefer-const": WARN,
"prefer-spread": OFF,
"prefer-template": OFF,
'no-confusing-arrow': ERR,
'no-const-assign': ERR,
'no-dupe-class-members': ERR,
'no-var': ERR,
'object-shorthand': OFF,
'prefer-arrow-callback': OFF,
'prefer-const': WARN,
'prefer-spread': OFF,
'prefer-template': OFF,
// JSDoc
//"require-jsdoc": OFF,
//"valid-jsdoc": WARN
},
// "require-jsdoc": OFF,
// "valid-jsdoc": WARN
'prettier/prettier': [ERR, { singleQuote: true, semi: false, printWidth: 100, tabWidth: 4 }]
}
}
View
@@ -1,10 +1,10 @@
const envalid = require('..')
module.exports = envalid.cleanEnv(process.env, {
HOST: envalid.host({ default: '127.0.0.1' }),
PORT: envalid.port({ default: 3000, desc: 'The port to start the server on' }),
HOST: envalid.host({ default: '127.0.0.1' }),
PORT: envalid.port({ default: 3000, desc: 'The port to start the server on' }),
// For this example, the MESSAGE env var will be read from the .env
// file in this directory (so the default value won't be used):
MESSAGE: envalid.str({ default: 'Hello, world' })
MESSAGE: envalid.str({ default: 'Hello, world' })
})
View
@@ -1,5 +1,16 @@
const { EnvError, EnvMissingError, makeValidator,
bool, num, str, json, url, email, host, port } = require('./lib/validators')
const {
EnvError,
EnvMissingError,
makeValidator,
bool,
num,
str,
json,
url,
email,
host,
port
} = require('./lib/validators')
const extend = (x = {}, y = {}) => Object.assign({}, x, y)
@@ -28,7 +39,6 @@ function validateVar({ spec = {}, name, rawValue }) {
return value
}
// Format a string error message for when a required env var is missing
function formatSpecDescription(spec) {
const egText = spec.example ? ` (eg. "${spec.example}")` : ''
@@ -61,9 +71,8 @@ function cleanEnv(inputEnv, specs = {}, options = {}) {
let output = {}
let defaultNodeEnv = ''
const errors = {}
const env = (options.dotEnvPath !== null)
? extendWithDotEnv(inputEnv, options.dotEnvPath)
: inputEnv
const env =
options.dotEnvPath !== null ? extendWithDotEnv(inputEnv, options.dotEnvPath) : inputEnv
const varKeys = Object.keys(specs)
// If validation for NODE_ENV isn't specified, use the default validation:
@@ -77,18 +86,19 @@ function cleanEnv(inputEnv, specs = {}, options = {}) {
for (const k of varKeys) {
const spec = specs[k]
const usingDevDefault = (env.NODE_ENV !== 'production') && (spec.hasOwnProperty('devDefault'))
const usingDevDefault = env.NODE_ENV !== 'production' && spec.hasOwnProperty('devDefault')
const devDefault = usingDevDefault ? spec.devDefault : undefined
let rawValue = env[k]
if (rawValue === undefined) {
rawValue = (devDefault === undefined ? spec.default : devDefault)
rawValue = devDefault === undefined ? spec.default : devDefault
}
// Default values can be anything falsy (including an explicitly set undefined), without
// triggering validation errors:
const usingFalsyDefault = ((spec.hasOwnProperty('default')) && (spec.default === rawValue)) ||
(usingDevDefault && (devDefault === rawValue))
const usingFalsyDefault =
(spec.hasOwnProperty('default') && spec.default === rawValue) ||
(usingDevDefault && devDefault === rawValue)
try {
if (rawValue === testOnlySymbol) {
@@ -112,14 +122,12 @@ function cleanEnv(inputEnv, specs = {}, options = {}) {
// If we need to run Object.assign() on output, we must do it before the
// defineProperties() call, otherwise the properties would be lost
output = options.strict
? output
: extend(env, output)
output = options.strict ? output : extend(env, output)
Object.defineProperties(output, {
isDev: { value: (defaultNodeEnv || output.NODE_ENV) === 'development' },
isDev: { value: (defaultNodeEnv || output.NODE_ENV) === 'development' },
isProduction: { value: (defaultNodeEnv || output.NODE_ENV) === 'production' },
isTest: { value: (defaultNodeEnv || output.NODE_ENV) === 'test' }
isTest: { value: (defaultNodeEnv || output.NODE_ENV) === 'test' }
})
if (options.transformer) {
@@ -134,23 +142,31 @@ function cleanEnv(inputEnv, specs = {}, options = {}) {
return Object.freeze(output)
}
/**
* Utility function for providing default values only when NODE_ENV=test
*
* For more context, see https://github.com/af/envalid/issues/32
*/
const testOnly = defaultValueForTests => {
return process.env.NODE_ENV === 'test'
? defaultValueForTests
: testOnlySymbol
return process.env.NODE_ENV === 'test' ? defaultValueForTests : testOnlySymbol
}
module.exports = {
cleanEnv, makeValidator, // core API
EnvError, EnvMissingError, // error subclasses
testOnly, // utility function(s)
bool, num, str, json, host, port, // built-in validators
url, email,
// core API
cleanEnv,
makeValidator,
// error subclasses
EnvError,
EnvMissingError,
// utility function(s)
testOnly,
// built-in validators
bool,
num,
str,
json,
host,
port,
url,
email
}
View
@@ -30,7 +30,9 @@ module.exports = function defaultReporter({ errors = {}, env = {} }) {
missingVarsOutput.join('\n'),
chalk.yellow('\n Exiting with error code 1'),
RULE
].filter(x => !!x).join('\n')
]
.filter(x => !!x)
.join('\n')
console.error(output)
process.exit(1)
View
@@ -1,6 +1,5 @@
const meant = require('meant')
/**
* Suggest similar env var(s) if possible; for use when an invalid var is accessed.
*/
@@ -20,28 +19,31 @@ const didYouMean = (scmd, commands) => {
*
* @return {Object} - Proxied environment object with get/set traps
*/
module.exports = (envObj, originalEnv) => new Proxy(envObj, {
get(target, name) {
// These checks are needed because calling console.log on a
// proxy that throws crashes the entire process. This whitelists
// the necessary properties for `console.log(envObj)` to work.
if (['inspect', Symbol.toStringTag].includes(name)) return envObj[name]
if (name.toString() === 'Symbol(util.inspect.custom)') return envObj[name]
const varExists = envObj.hasOwnProperty(name)
if (!varExists) {
if (originalEnv.hasOwnProperty(name)) {
throw new ReferenceError(`[envalid] Env var ${name} was accessed but not validated. This var is set in the environment; please add an envalid validator for it.`)
module.exports = (envObj, originalEnv) =>
new Proxy(envObj, {
get(target, name) {
// These checks are needed because calling console.log on a
// proxy that throws crashes the entire process. This whitelists
// the necessary properties for `console.log(envObj)` to work.
if (['inspect', Symbol.toStringTag].includes(name)) return envObj[name]
if (name.toString() === 'Symbol(util.inspect.custom)') return envObj[name]
const varExists = envObj.hasOwnProperty(name)
if (!varExists) {
if (originalEnv.hasOwnProperty(name)) {
throw new ReferenceError(
`[envalid] Env var ${name} was accessed but not validated. This var is set in the environment; please add an envalid validator for it.`
)
}
didYouMean(name, Object.keys(envObj))
throw new ReferenceError(`[envalid] Env var not found: ${name}`)
}
didYouMean(name, Object.keys(envObj))
throw new ReferenceError(`[envalid] Env var not found: ${name}`)
}
return envObj[name]
},
return envObj[name]
},
set(target, name) {
throw new TypeError(`[envalid] Attempt to mutate environment value: ${name}`)
},
})
set(target, name) {
throw new TypeError(`[envalid] Attempt to mutate environment value: ${name}`)
}
})
Oops, something went wrong.

0 comments on commit 3f8ed00

Please sign in to comment.