@pband/config (2.0.1-rc.4)
Installation
@pband:registry=https://git.pband.ch/api/packages/typescript/npm/npm install @pband/config@2.0.1-rc.4"@pband/config": "2.0.1-rc.4"About this package
config
Describe your configuration as a yup schema; this library reads it from environment variables (or files), validates it, and returns a typed result. It never throws.
import {parse, yup} from '@pband/config'
const schema = yup.object({
port: yup.number().default(3000).meta({description: 'Listening port'}),
db: yup.object({
host: yup.string().required(),
password: yup.string().required()
}),
hosts: yup.array(yup.string()).default([])
})
export type Config = yup.InferType<typeof schema>
const config = await parse(schema)
if (!config.ok) {
// config.error: [{env: 'DB_HOST', message: 'DB_HOST is a required field'}, ...]
// each one is already logged with console.error
return config
}
config.data.db.host
Use the yup this library exports, so your schema and the library share one yup.
Install
Published as @pband/config on a Gitea npm registry; no account or token is needed. Map
the scope in your project's .npmrc, then install it:
@pband:registry=https://git.pband.ch/api/packages/typescript/npm/
bun add @pband/config
Release candidates are published under the rc tag: bun add @pband/config@rc.
ESM only, with type declarations; runs on Node and Bun.
Upgrading from 1.x
2.0.0 returns @pband/result's Result. Code
reading ok and data is unchanged; two things are not:
- A failure's list is
error, noterrors. - A test comparing
check(schema)to{ok: true}still passes but no longer type-checks. Write it as in Check your schema in CI:expect(checked.ok || checked.error).toBe(true).
Env names
Each leaf of the schema is read from one variable: its path of keys, uppercased, joined
with _. db.host is read from DB_HOST. Keys are not converted: replyTo is read from
REPLYTO, reply_to from REPLY_TO. A key can only hold letters, digits and _.
- Files: add
__FILE(two_) to any env name, and set it to a path:DB_PASSWORD__FILE=/run/secrets/db_password. The file is read and trimmed. Setting bothDB_PASSWORDandDB_PASSWORD__FILEis an error. - Empty values:
DB_PORT=, or a file that is empty after trimming, counts as unset: defaults apply, and a required leaf is reported as required. - Arrays and tuples are split on
,, each item trimmed:HOSTS=a, bgives['a', 'b']. There is no escaping, and an empty item (a,,b) is an error.
Validation
The whole schema is validated once by yup, so everything yup does applies as documented:
required leaves, defaults, transforms, .test(), including cross-field tests reading
this.parent.
Optional objects: write .optional().default(undefined). A plain yup.object()
defaults to {}, so its required leaves always apply. With
.optional().default(undefined), the object is undefined when none of its leaves is set,
and its required leaves apply as soon as one is. Both parts matter: .optional() makes the
type | undefined, .default(undefined) makes the value undefined.
reply_to: yup.object({name: yup.string(), email: yup.string().email().required()}).optional().default(undefined)
Enums
Use string().oneOf() with the enum's values: the inferred type is the enum, and an
unknown value is a validation error listing the allowed ones.
enum Level {
error = 'error',
warn = 'warn',
info = 'info'
}
log: yup.string().lowercase().trim().oneOf(Object.values(Level)).default(Level.info)
// LOG=' WARN ' gives Level.warn; LOG=loud: "LOG must be one of the following values: error, warn, info"
An alias goes in a transform before oneOf:
.transform(v => (v === 'warning' ? 'warn' : v)). For an enum whose values aren't strings,
use mixed<E>().oneOf(...) with a transform from the env string to the value.
Errors and logs
parse returns a @pband/result Result: an Ok
whose data is the config, or an Err whose error lists one {env, message} per problem.
env is the env name, an object's prefix for an object-level test, or '' for the root. Messages never hold a value: yup's type errors, which do, are rewritten
(DB_PORT must be a number). A custom message using ${value} is yours to keep safe.
Nothing is logged when parsing succeeds; each error is logged with console.error. To see
where each leaf comes from, without values:
await parse(schema, {debug: true})
// [config] DB_HOST: from env
// [config] DB_PASSWORD: from file /run/secrets/db_password
// [config] PORT: default
Check your schema in CI
check(schema) returns an Ok, or an Err listing the problems when two leaves read the same
variable (db_name and db.name both read DB_NAME), when a leaf reads another's file
variant, or when a schema can't be read from env (yup.lazy, an array of objects). parse
calls it first, but a test catches it before a deployment does:
test('config schema', () => {
const checked = check(schema)
expect(checked.ok || checked.error).toBe(true) // a failure shows the errors
})
Document your config
doc(schema) lists every variable as {env, type, required, default, description}, the
description coming from .meta({description}). A leaf is required when parsing fails with
it alone unset, so a leaf of an optional object is not. markdown(schema) renders that list
as a table for a README:
| Variable | Type | Required | Default | Description |
|---|---|---|---|---|
PORT |
number | 3000 |
Listening port | |
DB_HOST |
string | yes |
Dependencies
Dependencies
| ID | Version |
|---|---|
| @pband/result | ^1.0.0 |
| yup | ^1.7.0 |
Development Dependencies
| ID | Version |
|---|---|
| @eslint/js | ^10.0.1 |
| @types/bun | ^1.4.3 |
| eslint | ^10.13.0 |
| jiti | ^2.7.0 |
| prettier | ^3.9.10 |
| typescript | ^6.0.3 |
| typescript-eslint | ^8.71.2 |