envyak 0.0.0-stage → 0.1.0

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 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.es.md ADDED
@@ -0,0 +1,194 @@
1
+ <picture>
2
+ <source media="(prefers-color-scheme: dark)" srcset="assets/banner-dark.svg">
3
+ <img alt="envyak: variables de entorno tipadas, todos los errores a la vez" src="assets/banner-light.svg" width="100%">
4
+ </picture>
5
+
6
+ [English](README.md) | [Português](README.pt.md) | **Español** | [日本語](README.ja.md)
7
+
8
+ [![npm](https://img.shields.io/npm/v/envyak?color=f4a52c)](https://www.npmjs.com/package/envyak)
9
+ [![CI](https://github.com/kwy404/envyak/actions/workflows/ci.yml/badge.svg)](https://github.com/kwy404/envyak/actions/workflows/ci.yml)
10
+ [![types](https://img.shields.io/badge/types-included-2756c5)](index.d.ts)
11
+ [![dependencies](https://img.shields.io/badge/dependencies-0-1d7a4f)](package.json)
12
+ [![size](https://img.shields.io/badge/min%2Bgzip-2.6%20kB-f4a52c)](#tamaño)
13
+ [![license](https://img.shields.io/badge/license-MIT-17203a)](LICENSE)
14
+
15
+ **envyak valida y convierte variables de entorno en Node.js, Bun, Deno y entornos edge, con tipos exactos de TypeScript y sin dependencias.** Describes cada variable una sola vez; envyak convierte las cadenas de `process.env` en números, booleanos, URLs, listas, JSON y fechas de verdad, informa de todas las variables ausentes o inválidas en un único `EnvError` y nunca imprime el valor de un secreto.
16
+
17
+ [Sitio web y playground en vivo](https://kwy404.github.io/envyak/es/)
18
+
19
+ ## Instalación
20
+
21
+ ```sh
22
+ npm i envyak
23
+ ```
24
+
25
+ ESM y CommonJS, tipos incluidos, Node 18 o posterior. Bun y Deno (`npm:envyak`) funcionan tal cual.
26
+
27
+ ## Inicio rápido
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
+ Cuando algo falla, el arranque se detiene con un único informe para todas las variables (los mensajes de la biblioteca están en inglés):
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
+ Lee cada clave de `schema` desde la fuente, la convierte y devuelve un objeto congelado con el tipo derivado del esquema. Si alguna variable falta o es inválida, lanza un único `EnvError` con todas ellas, en el orden del esquema.
64
+
65
+ | Opción | Por defecto | Significado |
66
+ | --- | --- | --- |
67
+ | `source` | `process.env`, luego `Deno.env.toObject()`, luego `{}` | De dónde leer. Pásala en Workers (bindings de `env`), en Vite (`import.meta.env`) o con un `.env` ya leído. `NODE_ENV` se lee de la misma fuente. |
68
+
69
+ El resultado está congelado, igual que las listas y los valores JSON que contiene. `toString()`, `toJSON()`, `util.inspect` (Node y Bun) y `Deno.inspect` muestran los valores secretos como `[secret]`. Leer `config.API_KEY` sigue dando a tu código el valor real.
70
+
71
+ ### Validadores
72
+
73
+ | Validador | Acepta | Tipo |
74
+ | --- | --- | --- |
75
+ | `str(options?)` | cualquier cadena no vacía; `minLength`, `maxLength`, `pattern` | `string` |
76
+ | `num(options?)` | un número decimal finito; `min`, `max` | `number` |
77
+ | `int(options?)` | un entero seguro escrito en base 10; `min`, `max` | `number` |
78
+ | `port(options?)` | un entero de 1 a 65535 | `number` |
79
+ | `bool(options?)` | `true false 1 0 yes no on off`, sin distinguir mayúsculas | `boolean` |
80
+ | `url(options?)` | una URL absoluta, leída con `new URL`; `protocols` | `string` |
81
+ | `email(options?)` | una `@`, sin espacios, un punto en el dominio | `string` |
82
+ | `oneOf(choices, options?)` | una de las cadenas de la lista | unión de las opciones |
83
+ | `list(item, options?)` | elementos separados por `separator` (`,` por defecto), cada uno convertido por `item` | `readonly T[]` |
84
+ | `json<T>(options?)` | cualquier texto JSON, congelado en profundidad | `T` (`unknown` por defecto) |
85
+ | `date(options?)` | una fecha o fecha y hora ISO 8601 que exista en el calendario | `Date` |
86
+ | `custom(parse, options?)` | lo que devuelva `parse(raw)`; lanza un `Error` para rechazar | el tipo de retorno |
87
+
88
+ ### Opciones comunes
89
+
90
+ Todos los validadores aceptan:
91
+
92
+ | Opción | Efecto en el tipo | Significado |
93
+ | --- | --- | --- |
94
+ | `default` | `T` | Se usa cuando la variable falta, en cualquier entorno. |
95
+ | `devDefault` | `T` | Se usa cuando la variable falta y `NODE_ENV` no es `production`. Ahí gana a `default`. En producción se aplica `default`, y sin él la variable es obligatoria. |
96
+ | `optional: true` | `T \| undefined` | Una variable ausente se convierte en `undefined` en lugar de un error. |
97
+ | `description` | ninguno | Aparece en la pista para arreglarlo. |
98
+ | `example` | ninguno | Aparece en la pista como `KEY=example`. |
99
+ | `secret: true` | ninguno | El valor nunca aparece en errores, issues, `toString`, `toJSON` ni en la salida de inspect. |
100
+
101
+ ### `EnvError`
102
+
103
+ `error.name` es `'EnvError'` y `error.issues` es un array de:
104
+
105
+ ```ts
106
+ interface Issue {
107
+ key: string; // el nombre de la variable
108
+ reason: 'missing' | 'invalid';
109
+ message: string; // lo que se esperaba; nunca contiene un valor secreto
110
+ hint: string; // cómo arreglarlo
111
+ secret: boolean;
112
+ received?: string; // el valor en bruto, solo si es inválido y no secreto
113
+ }
114
+ ```
115
+
116
+ ## Detalles de comportamiento
117
+
118
+ - **Vacío significa ausente.** `PORT=` en un archivo `.env` se trata como una variable sin definir, así que se aplica `default`. Si una cadena vacía es un valor válido para ti, usa `str({ default: '' })`.
119
+ - **Números estrictos.** `num` e `int` rechazan hexadecimal, octal, binario, `Infinity`, `NaN`, guiones bajos y cadenas en blanco. `int` también rechaza valores por encima de `Number.MAX_SAFE_INTEGER`.
120
+ - **Booleanos estrictos.** `bool` acepta exactamente `true false 1 0 yes no on off`, ignorando mayúsculas y espacios en los extremos. Cualquier otra cosa es un error, no `false`.
121
+ - **Las fechas siguen ECMAScript.** Una fecha sin hora como `2024-05-01` es medianoche en UTC, una fecha y hora sin desfase como `2024-05-01T12:00` es hora local, y `Z` o un desfase es exacto. Es el [formato de fecha y hora de ECMAScript](https://tc39.es/ecma262/#sec-date-time-string-format). Las fechas imposibles como `2024-02-30` se rechazan.
122
+ - **Las URLs usan el parser WHATWG** (`new URL`), descrito en el [URL Standard](https://url.spec.whatwg.org/). `protocols` compara el esquema sin los dos puntos.
123
+ - **El email es una comprobación básica**, no un análisis completo de la RFC 5322: una `@`, sin espacios, parte local no vacía y un punto en el dominio.
124
+ - **Los secretos se ocultan dos veces.** El issue de un secreto no tiene `received`, y si un parser propio pone el valor en bruto en su mensaje de error, el mensaje se sustituye por uno genérico.
125
+ - **Las variables desconocidas se ignoran.** Solo se leen y devuelven las claves del esquema.
126
+
127
+ ## Rendimiento
128
+
129
+ Lectura de las mismas 8 variables con cada biblioteca, mediana de 5 ejecuciones, más es mejor. Node v24.16.0 en Windows 10 x64, un equipo modesto. Ejecútalo tú mismo con `npm run bench` (mira `bench/run.mjs`).
130
+
131
+ | Biblioteca | Versión | Lecturas por segundo |
132
+ | --- | --- | ---: |
133
+ | comprobaciones escritas a mano (referencia) | | 1,166,400 |
134
+ | **envyak** | 0.1.0 | **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
+ Las comprobaciones escritas a mano son el techo: sin mensajes, sin ocultar secretos, sin reutilización. En esta máquina envyak y @t3-oss/env-core + zod se alternan de una ejecución a otra; tómalos como igual de rápidos.
140
+
141
+ ## Tamaño
142
+
143
+ Minificado y con gzip usando `bun build --minify`, con un esquema de cuatro validadores (`port`, `bool`, `url`, `str`), para que el tree shaking se aplique por igual a todas las bibliotecas. Ejecuta `npm run size`.
144
+
145
+ | Biblioteca | 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
+ La entrada completa de envyak ocupa 5.1 kB minificada y 2.6 kB con gzip.
154
+
155
+ ## Compatibilidad
156
+
157
+ - Node.js 18 o posterior, ESM (`import`) y CommonJS (`require`).
158
+ - Bun, probado en CI.
159
+ - Deno 2 mediante `npm:envyak`, probado en CI.
160
+ - Entornos edge como Cloudflare Workers: pasa los bindings como `source`.
161
+ - Navegadores y bundlers: no se importa ningún módulo propio de Node, y `sideEffects` es `false`.
162
+ - Los tipos de TypeScript vienen en el paquete y se prueban con `tsc` en CI.
163
+
164
+ ## ¿Por qué no otra biblioteca?
165
+
166
+ Las tres siguientes son buenas herramientas. Estos datos se comprobaron con los paquetes publicados (envalid 9.0.0, @t3-oss/env-core 0.13.11, znv 1.0.0 con zod 4.6.7):
167
+
168
+ - **envalid** no tiene dependencias y también informa de todos los errores. Su reporter por defecto imprime los problemas y llama a `process.exit(1)` en lugar de lanzar un error, los mensajes incluyen el valor rechazado y no hay opción para ocultar secretos. Su proxy estricto, que lanza un error al leer una clave desconocida, es una función que envyak no tiene.
169
+ - **@t3-oss/env-core** funciona con cualquier biblioteca Standard Schema (zod, valibot, arktype) y tiene una separación entre cliente y servidor pensada para frameworks, que envyak no tiene. Cuando falla, registra los problemas con `console.error` y lanza `Invalid environment variables`. La biblioteca de esquemas la pones tú, y es la mayor parte del tamaño.
170
+ - **znv** te da toda la potencia de los esquemas de zod. Necesita zod como peer, y el mensaje que lanza enumera los valores recibidos, secretos incluidos.
171
+
172
+ Elige envyak si quieres tipos exactos sin biblioteca de esquemas, un único error con pistas para arreglarlo y secretos fuera de los logs.
173
+
174
+ ## Preguntas frecuentes
175
+
176
+ **¿envyak carga mi archivo `.env`?**
177
+ No. Usa `node --env-file=.env`, deja que Bun o Deno lo lean, o usa el cargador que prefieras. envyak valida lo que termine en la fuente.
178
+
179
+ **¿Puedo usar esquemas de zod o valibot?**
180
+ Envuélvelos: `custom((raw) => schema.parse(raw))`. Si todo tu proyecto ya usa zod, quizá te convengan más @t3-oss/env-core o znv.
181
+
182
+ **¿Por qué el resultado está congelado?**
183
+ La configuración no debería cambiar después del arranque. Congelarla convierte una escritura accidental en un `TypeError` en modo estricto, y los tipos marcan todas las propiedades como `readonly`.
184
+
185
+ **¿Puedo reutilizar un esquema?**
186
+ Sí. Un esquema es un objeto simple de validadores; llama a `env(schema, { source })` tantas veces como necesites.
187
+
188
+ ## Sitio web
189
+
190
+ La página de `docs/` la genera `scripts/build-site.mjs`, que incrusta el `src/index.js` real para que el playground ejecute el código publicado. Está en inglés, portugués, español y japonés. Hecho con [Monsoon](https://github.com/kwy404/monsoon), [Voodoo.js](https://github.com/kwy404/Voodoo.js) y [glyphfox](https://github.com/kwy404/glyphfox).
191
+
192
+ ## Licencia
193
+
194
+ [MIT](LICENSE), 2026 Alexandre Kohler.
package/README.ja.md ADDED
@@ -0,0 +1,194 @@
1
+ <picture>
2
+ <source media="(prefers-color-scheme: dark)" srcset="assets/banner-dark.svg">
3
+ <img alt="envyak: 型付きの環境変数、エラーはまとめて一度に" src="assets/banner-light.svg" width="100%">
4
+ </picture>
5
+
6
+ [English](README.md) | [Português](README.pt.md) | [Español](README.es.md) | **日本語**
7
+
8
+ [![npm](https://img.shields.io/npm/v/envyak?color=f4a52c)](https://www.npmjs.com/package/envyak)
9
+ [![CI](https://github.com/kwy404/envyak/actions/workflows/ci.yml/badge.svg)](https://github.com/kwy404/envyak/actions/workflows/ci.yml)
10
+ [![types](https://img.shields.io/badge/types-included-2756c5)](index.d.ts)
11
+ [![dependencies](https://img.shields.io/badge/dependencies-0-1d7a4f)](package.json)
12
+ [![size](https://img.shields.io/badge/min%2Bgzip-2.6%20kB-f4a52c)](#サイズ)
13
+ [![license](https://img.shields.io/badge/license-MIT-17203a)](LICENSE)
14
+
15
+ **envyak は Node.js、Bun、Deno、エッジランタイムで環境変数を検証して変換するライブラリです。TypeScript の型を正確に推論し、依存パッケージはありません。** 変数を一度記述するだけで、`process.env` の文字列を本物の数値、真偽値、URL、リスト、JSON、日付に変換します。欠けている変数や不正な変数はひとつの `EnvError` にまとめて報告し、シークレットの値を表示することはありません。
16
+
17
+ [Web サイトとライブプレイグラウンド](https://kwy404.github.io/envyak/ja/)
18
+
19
+ ## インストール
20
+
21
+ ```sh
22
+ npm i envyak
23
+ ```
24
+
25
+ ESM と CommonJS に対応し、型定義を同梱しています。Node 18 以降が必要です。Bun と Deno (`npm:envyak`) ではそのまま動きます。
26
+
27
+ ## クイックスタート
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
+ 問題があると、起動時にすべての変数をまとめたレポートで止まります (ライブラリのメッセージは英語です)。
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
+ `schema` のキーをすべてソースから読み取って変換し、スキーマから型付けされた凍結オブジェクトを返します。欠けている変数や不正な変数があれば、スキーマの順にすべてを並べたひとつの `EnvError` を投げます。
64
+
65
+ | オプション | デフォルト | 意味 |
66
+ | --- | --- | --- |
67
+ | `source` | `process.env`、次に `Deno.env.toObject()`、最後に `{}` | 読み取り元です。Workers (`env` のバインディング)、Vite (`import.meta.env`)、読み込み済みの `.env` などを渡せます。`NODE_ENV` も同じソースから読みます。 |
68
+
69
+ 結果は凍結され、中のリストや JSON の値も凍結されます。`toString()`、`toJSON()`、`util.inspect` (Node と Bun)、`Deno.inspect` ではシークレットが `[secret]` と表示されます。`config.API_KEY` を読めば、コードには本当の値が渡ります。
70
+
71
+ ### バリデーター
72
+
73
+ | バリデーター | 受け付ける値 | 型 |
74
+ | --- | --- | --- |
75
+ | `str(options?)` | 空でない任意の文字列。`minLength`、`maxLength`、`pattern` | `string` |
76
+ | `num(options?)` | 有限の 10 進数。`min`、`max` | `number` |
77
+ | `int(options?)` | 10 進数で書かれた安全な整数。`min`、`max` | `number` |
78
+ | `port(options?)` | 1 から 65535 までの整数 | `number` |
79
+ | `bool(options?)` | `true false 1 0 yes no on off`、大文字小文字は区別しない | `boolean` |
80
+ | `url(options?)` | `new URL` で解釈できる絶対 URL。`protocols` | `string` |
81
+ | `email(options?)` | `@` がひとつ、空白なし、ドメインにドットがある | `string` |
82
+ | `oneOf(choices, options?)` | 列挙した文字列のどれか | 選択肢のユニオン |
83
+ | `list(item, options?)` | `separator` (デフォルトは `,`) で区切った項目。それぞれを `item` で変換 | `readonly T[]` |
84
+ | `json<T>(options?)` | 任意の JSON テキスト。深く凍結 | `T` (デフォルトは `unknown`) |
85
+ | `date(options?)` | 暦の上に実在する ISO 8601 の日付または日時 | `Date` |
86
+ | `custom(parse, options?)` | `parse(raw)` が返すもの。拒否するときは `Error` を投げる | 戻り値の型 |
87
+
88
+ ### 共通オプション
89
+
90
+ すべてのバリデーターが次のオプションを受け付けます。
91
+
92
+ | オプション | 型への影響 | 意味 |
93
+ | --- | --- | --- |
94
+ | `default` | `T` | 変数が欠けているとき、どの環境でも使われます。 |
95
+ | `devDefault` | `T` | 変数が欠けていて `NODE_ENV` が `production` でないときに使われ、`default` より優先されます。本番では `default` が使われ、それもなければ必須になります。 |
96
+ | `optional: true` | `T \| undefined` | 欠けている変数はエラーではなく `undefined` になります。 |
97
+ | `description` | なし | 直し方のヒントに表示されます。 |
98
+ | `example` | なし | 直し方のヒントに `KEY=example` の形で表示されます。 |
99
+ | `secret: true` | なし | 値はエラー、issues、`toString`、`toJSON`、inspect の出力に一切現れません。 |
100
+
101
+ ### `EnvError`
102
+
103
+ `error.name` は `'EnvError'` で、`error.issues` は次の配列です。
104
+
105
+ ```ts
106
+ interface Issue {
107
+ key: string; // 変数名
108
+ reason: 'missing' | 'invalid';
109
+ message: string; // 期待した内容。シークレットの値は含まない
110
+ hint: string; // 直し方
111
+ secret: boolean;
112
+ received?: string; // 生の値。不正でシークレットでないときだけ
113
+ }
114
+ ```
115
+
116
+ ## 動作の詳細
117
+
118
+ - **空は未設定と同じです。** `.env` ファイルの `PORT=` は未設定として扱われ、`default` が使われます。空文字列を正しい値にしたいときは `str({ default: '' })` を使ってください。
119
+ - **数値は厳格です。** `num` と `int` は 16 進数、8 進数、2 進数、`Infinity`、`NaN`、アンダースコア、空白だけの文字列を拒否します。`int` は `Number.MAX_SAFE_INTEGER` を超える値も拒否します。
120
+ - **真偽値も厳格です。** `bool` が受け付けるのは `true false 1 0 yes no on off` だけで、大文字小文字と前後の空白は無視します。それ以外は `false` ではなくエラーになります。
121
+ - **日付は ECMAScript に従います。** `2024-05-01` のような日付だけの値は UTC の午前 0 時、`2024-05-01T12:00` のようにオフセットのない日時はローカル時刻、`Z` やオフセットがあればその時刻そのものです。これは [ECMAScript の日時文字列フォーマット](https://tc39.es/ecma262/#sec-date-time-string-format) と同じです。`2024-02-30` のような存在しない日付は拒否します。
122
+ - **URL は WHATWG のパーサー** (`new URL`) で解釈します。仕様は [URL Standard](https://url.spec.whatwg.org/) にあります。`protocols` はコロンを除いたスキームと比較します。
123
+ - **メールアドレスは簡易チェックです。** RFC 5322 の完全な解析ではなく、`@` がひとつ、空白なし、空でないローカル部、ドメインのドットを確認します。
124
+ - **シークレットは二重に隠します。** シークレットの issue には `received` がなく、独自パーサーがエラーメッセージに生の値を入れた場合はメッセージを汎用のものに置き換えます。
125
+ - **未知の変数は無視します。** 読み取って返すのはスキーマにあるキーだけです。
126
+
127
+ ## ベンチマーク
128
+
129
+ 同じ 8 個の変数を各ライブラリで読み取り、5 回の計測の中央値を取りました。大きいほど速い。計測環境は Windows 10 x64 上の Node v24.16.0、ごく普通のデスクトップです。`npm run bench` で自分でも実行できます (`bench/run.mjs` を参照)。
130
+
131
+ | ライブラリ | バージョン | 1 秒あたりの読み取り回数 |
132
+ | --- | --- | ---: |
133
+ | 手書きのチェック (基準) | | 1,166,400 |
134
+ | **envyak** | 0.1.0 | **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
+ 手書きのチェックは上限の目安です。メッセージもマスクも再利用もありません。このマシンでは envyak と @t3-oss/env-core + zod の順位は計測ごとに入れ替わるので、同程度の速さと考えてください。
140
+
141
+ ## サイズ
142
+
143
+ `bun build --minify` で minify と gzip をかけたサイズです。4 つのバリデーター (`port`、`bool`、`url`、`str`) を使うスキーマで計測したので、ツリーシェイキングはどのライブラリにも同じように効きます。`npm run size` で計測できます。
144
+
145
+ | ライブラリ | 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
+ envyak のエントリー全体は minify 後 5.1 kB、gzip 後 2.6 kB です。
154
+
155
+ ## 互換性
156
+
157
+ - Node.js 18 以降。ESM (`import`) と CommonJS (`require`)。
158
+ - Bun。CI でテストしています。
159
+ - Deno 2 (`npm:envyak` 経由)。CI でテストしています。
160
+ - Cloudflare Workers などのエッジランタイム。バインディングを `source` に渡してください。
161
+ - ブラウザとバンドラー。Node の組み込みモジュールは読み込まず、`sideEffects` は `false` です。
162
+ - TypeScript の型定義はパッケージに含まれ、CI で `tsc` を使ってテストしています。
163
+
164
+ ## ほかのライブラリではだめなのか
165
+
166
+ 次の 3 つはどれも良いツールです。以下の内容は公開されているパッケージ (envalid 9.0.0、@t3-oss/env-core 0.13.11、znv 1.0.0 と zod 4.6.7) で確認しました。
167
+
168
+ - **envalid** は依存がなく、すべてのエラーを報告します。標準のレポーターは問題を表示したあと、例外を投げずに `process.exit(1)` を呼びます。エラーメッセージには拒否した値が含まれ、シークレットを隠すオプションはありません。未知のキーを読むと例外を投げる厳格なプロキシは、envyak にはない機能です。
169
+ - **@t3-oss/env-core** は Standard Schema に対応した任意のライブラリ (zod、valibot、arktype) と組み合わせて使え、フレームワーク向けのクライアントとサーバーの分離があります。これは envyak にはありません。失敗すると `console.error` で問題をログに出してから `Invalid environment variables` を投げます。スキーマライブラリは自分で用意する必要があり、サイズの大半はそれが占めます。
170
+ - **znv** は zod スキーマの表現力をそのまま使えます。zod を peer として必要とし、投げるメッセージには受け取った値が並び、シークレットも含まれます。
171
+
172
+ スキーマライブラリなしで正確な型がほしい、直し方つきのエラーをひとつにまとめたい、シークレットをログに出したくない、という場合は envyak を選んでください。
173
+
174
+ ## よくある質問
175
+
176
+ **envyak は `.env` ファイルを読み込みますか?**
177
+ いいえ。`node --env-file=.env` を使うか、Bun や Deno に読ませるか、好きなローダーを使ってください。envyak はソースに入っている値を検証します。
178
+
179
+ **zod や valibot のスキーマは使えますか?**
180
+ custom で包んでください: `custom((raw) => schema.parse(raw))`。すべてを zod で組んでいるなら、@t3-oss/env-core や znv のほうが合うかもしれません。
181
+
182
+ **結果が凍結されているのはなぜですか?**
183
+ 設定は起動後に変わるべきではありません。凍結しておけば、うっかり書き込んだときに strict モードで `TypeError` になり、型でもすべてのプロパティが `readonly` になります。
184
+
185
+ **スキーマは使い回せますか?**
186
+ はい。スキーマはバリデーターを並べただけのオブジェクトなので、`env(schema, { source })` を何度でも呼べます。
187
+
188
+ ## Web サイト
189
+
190
+ `docs/` のページは `scripts/build-site.mjs` で生成しています。本物の `src/index.js` を埋め込んでいるので、プレイグラウンドは公開中のコードをそのまま実行します。英語、ポルトガル語、スペイン語、日本語で読めます。[Monsoon](https://github.com/kwy404/monsoon)、[Voodoo.js](https://github.com/kwy404/Voodoo.js)、[glyphfox](https://github.com/kwy404/glyphfox) で作られています。
191
+
192
+ ## ライセンス
193
+
194
+ [MIT](LICENSE)、2026 Alexandre Kohler。
package/README.md CHANGED
@@ -1,3 +1,194 @@
1
- # Temporary Holding Version
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
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
6
+ **English** | [Português](README.pt.md) | [Español](README.es.md) | [日本語](README.ja.md)
7
+
8
+ [![npm](https://img.shields.io/npm/v/envyak?color=f4a52c)](https://www.npmjs.com/package/envyak)
9
+ [![CI](https://github.com/kwy404/envyak/actions/workflows/ci.yml/badge.svg)](https://github.com/kwy404/envyak/actions/workflows/ci.yml)
10
+ [![types](https://img.shields.io/badge/types-included-2756c5)](index.d.ts)
11
+ [![dependencies](https://img.shields.io/badge/dependencies-0-1d7a4f)](package.json)
12
+ [![size](https://img.shields.io/badge/min%2Bgzip-2.6%20kB-f4a52c)](#size)
13
+ [![license](https://img.shields.io/badge/license-MIT-17203a)](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.0 | **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.