# Environment Validation

# Environment Validation

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [src/env/__tests__/env-validator.test.ts](src/env/__tests__/env-validator.test.ts)
- [src/env/env-validator.ts](src/env/env-validator.ts)

</details>



The `env` module provides a centralized mechanism for validating process environment variables. Its primary purpose is to replace scattered, manual checks across microservices with a structured schema definition and uniform error reporting. Unlike the `Config` module, which interacts with external data sources, this module is pure and only operates on `process.env` [src/env/env-validator.ts:15-21]().

## Core Components

The validation logic is built around three primary structures:

1.  **`EnvSchema`**: A dictionary defining the requirements for each environment variable, including its necessity, fallback value, and a human-readable description [src/env/env-validator.ts:1-7]().
2.  **`validateEnv`**: A non-throwing function that evaluates the current `process.env` against a schema and returns a detailed result [src/env/env-validator.ts:22-35]().
3.  **`requireEnv`**: A wrapper that invokes `validateEnv` but throws an `Error` containing all validation failures if the environment is invalid [src/env/env-validator.ts:40-46]().

### Data Structures

| Interface | Property | Type | Description |
| :--- | :--- | :--- | :--- |
| **`EnvSchema`** | `required` | `boolean` | If `true`, validation fails if the variable is `undefined` or `""`. |
| | `default` | `string` | (Optional) Value to use if the variable is missing from `process.env`. |
| | `description` | `string` | (Optional) Human-readable text appended to error messages. |
| **`EnvValidationResult`** | `valid` | `boolean` | `true` if all requirements are met. |
| | `errors` | `string[]` | List of error messages for missing required variables. |
| | `env` | `Record<string, string \| undefined>` | The resolved environment (including defaults). |

**Sources:** [src/env/env-validator.ts:1-13]()

## Validation Flow

The validation logic iterates through the provided `EnvSchema`, resolves values from `process.env`, and applies defaults before checking the `required` constraint.

### Validation Sequence
This diagram illustrates how `validateEnv` processes a schema against `process.env`.

```mermaid
graph TD
    subgraph "Natural Language Space"
        A["Developer defines requirements"]
        B["Runtime Environment"]
        C["Validation Report"]
    end

    subgraph "Code Entity Space"
        A --- D["EnvSchema"]
        B --- E["process.env"]
        D --> F["validateEnv()"]
        E --> F
        F --> G["EnvValidationResult"]
        G --- C
    end

    subgraph "Logic Flow"
        F1["Read process.env[key]"]
        F2{"Is Value Null?"}
        F3["Apply spec.default"]
        F4{"Is Required & Empty?"}
        F5["Push to errors[]"]
        
        F --> F1 --> F2
        F2 -- "Yes" --> F3 --> F4
        F2 -- "No" --> F4
        F4 -- "Yes" --> F5
    end
```
**Sources:** [src/env/env-validator.ts:22-35]()

## Usage Patterns

### Soft Validation (`validateEnv`)
Use `validateEnv` when the application needs to handle missing variables gracefully or report errors through a specific logging channel without crashing.

```typescript
import { validateEnv } from "@primebrick/sdk";

const result = validateEnv({
  PORT: { required: false, default: "3000" },
  DB_URL: { required: true, description: "Connection string for Postgres" }
});

if (!result.valid) {
  console.error("Missing variables:", result.errors);
}
```
**Sources:** [src/env/env-validator.ts:22-35](), [src/env/__tests__/env-validator.test.ts:15-21]()

### Strict Validation (`requireEnv`)
Use `requireEnv` at the entry point of a microservice to ensure the process fails fast if the environment is misconfigured. It aggregates all errors into a single exception [src/env/env-validator.ts:40-46]().

```mermaid
sequenceDiagram
    participant App as "Microservice Entry"
    participant SDK as "requireEnv()"
    participant Proc as "process.env"

    App->>SDK: requireEnv(schema)
    SDK->>Proc: Access variables
    alt Validation Fails
        SDK-->>App: throw Error("Environment validation failed...")
    else Validation Succeeds
        SDK-->>App: return Record<string, string>
    end
```
**Sources:** [src/env/env-validator.ts:40-46](), [src/env/__tests__/env-validator.test.ts:75-83]()

## Behavior Rules

1.  **Empty Strings**: If a variable is set to an empty string (`""`) and is marked as `required: true`, validation will fail [src/env/env-validator.ts:29-31](), [src/env/__tests__/env-validator.test.ts:31-35]().
2.  **Default Priority**: The value in `process.env` always takes precedence over the `default` field in the schema [src/env/env-validator.ts:27-28](), [src/env/__tests__/env-validator.test.ts:44-48]().
3.  **Error Formatting**: If a `description` is provided, it is appended in parentheses to the error message (e.g., `VARIABLE is required (needed for X)`) [src/env/env-validator.ts:30](), [src/env/__tests__/env-validator.test.ts:23-29]().

**Sources:** [src/env/env-validator.ts:22-46](), [src/env/__tests__/env-validator.test.ts:1-83]()

---
