env/load.ts

Generic environment loading from @fuzdev/fuz_schema object schemas.

Provides load_env, which reads each key of an object schema with a getter and validates the values. Apps handle error messages themselves (they're always app-specific).

view source

Declarations
#

3 declarations

EnvValidationError
#

env/load.ts view source

import {EnvValidationError} from '@fuzdev/fuz_app/env/load.js';

Error thrown when environment validation fails.

Contains structured information for apps to format their own error messages.

inheritance

extends: Error

raw

The raw env values that were read, every key of the schema, unset ones as undefined.

type Record<string, string | undefined>

readonly

issues

The validation issues, which hold no env value, only the keys in their paths.

type SchemaIssue[]

readonly

all_undefined

True if every env var was undefined (nothing loaded).

type boolean

readonly

constructor

type new (raw: Record<string, string | undefined>, issues: SchemaIssue[]): EnvValidationError

raw

type Record<string, string | undefined>

issues

type SchemaIssue[]

format_issues

Format the validation issues as human-readable strings.

type (): string[]

returns string[]

array of formatted issue strings like "PORT: expected decimal digits, received string"

load_env
#

env/load.ts view source

<T extends Schema<Record<string, unknown>, any>>(schema: T, get_env: (key: string) => string | undefined): Infer<T> import {load_env} from '@fuzdev/fuz_app/env/load.js';

Load and validate env vars against a @fuzdev/fuz_schema object schema.

Reads every key of the schema's entries with get_env. An unset var is left out of the object parsed, not given as undefined, so it reads as a missing key: a pipe that starts with an optional runs none of its steps for it, as it would for an absent key of any object. raw still lists it, as undefined.

schema

an object schema (object, strip_object, ..., under any wrappers) of the expected env vars

type T

get_env

function to read an env var by key

type (key: string) => string | undefined

returns

Infer<T>

validated env object

generics

load_env<T extends Schema<Record<string, unknown>, any>>
T
constraint Schema<Record<string, unknown>, any>

throws

  • TypeError - if `schema` is not an object schema
  • EnvValidationError - if validation fails

log_env_validation_error
#

env/load.ts view source

(error: EnvValidationError, label?: string | undefined): void import {log_env_validation_error} from '@fuzdev/fuz_app/env/load.js';

Log formatted env validation issues to stderr.

Handles the common case: labels each issue with an optional prefix. Callers who want app-specific "getting started" instructions should check error.all_undefined before calling this.

error

the env validation error

label?

optional prefix for log lines (e.g., 'server', 'env')

type string
optional

returns

void