@enclosurejs/config
v1.1.0
Published
Immutable typed runtime configuration for Enclosure apps
Readme
@enclosurejs/config — Immutable typed runtime configuration
[!IMPORTANT] This package provides a single, frozen, fully-typed configuration object available from the earliest startup phase. One module — all config layers merged. Zero external dependencies. Works with any backend.
The Problem
Every application needs a runtime configuration object — API URLs, feature flags, build mode, debug toggles. Assembling this from environment variables, build metadata, and defaults means ad-hoc merging code, inconsistent coercion, and mutable objects that drift after startup.
@enclosurejs/config solves this with buildConfig() — a pure function that shallow-merges four layers (defaults < stamp < env < overrides), coerces env vars by type, and returns a frozen object. createConfigModule() wraps it as an Enclosure Module that provides ConfigToken for DI consumers. mapEnv() is exposed separately for use outside the module system.
Architecture
┌─────────────────────────────────────────────────────────────────┐
│ Startup │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐ │
│ │ defaults │ │ stamp │ │ env vars │ │ overrides │ │
│ │ (T) │ │ (mapped) │ │ (mapped) │ │ (CLI, test) │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────┬───────┘ │
│ │ │ │ │ │
│ └──────┬───────┴─────────────┴───────────────┘ │
│ ▼ │
│ buildConfig(options) │
│ │ │
│ Object.freeze(merged) │
│ │ │
│ ctx.provide(ConfigToken, config) │
└──────────────┼──────────────────────────────────────────────────┘
▼
┌─────────────────────────────────────────────────────────────────┐
│ Runtime │
│ │
│ const config = ctx.use(ConfigToken) │
│ config.apiUrl // "https://prod.io" │
│ config.debug // false │
│ config.port // 9090 │
│ // config is Readonly<T> — mutation throws in strict mode │
└─────────────────────────────────────────────────────────────────┘Merge order (last wins, shallow): defaults < stamp (mapped) < env (mapped) < overrides.
Dependency rule: @enclosurejs/config imports only @enclosurejs/core (peer) and optionally @enclosurejs/stamp (for the Stamp type). No external runtime dependencies.
Quick Start
1. Install
pnpm add @enclosurejs/config2a. Module usage (with Enclosure DI)
import { createApp } from '@enclosurejs/core';
import { createConfigModule, ConfigToken } from '@enclosurejs/config';
import stamp from 'virtual:stamp';
const app = createApp({
modules: [
createConfigModule({
defaults: {
apiUrl: 'http://localhost:3000',
debug: false,
mode: 'development' as string,
version: '0.0.0',
},
stamp,
mapStamp: (s) => ({ mode: s.mode, version: s.version, debug: s.dev || s.dirty }),
env: import.meta.env,
envMap: { apiUrl: 'VITE_API_URL' },
}),
],
});// downstream module
const dbModule: Module = {
id: 'database',
requires: ['config'],
install(ctx) {
const config = ctx.context.use(ConfigToken);
// config is Readonly<T>, fully typed
},
};2b. Standalone usage (without DI)
import { buildConfig } from '@enclosurejs/config';
const config = buildConfig({
defaults: { apiUrl: 'http://localhost:3000', debug: false, port: 8080 },
env: process.env,
envMap: { apiUrl: 'API_URL', port: 'PORT', debug: 'DEBUG' },
overrides: { debug: true },
});
// config is frozen and typed2c. Env mapping only
import { mapEnv } from '@enclosurejs/config';
const partial = mapEnv(
{ port: 8080, debug: false, name: 'app' },
{ port: 'PORT', debug: 'DEBUG', name: 'APP_NAME' },
process.env,
);
// partial: { port: 9090, debug: true } (only keys with matching env vars)How It Works
Layer Merging
buildConfig() performs a shallow Object.freeze({ ...defaults, ...stampPartial, ...envPartial, ...overrides }). Each layer is optional — omit stamp/mapStamp or env/envMap and those layers are skipped. Both members of a pair must be present: stamp without mapStamp (or vice versa) is a no-op, same for env/envMap.
Env Var Coercion
mapEnv() coerces environment variable strings into the correct type based on the corresponding default value:
- boolean —
"true"or"1"→true, everything else →false - number —
parseFloat(), skipped if result isNaN - string — used as-is
- other types (object, array) — silently ignored
Missing or undefined env vars are skipped entirely.
Stamp Integration
The mapStamp function is user-supplied — the framework provides the Stamp object, the app decides which fields map to config keys. This keeps the config package decoupled from stamp internals.
Freeze Guarantee
The returned config is Object.freeze'd — mutation throws in strict mode, silently fails otherwise. Config is immutable after startup by design.
API
Exports (@enclosurejs/config)
| Export | Kind | Purpose |
| -------------------- | -------- | ------------------------------------------------------------------- |
| createConfigModule | function | Module factory — merges layers, provides ConfigToken |
| ConfigToken | token | DI token to resolve the frozen config object |
| buildConfig | function | Pure merge + freeze — usable outside the module system |
| mapEnv | function | Coerces env vars into a typed partial config object |
| ConfigOptions | type | Configuration for buildConfig / createConfigModule |
| EnvMapping | type | Maps config keys to env var names |
| EnvSource | type | Environment variable source (Record<string, string \| undefined>) |
ConfigOptions<T>
| Field | Type | Required | Description |
| ----------- | ------------------------------ | -------- | --------------------------------------------------------------- |
| defaults | T | Yes | Full default config object — TypeScript infers T from this |
| env | EnvSource | No | Environment variables source (process.env, import.meta.env) |
| envMap | EnvMapping<T> | No | Maps config keys to env var names |
| stamp | Stamp | No | Build metadata from @enclosurejs/stamp |
| mapStamp | (stamp: Stamp) => Partial<T> | No | Maps stamp fields into config fields |
| overrides | Partial<T> | No | Highest-priority overrides (CLI flags, test fixtures) |
Configuration
No configuration files. The only required field is defaults — everything else is opt-in:
// Minimal — just defaults
createConfigModule({ defaults: { apiUrl: 'http://localhost' } });
// With env vars
createConfigModule({
defaults: { port: 3000, debug: false },
env: process.env,
envMap: { port: 'PORT', debug: 'DEBUG' },
});
// With stamp + env + overrides
createConfigModule({
defaults: { apiUrl: 'http://localhost', mode: 'dev', version: '0.0.0' },
stamp,
mapStamp: (s) => ({ mode: s.mode, version: s.version }),
env: import.meta.env,
envMap: { apiUrl: 'VITE_API_URL' },
overrides: { debug: true },
});Types Exported
| Type | Used by |
| --------------- | -------------------------------------------------------- |
| ConfigOptions | Module factories, build scripts, test fixtures |
| EnvMapping | Env var configuration |
| EnvSource | Custom env sources (test doubles, filtered environments) |
Safety
Immutability
- The returned config is
Object.freeze'd — mutation throws in strict mode - Config is assembled once at startup — no runtime reload, no race conditions
Type Safety
Tis inferred fromdefaults— downstream code gets exact types, notRecord<string, unknown>envMapkeys are constrained tokeyof T— typos are caught at compile timemapStampreturn type isPartial<T>— can only produce valid config fields
Env Coercion Safety
- Coercion is driven by the default value's type, not the env string — no accidental string-to-object
NaNresults from number coercion are silently skipped — no crash, no invalid config- Unsupported types (object, array) are ignored — only boolean, number, string are coerced
Dependency Safety
- Zero external runtime dependencies — only
@enclosurejs/core(peer) and@enclosurejs/stamp(optional peer, types only) @enclosurejs/stampis optional — config works without build metadata
Benchmarks
Not applicable. @enclosurejs/config runs once at startup — a single synchronous Object.freeze({ ...spread }). There is no runtime hot path to benchmark. Execution time is dominated by the env var iteration, which processes at most |envMap| entries.
Bundle Size
| Output | File | Size |
| ------------ | ------------ | ------- |
| Runtime (JS) | index.js | 1.41 KB |
| Types (DTS) | index.d.ts | 1.92 KB |
| Total | | 3.33 KB |
Single entrypoint — all exports bundled into one file. Zero runtime dependencies.
Quality
| Metric | Value |
| --------------------- | ------------------------------------------------------------------ |
| Unit tests | 47 (all pass) |
| Test files | 3 (env.test.ts, merge.test.ts, module.test.ts) |
| Source files | 5 (index.ts, module.ts, merge.ts, env.ts, types.ts) |
| External dependencies | 0 |
| Peer dependencies | @enclosurejs/core (required), @enclosurejs/stamp (optional) |
| Coverage thresholds | statements >= 90%, branches >= 85%, functions >= 95%, lines >= 90% |
Quality Layers
Layer 1: STATIC ANALYSIS (every commit)
tsc --noEmit strict mode, zero errors
eslint ESLint 9 flat config, zero warnings
prettier --check formatting
Layer 2: UNIT TESTS (every commit)
47 tests env coercion, merge order, freeze, DI integration
v8 coverage statements 100%, branches 95%, functions 100%, lines 100%
Layer 3: BENCHMARKS
N/A startup-time utility, no runtime path to benchmark
Layer 4: PACKAGE HEALTH
0 external deps pure TypeScript
tsup build ESM + DTS output, single entrypointFile Structure
packages/config/
├── src/
│ ├── index.ts Barrel: all public exports
│ ├── types.ts ConfigOptions<T>, EnvMapping<T>, EnvSource
│ ├── merge.ts buildConfig() — pure merge + freeze
│ ├── env.ts mapEnv() — env var coercion
│ ├── module.ts createConfigModule(), ConfigToken
│ └── __tests__/
│ ├── env.test.ts 20 tests — coercion: bool, number, string, NaN, Infinity, missing
│ ├── merge.test.ts 18 tests — merge order, freeze, layers, immutability
│ └── module.test.ts 9 tests — DI integration, token, frozen output
├── package.json
├── tsconfig.json
├── tsup.config.ts
└── spec.mdLicense
MIT
