envyak 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +193 -2
- package/dist/index.cjs +391 -0
- package/dist/index.d.cts +249 -0
- package/index.d.ts +249 -0
- package/package.json +71 -4
- package/src/index.js +388 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Alexandre Kohler
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,194 @@
|
|
|
1
|
-
|
|
1
|
+
<picture>
|
|
2
|
+
<source media="(prefers-color-scheme: dark)" srcset="assets/banner-dark.svg">
|
|
3
|
+
<img alt="envyak: typed environment variables, every error at once" src="assets/banner-light.svg" width="100%">
|
|
4
|
+
</picture>
|
|
2
5
|
|
|
3
|
-
|
|
6
|
+
**English** | [Português](i18n/README.pt.md) | [Español](i18n/README.es.md) | [日本語](i18n/README.ja.md)
|
|
7
|
+
|
|
8
|
+
[](https://www.npmjs.com/package/envyak)
|
|
9
|
+
[](https://github.com/kwy404/envyak/actions/workflows/ci.yml)
|
|
10
|
+
[](index.d.ts)
|
|
11
|
+
[](package.json)
|
|
12
|
+
[](#size)
|
|
13
|
+
[](LICENSE)
|
|
14
|
+
|
|
15
|
+
**envyak validates and parses environment variables for Node.js, Bun, Deno and edge runtimes, with exact TypeScript types and zero dependencies.** You describe each variable once; envyak turns `process.env` strings into real numbers, booleans, URLs, lists, JSON and dates, reports every missing or invalid variable in one `EnvError`, and never prints the value of a secret.
|
|
16
|
+
|
|
17
|
+
[Website and live playground](https://kwy404.github.io/envyak/)
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm i envyak
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
ESM and CommonJS, types included, Node 18 or newer. Bun and Deno (`npm:envyak`) work as is.
|
|
26
|
+
|
|
27
|
+
## Quick start
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
// config.ts
|
|
31
|
+
import { env, port, bool, url, oneOf, str } from 'envyak';
|
|
32
|
+
|
|
33
|
+
export const config = env({
|
|
34
|
+
PORT: port({ default: 3000 }),
|
|
35
|
+
DEBUG: bool({ default: false }),
|
|
36
|
+
DATABASE_URL: url({ protocols: ['postgres', 'postgresql'] }),
|
|
37
|
+
NODE_ENV: oneOf(['development', 'production', 'test']),
|
|
38
|
+
API_KEY: str({ secret: true, minLength: 32 }),
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
config.PORT; // number
|
|
42
|
+
config.NODE_ENV; // 'development' | 'production' | 'test'
|
|
43
|
+
String(config); // {"PORT":3000,...,"API_KEY":"[secret]"}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
When something is wrong, startup stops with one report for every variable:
|
|
47
|
+
|
|
48
|
+
```text
|
|
49
|
+
EnvError: 3 environment variables are missing or invalid:
|
|
50
|
+
|
|
51
|
+
DATABASE_URL is missing
|
|
52
|
+
fix: set DATABASE_URL, for example DATABASE_URL=https://example.com
|
|
53
|
+
PORT expected a port number from 1 to 65535, got "70000"
|
|
54
|
+
fix: set PORT, for example PORT=3000
|
|
55
|
+
API_KEY expected a string of at least 32 characters, got a secret value (hidden)
|
|
56
|
+
fix: set API_KEY to a string of at least 32 characters
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## API
|
|
60
|
+
|
|
61
|
+
### `env(schema, options?)`
|
|
62
|
+
|
|
63
|
+
Reads every key of `schema` from the source, parses it, and returns a frozen object typed from the schema. If any variable is missing or invalid it throws one `EnvError` listing all of them, in schema order.
|
|
64
|
+
|
|
65
|
+
| Option | Default | Meaning |
|
|
66
|
+
| --- | --- | --- |
|
|
67
|
+
| `source` | `process.env`, then `Deno.env.toObject()`, then `{}` | Where to read from. Pass it on Workers (`env` bindings), in Vite (`import.meta.env`) or with a parsed `.env`. `NODE_ENV` is read from the same source. |
|
|
68
|
+
|
|
69
|
+
The result is frozen, and so are lists and JSON values inside it. `toString()`, `toJSON()`, `util.inspect` (Node and Bun) and `Deno.inspect` show secret values as `[secret]`. Reading `config.API_KEY` gives your code the real value.
|
|
70
|
+
|
|
71
|
+
### Validators
|
|
72
|
+
|
|
73
|
+
| Validator | Accepts | Type |
|
|
74
|
+
| --- | --- | --- |
|
|
75
|
+
| `str(options?)` | any non empty string; `minLength`, `maxLength`, `pattern` | `string` |
|
|
76
|
+
| `num(options?)` | a finite decimal number; `min`, `max` | `number` |
|
|
77
|
+
| `int(options?)` | a safe integer written in base 10; `min`, `max` | `number` |
|
|
78
|
+
| `port(options?)` | an integer from 1 to 65535 | `number` |
|
|
79
|
+
| `bool(options?)` | `true false 1 0 yes no on off`, any case | `boolean` |
|
|
80
|
+
| `url(options?)` | an absolute URL, parsed with `new URL`; `protocols` | `string` |
|
|
81
|
+
| `email(options?)` | one `@`, no spaces, a dot in the domain | `string` |
|
|
82
|
+
| `oneOf(choices, options?)` | one of the listed strings | union of the choices |
|
|
83
|
+
| `list(item, options?)` | items split by `separator` (`,` by default), each parsed by `item` | `readonly T[]` |
|
|
84
|
+
| `json<T>(options?)` | any JSON text, deep frozen | `T` (`unknown` by default) |
|
|
85
|
+
| `date(options?)` | an ISO 8601 date or date and time that exists on the calendar | `Date` |
|
|
86
|
+
| `custom(parse, options?)` | whatever `parse(raw)` returns; throw an `Error` to reject | the return type |
|
|
87
|
+
|
|
88
|
+
### Common options
|
|
89
|
+
|
|
90
|
+
Every validator accepts these:
|
|
91
|
+
|
|
92
|
+
| Option | Effect on the type | Meaning |
|
|
93
|
+
| --- | --- | --- |
|
|
94
|
+
| `default` | `T` | Used when the variable is missing, in every environment. |
|
|
95
|
+
| `devDefault` | `T` | Used when the variable is missing and `NODE_ENV` is not `production`. It wins over `default` there. In production `default` applies, and without one the variable is required. |
|
|
96
|
+
| `optional: true` | `T \| undefined` | A missing variable becomes `undefined` instead of an error. |
|
|
97
|
+
| `description` | none | Shown in the fix hint. |
|
|
98
|
+
| `example` | none | Shown in the fix hint as `KEY=example`. |
|
|
99
|
+
| `secret: true` | none | The value never appears in errors, issues, `toString`, `toJSON` or inspect output. |
|
|
100
|
+
|
|
101
|
+
### `EnvError`
|
|
102
|
+
|
|
103
|
+
`error.name` is `'EnvError'` and `error.issues` is an array of:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
interface Issue {
|
|
107
|
+
key: string; // the variable name
|
|
108
|
+
reason: 'missing' | 'invalid';
|
|
109
|
+
message: string; // what was expected; never holds a secret value
|
|
110
|
+
hint: string; // how to fix it
|
|
111
|
+
secret: boolean;
|
|
112
|
+
received?: string; // the raw value, only when invalid and not secret
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Behavior notes
|
|
117
|
+
|
|
118
|
+
- **Empty means missing.** `PORT=` in a `.env` file is treated like an unset variable, so `default` applies. If an empty string is a real value for you, use `str({ default: '' })`.
|
|
119
|
+
- **Strict numbers.** `num` and `int` reject hex, octal, binary, `Infinity`, `NaN`, underscores and blank strings. `int` also rejects values beyond `Number.MAX_SAFE_INTEGER`.
|
|
120
|
+
- **Strict booleans.** `bool` accepts exactly `true false 1 0 yes no on off`, ignoring case and surrounding spaces. Anything else is an error, not `false`.
|
|
121
|
+
- **Dates follow ECMAScript.** A date only value such as `2024-05-01` is midnight UTC, a date time without offset such as `2024-05-01T12:00` is local time, and `Z` or an offset is exact. This matches the [ECMAScript date time string format](https://tc39.es/ecma262/#sec-date-time-string-format). Impossible dates like `2024-02-30` are rejected.
|
|
122
|
+
- **URLs use the WHATWG parser** (`new URL`), as described in the [URL Standard](https://url.spec.whatwg.org/). `protocols` compares the scheme without the colon.
|
|
123
|
+
- **Email is a sanity check**, not full RFC 5322 parsing: one `@`, no whitespace, a non empty local part and a dot inside the domain.
|
|
124
|
+
- **Secrets are hidden twice.** A secret's issue has no `received`, and if a custom parser puts the raw value in its error message, the message is replaced with a generic one.
|
|
125
|
+
- **Unknown variables are ignored.** Only keys in the schema are read and returned.
|
|
126
|
+
|
|
127
|
+
## Benchmarks
|
|
128
|
+
|
|
129
|
+
Parsing the same 8 variables with each library, median of 5 runs, more is better. Node v24.16.0 on Windows 10 x64, a modest desktop. Run it yourself with `npm run bench` (see `bench/run.mjs`).
|
|
130
|
+
|
|
131
|
+
| Library | Version | Parses per second |
|
|
132
|
+
| --- | --- | ---: |
|
|
133
|
+
| hand written checks (baseline) | | 1,166,400 |
|
|
134
|
+
| **envyak** | 0.1.1 | **560,800** |
|
|
135
|
+
| @t3-oss/env-core + zod | 0.13.11, zod 4.6.7 | 559,600 |
|
|
136
|
+
| envalid | 9.0.0 | 92,400 |
|
|
137
|
+
| znv + zod | 1.0.0, zod 4.6.7 | 44,000 |
|
|
138
|
+
|
|
139
|
+
Hand written checks are the ceiling: no messages, no masking, no reuse. On this machine envyak and @t3-oss/env-core + zod trade places from run to run; treat them as equally fast.
|
|
140
|
+
|
|
141
|
+
## Size
|
|
142
|
+
|
|
143
|
+
Minified and gzipped with `bun build --minify`, for a schema using four validators (`port`, `bool`, `url`, `str`), so tree shaking applies equally to every library. Run `npm run size`.
|
|
144
|
+
|
|
145
|
+
| Library | min+gzip |
|
|
146
|
+
| --- | ---: |
|
|
147
|
+
| **envyak** | **1.8 kB** |
|
|
148
|
+
| envalid | 2.3 kB |
|
|
149
|
+
| @t3-oss/env-core + zod/mini | 4.5 kB |
|
|
150
|
+
| @t3-oss/env-core + zod | 93.2 kB |
|
|
151
|
+
| znv + zod | 94.3 kB |
|
|
152
|
+
|
|
153
|
+
The whole envyak entry is 5.1 kB minified, 2.6 kB gzipped.
|
|
154
|
+
|
|
155
|
+
## Compatibility
|
|
156
|
+
|
|
157
|
+
- Node.js 18 or newer, ESM (`import`) and CommonJS (`require`).
|
|
158
|
+
- Bun, tested in CI.
|
|
159
|
+
- Deno 2 through `npm:envyak`, tested in CI.
|
|
160
|
+
- Edge runtimes such as Cloudflare Workers: pass the bindings as `source`.
|
|
161
|
+
- Browsers and bundlers: no Node built ins are imported, and `sideEffects` is `false`.
|
|
162
|
+
- TypeScript types ship with the package and are tested with `tsc` in CI.
|
|
163
|
+
|
|
164
|
+
## Why not another library?
|
|
165
|
+
|
|
166
|
+
All three below are good tools. These facts were checked against the published packages (envalid 9.0.0, @t3-oss/env-core 0.13.11, znv 1.0.0 with zod 4.6.7):
|
|
167
|
+
|
|
168
|
+
- **envalid** has no dependencies and also reports every error. Its default reporter prints the problems and calls `process.exit(1)` instead of throwing, error messages include the rejected value, and there is no option to mask secrets. Its strict proxy, which throws when you read an unknown key, is a feature envyak does not have.
|
|
169
|
+
- **@t3-oss/env-core** works with any Standard Schema library (zod, valibot, arktype) and has a client and server split built for frameworks, which envyak does not have. On failure it logs the issues with `console.error` and throws `Invalid environment variables`. You bring the schema library, which is most of the size.
|
|
170
|
+
- **znv** gives you the full power of zod schemas. It needs zod as a peer, and its thrown message lists the received values, secrets included.
|
|
171
|
+
|
|
172
|
+
Pick envyak if you want exact types without a schema library, one thrown error with fix hints, and secrets that stay out of logs.
|
|
173
|
+
|
|
174
|
+
## FAQ
|
|
175
|
+
|
|
176
|
+
**Does envyak load my `.env` file?**
|
|
177
|
+
No. Use `node --env-file=.env`, let Bun or Deno read it, or use any loader. envyak validates whatever ends up in the source.
|
|
178
|
+
|
|
179
|
+
**Can I use zod or valibot schemas?**
|
|
180
|
+
Wrap them: `custom((raw) => schema.parse(raw))`. If your whole project is built on zod, @t3-oss/env-core or znv may suit you better.
|
|
181
|
+
|
|
182
|
+
**Why is the result frozen?**
|
|
183
|
+
Configuration should not change after startup. Freezing turns an accidental write into a `TypeError` in strict mode, and the types mark every property `readonly`.
|
|
184
|
+
|
|
185
|
+
**Can I reuse a schema?**
|
|
186
|
+
Yes. A schema is a plain object of validators; call `env(schema, { source })` as many times as you need.
|
|
187
|
+
|
|
188
|
+
## Website
|
|
189
|
+
|
|
190
|
+
The landing page in `docs/` is built by `scripts/build-site.mjs`, which inlines the real `src/index.js` so the playground runs the published code. It is available in English, Portuguese, Spanish and Japanese. Built with [Monsoon](https://github.com/kwy404/monsoon), [Voodoo.js](https://github.com/kwy404/Voodoo.js) and [glyphfox](https://github.com/kwy404/glyphfox).
|
|
191
|
+
|
|
192
|
+
## License
|
|
193
|
+
|
|
194
|
+
[MIT](LICENSE), 2026 Alexandre Kohler.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* envyak: typed environment variables with zero dependencies.
|
|
4
|
+
*
|
|
5
|
+
* A schema maps variable names to validators. `env(schema)` reads every
|
|
6
|
+
* variable, collects every problem, and either returns a frozen object of
|
|
7
|
+
* parsed values or throws one `EnvError` that lists all of them.
|
|
8
|
+
*
|
|
9
|
+
* @module envyak
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const MASK = '[secret]';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @typedef {object} Issue
|
|
16
|
+
* @property {string} key Variable name.
|
|
17
|
+
* @property {'missing' | 'invalid'} reason Why it failed.
|
|
18
|
+
* @property {string} message What was expected (never contains a secret value).
|
|
19
|
+
* @property {string} hint How to fix it.
|
|
20
|
+
* @property {boolean} secret Whether the variable is marked secret.
|
|
21
|
+
* @property {string} [received] The raw value, only for variables not marked secret.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** Error thrown by `env()` with every missing or invalid variable. */
|
|
25
|
+
class EnvError extends Error {
|
|
26
|
+
/** @param {Issue[]} issues */
|
|
27
|
+
constructor(issues) {
|
|
28
|
+
const width = Math.max(0, ...issues.map((i) => i.key.length));
|
|
29
|
+
const n = issues.length;
|
|
30
|
+
super(
|
|
31
|
+
`${n} environment variable${n === 1 ? ' is' : 's are'} missing or invalid:\n` +
|
|
32
|
+
issues
|
|
33
|
+
.map(
|
|
34
|
+
(i) =>
|
|
35
|
+
`\n ${i.key.padEnd(width)} ${i.message}${
|
|
36
|
+
i.received !== undefined
|
|
37
|
+
? `, got ${JSON.stringify(i.received)}`
|
|
38
|
+
: i.secret && i.reason === 'invalid'
|
|
39
|
+
? ', got a secret value (hidden)'
|
|
40
|
+
: ''
|
|
41
|
+
}\n ${' '.repeat(width)} fix: ${i.hint}`,
|
|
42
|
+
)
|
|
43
|
+
.join(''),
|
|
44
|
+
);
|
|
45
|
+
this.name = 'EnvError';
|
|
46
|
+
/** @type {Issue[]} */
|
|
47
|
+
this.issues = issues;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Rejects a value from inside a validator. */
|
|
52
|
+
const fail = (expect) => {
|
|
53
|
+
throw new Error('expected ' + expect);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const range = (what, min, max, unit = '') =>
|
|
57
|
+
what +
|
|
58
|
+
(min !== undefined && max !== undefined
|
|
59
|
+
? ` from ${min} to ${max}${unit}`
|
|
60
|
+
: min !== undefined
|
|
61
|
+
? ` of at least ${min}${unit}`
|
|
62
|
+
: max !== undefined
|
|
63
|
+
? ` of at most ${max}${unit}`
|
|
64
|
+
: '');
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Builds a validator. `parse` receives a non-empty string and returns the
|
|
68
|
+
* typed value or throws an Error.
|
|
69
|
+
*/
|
|
70
|
+
const make = (type, expect, example, parse, options = {}) =>
|
|
71
|
+
Object.freeze({ type, expect, example, parse, options });
|
|
72
|
+
|
|
73
|
+
const NUM = /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
|
|
74
|
+
const INT = /^[+-]?\d+$/;
|
|
75
|
+
|
|
76
|
+
const numeric = (type, what, re, options = {}, min = options.min, max = options.max, example = min ?? max ?? 42) => {
|
|
77
|
+
const expect = range(what, min, max);
|
|
78
|
+
return make(
|
|
79
|
+
type,
|
|
80
|
+
expect,
|
|
81
|
+
String(example),
|
|
82
|
+
(raw) => {
|
|
83
|
+
const v = raw.trim();
|
|
84
|
+
const n = Number(v);
|
|
85
|
+
if (!re.test(v) || !Number.isFinite(n) || (type !== 'num' && !Number.isSafeInteger(n))) fail(expect);
|
|
86
|
+
if (n < min || n > max) fail(expect);
|
|
87
|
+
return n;
|
|
88
|
+
},
|
|
89
|
+
options,
|
|
90
|
+
);
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/** Any non-empty string, kept as written. Options: `minLength`, `maxLength`, `pattern`. */
|
|
94
|
+
const str = (options = {}) => {
|
|
95
|
+
const { minLength: lo, maxLength: hi, pattern } = options;
|
|
96
|
+
const expect = range('a string', lo, hi, ' characters') + (pattern ? ` matching ${pattern}` : '');
|
|
97
|
+
return make(
|
|
98
|
+
'str',
|
|
99
|
+
expect,
|
|
100
|
+
undefined,
|
|
101
|
+
(raw) => {
|
|
102
|
+
if (raw.length < lo || raw.length > hi) fail(expect);
|
|
103
|
+
if (pattern) {
|
|
104
|
+
pattern.lastIndex = 0;
|
|
105
|
+
if (!pattern.test(raw)) fail(expect);
|
|
106
|
+
}
|
|
107
|
+
return raw;
|
|
108
|
+
},
|
|
109
|
+
options,
|
|
110
|
+
);
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/** A finite decimal number (no hex, no Infinity). Options: `min`, `max`. */
|
|
114
|
+
const num = (options) => numeric('num', 'a number', NUM, options);
|
|
115
|
+
|
|
116
|
+
/** A safe integer in base 10. Options: `min`, `max`. */
|
|
117
|
+
const int = (options) => numeric('int', 'an integer', INT, options);
|
|
118
|
+
|
|
119
|
+
/** An integer from 1 to 65535. */
|
|
120
|
+
const port = (options) => numeric('port', 'a port number', INT, options, 1, 65535, 3000);
|
|
121
|
+
|
|
122
|
+
const BOOL = { __proto__: null, true: true, false: false, 1: true, 0: false, yes: true, no: false, on: true, off: false };
|
|
123
|
+
const BOOL_EXPECT = 'true, false, 1, 0, yes, no, on or off';
|
|
124
|
+
|
|
125
|
+
/** true, false, 1, 0, yes, no, on or off, case insensitive. Nothing else. */
|
|
126
|
+
const bool = (options) =>
|
|
127
|
+
make(
|
|
128
|
+
'bool',
|
|
129
|
+
BOOL_EXPECT,
|
|
130
|
+
'true',
|
|
131
|
+
(raw) => {
|
|
132
|
+
const v = BOOL[raw.trim().toLowerCase()];
|
|
133
|
+
return v === undefined ? fail(BOOL_EXPECT) : v;
|
|
134
|
+
},
|
|
135
|
+
options,
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
/** An absolute URL accepted by the WHATWG URL parser. Option: `protocols`. */
|
|
139
|
+
const url = (options = {}) => {
|
|
140
|
+
const p = options.protocols;
|
|
141
|
+
const expect = 'an absolute URL' + (p ? ` using ${p.join(' or ')}` : '');
|
|
142
|
+
return make(
|
|
143
|
+
'url',
|
|
144
|
+
expect,
|
|
145
|
+
`${p ? p[0] : 'https'}://example.com`,
|
|
146
|
+
(raw) => {
|
|
147
|
+
const v = raw.trim();
|
|
148
|
+
let u;
|
|
149
|
+
try {
|
|
150
|
+
u = new URL(v);
|
|
151
|
+
} catch {
|
|
152
|
+
fail(expect);
|
|
153
|
+
}
|
|
154
|
+
if (p && !p.includes(u.protocol.slice(0, -1))) fail(expect);
|
|
155
|
+
return v;
|
|
156
|
+
},
|
|
157
|
+
options,
|
|
158
|
+
);
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
/** One `@`, no spaces, a dot in the domain, at most 254 characters. */
|
|
162
|
+
const email = (options) =>
|
|
163
|
+
make(
|
|
164
|
+
'email',
|
|
165
|
+
'an email address',
|
|
166
|
+
'team@example.com',
|
|
167
|
+
(raw) => {
|
|
168
|
+
const v = raw.trim();
|
|
169
|
+
return v.length < 255 && /^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/.test(v) ? v : fail('an email address');
|
|
170
|
+
},
|
|
171
|
+
options,
|
|
172
|
+
);
|
|
173
|
+
|
|
174
|
+
/** One of the given strings, compared exactly after trimming. */
|
|
175
|
+
const oneOf = (choices, options) => {
|
|
176
|
+
const expect = 'one of ' + choices.join(', ');
|
|
177
|
+
return make(
|
|
178
|
+
'oneOf',
|
|
179
|
+
expect,
|
|
180
|
+
choices[0],
|
|
181
|
+
(raw) => {
|
|
182
|
+
const v = raw.trim();
|
|
183
|
+
return choices.includes(v) ? v : fail(expect);
|
|
184
|
+
},
|
|
185
|
+
options,
|
|
186
|
+
);
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
const freeze = (v) => {
|
|
190
|
+
if (v && typeof v === 'object') {
|
|
191
|
+
Object.freeze(v);
|
|
192
|
+
Object.values(v).forEach(freeze);
|
|
193
|
+
}
|
|
194
|
+
return v;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* A separated list. Items are trimmed, empty items are skipped and each item
|
|
199
|
+
* goes through `item`. Option: `separator` (string or RegExp, default `,`).
|
|
200
|
+
*/
|
|
201
|
+
const list = (item, options = {}) => {
|
|
202
|
+
const sep = options.separator ?? ',';
|
|
203
|
+
return make(
|
|
204
|
+
'list',
|
|
205
|
+
`a list separated by "${sep}"`,
|
|
206
|
+
item.example && [item.example, item.example].join(typeof sep === 'string' ? sep : ','),
|
|
207
|
+
(raw) =>
|
|
208
|
+
Object.freeze(
|
|
209
|
+
raw
|
|
210
|
+
.split(sep)
|
|
211
|
+
.map((s) => s.trim())
|
|
212
|
+
.filter(Boolean)
|
|
213
|
+
.map((s, i) => {
|
|
214
|
+
try {
|
|
215
|
+
return item.parse(s);
|
|
216
|
+
} catch (e) {
|
|
217
|
+
throw new Error(`item ${i + 1}: ${e.message}`);
|
|
218
|
+
}
|
|
219
|
+
}),
|
|
220
|
+
),
|
|
221
|
+
options,
|
|
222
|
+
);
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
/** Any JSON text. The parsed value is deep frozen. */
|
|
226
|
+
const json = (options) =>
|
|
227
|
+
make(
|
|
228
|
+
'json',
|
|
229
|
+
'valid JSON',
|
|
230
|
+
'{"key":"value"}',
|
|
231
|
+
(raw) => {
|
|
232
|
+
try {
|
|
233
|
+
return freeze(JSON.parse(raw));
|
|
234
|
+
} catch {
|
|
235
|
+
fail('valid JSON');
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
options,
|
|
239
|
+
);
|
|
240
|
+
|
|
241
|
+
const DATE = /^(\d{4})-(\d\d)-(\d\d)(?:T(\d\d):(\d\d)(?::(\d\d)(?:\.(\d{1,3}))?)?(Z|[+-]\d\d:\d\d)?)?$/;
|
|
242
|
+
const DATE_EXPECT = 'an ISO 8601 date such as 2024-05-01 or 2024-05-01T12:00:00Z';
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* An ISO 8601 date (`YYYY-MM-DD`, UTC midnight) or date time
|
|
246
|
+
* (`YYYY-MM-DDTHH:mm[:ss[.sss]][Z|+HH:mm]`, local time when there is no offset).
|
|
247
|
+
*/
|
|
248
|
+
const date = (options) =>
|
|
249
|
+
make(
|
|
250
|
+
'date',
|
|
251
|
+
DATE_EXPECT,
|
|
252
|
+
'2024-05-01',
|
|
253
|
+
(raw) => {
|
|
254
|
+
const m = DATE.exec(raw.trim()) || fail(DATE_EXPECT);
|
|
255
|
+
const [y, mo, d, h, mi, s] = m.slice(1, 7).map((x) => +(x || 0));
|
|
256
|
+
const ms = +(m[7] || '').padEnd(3, '0');
|
|
257
|
+
const z = m[8];
|
|
258
|
+
// Day 0 of the next month is the last day of this one; the year is
|
|
259
|
+
// shifted into the 400 year cycle so Date.UTC never sees 0 to 99.
|
|
260
|
+
const days = new Date(Date.UTC(2000 + (y % 400), mo, 0)).getUTCDate();
|
|
261
|
+
const oh = z && z !== 'Z' ? +z.slice(1, 3) : 0;
|
|
262
|
+
const om = z && z !== 'Z' ? +z.slice(4) : 0;
|
|
263
|
+
if (mo < 1 || mo > 12 || d < 1 || d > days || h > 23 || mi > 59 || s > 59 || oh > 23 || om > 59)
|
|
264
|
+
fail(DATE_EXPECT);
|
|
265
|
+
const out = new Date(0);
|
|
266
|
+
if (m[4] && !z) {
|
|
267
|
+
// A date time without an offset is local time, as in ECMAScript.
|
|
268
|
+
out.setFullYear(y, mo - 1, d);
|
|
269
|
+
out.setHours(h, mi, s, ms);
|
|
270
|
+
} else {
|
|
271
|
+
out.setUTCFullYear(y, mo - 1, d);
|
|
272
|
+
out.setUTCHours(h, mi, s, ms);
|
|
273
|
+
out.setTime(out.getTime() - (z && z[0] === '-' ? -1 : 1) * (oh * 60 + om) * 6e4);
|
|
274
|
+
}
|
|
275
|
+
return out;
|
|
276
|
+
},
|
|
277
|
+
options,
|
|
278
|
+
);
|
|
279
|
+
|
|
280
|
+
/** Your own parser: return the value, or throw an Error whose message says what was expected. */
|
|
281
|
+
const custom = (fn, options) => make('custom', 'a valid value', undefined, (raw) => fn(raw), options);
|
|
282
|
+
|
|
283
|
+
const defaultSource = () => {
|
|
284
|
+
const g = globalThis;
|
|
285
|
+
if (g.process && g.process.env) return g.process.env;
|
|
286
|
+
try {
|
|
287
|
+
return g.Deno.env.toObject();
|
|
288
|
+
} catch {
|
|
289
|
+
return {};
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
const fix = (key, spec) => {
|
|
294
|
+
const o = spec.options;
|
|
295
|
+
const example = o.example ?? spec.example;
|
|
296
|
+
return (
|
|
297
|
+
`set ${key}` +
|
|
298
|
+
(o.description ? ` (${o.description})` : '') +
|
|
299
|
+
(example === undefined ? ` to ${spec.expect}` : `, for example ${key}=${example}`)
|
|
300
|
+
);
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
const SECRETS = Symbol('secrets');
|
|
304
|
+
|
|
305
|
+
const masked = (out) => {
|
|
306
|
+
const copy = { ...out };
|
|
307
|
+
for (const key of out[SECRETS]) if (copy[key] !== undefined) copy[key] = MASK;
|
|
308
|
+
return copy;
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
// Shared by every result: the helpers are not own properties, so Object.keys
|
|
312
|
+
// and spreading see only the variables. They are writable (but not
|
|
313
|
+
// enumerable) so a variable with the same name can still be set and shadows
|
|
314
|
+
// its helper.
|
|
315
|
+
const method = (value) => ({ value, writable: true });
|
|
316
|
+
const PROTO = Object.defineProperties(
|
|
317
|
+
{},
|
|
318
|
+
{
|
|
319
|
+
toString: method(function () {
|
|
320
|
+
return JSON.stringify(masked(this));
|
|
321
|
+
}),
|
|
322
|
+
toJSON: method(function () {
|
|
323
|
+
return masked(this);
|
|
324
|
+
}),
|
|
325
|
+
[Symbol.for('nodejs.util.inspect.custom')]: method(function () {
|
|
326
|
+
return masked(this);
|
|
327
|
+
}),
|
|
328
|
+
[Symbol.for('Deno.customInspect')]: method(function (inspect, opts) {
|
|
329
|
+
return inspect(masked(this), opts);
|
|
330
|
+
}),
|
|
331
|
+
},
|
|
332
|
+
);
|
|
333
|
+
|
|
334
|
+
/** Per schema prototype that records the secret keys, so a result costs no extra allocation. */
|
|
335
|
+
const protos = new WeakMap();
|
|
336
|
+
const protoFor = (schema, secrets) => {
|
|
337
|
+
let proto = protos.get(schema);
|
|
338
|
+
if (!proto || proto[SECRETS].join() !== secrets.join()) {
|
|
339
|
+
proto = Object.freeze(Object.create(PROTO, { [SECRETS]: { value: secrets } }));
|
|
340
|
+
protos.set(schema, proto);
|
|
341
|
+
}
|
|
342
|
+
return proto;
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Reads, validates and parses every variable in `schema`.
|
|
347
|
+
*
|
|
348
|
+
* @param {Record<string, ReturnType<typeof make>>} schema
|
|
349
|
+
* @param {{ source?: Record<string, unknown> }} [options]
|
|
350
|
+
* @returns {Readonly<Record<string, unknown>>}
|
|
351
|
+
* @throws {EnvError} when any variable is missing or invalid.
|
|
352
|
+
*/
|
|
353
|
+
function env(schema, options = {}) {
|
|
354
|
+
const source = options.source || defaultSource();
|
|
355
|
+
const production = source.NODE_ENV === 'production';
|
|
356
|
+
const keys = Object.keys(schema);
|
|
357
|
+
const out = Object.create(
|
|
358
|
+
protoFor(
|
|
359
|
+
schema,
|
|
360
|
+
keys.filter((key) => schema[key].options.secret),
|
|
361
|
+
),
|
|
362
|
+
);
|
|
363
|
+
const issues = [];
|
|
364
|
+
for (const key of keys) {
|
|
365
|
+
const spec = schema[key];
|
|
366
|
+
const o = spec.options;
|
|
367
|
+
const raw = source[key];
|
|
368
|
+
if (raw == null || raw === '') {
|
|
369
|
+
if (o.devDefault !== undefined && !production) out[key] = o.devDefault;
|
|
370
|
+
else if (o.default !== undefined) out[key] = o.default;
|
|
371
|
+
else if (o.optional) out[key] = undefined;
|
|
372
|
+
else issues.push({ key, reason: 'missing', message: 'is missing', hint: fix(key, spec), secret: !!o.secret });
|
|
373
|
+
} else {
|
|
374
|
+
const text = typeof raw === 'object' || typeof raw === 'function' || typeof raw === 'symbol' ? null : String(raw);
|
|
375
|
+
try {
|
|
376
|
+
if (text === null) throw new Error(`expected a string, got ${typeof raw}`);
|
|
377
|
+
out[key] = spec.parse(text);
|
|
378
|
+
} catch (e) {
|
|
379
|
+
let message = String((e && e.message) || e);
|
|
380
|
+
if (o.secret && text !== null && message.includes(text)) message = 'expected ' + spec.expect;
|
|
381
|
+
const issue = { key, reason: 'invalid', message, hint: fix(key, spec), secret: !!o.secret };
|
|
382
|
+
if (!o.secret && text !== null) issue.received = text;
|
|
383
|
+
issues.push(issue);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
if (issues.length) throw new EnvError(issues);
|
|
388
|
+
return Object.freeze(out);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
module.exports = { EnvError, bool, custom, date, email, env, int, json, list, num, oneOf, port, str, url };
|