@bymax-one/nest-config 1.2.0 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +96 -3
- package/README.md +224 -30
- package/dist/index.cjs +4 -0
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/internal/index.cjs +49 -13
- package/dist/internal/index.d.cts +30 -17
- package/dist/internal/index.d.ts +30 -17
- package/dist/internal/index.mjs +49 -13
- package/dist/testing/index.cjs +58 -9
- package/dist/testing/index.d.cts +4 -1
- package/dist/testing/index.d.ts +4 -1
- package/dist/testing/index.mjs +59 -10
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -11,6 +11,96 @@ as the GitHub Release body, so each released version needs a matching
|
|
|
11
11
|
|
|
12
12
|
## [Unreleased]
|
|
13
13
|
|
|
14
|
+
## [1.2.2] - 2026-10-31
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
|
|
18
|
+
- **`resolveSourceNames` and the `SourceBinding` type are exported from the package root.**
|
|
19
|
+
`resolveSourceNames(schema)` returns one `{ path, variable }` binding per leaf of a
|
|
20
|
+
`defineEnv` schema, in declaration order: the environment variable that leaf reads. It is the
|
|
21
|
+
function validation resolves its variables through, so the list equals what `forRoot` reads,
|
|
22
|
+
and a test can assert that every variable the schema declares appears in `.env.example`
|
|
23
|
+
without re-deriving the naming rules. Two distinct paths can derive one variable and both
|
|
24
|
+
bindings are returned, and declared is not required; the README section lists what the list
|
|
25
|
+
does not tell you. Both names were already importable from `./internal`, which promises
|
|
26
|
+
nothing; they are public now. **Apply to a derived backend:** nothing is required; import
|
|
27
|
+
`resolveSourceNames` from `@bymax-one/nest-config` rather than from `./internal`.
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
|
|
31
|
+
- **A rule on a namespace that names no leaf is reported, not dropped.** A `.check`, `.refine` or
|
|
32
|
+
`.superRefine` on a namespace whose issue sets no `path` made the validation fail with
|
|
33
|
+
`environment validation failed (0 issues)` and an empty report. It is reported against the
|
|
34
|
+
namespace now: the issue's `path` is the namespace key, the variable column shows its prefix
|
|
35
|
+
followed by `*` (`STORAGE_*`), and the author's message is kept; a rule on the whole schema
|
|
36
|
+
reports `(schema)`. Such a rule runs once the namespace's own leaves are valid.
|
|
37
|
+
- **`meta({ env })` is found wherever it sits in the chain.** `z.string().meta({ env: 'L' }).default('x')`
|
|
38
|
+
silently read the derived name, because a wrapper builds a node that carries no metadata.
|
|
39
|
+
The override is read through them, the outermost usable one wins, and `resolveSourceNames` gives
|
|
40
|
+
the same answer as validation. **Apply to a derived backend:** a leaf that wrote `meta({ env })`
|
|
41
|
+
before a wrapper now reads that variable instead of the derived one; check that the variable is
|
|
42
|
+
set where the derived name was.
|
|
43
|
+
- **An asynchronous `onValidationError` that rejects no longer leaves an unhandled rejection.** The
|
|
44
|
+
provider awaits the hook, so the boot fails after it finishes, with the original validation error;
|
|
45
|
+
the hook's error, thrown or rejected, is attached to it as a non-enumerable `cause`. A hook that
|
|
46
|
+
threw was swallowed with no trace before. The hook's type returns `unknown`, so every existing
|
|
47
|
+
hook still compiles; a hook that never settles now holds the boot, since there is no timeout.
|
|
48
|
+
- **`createTestConfig` and `configTestingModule` synthesize more leaf types and say what to
|
|
49
|
+
override.** Leaf types that used to fail validation now get a placeholder or are left to the
|
|
50
|
+
schema. A leaf no placeholder can satisfy (a regex, a `.refine`)
|
|
51
|
+
fails with an issue that names it and says to override it, and `configTestingModule` raises
|
|
52
|
+
that when it is called instead of when the module compiles.
|
|
53
|
+
|
|
54
|
+
### Documentation
|
|
55
|
+
|
|
56
|
+
- **The README now states what the code does.** The sample failure report printed messages
|
|
57
|
+
the validator never produces and was misaligned; it is now the exact output for the inputs
|
|
58
|
+
it documents. The Tech Stack and mutation-score figures, and the `configTestingModule`
|
|
59
|
+
example, now match the code, and the library is no longer said to have property-based
|
|
60
|
+
tests (the value-free guarantee is held by sentinel-secret tests).
|
|
61
|
+
|
|
62
|
+
- **Where "deep-frozen" stops is stated.** Plain objects and arrays are frozen; a `Date`, `Map`
|
|
63
|
+
or `Set` leaf is frozen as an object but keeps its mutators.
|
|
64
|
+
|
|
65
|
+
### Tests
|
|
66
|
+
|
|
67
|
+
- **A contract spec pins the README to the code.** `src/readme-contract.spec.ts` parses the
|
|
68
|
+
README and asserts its documented defaults, error catalog, peer table, mutation score and
|
|
69
|
+
first sample report against the code, so the next drift fails CI.
|
|
70
|
+
|
|
71
|
+
## [1.2.1] - 2026-10-30
|
|
72
|
+
|
|
73
|
+
### Security
|
|
74
|
+
|
|
75
|
+
- **The `zod` peer range now starts at `4.6.6`, the first release without
|
|
76
|
+
GHSA-mrhx-c7xc-m3w5** (high: memory exhaustion while validating oversized constrained
|
|
77
|
+
collections). The range `^4.0.0` declared installs below it as supported, and the
|
|
78
|
+
advisory applies to them in an application that validates untrusted collection input
|
|
79
|
+
through its own schemas. **Apply to a derived backend:** raise `zod` to `4.6.6` or later
|
|
80
|
+
(`pnpm up zod`); an install below it is outside the declared peer range.
|
|
81
|
+
|
|
82
|
+
### Documentation
|
|
83
|
+
|
|
84
|
+
- **Support policy: only the latest minor receives security fixes, and the Discussions
|
|
85
|
+
link is gone.** `SECURITY.md` supports the latest minor alone; earlier versions get no fix and no
|
|
86
|
+
backport, and the guidance is to upgrade. The issue-template chooser no longer links to
|
|
87
|
+
Discussions; the security contact by e-mail remains.
|
|
88
|
+
|
|
89
|
+
- **`strict` names the two prefixed-variable sources a search will not find.** Both came
|
|
90
|
+
from an adopter enabling it in a real deployment. A container's own `environment:` block
|
|
91
|
+
assigns a variable whose host-side name is a different one, so a search over
|
|
92
|
+
interpolations misses it — and it fails on the default path, because Compose assigns an
|
|
93
|
+
unset interpolation the empty string rather than absent, and validation skips only
|
|
94
|
+
`undefined`. Kubernetes service links appear in no file at all: at the default
|
|
95
|
+
`enableServiceLinks`, a Service named `redis` supplies `REDIS_PORT`,
|
|
96
|
+
`REDIS_SERVICE_HOST`, `REDIS_SERVICE_PORT` and the `REDIS_PORT_6379_TCP*` family into a
|
|
97
|
+
closed `redis` namespace — a crash loop in production that never appears in CI.
|
|
98
|
+
|
|
99
|
+
The cost of an open namespace is also stated in its sharpest form rather than its
|
|
100
|
+
general one: the typo it cannot catch may be in that namespace's own declared variable,
|
|
101
|
+
so `OTEL_ENABLE` is waived, the leaf falls back to its default, and the feature stays
|
|
102
|
+
off with nothing reported.
|
|
103
|
+
|
|
14
104
|
## [1.2.0] - 2026-09-04
|
|
15
105
|
|
|
16
106
|
### Added
|
|
@@ -49,8 +139,9 @@ as the GitHub Release body, so each released version needs a matching
|
|
|
49
139
|
(GHSA-5jgf-p345-68v8, GHSA-jqff-g426-hqxp — host confusion; GHSA-f65p-4m7j-42xc,
|
|
50
140
|
GHSA-fph4-wmhf-6fwf — server-side request forgery; CVSS 7.5 each) and `qs`
|
|
51
141
|
(GHSA-4mjr-xmp4-gh2g, GHSA-x5fp-wj9c-mxmx, CVSS 6.3 each). All three are reached through
|
|
52
|
-
the mutation-testing and commit-tooling chains, none is a runtime dependency, and
|
|
53
|
-
package ships `dist`
|
|
142
|
+
the mutation-testing and commit-tooling chains, none is a runtime dependency, and the
|
|
143
|
+
package ships only `dist` as runtime code — so no consumer resolved a vulnerable version
|
|
144
|
+
through it.
|
|
54
145
|
|
|
55
146
|
Recorded here rather than omitted as internal because a consumer reading an advisory feed
|
|
56
147
|
needs to know whether a library in their tree pulled one in, and "it did not" is an answer
|
|
@@ -375,4 +466,6 @@ have regressed from. They are kept because the reasoning is worth having.
|
|
|
375
466
|
[1.1.2]: https://github.com/bymaxone/nest-config/compare/v1.1.1...v1.1.2
|
|
376
467
|
[1.1.3]: https://github.com/bymaxone/nest-config/compare/v1.1.2...v1.1.3
|
|
377
468
|
[1.2.0]: https://github.com/bymaxone/nest-config/compare/v1.1.3...v1.2.0
|
|
378
|
-
[
|
|
469
|
+
[1.2.1]: https://github.com/bymaxone/nest-config/compare/v1.2.0...v1.2.1
|
|
470
|
+
[1.2.2]: https://github.com/bymaxone/nest-config/compare/v1.2.1...v1.2.2
|
|
471
|
+
[Unreleased]: https://github.com/bymaxone/nest-config/compare/v1.2.2...HEAD
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
<a href="https://www.npmjs.com/package/@bymax-one/nest-config"><img src="https://img.shields.io/npm/dm/@bymax-one/nest-config?style=flat-square&colorA=000000&colorB=000000" alt="npm downloads" /></a>
|
|
15
15
|
<a href="https://github.com/bymaxone/nest-config/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/bymaxone/nest-config/ci.yml?branch=main&style=flat-square&colorA=000000&label=CI" alt="CI status" /></a>
|
|
16
16
|
<a href="https://github.com/bymaxone/nest-config/actions/workflows/ci.yml"><img src="https://img.shields.io/badge/coverage-100%25-brightgreen?style=flat-square&colorA=000000" alt="coverage" /></a>
|
|
17
|
-
<a href="https://github.com/bymaxone/nest-config/blob/main/docs/mutation_testing_results.md"><img src="https://img.shields.io/badge/mutation-99.
|
|
17
|
+
<a href="https://github.com/bymaxone/nest-config/blob/main/docs/mutation_testing_results.md"><img src="https://img.shields.io/badge/mutation-99.69%25-brightgreen?style=flat-square&colorA=000000" alt="mutation score" /></a>
|
|
18
18
|
<a href="https://scorecard.dev/viewer/?uri=github.com/bymaxone/nest-config"><img src="https://api.scorecard.dev/projects/github.com/bymaxone/nest-config/badge?style=flat-square" alt="OpenSSF Scorecard" /></a>
|
|
19
19
|
<a href="https://github.com/bymaxone/nest-config/blob/main/LICENSE"><img src="https://img.shields.io/github/license/bymaxone/nest-config?style=flat-square&colorA=000000&colorB=000000" alt="license" /></a>
|
|
20
20
|
<a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-strict-3178C6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript" /></a>
|
|
@@ -75,8 +75,10 @@ minimal.
|
|
|
75
75
|
|
|
76
76
|
### 🔒 The Validated Object
|
|
77
77
|
|
|
78
|
-
- ✅ **Immutable by construction** — deep-frozen before
|
|
79
|
-
configuration is a fact about the process, not a mutable
|
|
78
|
+
- ✅ **Immutable by construction** — plain objects and arrays are deep-frozen before the
|
|
79
|
+
object enters the DI container; configuration is a fact about the process, not a mutable
|
|
80
|
+
bag (a `Date`, `Map` or `Set` leaf is frozen as an object but keeps its own mutators, see
|
|
81
|
+
[The validated object is frozen](#the-validated-object-is-frozen))
|
|
80
82
|
- ✅ **Typed dot-path access** — `get('database.url')` is `string`, `get('server.port')` is
|
|
81
83
|
`number`, with no casts and no `any` in the chain
|
|
82
84
|
- ✅ **Injectable environment** — the raw source defaults to `process.env` but is a plain
|
|
@@ -101,7 +103,7 @@ minimal.
|
|
|
101
103
|
|
|
102
104
|
| Subpath | Contents |
|
|
103
105
|
| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
104
|
-
| `.` | `BymaxConfigModule`, `ConfigService`, `defineEnv`, the DI tokens, `BymaxConfigValidationError` and every option type
|
|
106
|
+
| `.` | `BymaxConfigModule`, `ConfigService`, `defineEnv`, `resolveSourceNames`, the DI tokens, `BymaxConfigValidationError` and every option type |
|
|
105
107
|
| `./testing` | `configTestingModule`, `createTestConfig` — a validated config for a test without booting the application's own |
|
|
106
108
|
| `./internal` | The shared runtime both entry points build on. **Not public API**: it is in the `exports` map because it has to resolve at runtime, not because it is meant to be imported |
|
|
107
109
|
|
|
@@ -125,7 +127,7 @@ pnpm add @bymax-one/nest-config @nestjs/common @nestjs/core reflect-metadata zod
|
|
|
125
127
|
| `@nestjs/common` | `^11.0.16` |
|
|
126
128
|
| `@nestjs/core` | `^11.1.18` |
|
|
127
129
|
| `reflect-metadata` | `^0.2.0` |
|
|
128
|
-
| `zod` | `^4.
|
|
130
|
+
| `zod` | `^4.6.6` |
|
|
129
131
|
|
|
130
132
|
## 🚀 Quick Start
|
|
131
133
|
|
|
@@ -197,13 +199,16 @@ aggregated report, never one violation at a time:
|
|
|
197
199
|
```
|
|
198
200
|
BymaxConfigValidationError: environment validation failed (3 issues)
|
|
199
201
|
|
|
200
|
-
DATABASE_URL missing required value
|
|
201
|
-
AUTH_JWT_SECRET
|
|
202
|
-
SERVER_PORT
|
|
202
|
+
DATABASE_URL missing required value
|
|
203
|
+
AUTH_JWT_SECRET too short (expected: string, minimum 32 characters)
|
|
204
|
+
SERVER_PORT out of range (expected: number <= 65535)
|
|
203
205
|
|
|
204
206
|
Fix the variables above and restart the process.
|
|
205
207
|
```
|
|
206
208
|
|
|
209
|
+
The report has one line per variable: when a leaf fails several rules, the line shows the first
|
|
210
|
+
one Zod lists, and fixing it can reveal the next on the following start.
|
|
211
|
+
|
|
207
212
|
In a message this package generates, raw values are never printed — not
|
|
208
213
|
truncated, not masked, absent. That is a hard guarantee, verified by tests. The
|
|
209
214
|
one exception is a message you write yourself, described next.
|
|
@@ -237,6 +242,13 @@ that exact string is reserved — a schema that authors it verbatim reports
|
|
|
237
242
|
custom error map) the default no longer matches, so the localized default is
|
|
238
243
|
reported as written instead.
|
|
239
244
|
|
|
245
|
+
A rule on a namespace as a whole, such as a `.check` that compares two of its leaves, names no
|
|
246
|
+
leaf unless its issue sets a `path`. Without one it is reported against the namespace: the
|
|
247
|
+
`path` is the namespace key, the variable column shows its prefix followed by `*`
|
|
248
|
+
(`STORAGE_*`), and the message is the one the rule wrote. A rule on the whole schema is reported
|
|
249
|
+
with the variable column `(schema)` and an empty `path`. Zod does not run a namespace's own rule
|
|
250
|
+
once one of that namespace's leaves has failed, so such a rule appears once the leaves are valid.
|
|
251
|
+
|
|
240
252
|
## 📖 API Reference
|
|
241
253
|
|
|
242
254
|
### `defineEnv(shape)`
|
|
@@ -248,6 +260,11 @@ rewriting, cloning, or wrapping them, so coercion and defaults stay explicit
|
|
|
248
260
|
consumer choices. Leaves use `z.coerce.*` because the source arrives as
|
|
249
261
|
strings (the shape of `process.env`).
|
|
250
262
|
|
|
263
|
+
Two things follow from that. `z.coerce.boolean()` is `Boolean(value)`: any non-empty string,
|
|
264
|
+
including `'false'`, becomes `true`, so use `z.stringbool()` for a flag. And a variable set to the
|
|
265
|
+
empty string is present, not missing: `z.string()` accepts it and `z.coerce.number()` turns it into
|
|
266
|
+
`0`, so add `.min(1)` or a bound where empty should fail.
|
|
267
|
+
|
|
251
268
|
A leaf can override its derived variable name through schema metadata when a
|
|
252
269
|
legacy name must be preserved:
|
|
253
270
|
|
|
@@ -258,6 +275,11 @@ database: z.object({
|
|
|
258
275
|
})
|
|
259
276
|
```
|
|
260
277
|
|
|
278
|
+
The override is found wherever `meta` sits in the chain: `z.string().meta({ env: 'LEGACY' }).default('x')`
|
|
279
|
+
and `z.string().default('x').meta({ env: 'LEGACY' })` both read `LEGACY`. When more than one layer sets it, the outermost usable one wins, and an
|
|
280
|
+
empty or non-string value is skipped. `resolveSourceNames` answers the same, because validation
|
|
281
|
+
reads its variables through it.
|
|
282
|
+
|
|
261
283
|
A namespace can declare itself **open**, which waives strict unknown-key
|
|
262
284
|
detection for the rest of its prefix. Use it when the prefix is shared with
|
|
263
285
|
another program that reads its own variables — see
|
|
@@ -272,6 +294,9 @@ otel: z.object({ enabled: z.stringbool().default(false) }).meta({ open: true })
|
|
|
272
294
|
Only the literal `true` opens a namespace. Any other value, and any metadata
|
|
273
295
|
without the key, leaves detection in force.
|
|
274
296
|
|
|
297
|
+
Write `.meta({ open: true })` last: methods that build a new object schema, such as `.strict()`,
|
|
298
|
+
`.extend()` or `.pick()`, drop the metadata and close the namespace again.
|
|
299
|
+
|
|
275
300
|
### `BymaxConfigModule`
|
|
276
301
|
|
|
277
302
|
| Method | Signature |
|
|
@@ -281,12 +306,12 @@ without the key, leaves detection in force.
|
|
|
281
306
|
|
|
282
307
|
`BymaxConfigModuleOptions`:
|
|
283
308
|
|
|
284
|
-
| Field | Type
|
|
285
|
-
| ------------------- |
|
|
286
|
-
| `schema` | `EnvSchema`
|
|
287
|
-
| `source` | `Record<string, string \| undefined>`
|
|
288
|
-
| `onValidationError` | `(issues: ReadonlyArray<ConfigIssue>) =>
|
|
289
|
-
| `strict` | `boolean`
|
|
309
|
+
| Field | Type | Required | Notes |
|
|
310
|
+
| ------------------- | ------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
311
|
+
| `schema` | `EnvSchema` | yes | Produced by `defineEnv`. |
|
|
312
|
+
| `source` | `Record<string, string \| undefined>` | no | Defaults to `process.env` in the provider factory. Injectable for tests. |
|
|
313
|
+
| `onValidationError` | `(issues: ReadonlyArray<ConfigIssue>) => unknown` | no | Observability hook invoked before the fail-fast throw; a promise it returns is awaited. Cannot suppress the failure. |
|
|
314
|
+
| `strict` | `boolean` | no | When true, source variables matching a namespace prefix but no declared leaf raise `BYMAX_CONFIG_UNKNOWN_KEY`. Defaults to `false`. Read [Strict mode and shared prefixes](#strict-mode-and-shared-prefixes) before enabling it. |
|
|
290
315
|
|
|
291
316
|
`forRootAsync` resolves the source through another provider, for example a
|
|
292
317
|
secrets-manager client composed with `process.env`:
|
|
@@ -304,6 +329,21 @@ BymaxConfigModule.forRootAsync({
|
|
|
304
329
|
})
|
|
305
330
|
```
|
|
306
331
|
|
|
332
|
+
`forRootAsync` takes Nest's configurable-module options: `useFactory` with
|
|
333
|
+
`inject` and `imports`, shown above; `useClass`, a class whose `create()` returns the options; and
|
|
334
|
+
`useExisting`, which reuses a provider that is already registered (import its module through
|
|
335
|
+
`imports`):
|
|
336
|
+
|
|
337
|
+
```typescript
|
|
338
|
+
class ConfigOptionsFactory {
|
|
339
|
+
public create(): { schema: typeof envSchema; source: Record<string, string | undefined> } {
|
|
340
|
+
return { schema: envSchema, source: { ...process.env } }
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
BymaxConfigModule.forRootAsync({ useClass: ConfigOptionsFactory })
|
|
345
|
+
```
|
|
346
|
+
|
|
307
347
|
`isGlobal` defaults to `true` and can be set to `false` through the standard
|
|
308
348
|
extras when an application intentionally scopes configuration to a submodule.
|
|
309
349
|
|
|
@@ -343,11 +383,60 @@ What the waiver does and does not do:
|
|
|
343
383
|
and `otelExporter` (closed), `OTEL_EXPORTER_TYPO` belongs to `otelExporter`
|
|
344
384
|
and is still reported.
|
|
345
385
|
|
|
386
|
+
#### Where prefixed variables come from that a sweep will miss
|
|
387
|
+
|
|
388
|
+
Before enabling `strict`, know that reading your own repository does not enumerate
|
|
389
|
+
what reaches `process.env`. Two sources defeat a migration sweep in different ways
|
|
390
|
+
— one because the search you would naturally run is the wrong one, the other
|
|
391
|
+
because there is nothing to search — and both were found by adopters rather than
|
|
392
|
+
by reading manifests.
|
|
393
|
+
|
|
394
|
+
**A container's own `environment:` block.** Compose assigns variables to the
|
|
395
|
+
container with no `${...}` on the host side to give them away:
|
|
396
|
+
|
|
397
|
+
```yaml
|
|
398
|
+
services:
|
|
399
|
+
app:
|
|
400
|
+
environment:
|
|
401
|
+
REDIS_PASSWORD: ${STACK_REDIS_PASSWORD:-}
|
|
402
|
+
```
|
|
403
|
+
|
|
404
|
+
`REDIS_PASSWORD` lands in the application's environment. A repository-wide search
|
|
405
|
+
for the prefix does find this line — but the search a migration actually reaches
|
|
406
|
+
for is over interpolations, `${REDIS_`, and that one finds nothing, because the
|
|
407
|
+
interpolated name is the _other_ one. The variable the container receives and the
|
|
408
|
+
variable the host supplies are different names on the same line.
|
|
409
|
+
|
|
410
|
+
This one fails on the default path rather than only when someone opts in, and the
|
|
411
|
+
reason is worth stating: **Compose assigns an unset interpolation the empty string,
|
|
412
|
+
not absent.** Validation skips a variable whose value is `undefined` — an absent
|
|
413
|
+
variable is the schema's business, not strict mode's — and `''` is not `undefined`.
|
|
414
|
+
So the boot fails even when nobody set a password. That is deliberate: a validator
|
|
415
|
+
that ignored empty strings would also ignore a real misconfiguration that sets one.
|
|
416
|
+
|
|
417
|
+
**Kubernetes service links, which appear in no file at all.** With
|
|
418
|
+
`enableServiceLinks` at its default, a pod receives Docker-link-compatible
|
|
419
|
+
variables for every Service in its namespace. A Service named `redis` supplies
|
|
420
|
+
`REDIS_PORT`, `REDIS_SERVICE_HOST`, `REDIS_SERVICE_PORT` and the
|
|
421
|
+
`REDIS_PORT_6379_TCP*` family — all inside a closed `redis` namespace, none
|
|
422
|
+
declared, none written down anywhere you can search. Under `strict` that is a crash
|
|
423
|
+
loop in production over variables the application never reads, and it will not have
|
|
424
|
+
appeared in CI.
|
|
425
|
+
|
|
426
|
+
Set `enableServiceLinks: false` on the pod spec, or open the namespace. Managed
|
|
427
|
+
add-ons injecting names like `REDIS_PUBLIC_URL` or `DATABASE_URL_UNPOOLED` are the
|
|
428
|
+
same family.
|
|
429
|
+
|
|
346
430
|
**The cost, stated plainly:** an open namespace cannot tell a foreign variable
|
|
347
|
-
from a misspelled local one.
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
431
|
+
from a misspelled local one. No design removes this — the two cases are
|
|
432
|
+
indistinguishable by name — so open the namespaces whose prefix genuinely belongs
|
|
433
|
+
to someone else, and leave the rest closed.
|
|
434
|
+
|
|
435
|
+
The sharpest form of that cost is worth seeing before you accept it. The typo can
|
|
436
|
+
be in the open namespace's **own** declared variable: write `OTEL_ENABLE` instead
|
|
437
|
+
of `OTEL_ENABLED` and it is waived like any other unclaimed name, the leaf falls
|
|
438
|
+
back to its default, and the feature you meant to switch on stays off with nothing
|
|
439
|
+
reported. A closed namespace would have named that variable and refused to boot.
|
|
351
440
|
|
|
352
441
|
> Filtering the foreign names out of `source` instead is **not** equivalent, and
|
|
353
442
|
> is worse in a way that is easy to miss: removing `OTEL_*` from the source also
|
|
@@ -368,6 +457,10 @@ Because validation completed at bootstrap, `get` never throws for a declared
|
|
|
368
457
|
path: every leaf either passed validation, received its default, or the
|
|
369
458
|
process did not start.
|
|
370
459
|
|
|
460
|
+
The class is named `ConfigService`, as the one in `@nestjs/config` is; a backend that imports both
|
|
461
|
+
aliases one of them: `import { ConfigService as BymaxConfigService } from '@bymax-one/nest-config'`.
|
|
462
|
+
`has` is `value !== undefined`, so an absent optional leaf is `false` and a `null` is `true`.
|
|
463
|
+
|
|
371
464
|
### `BymaxConfigValidationError` and `ConfigIssue`
|
|
372
465
|
|
|
373
466
|
```typescript
|
|
@@ -397,6 +490,13 @@ exception is the one described above: a `custom` message written by your own sch
|
|
|
397
490
|
is printed as written, so if one of yours interpolates a value, reviewing it before
|
|
398
491
|
it reaches a log is the schema author's job, not this package's.
|
|
399
492
|
|
|
493
|
+
The hook may be asynchronous: a promise it returns is awaited before the boot fails, so a
|
|
494
|
+
report on its way to a log sink is not cut off by the process exiting. There is no timeout, so
|
|
495
|
+
a hook that never settles holds the boot. If the hook throws or rejects, the boot still fails
|
|
496
|
+
with the original validation error, unchanged in class, `code`, `issues` and `message`, and the
|
|
497
|
+
hook's error is attached to it as `error.cause` (non-enumerable, so `code` and `issues` stay
|
|
498
|
+
the only own enumerable properties).
|
|
499
|
+
|
|
400
500
|
If you also log the thrown error from a bootstrap `catch`, how you pass it decides
|
|
401
501
|
what survives. `code` and `issues` are the **only two own enumerable properties** of
|
|
402
502
|
`BymaxConfigValidationError`; `name`, `message` and `stack` are non-enumerable, as
|
|
@@ -467,9 +567,10 @@ failure, and `issues` is what an alert or a dashboard keys on per variable.
|
|
|
467
567
|
|
|
468
568
|
### Injection tokens
|
|
469
569
|
|
|
470
|
-
`BYMAX_CONFIG`
|
|
471
|
-
|
|
472
|
-
|
|
570
|
+
`BYMAX_CONFIG` is a `Symbol` token for the raw frozen config, exported by the module for advanced
|
|
571
|
+
factory-style wiring that does not go through `ConfigService`. `BYMAX_CONFIG_OPTIONS` is the token of
|
|
572
|
+
the module's own options: it is provided inside the module only, so a provider in another module
|
|
573
|
+
cannot inject it, and the options it holds include the raw `source` record. Do not build on it.
|
|
473
574
|
|
|
474
575
|
```typescript
|
|
475
576
|
import { Inject, Injectable } from '@nestjs/common'
|
|
@@ -487,10 +588,64 @@ export class RawConfigConsumer {
|
|
|
487
588
|
`EnvSchema`, `EnvShape`, `EnvOutput`, `EnvLeaf`, and `EnvNamespace` type the
|
|
488
589
|
two-level schema shape produced by `defineEnv`; `Path<T>` and `PathValue<T, P>`
|
|
489
590
|
are the template-literal utilities behind `ConfigService.get`'s compile-time
|
|
490
|
-
dot-path inference, limited to the two-level namespace convention. All
|
|
591
|
+
dot-path inference, limited to the two-level namespace convention. All of them
|
|
491
592
|
are exported for advanced generic code (custom decorators, typed wrappers)
|
|
492
593
|
that needs to reference the schema shape directly.
|
|
493
594
|
|
|
595
|
+
### `resolveSourceNames(schema)`
|
|
596
|
+
|
|
597
|
+
Lists the variable every leaf of a schema reads. It is the function validation itself
|
|
598
|
+
resolves its variables through, so the list cannot drift from what `forRoot` reads.
|
|
599
|
+
|
|
600
|
+
| Parameter | Type | Returns |
|
|
601
|
+
| --------- | ---------------------------- | -------------------------- |
|
|
602
|
+
| `schema` | `EnvSchema` from `defineEnv` | `readonly SourceBinding[]` |
|
|
603
|
+
|
|
604
|
+
`SourceBinding` is `{ path: string; variable: string }`: the leaf's dot path and the
|
|
605
|
+
environment variable it reads. The list has one entry per declared leaf, in declaration
|
|
606
|
+
order. A leaf reads its `meta({ env })` override when that is a non-empty string, and
|
|
607
|
+
otherwise `NAMESPACE_LEAF` in SCREAMING_SNAKE_CASE, with a camelCase key split into words.
|
|
608
|
+
It reads the schema only, never a source record, so it works on a schema exported as a
|
|
609
|
+
value.
|
|
610
|
+
|
|
611
|
+
```typescript
|
|
612
|
+
// For the Quick Start schema:
|
|
613
|
+
resolveSourceNames(envSchema).map((binding) => binding.variable)
|
|
614
|
+
// ['SERVER_PORT', 'SERVER_ENV', 'DATABASE_URL', 'REDIS_URL', 'LOG_LEVEL']
|
|
615
|
+
```
|
|
616
|
+
|
|
617
|
+
A test that keeps `.env.example` honest is the usual use:
|
|
618
|
+
|
|
619
|
+
```typescript
|
|
620
|
+
import { readFileSync } from 'node:fs'
|
|
621
|
+
import { resolveSourceNames } from '@bymax-one/nest-config'
|
|
622
|
+
import { envSchema } from './config/env.schema'
|
|
623
|
+
|
|
624
|
+
it('documents every variable the schema reads in .env.example', () => {
|
|
625
|
+
const example = readFileSync('.env.example', 'utf8')
|
|
626
|
+
const documented = new Set(
|
|
627
|
+
example.split('\n').map((line) => /^#?\s*([A-Z][A-Z0-9_]*)=/.exec(line)?.[1])
|
|
628
|
+
)
|
|
629
|
+
const missing = resolveSourceNames(envSchema).filter(({ variable }) => !documented.has(variable))
|
|
630
|
+
expect(missing).toEqual([])
|
|
631
|
+
})
|
|
632
|
+
```
|
|
633
|
+
|
|
634
|
+
#### What it does not tell you
|
|
635
|
+
|
|
636
|
+
- **Declared is not required.** A leaf with a default, or an optional leaf, is listed like
|
|
637
|
+
any other. Whether it belongs in a template file is your policy; the list says only that
|
|
638
|
+
the schema reads it.
|
|
639
|
+
- **Two paths can read one variable.** Names are derived from the keys, so `a.bC` and
|
|
640
|
+
`aB.c` both derive `A_B_C`, and `httpServer.port` and `HTTPServer.port` both derive
|
|
641
|
+
`HTTP_SERVER_PORT`. Every binding is returned and none is dropped; validation reads the
|
|
642
|
+
shared variable for both leaves.
|
|
643
|
+
- **An open namespace changes nothing.** `meta({ open: true })` only waives strict
|
|
644
|
+
unknown-key detection, so the list is the same whether a namespace is open or closed. It
|
|
645
|
+
does not help to find variables in `.env.example` that no leaf reads.
|
|
646
|
+
- **Two-level schemas only.** Deeper nesting is outside this contract, as it
|
|
647
|
+
is for `Path` and `PathValue`.
|
|
648
|
+
|
|
494
649
|
## 🚨 Error Catalog
|
|
495
650
|
|
|
496
651
|
| Code | Meaning |
|
|
@@ -572,7 +727,7 @@ guaranteed to be printed, logged, and pasted into an issue. That shapes the whol
|
|
|
572
727
|
Every message this library generates states the _expected_ constraint — the type, the
|
|
573
728
|
allowed enum options taken from the schema, the bound — and never the received value.
|
|
574
729
|
`env-validator` and `report-formatter` each say so in their own contracts, and
|
|
575
|
-
|
|
730
|
+
sentinel-secret tests hold them to it. The messages you write yourself are the exception,
|
|
576
731
|
covered below.
|
|
577
732
|
|
|
578
733
|
### The service does not serialize its configuration
|
|
@@ -594,8 +749,16 @@ does not serve one request.
|
|
|
594
749
|
|
|
595
750
|
### The validated object is frozen
|
|
596
751
|
|
|
597
|
-
|
|
598
|
-
rewrites
|
|
752
|
+
Plain objects and arrays are deep-frozen before the object enters the container, so nothing
|
|
753
|
+
in the running process rewrites those values under a component that already read them.
|
|
754
|
+
|
|
755
|
+
A `Date`, a `Map` or a `Set` leaf is frozen as an object but is **not** made immutable:
|
|
756
|
+
`setTime`, `Map.prototype.set` and `Set.prototype.add` still work, because the state they
|
|
757
|
+
change lives in internal slots that `Object.freeze` cannot reach, and the entries of a `Map` or
|
|
758
|
+
`Set` are not visited. Wrapping them in a read-only proxy was measured and rejected: it fails
|
|
759
|
+
`util.types.isDate`, reports `[object Object]` to `Object.prototype.toString`, cannot be given to
|
|
760
|
+
`structuredClone`, and does not satisfy `assert.deepStrictEqual` against a real `Date`. Prefer a
|
|
761
|
+
string or number leaf, or a `.transform` to a plain value, where immutability matters.
|
|
599
762
|
|
|
600
763
|
### Nothing is read from anywhere but the source you name
|
|
601
764
|
|
|
@@ -620,7 +783,7 @@ report.
|
|
|
620
783
|
| Error messages | Expected constraint only — type, schema-declared enum options, bounds; never the received value. A `custom` message from your own schema is the exception: it prints as written |
|
|
621
784
|
| Failure mode | Refuse to start; the whole schema is validated before the context finishes building |
|
|
622
785
|
| Aggregation | Every failure reported at once, so a fix cycle is one restart rather than one per variable |
|
|
623
|
-
| Immutability |
|
|
786
|
+
| Immutability | Plain objects and arrays in the validated result are frozen before it is provided; a `Date`, `Map` or `Set` keeps its mutators |
|
|
624
787
|
| Service state | The root lives in a private field; serializing the injected service yields namespace names only |
|
|
625
788
|
| Sources | `process.env` only — no file, no network, no remote provider |
|
|
626
789
|
| Type surface | Dot paths checked against the schema at compile time; a typo is a build error, not a runtime `undefined` |
|
|
@@ -637,11 +800,11 @@ report.
|
|
|
637
800
|
|
|
638
801
|
- **Runtime:** Node.js 24+
|
|
639
802
|
- **Framework:** NestJS 11 (`ConfigurableModuleBuilder`, `@Global()`, `Symbol()` tokens)
|
|
640
|
-
- **Validation:** Zod `^4` (peer) — the schema language, the coercion and the error source
|
|
803
|
+
- **Validation:** Zod `^4.6.6` (peer) — the schema language, the coercion and the error source
|
|
641
804
|
- **Build:** tsup — ESM + CJS per subpath, with `.d.ts` _and_ `.d.cts` declarations,
|
|
642
805
|
and one shared `./internal` bundle so the module and its testing entry point hold
|
|
643
806
|
a single class identity
|
|
644
|
-
- **Tests:** Jest, including
|
|
807
|
+
- **Tests:** Jest, including sentinel-secret tests over the validator and the report formatter, + Stryker (mutation)
|
|
645
808
|
- **TypeScript:** 5.x strict (`noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`), zero `any`
|
|
646
809
|
|
|
647
810
|
---
|
|
@@ -652,7 +815,7 @@ Configuration decides whether a process may start at all, so the suite is held t
|
|
|
652
815
|
beyond "the tests pass".
|
|
653
816
|
|
|
654
817
|
- ✅ **100% line coverage** — statements, branches, functions and lines, enforced as a gate
|
|
655
|
-
- ✅ **99.
|
|
818
|
+
- ✅ **99.69% mutation score** — verified with [Stryker](https://stryker-mutator.io/) at
|
|
656
819
|
`break: 95`; ten provable equivalents carry their reason inline, and the one survivor left
|
|
657
820
|
is an equivalent no directive can reach, so it stays counted rather than silenced
|
|
658
821
|
([report](./docs/mutation_testing_results.md))
|
|
@@ -687,6 +850,30 @@ values elsewhere), applies selective overrides, then runs the exact
|
|
|
687
850
|
production pipeline (validate, freeze), so a test exercises the same code
|
|
688
851
|
path a running application does.
|
|
689
852
|
|
|
853
|
+
```typescript
|
|
854
|
+
// Leaves createTestConfig fills without an override:
|
|
855
|
+
defineEnv({
|
|
856
|
+
text: z.object({ a: z.string().min(8), b: z.email(), c: z.url(), d: z.uuid() }),
|
|
857
|
+
time: z.object({
|
|
858
|
+
at: z.iso.datetime(),
|
|
859
|
+
on: z.iso.date(),
|
|
860
|
+
clock: z.iso.time(),
|
|
861
|
+
when: z.coerce.date()
|
|
862
|
+
}),
|
|
863
|
+
scalar: z.object({
|
|
864
|
+
n: z.coerce.number().int().min(1),
|
|
865
|
+
flag: z.stringbool(),
|
|
866
|
+
kind: z.enum(['a', 'b']),
|
|
867
|
+
fixed: z.literal('x')
|
|
868
|
+
})
|
|
869
|
+
})
|
|
870
|
+
```
|
|
871
|
+
|
|
872
|
+
A leaf no placeholder can be known to satisfy, such as a
|
|
873
|
+
`z.string().regex(...)` or a `.refine(...)` rule, makes the helper throw a
|
|
874
|
+
`BymaxConfigValidationError` whose issue says `no placeholder satisfies this leaf` and names it
|
|
875
|
+
(`pass an override for region.code`); give that leaf an override and the helper builds.
|
|
876
|
+
|
|
690
877
|
```typescript
|
|
691
878
|
import { createTestConfig } from '@bymax-one/nest-config/testing'
|
|
692
879
|
import { envSchema } from './config/env.schema'
|
|
@@ -706,11 +893,18 @@ import { envSchema } from './config/env.schema'
|
|
|
706
893
|
import { FeatureProvider } from './feature.provider'
|
|
707
894
|
|
|
708
895
|
const moduleRef = await Test.createTestingModule({
|
|
709
|
-
imports: [configTestingModule(envSchema, { server: { port:
|
|
896
|
+
imports: [configTestingModule(envSchema, { server: { port: 8080 } })],
|
|
710
897
|
providers: [FeatureProvider]
|
|
711
898
|
}).compile()
|
|
712
899
|
```
|
|
713
900
|
|
|
901
|
+
Overrides mirror the `namespace.leaf` shape with every key optional and typed from the schema. Each value is converted with `String(value)` before validation, so give
|
|
902
|
+
a leaf what its environment variable would hold; an object becomes `'[object Object]'`, and an override
|
|
903
|
+
of `undefined` is ignored, so a defaulted leaf cannot be unset. Neither helper takes `strict`, a
|
|
904
|
+
custom `source`, a hook or `isGlobal`: `configTestingModule` registers the module globally, and a
|
|
905
|
+
failure case (a missing variable, a strict violation) is built with
|
|
906
|
+
`BymaxConfigModule.forRoot({ schema, source, strict: true })` and a source you write.
|
|
907
|
+
|
|
714
908
|
Placeholder synthesis never fabricates values that could accidentally pass a
|
|
715
909
|
secret-strength constraint; length and format constraints are honored. The
|
|
716
910
|
subpath has no Jest dependency and works with any runner, though the family
|
package/dist/index.cjs
CHANGED
|
@@ -32,3 +32,7 @@ Object.defineProperty(exports, "defineEnv", {
|
|
|
32
32
|
enumerable: true,
|
|
33
33
|
get: function () { return internal.defineEnv; }
|
|
34
34
|
});
|
|
35
|
+
Object.defineProperty(exports, "resolveSourceNames", {
|
|
36
|
+
enumerable: true,
|
|
37
|
+
get: function () { return internal.resolveSourceNames; }
|
|
38
|
+
});
|
package/dist/index.d.cts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { BYMAX_CONFIG, BYMAX_CONFIG_OPTIONS, BymaxConfigModule, BymaxConfigModuleOptions, BymaxConfigValidationError, ConfigErrorCode, ConfigIssue, ConfigIssueCode, ConfigService, ConfigValidationCode, EnvLeaf, EnvNamespace, EnvOutput, EnvSchema, EnvShape, Path, PathValue, defineEnv } from '@bymax-one/nest-config/internal';
|
|
1
|
+
export { BYMAX_CONFIG, BYMAX_CONFIG_OPTIONS, BymaxConfigModule, BymaxConfigModuleOptions, BymaxConfigValidationError, ConfigErrorCode, ConfigIssue, ConfigIssueCode, ConfigService, ConfigValidationCode, EnvLeaf, EnvNamespace, EnvOutput, EnvSchema, EnvShape, Path, PathValue, SourceBinding, defineEnv, resolveSourceNames } from '@bymax-one/nest-config/internal';
|
package/dist/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { BYMAX_CONFIG, BYMAX_CONFIG_OPTIONS, BymaxConfigModule, BymaxConfigModuleOptions, BymaxConfigValidationError, ConfigErrorCode, ConfigIssue, ConfigIssueCode, ConfigService, ConfigValidationCode, EnvLeaf, EnvNamespace, EnvOutput, EnvSchema, EnvShape, Path, PathValue, defineEnv } from '@bymax-one/nest-config/internal';
|
|
1
|
+
export { BYMAX_CONFIG, BYMAX_CONFIG_OPTIONS, BymaxConfigModule, BymaxConfigModuleOptions, BymaxConfigValidationError, ConfigErrorCode, ConfigIssue, ConfigIssueCode, ConfigService, ConfigValidationCode, EnvLeaf, EnvNamespace, EnvOutput, EnvSchema, EnvShape, Path, PathValue, SourceBinding, defineEnv, resolveSourceNames } from '@bymax-one/nest-config/internal';
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { BYMAX_CONFIG, BYMAX_CONFIG_OPTIONS, BymaxConfigModule, BymaxConfigValidationError, ConfigErrorCode, ConfigService, defineEnv } from '@bymax-one/nest-config/internal';
|
|
1
|
+
export { BYMAX_CONFIG, BYMAX_CONFIG_OPTIONS, BymaxConfigModule, BymaxConfigValidationError, ConfigErrorCode, ConfigService, defineEnv, resolveSourceNames } from '@bymax-one/nest-config/internal';
|