@zh-moody/safe-env 0.1.3 → 0.1.16

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.
Files changed (3) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +144 -144
  3. package/package.json +16 -3
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Moody (https://github.com/zhMoody)
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.
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Moody (https://github.com/zhMoody)
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,144 +1,144 @@
1
- # @zh-moody/safe-env 🛡️
2
-
3
- [![npm version](https://img.shields.io/npm/v/@zh-moody/safe-env.svg?style=flat-square)](https://www.npmjs.com/package/@zh-moody/safe-env)
4
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT)
5
- [![GitHub stars](https://img.shields.io/github/stars/zhMoody/safe-env?style=flat-square)](https://github.com/zhMoody/safe-env)
6
-
7
- **告别 `undefined`!在应用启动的第一行,拦截所有错误配置。**
8
-
9
- 无论你在写 Vue、React 还是 Node.js,环境变量配置永远是 Bug 的温床。`safe-env` 通过强类型 Schema 校验,确保你的应用在拥有正确配置的前提下才启动。
10
-
11
- ---
12
-
13
- ### 🔗 链接 (Links)
14
-
15
- - **GitHub Repository**: [https://github.com/zhMoody/safe-env](https://github.com/zhMoody/safe-env)
16
- - **NPM Package**: [https://www.npmjs.com/package/@zh-moody/safe-env](https://www.npmjs.com/package/@zh-moody/safe-env)
17
-
18
- ---
19
-
20
- ### 🚀 核心特性
21
-
22
- - **类型安全**:自动推断配置对象类型,拥有完美的 IDE 补全。
23
- - **链式校验**:内置 `min`, `max`, `validate`, `enum` 等校验逻辑。
24
- - **自动前缀**:支持 `VITE_` 或 `REACT_APP_` 自动补全,代码里用 `PORT`,配置里用 `VITE_PORT`。
25
- - **跨端兼容**:自动识别 Node/浏览器环境,支持双端“防御性退出”。
26
- - **极致轻量**:Minified 体积约 **2.6 KB**,Gzip 后仅 **1.3 KB**,零运行时依赖。
27
-
28
- ---
29
-
30
- ### 🚀 快速上手
31
-
32
- #### 🔹 [Vite / React / Vue] 端使用
33
- 在前端,环境变量由构建工具(如 Vite)注入到 `import.meta.env` 中。
34
-
35
- **1. 准备 `.env` 文件:**
36
- ```bash
37
- VITE_API_URL=https://api.com
38
- VITE_PORT=3000
39
- ```
40
-
41
- **2. 定义配置 (`src/env.ts`):**
42
- ```typescript
43
- import { safeEnv, s } from '@zh-moody/safe-env';
44
-
45
- export const config = safeEnv({
46
- apiUrl: s.string().from('VITE_API_URL'), // 别名映射
47
- port: s.number(3000).from('VITE_PORT'),
48
- }, {
49
- source: import.meta.env // ⚠️ 浏览器端必须手动传入数据源
50
- });
51
- ```
52
-
53
- ---
54
-
55
- #### 🔸 [Node.js / 服务端] 端使用
56
- 在后端,库会自动寻找并解析磁盘上的 `.env` 文件。
57
-
58
- **1. 准备 `.env` 文件:**
59
- ```bash
60
- DB_HOST=localhost
61
- DB_PORT=5432
62
- ```
63
-
64
- **2. 定义配置 (`src/db.ts`):**
65
- ```typescript
66
- import { safeEnv, s } from '@zh-moody/safe-env';
67
-
68
- const dbConfig = safeEnv({
69
- DB_HOST: s.string('localhost'),
70
- DB_PORT: s.number(5432)
71
- }); // ⚠️ Node 端无需传 source,会自动读取文件
72
-
73
- export default dbConfig;
74
- ```
75
-
76
- ---
77
-
78
- ### 📂 核心对比:Schema 与 .env 对应关系
79
-
80
- | Schema 定义 | .env 中的写法 | 结果 |
81
- | :--- | :--- | :--- |
82
- | `s.string()` | `KEY=val` | ✅ 通过 |
83
- | `s.string()` | *(未填写)* | ❌ **报错并拦截启动** |
84
- | `s.string('App')` | `KEY=` (留空) | ✅ 自动降级为 `'App'` |
85
- | `s.number()` | `KEY=abc` | ❌ **报错:Invalid number** |
86
-
87
- ---
88
-
89
- ### 🛠️ API 详解
90
-
91
- #### 1. 定义字段 (`s.xxx`)
92
- - `s.string(default?)`: 字符串。若无默认值则必填。
93
- - `s.number(default?)`: 数字。自动将字符串转为 `number`。
94
- - `s.boolean(default?)`: 布尔。将 `"true"` 解析为 `true`。
95
- - `s.enum(options, default?)`: 枚举。值必须在数组中。
96
- - 示例:`s.enum(['dev', 'prod'], 'dev')`
97
-
98
- #### 2. 增强校验 (链式调用)
99
- 每个通过 `s` 定义的字段都可以调用以下方法进行增强:
100
-
101
- - **`.from(key)`**: 指定环境变量名。
102
- ```typescript
103
- // 即使变量叫 VITE_PATH,代码里也可以叫 port
104
- port: s.number().from('VITE_PATH')
105
- ```
106
-
107
- - **`.min(n)` / `.max(n)`**: 限制数字取值范围。
108
- ```typescript
109
- // 端口必须在 1-65535 之间
110
- PORT: s.number().min(1).max(65535)
111
- ```
112
-
113
- - **`.validate(fn, msg?)`**: 自定义校验(如:邮箱、URL 格式)。
114
- ```typescript
115
- // 必须是安全地址
116
- API: s.string().validate(v => v.startsWith('https'), 'Must be HTTPS')
117
- ```
118
-
119
- #### 3. 加载选项 (`SafeEnvOptions`)
120
-
121
- | 选项 | 适用环境 | 说明 |
122
- | :--- | :--- | :--- |
123
- | `source` | **[Vite/浏览器]** | **必填**。传入 `import.meta.env` 或 `process.env`。 |
124
- | `prefix` | **通用** | **可选**。自动补全前缀,如 `prefix: 'VITE_'`。 |
125
- | `mode` | **[Node.js]** | **可选**。指定模式(dev/prod)以加载对应的 `.env.prod` 等文件。 |
126
- | `loadProcessEnv` | **[Node.js]** | **可选**。是否加载系统环境变量,默认 `true`。 |
127
-
128
- ---
129
-
130
- ### 🎨 错误报告:长什么样?
131
-
132
- 当校验失败时,`safe-env` 会在控制台打印一个显眼的表格,告诉你哪个字段错了、原因是什么以及当前的值。在浏览器中这会抛出一个 Error 阻止应用启动,在 Node.js 中会直接 `process.exit(1)`。
133
-
134
- ---
135
-
136
- ### 📦 跨平台支持
137
- - **前端**: Vite (Vue/React/Vanilla)。
138
- - **后端**: Node.js (ESM/CJS)。
139
-
140
- ---
141
-
142
- ### 📄 开源协议 (License)
143
-
144
- [MIT License](./LICENSE) - Copyright (c) 2025 Moody.
1
+ # @zh-moody/safe-env 🛡️
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@zh-moody/safe-env.svg?style=flat-square)](https://www.npmjs.com/package/@zh-moody/safe-env)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT)
5
+ [![GitHub stars](https://img.shields.io/github/stars/zhMoody/safe-env?style=flat-square)](https://github.com/zhMoody/safe-env)
6
+
7
+ **告别 `undefined`!在应用启动的第一行,拦截所有错误配置。**
8
+
9
+ 无论你在写 Vue、React 还是 Node.js,环境变量配置永远是 Bug 的温床。`safe-env` 通过强类型 Schema 校验,确保你的应用在拥有正确配置的前提下才启动。
10
+
11
+ ---
12
+
13
+ ### 🔗 链接 (Links)
14
+
15
+ - **GitHub Repository**: [https://github.com/zhMoody/safe-env](https://github.com/zhMoody/safe-env)
16
+ - **NPM Package**: [https://www.npmjs.com/package/@zh-moody/safe-env](https://www.npmjs.com/package/@zh-moody/safe-env)
17
+
18
+ ---
19
+
20
+ ### 🚀 核心特性
21
+
22
+ - **类型安全**:自动推断配置对象类型,拥有完美的 IDE 补全。
23
+ - **链式校验**:内置 `min`, `max`, `validate`, `enum` 等校验逻辑。
24
+ - **自动前缀**:支持 `VITE_` 或 `REACT_APP_` 自动补全,代码里用 `PORT`,配置里用 `VITE_PORT`。
25
+ - **跨端兼容**:自动识别 Node/浏览器环境,支持双端“防御性退出”。
26
+ - **极致轻量**:Minified 体积约 **2.6 KB**,Gzip 后仅 **1.3 KB**,零运行时依赖。
27
+
28
+ ---
29
+
30
+ ### 🚀 快速上手
31
+
32
+ #### 🔹 [Vite / React / Vue] 端使用
33
+ 在前端,环境变量由构建工具(如 Vite)注入到 `import.meta.env` 中。
34
+
35
+ **1. 准备 `.env` 文件:**
36
+ ```bash
37
+ VITE_API_URL=https://api.com
38
+ VITE_PORT=3000
39
+ ```
40
+
41
+ **2. 定义配置 (`src/env.ts`):**
42
+ ```typescript
43
+ import { safeEnv, s } from '@zh-moody/safe-env';
44
+
45
+ export const config = safeEnv({
46
+ apiUrl: s.string().from('VITE_API_URL'), // 别名映射
47
+ port: s.number(3000).from('VITE_PORT'),
48
+ }, {
49
+ source: import.meta.env // ⚠️ 浏览器端必须手动传入数据源
50
+ });
51
+ ```
52
+
53
+ ---
54
+
55
+ #### 🔸 [Node.js / 服务端] 端使用
56
+ 在后端,库会自动寻找并解析磁盘上的 `.env` 文件。
57
+
58
+ **1. 准备 `.env` 文件:**
59
+ ```bash
60
+ DB_HOST=localhost
61
+ DB_PORT=5432
62
+ ```
63
+
64
+ **2. 定义配置 (`src/db.ts`):**
65
+ ```typescript
66
+ import { safeEnv, s } from '@zh-moody/safe-env';
67
+
68
+ const dbConfig = safeEnv({
69
+ DB_HOST: s.string('localhost'),
70
+ DB_PORT: s.number(5432)
71
+ }); // ⚠️ Node 端无需传 source,会自动读取文件
72
+
73
+ export default dbConfig;
74
+ ```
75
+
76
+ ---
77
+
78
+ ### 📂 核心对比:Schema 与 .env 对应关系
79
+
80
+ | Schema 定义 | .env 中的写法 | 结果 |
81
+ | :--- | :--- | :--- |
82
+ | `s.string()` | `KEY=val` | ✅ 通过 |
83
+ | `s.string()` | *(未填写)* | ❌ **报错并拦截启动** |
84
+ | `s.string('App')` | `KEY=` (留空) | ✅ 自动降级为 `'App'` |
85
+ | `s.number()` | `KEY=abc` | ❌ **报错:Invalid number** |
86
+
87
+ ---
88
+
89
+ ### 🛠️ API 详解
90
+
91
+ #### 1. 定义字段 (`s.xxx`)
92
+ - `s.string(default?)`: 字符串。若无默认值则必填。
93
+ - `s.number(default?)`: 数字。自动将字符串转为 `number`。
94
+ - `s.boolean(default?)`: 布尔。将 `"true"` 解析为 `true`。
95
+ - `s.enum(options, default?)`: 枚举。值必须在数组中。
96
+ - 示例:`s.enum(['dev', 'prod'], 'dev')`
97
+
98
+ #### 2. 增强校验 (链式调用)
99
+ 每个通过 `s` 定义的字段都可以调用以下方法进行增强:
100
+
101
+ - **`.from(key)`**: 指定环境变量名。
102
+ ```typescript
103
+ // 即使变量叫 VITE_PATH,代码里也可以叫 port
104
+ port: s.number().from('VITE_PATH')
105
+ ```
106
+
107
+ - **`.min(n)` / `.max(n)`**: 限制数字取值范围。
108
+ ```typescript
109
+ // 端口必须在 1-65535 之间
110
+ PORT: s.number().min(1).max(65535)
111
+ ```
112
+
113
+ - **`.validate(fn, msg?)`**: 自定义校验(如:邮箱、URL 格式)。
114
+ ```typescript
115
+ // 必须是安全地址
116
+ API: s.string().validate(v => v.startsWith('https'), 'Must be HTTPS')
117
+ ```
118
+
119
+ #### 3. 加载选项 (`SafeEnvOptions`)
120
+
121
+ | 选项 | 适用环境 | 说明 |
122
+ | :--- | :--- | :--- |
123
+ | `source` | **[Vite/浏览器]** | **必填**。传入 `import.meta.env` 或 `process.env`。 |
124
+ | `prefix` | **通用** | **可选**。自动补全前缀,如 `prefix: 'VITE_'`。 |
125
+ | `mode` | **[Node.js]** | **可选**。指定模式(dev/prod)以加载对应的 `.env.prod` 等文件。 |
126
+ | `loadProcessEnv` | **[Node.js]** | **可选**。是否加载系统环境变量,默认 `true`。 |
127
+
128
+ ---
129
+
130
+ ### 🎨 错误报告:长什么样?
131
+
132
+ 当校验失败时,`safe-env` 会在控制台打印一个显眼的表格,告诉你哪个字段错了、原因是什么以及当前的值。在浏览器中这会抛出一个 Error 阻止应用启动,在 Node.js 中会直接 `process.exit(1)`。
133
+
134
+ ---
135
+
136
+ ### 📦 跨平台支持
137
+ - **前端**: Vite (Vue/React/Vanilla)。
138
+ - **后端**: Node.js (ESM/CJS)。
139
+
140
+ ---
141
+
142
+ ### 📄 开源协议 (License)
143
+
144
+ [MIT License](./LICENSE) - Copyright (c) 2025 Moody.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zh-moody/safe-env",
3
- "version": "0.1.3",
4
- "description": "",
3
+ "version": "0.1.16",
4
+ "description": "Type-safe environment variables for Node.js and Browser with schema validation.",
5
5
  "author": "Moody",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/zhMoody/safe-env#readme",
@@ -9,6 +9,11 @@
9
9
  "type": "git",
10
10
  "url": "git+https://github.com/zhMoody/safe-env.git"
11
11
  },
12
+ "publishConfig": {
13
+ "access": "public",
14
+ "provenance": true,
15
+ "registry": "https://registry.npmjs.org/"
16
+ },
12
17
  "bugs": {
13
18
  "url": "https://github.com/zhMoody/safe-env/issues"
14
19
  },
@@ -32,7 +37,15 @@
32
37
  "require": "./dist/index.cjs"
33
38
  }
34
39
  },
35
- "keywords": [],
40
+ "keywords": [
41
+ "env",
42
+ "environment",
43
+ "dotenv",
44
+ "validation",
45
+ "schema",
46
+ "type-safe",
47
+ "typescript"
48
+ ],
36
49
  "files": [
37
50
  "dist"
38
51
  ],