diff --git a/README.md b/README.md index 85658f7..f22bd0d 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,10 @@ Each validation function accepts an (optional) object with the following attribu helper (which is wrapped around a `devDefault` and therefore can't coexist with a separate dev value), `testDefault` can be combined with `default` and `devDefault` to provide distinct values for production, development, and test. +- `warning` - A message that is logged (without failing) when the env var is not set and a + fallback value (`default`, `devDefault`, or `testDefault`) is used. Combine with + `default: undefined` to allow the program to run without the env var while still + surfacing a warning. - `desc` - A string that describes the env var. - `example` - An example value for the env var. - `docs` - A URL that leads to more detailed documentation about the env var. diff --git a/src/core.ts b/src/core.ts index 86ae713..52db1cc 100644 --- a/src/core.ts +++ b/src/core.ts @@ -64,6 +64,7 @@ export function getSanitizedEnv( const cleanedEnv = {} as SpecsOutput const castedSpecs = specs as unknown as Record> const errors = {} as Record + const warnings = {} as Record const varKeys = Object.keys(castedSpecs) as Array const rawNodeEnv = readRawEnvValue(environment, 'NODE_ENV') @@ -78,26 +79,26 @@ export function getSanitizedEnv( // Use testDefault only when NODE_ENV is 'test'. Takes priority over devDefault and default. if (rawNodeEnv === 'test' && Object.hasOwn(spec, 'testDefault')) { cleanedEnv[k] = spec.testDefault - continue + } else { + // Use devDefault values only if NODE_ENV was explicitly set, and isn't 'production' + const usingDevDefault = + rawNodeEnv && rawNodeEnv !== 'production' && Object.hasOwn(spec, 'devDefault') + + if (usingDevDefault) { + cleanedEnv[k] = spec.devDefault + } else if ('default' in spec) { + cleanedEnv[k] = spec.default + } else { + // Throw error when no default value is provided + cleanedEnv[k] = undefined + throw new EnvMissingError(formatSpecDescription(spec)) + } } - // Use devDefault values only if NODE_ENV was explicitly set, and isn't 'production' - const usingDevDefault = - rawNodeEnv && rawNodeEnv !== 'production' && Object.hasOwn(spec, 'devDefault') - - if (usingDevDefault) { - cleanedEnv[k] = spec.devDefault - continue - } - - if ('default' in spec) { - cleanedEnv[k] = spec.default - continue - } - - // Throw error when no default value is provided - cleanedEnv[k] = undefined - throw new EnvMissingError(formatSpecDescription(spec)) + // A `warning` message is surfaced (without failing) whenever the env var was + // not set and a fallback value was used + if (spec.warning) warnings[k] = spec.warning + continue } cleanedEnv[k] = validateVar({ name: k as string, spec, rawValue }) @@ -122,7 +123,11 @@ export function getSanitizedEnv( } } - const reporter = options?.reporter || defaultReporter - reporter({ errors, env: cleanedEnv }) + // With `reporter: null`, errors are thrown instead of reported; in that case the + // caller opts out of all reporting, including warnings + if (options?.reporter !== null) { + const reporter = options?.reporter || defaultReporter + reporter({ errors, warnings, env: cleanedEnv }) + } return cleanedEnv } diff --git a/src/reporter.ts b/src/reporter.ts index cf8bea0..dbfa998 100644 --- a/src/reporter.ts +++ b/src/reporter.ts @@ -69,9 +69,19 @@ export const envalidErrorFormatter = ( } export const defaultReporter = ( - { errors = {} }: ReporterOptions, + { errors = {}, warnings = {} }: ReporterOptions, { onError, logger }: ExtraOptions = { logger: defaultLogger }, ) => { + // Warnings are informational, and never affect the exit behavior + const warningsOutput = Object.entries(warnings).map( + ([k, message]) => ` ${colors.blue(k)}: ${message}`, + ) + if (warningsOutput.length) { + warningsOutput.sort() + warningsOutput.unshift(` ${colors.yellow('Warnings')}:`) + logger([RULE, warningsOutput.join('\n'), RULE].join('\n')) + } + if (!Object.keys(errors).length) return envalidErrorFormatter(errors, logger) diff --git a/src/types.ts b/src/types.ts index 0316078..b27d8ca 100644 --- a/src/types.ts +++ b/src/types.ts @@ -29,6 +29,14 @@ export interface Spec { */ testDefault?: NonNullable | undefined + /** + * A message that is logged (without failing) when the env var is not set and a + * fallback value (`default`, `devDefault`, or `testDefault`) is used. + * Combine with `default: undefined` to allow the program to run without the env + * var while still surfacing a warning. + */ + warning?: string + /** * A function (env -> boolean) that allows an env var to be required only when certain * conditions are met with the rest of the env object. Use With default: undefined. @@ -149,6 +157,12 @@ export interface CleanedEnvAccessors { export interface ReporterOptions { errors: Partial> + /** + * Warning messages for env vars that were not set and had a fallback value + * (`default`, `devDefault`, or `testDefault`) used. Only populated for specs that + * include a `warning` message. + */ + warnings?: Partial> env: unknown } diff --git a/tests/reporter.test.ts b/tests/reporter.test.ts index f56b19a..5fabaf6 100644 --- a/tests/reporter.test.ts +++ b/tests/reporter.test.ts @@ -120,6 +120,93 @@ describe('default reporter', () => { }) }) +describe('default reporter with warnings', () => { + let logger: MockedFunction + let exitSpy: any = null + + beforeEach(() => { + logger = vi.fn() + exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any) + }) + + afterEach(() => { + exitSpy?.mockRestore() + }) + + test('prints warnings without exiting when there are no errors', () => { + defaultReporter( + { + errors: {}, + warnings: { FOO: 'FOO is not set' }, + env: {}, + }, + { logger }, + ) + + expect(logger).toHaveBeenCalledTimes(1) + const output = logger?.mock?.calls?.[0]?.[0] + expect(output).toMatch(/Warnings\S*:/) + expect(output).toMatch(/FOO\S*: FOO is not set/) + expect(output).not.toMatch(/Exiting with error code 1/) + expect(exitSpy).toHaveBeenCalledTimes(0) + }) + + test('prints both warnings and errors, and still exits when errors exist', () => { + defaultReporter( + { + errors: { FOO: new EnvMissingError() }, + warnings: { BAR: 'BAR is not set' }, + env: {}, + }, + { logger }, + ) + + expect(logger).toHaveBeenCalledTimes(3) + + const warningsOutput = logger?.mock?.calls?.[0]?.[0] + expect(warningsOutput).toMatch(/Warnings\S*:/) + expect(warningsOutput).toMatch(/BAR\S*: BAR is not set/) + + const errorsOutput = logger?.mock?.calls?.[1]?.[0] + expect(errorsOutput).toMatch(/Missing\S+ environment variables:/) + expect(errorsOutput).not.toMatch(/Warnings\S*:/) + + const exitOutput = logger?.mock?.calls?.[2]?.[0] + expect(exitOutput).toMatch(/Exiting with error code 1/) + + expect(exitSpy).toHaveBeenCalledTimes(1) + expect(exitSpy).toHaveBeenCalledWith(1) + }) + + test('sorts multiple warnings', () => { + defaultReporter( + { + errors: {}, + warnings: { ZEBRA: 'z', ALPACA: 'a' }, + env: {}, + }, + { logger }, + ) + + const output = logger?.mock?.calls?.[0]?.[0] + expect(output.indexOf(': a')).toBeGreaterThan(-1) + expect(output.indexOf(': a')).toBeLessThan(output.indexOf(': z')) + }) + + test('does nothing when there are no errors or warnings', () => { + defaultReporter( + { + errors: {}, + warnings: {}, + env: { FOO: 'great success' }, + }, + { logger }, + ) + expect(logger).toHaveBeenCalledTimes(0) + expect(exitSpy).toHaveBeenCalledTimes(0) + }) +}) + describe('envalidErrorFormatter', () => { let logger: MockedFunction diff --git a/tests/requiredWhen.test.ts b/tests/requiredWhen.test.ts index e1ac8f4..8be4179 100644 --- a/tests/requiredWhen.test.ts +++ b/tests/requiredWhen.test.ts @@ -30,6 +30,7 @@ describe('requiredWhen', () => { id: undefined, }, errors: {}, + warnings: {}, }) }) @@ -51,6 +52,7 @@ describe('requiredWhen', () => { id: undefined, }, errors: {}, + warnings: {}, }) cleanEnv( @@ -70,6 +72,7 @@ describe('requiredWhen', () => { autoExtractId: undefined, }, errors: {}, + warnings: {}, }) }) @@ -102,6 +105,7 @@ describe('requiredWhen', () => { ), ), }, + warnings: {}, }) }) @@ -126,6 +130,7 @@ describe('requiredWhen', () => { id: 123, }, errors: {}, + warnings: {}, }) }) @@ -152,6 +157,7 @@ describe('requiredWhen', () => { errors: { id: new EnvError(`Invalid number input: "abc"`), }, + warnings: {}, }) }) }) diff --git a/tests/warning.test.ts b/tests/warning.test.ts new file mode 100644 index 0000000..225554e --- /dev/null +++ b/tests/warning.test.ts @@ -0,0 +1,134 @@ +import { describe, test, expect, vi, beforeEach } from 'vitest' +import { expectTypeOf } from 'expect-type' +import { cleanEnv, defaultReporter, EnvMissingError, str } from '../src' +import { formatSpecDescription } from '../src/core' + +vi.mock('../src/reporter') +const mockedDefaultReporter: vi.Mock = >defaultReporter +mockedDefaultReporter.mockImplementation(() => {}) + +describe('warning option', () => { + beforeEach(() => { + mockedDefaultReporter.mockClear() + }) + + test('warning is recorded when the env var is missing and a default is used', () => { + cleanEnv({}, { FOO: str({ default: 'fallback', warning: 'FOO is not set' }) }) + + expect(mockedDefaultReporter).toHaveBeenCalledTimes(1) + expect(mockedDefaultReporter).toHaveBeenCalledWith({ + env: { FOO: 'fallback' }, + errors: {}, + warnings: { FOO: 'FOO is not set' }, + }) + }) + + test('no warning is recorded when the env var is set', () => { + cleanEnv({ FOO: 'value' }, { FOO: str({ default: 'fallback', warning: 'FOO is not set' }) }) + + expect(mockedDefaultReporter).toHaveBeenCalledTimes(1) + expect(mockedDefaultReporter).toHaveBeenCalledWith({ + env: { FOO: 'value' }, + errors: {}, + warnings: {}, + }) + }) + + test('empty string env value counts as missing', () => { + cleanEnv({ FOO: ' ' }, { FOO: str({ default: 'fallback', warning: 'FOO is not set' }) }) + + expect(mockedDefaultReporter).toHaveBeenCalledTimes(1) + expect(mockedDefaultReporter).toHaveBeenCalledWith({ + env: { FOO: 'fallback' }, + errors: {}, + warnings: { FOO: 'FOO is not set' }, + }) + }) + + test('warning is recorded when devDefault is used', () => { + cleanEnv( + { NODE_ENV: 'development' }, + { FOO: str({ devDefault: 'dev-fallback', warning: 'FOO is not set' }) }, + ) + + expect(mockedDefaultReporter).toHaveBeenCalledTimes(1) + expect(mockedDefaultReporter).toHaveBeenCalledWith({ + env: { FOO: 'dev-fallback' }, + errors: {}, + warnings: { FOO: 'FOO is not set' }, + }) + }) + + test('warning is recorded when testDefault is used', () => { + cleanEnv( + { NODE_ENV: 'test' }, + { FOO: str({ testDefault: 'test-fallback', warning: 'FOO is not set' }) }, + ) + + expect(mockedDefaultReporter).toHaveBeenCalledTimes(1) + expect(mockedDefaultReporter).toHaveBeenCalledWith({ + env: { FOO: 'test-fallback' }, + errors: {}, + warnings: { FOO: 'FOO is not set' }, + }) + }) + + test('no warning in production when only devDefault is provided (missing var errors)', () => { + cleanEnv( + { NODE_ENV: 'production' }, + { FOO: str({ devDefault: 'dev-fallback', warning: 'FOO is not set' }) }, + ) + + expect(mockedDefaultReporter).toHaveBeenCalledTimes(1) + expect(mockedDefaultReporter).toHaveBeenCalledWith({ + env: { FOO: undefined }, + errors: { + FOO: new EnvMissingError(formatSpecDescription(str({ devDefault: 'dev-fallback' }))), + }, + warnings: {}, + }) + }) + + test('missing var without any default errors even when a warning is provided', () => { + cleanEnv({}, { FOO: str({ warning: 'FOO is not set' }) }) + + expect(mockedDefaultReporter).toHaveBeenCalledTimes(1) + expect(mockedDefaultReporter).toHaveBeenCalledWith({ + env: { FOO: undefined }, + errors: { FOO: new EnvMissingError(formatSpecDescription(str())) }, + warnings: {}, + }) + }) + + test('default: undefined + warning allows the program to run without the env var', () => { + cleanEnv({}, { FOO: str({ default: undefined, warning: 'FOO is not set; feature disabled' }) }) + + expect(mockedDefaultReporter).toHaveBeenCalledTimes(1) + expect(mockedDefaultReporter).toHaveBeenCalledWith({ + env: { FOO: undefined }, + errors: {}, + warnings: { FOO: 'FOO is not set; feature disabled' }, + }) + }) + + test('reporter: null skips warning reporting and does not throw when only warnings exist', () => { + const env = cleanEnv( + {}, + { FOO: str({ default: 'fallback', warning: 'FOO is not set' }) }, + { reporter: null }, + ) + + expect(mockedDefaultReporter).not.toHaveBeenCalled() + expect(env.FOO).toEqual('fallback') + }) + + test('types: warning with default: undefined yields an optional output', () => { + const env = cleanEnv({}, { FOO: str({ default: undefined, warning: 'FOO is not set' }) }) + expectTypeOf(env.FOO).toEqualTypeOf() + }) + + test('types: warning alone keeps the output required', () => { + const env = cleanEnv({ FOO: 'value' }, { FOO: str({ warning: 'FOO is not set' }) }) + expectTypeOf(env.FOO).toEqualTypeOf() + }) +})