@systemix/env 0.2.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 shahadathhs
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 ADDED
@@ -0,0 +1,127 @@
1
+ # @systemix/env
2
+
3
+ Typed environment variable loading and validation. Zero dependencies. Built-in .env file support.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @systemix/env
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import { load } from '@systemix/env';
15
+
16
+ const env = load({
17
+ NODE_ENV: { type: 'string', default: 'development' },
18
+ PORT: { type: 'number', default: 3000 },
19
+ DATABASE_URL: { type: 'string', required: true, secret: true },
20
+ DEBUG: { type: 'boolean', default: false },
21
+ });
22
+
23
+ console.log(env.PORT); // number
24
+ console.log(env.toSafeLog()); // { DATABASE_URL: '***', ... }
25
+ ```
26
+
27
+ ## Schema
28
+
29
+ | Property | Type | Description |
30
+ | ----------- | ----------------------------------- | --------------------------------- |
31
+ | `type` | `'string' \| 'number' \| 'boolean'` | How to parse the value |
32
+ | `required` | `boolean` | If true, throws when missing |
33
+ | `default` | `string \| number \| boolean` | Used when var is missing or empty |
34
+ | `min` | `number` | Min value (number type) |
35
+ | `max` | `number` | Max value (number type) |
36
+ | `regex` | `RegExp` | Must match (string type) |
37
+ | `oneOf` | `string[]` | Allowed values (string type) |
38
+ | `transform` | `(raw) => value` | Custom parser |
39
+ | `secret` | `boolean` | Masked in `toSafeLog()` |
40
+
41
+ ## Options
42
+
43
+ Pass options as second argument. For backward compat, a plain `Record` is treated as `{ source }`:
44
+
45
+ ```typescript
46
+ load(schema, { PORT: '4000' }); // legacy: treated as source
47
+ load(schema, {
48
+ source: { PORT: '4000' }, // Custom env source
49
+ fromFile: '.env.local', // Load from .env file(s)
50
+ fromFile: ['.env', '.env.local'], // Multiple files, later overrides
51
+ strict: true, // Ignore vars not in schema
52
+ });
53
+ ```
54
+
55
+ ## .env File Loading
56
+
57
+ Load from file. Cross-platform (Windows, macOS, Linux).
58
+
59
+ ```typescript
60
+ const env = load(schema, { fromFile: '.env.local' });
61
+ ```
62
+
63
+ Or parse content yourself:
64
+
65
+ ```typescript
66
+ import { parseEnvFile } from '@systemix/env';
67
+
68
+ const vars = parseEnvFile(readFileSync('.env', 'utf-8'));
69
+ ```
70
+
71
+ ## Secret Masking
72
+
73
+ Mark sensitive vars with `secret: true`. Use `toSafeLog()` for logging:
74
+
75
+ ```typescript
76
+ const env = load(
77
+ {
78
+ API_KEY: { type: 'string', secret: true },
79
+ PORT: { type: 'number' },
80
+ },
81
+ { source: { API_KEY: 'sk-123', PORT: '3000' } },
82
+ );
83
+
84
+ console.log(env.toSafeLog());
85
+ // { API_KEY: '***', PORT: 3000 }
86
+ ```
87
+
88
+ ## Batch Error Reporting
89
+
90
+ All validation errors are collected and thrown together:
91
+
92
+ ```
93
+ Env validation failed:
94
+ - Missing required env var: DATABASE_URL
95
+ - PORT: must be >= 1
96
+ ```
97
+
98
+ ## Config (OOP)
99
+
100
+ Class-based usage with get, getOrThrow, has:
101
+
102
+ ```typescript
103
+ import { Config } from '@systemix/env';
104
+
105
+ const config = Config.fromEnv({
106
+ PORT: { type: 'number', default: 3000 },
107
+ DATABASE_URL: { type: 'string', required: true },
108
+ });
109
+
110
+ config.get('PORT'); // number | undefined
111
+ config.get('PORT', 4000); // number (default when undefined)
112
+ config.getOrThrow('DATABASE_URL'); // throws if not set
113
+ config.has('PORT'); // boolean
114
+ config.toSafeLog(); // masked for logging
115
+ config.getRaw(); // raw env object
116
+ ```
117
+
118
+ Create from existing env: `Config.from(load(schema))`.
119
+
120
+ ## Boolean Parsing
121
+
122
+ - `true`: `"true"`, `"1"`, `"yes"`
123
+ - `false`: `"false"`, `"0"`, `"no"`, `""`
124
+
125
+ ## License
126
+
127
+ MIT © [Shahadath Hossen Sajib](https://github.com/shahadathhs)
package/dist/index.cjs ADDED
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Config: () => Config,
24
+ load: () => load,
25
+ parseEnvFile: () => parseEnvFile
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/env/parse.ts
30
+ function parseBoolean(raw) {
31
+ const lower = raw.toLowerCase().trim();
32
+ if (lower === "true" || lower === "1" || lower === "yes") return true;
33
+ if (lower === "false" || lower === "0" || lower === "no" || lower === "")
34
+ return false;
35
+ throw new Error(`Invalid boolean value: "${raw}"`);
36
+ }
37
+ function parseNumber(raw) {
38
+ const n = Number(raw);
39
+ if (!Number.isFinite(n)) {
40
+ throw new Error(`Invalid number value: "${raw}"`);
41
+ }
42
+ return n;
43
+ }
44
+ function parseEnvFile(content) {
45
+ const result = {};
46
+ const lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
47
+ for (const line of lines) {
48
+ const trimmed = line.trim();
49
+ if (!trimmed || trimmed.startsWith("#")) continue;
50
+ const eqIndex = trimmed.indexOf("=");
51
+ if (eqIndex === -1) continue;
52
+ const key = trimmed.slice(0, eqIndex).trim();
53
+ let value = trimmed.slice(eqIndex + 1).trim();
54
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
55
+ value = value.slice(1, -1).replace(/\\(.)/g, "$1");
56
+ }
57
+ result[key] = value;
58
+ }
59
+ return result;
60
+ }
61
+
62
+ // src/env/file.ts
63
+ var import_node_fs = require("fs");
64
+ var import_node_path = require("path");
65
+ function loadEnvFile(filePath, cwd) {
66
+ const resolved = (0, import_node_path.resolve)(cwd, filePath);
67
+ if (!(0, import_node_fs.existsSync)(resolved)) {
68
+ return {};
69
+ }
70
+ const content = (0, import_node_fs.readFileSync)(resolved, "utf-8");
71
+ return parseEnvFile(content);
72
+ }
73
+ function getCwd() {
74
+ return typeof globalThis.process?.cwd === "function" ? globalThis.process.cwd() : ".";
75
+ }
76
+ function mergeEnv(base, overlay) {
77
+ const merged = { ...base };
78
+ for (const [k, v] of Object.entries(overlay)) {
79
+ merged[k] = v;
80
+ }
81
+ return merged;
82
+ }
83
+ function getEnvSource() {
84
+ const env = globalThis.process?.env;
85
+ if (env && typeof env === "object") {
86
+ return env;
87
+ }
88
+ return {};
89
+ }
90
+
91
+ // src/env/load.ts
92
+ var MASK = "***";
93
+ function load(schema, options) {
94
+ const opts = options ?? {};
95
+ const isLegacySource = opts && typeof opts === "object" && !Array.isArray(opts) && !("source" in opts) && !("fromFile" in opts) && !("strict" in opts);
96
+ const normalized = isLegacySource ? { source: opts } : opts;
97
+ const { source, fromFile, strict = false } = normalized;
98
+ let env = source ?? getEnvSource();
99
+ if (fromFile) {
100
+ const cwd = getCwd();
101
+ const files = Array.isArray(fromFile) ? fromFile : [fromFile];
102
+ for (const f of files) {
103
+ const loaded = loadEnvFile(f, cwd);
104
+ env = mergeEnv(env, loaded);
105
+ }
106
+ }
107
+ if (strict) {
108
+ const schemaKeys2 = new Set(Object.keys(schema));
109
+ const filtered = {};
110
+ for (const [k, v] of Object.entries(env)) {
111
+ if (schemaKeys2.has(k)) filtered[k] = v;
112
+ }
113
+ env = filtered;
114
+ }
115
+ const schemaKeys = Object.keys(schema);
116
+ const errors = [];
117
+ const result = {};
118
+ for (const key of schemaKeys) {
119
+ const def = schema[key];
120
+ const raw = env[key];
121
+ const { type, required = false, default: defaultValue } = def;
122
+ if (raw === void 0 || raw === "") {
123
+ if (required && defaultValue === void 0) {
124
+ errors.push(`Missing required env var: ${key}`);
125
+ continue;
126
+ }
127
+ result[key] = defaultValue ?? void 0;
128
+ continue;
129
+ }
130
+ try {
131
+ let value;
132
+ if (def.transform) {
133
+ value = def.transform(raw);
134
+ } else {
135
+ switch (type) {
136
+ case "string":
137
+ value = raw;
138
+ break;
139
+ case "number":
140
+ value = parseNumber(raw);
141
+ break;
142
+ case "boolean":
143
+ value = parseBoolean(raw);
144
+ break;
145
+ default:
146
+ value = raw;
147
+ }
148
+ }
149
+ if (type === "number" && typeof value === "number") {
150
+ if (def.min !== void 0 && value < def.min) {
151
+ errors.push(`${key}: must be >= ${def.min}`);
152
+ continue;
153
+ }
154
+ if (def.max !== void 0 && value > def.max) {
155
+ errors.push(`${key}: must be <= ${def.max}`);
156
+ continue;
157
+ }
158
+ }
159
+ if (type === "string" && typeof value === "string") {
160
+ if (def.regex && !def.regex.test(value)) {
161
+ errors.push(`${key}: must match ${def.regex}`);
162
+ continue;
163
+ }
164
+ if (def.oneOf && !def.oneOf.includes(value)) {
165
+ errors.push(`${key}: must be one of [${def.oneOf.join(", ")}]`);
166
+ continue;
167
+ }
168
+ }
169
+ result[key] = value;
170
+ } catch (err) {
171
+ errors.push(
172
+ `${key}: ${err instanceof Error ? err.message : String(err)}`
173
+ );
174
+ }
175
+ }
176
+ if (errors.length > 0) {
177
+ throw new Error(
178
+ `Env validation failed:
179
+ ${errors.map((e) => ` - ${e}`).join("\n")}`
180
+ );
181
+ }
182
+ const toSafeLog = () => {
183
+ const safe = {};
184
+ for (const key of schemaKeys) {
185
+ const def = schema[key];
186
+ const val = result[key];
187
+ safe[key] = def.secret && val !== void 0 ? MASK : val;
188
+ }
189
+ return safe;
190
+ };
191
+ return Object.assign(result, { toSafeLog });
192
+ }
193
+
194
+ // src/config.ts
195
+ var Config = class _Config {
196
+ constructor(config) {
197
+ this.config = config;
198
+ }
199
+ /**
200
+ * Create Config from a schema and env source.
201
+ * @param schema - Env variable definitions
202
+ * @param options - Source, fromFile, or strict. Legacy: plain object as source.
203
+ */
204
+ static fromEnv(schema, options) {
205
+ const config = load(schema, options);
206
+ return new _Config(config);
207
+ }
208
+ /** Create Config from an existing load() result. */
209
+ static from(config) {
210
+ return new _Config(config);
211
+ }
212
+ get(key, defaultValue) {
213
+ const val = this.config[key];
214
+ if (defaultValue !== void 0 && val === void 0) return defaultValue;
215
+ return val;
216
+ }
217
+ /** Get value by key, or throw if not set. */
218
+ getOrThrow(key) {
219
+ const val = this.config[key];
220
+ if (val === void 0) {
221
+ throw new Error(`Config key "${String(key)}" is not set`);
222
+ }
223
+ return val;
224
+ }
225
+ /** Check if key is set. */
226
+ has(key) {
227
+ return this.config[key] !== void 0;
228
+ }
229
+ /** Return a copy with secret values masked as '***'. */
230
+ toSafeLog() {
231
+ return this.config.toSafeLog();
232
+ }
233
+ /** Get the raw env result (no masking). */
234
+ getRaw() {
235
+ return this.config;
236
+ }
237
+ };
238
+ // Annotate the CommonJS export names for ESM import in node:
239
+ 0 && (module.exports = {
240
+ Config,
241
+ load,
242
+ parseEnvFile
243
+ });
@@ -0,0 +1,43 @@
1
+ type EnvVarType = 'string' | 'number' | 'boolean';
2
+ interface EnvVarSchema<T extends EnvVarType = EnvVarType> {
3
+ type: T;
4
+ required?: boolean;
5
+ default?: T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : never;
6
+ min?: number;
7
+ max?: number;
8
+ regex?: RegExp;
9
+ oneOf?: readonly string[];
10
+ transform?: (raw: string) => string | number | boolean;
11
+ secret?: boolean;
12
+ }
13
+ type EnvSchema = Record<string, EnvVarSchema<'string' | 'number' | 'boolean'>>;
14
+ type EnvValueFor<S extends EnvVarSchema<EnvVarType>> = S['type'] extends 'string' ? string : S['type'] extends 'number' ? number : S['type'] extends 'boolean' ? boolean : never;
15
+ type EnvResult<T extends EnvSchema> = {
16
+ [K in keyof T]: T[K]['required'] extends true ? EnvValueFor<T[K]> : T[K]['default'] extends EnvValueFor<T[K]> ? EnvValueFor<T[K]> : EnvValueFor<T[K]> | undefined;
17
+ } & {
18
+ toSafeLog(): Record<string, string | number | boolean | undefined>;
19
+ };
20
+ interface LoadOptions {
21
+ source?: Record<string, string | undefined>;
22
+ fromFile?: string | string[];
23
+ strict?: boolean;
24
+ }
25
+
26
+ declare function parseEnvFile(content: string): Record<string, string>;
27
+
28
+ declare function load<T extends EnvSchema>(schema: T, options?: LoadOptions | Record<string, string | undefined>): EnvResult<T>;
29
+
30
+ declare class Config<T extends EnvSchema> {
31
+ private readonly config;
32
+ private constructor();
33
+ static fromEnv<S extends EnvSchema>(schema: S, options?: LoadOptions | Record<string, string | undefined>): Config<S>;
34
+ static from<S extends EnvSchema>(config: EnvResult<S>): Config<S>;
35
+ get<K extends keyof T>(key: K): EnvResult<T>[K] | undefined;
36
+ get<K extends keyof T>(key: K, defaultValue: EnvResult<T>[K]): EnvResult<T>[K];
37
+ getOrThrow<K extends keyof T>(key: K): EnvResult<T>[K];
38
+ has(key: keyof T): boolean;
39
+ toSafeLog(): Record<string, string | number | boolean | undefined>;
40
+ getRaw(): EnvResult<T>;
41
+ }
42
+
43
+ export { Config, type EnvResult, type EnvSchema, type EnvVarSchema, type EnvVarType, type LoadOptions, load, parseEnvFile };
@@ -0,0 +1,43 @@
1
+ type EnvVarType = 'string' | 'number' | 'boolean';
2
+ interface EnvVarSchema<T extends EnvVarType = EnvVarType> {
3
+ type: T;
4
+ required?: boolean;
5
+ default?: T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : never;
6
+ min?: number;
7
+ max?: number;
8
+ regex?: RegExp;
9
+ oneOf?: readonly string[];
10
+ transform?: (raw: string) => string | number | boolean;
11
+ secret?: boolean;
12
+ }
13
+ type EnvSchema = Record<string, EnvVarSchema<'string' | 'number' | 'boolean'>>;
14
+ type EnvValueFor<S extends EnvVarSchema<EnvVarType>> = S['type'] extends 'string' ? string : S['type'] extends 'number' ? number : S['type'] extends 'boolean' ? boolean : never;
15
+ type EnvResult<T extends EnvSchema> = {
16
+ [K in keyof T]: T[K]['required'] extends true ? EnvValueFor<T[K]> : T[K]['default'] extends EnvValueFor<T[K]> ? EnvValueFor<T[K]> : EnvValueFor<T[K]> | undefined;
17
+ } & {
18
+ toSafeLog(): Record<string, string | number | boolean | undefined>;
19
+ };
20
+ interface LoadOptions {
21
+ source?: Record<string, string | undefined>;
22
+ fromFile?: string | string[];
23
+ strict?: boolean;
24
+ }
25
+
26
+ declare function parseEnvFile(content: string): Record<string, string>;
27
+
28
+ declare function load<T extends EnvSchema>(schema: T, options?: LoadOptions | Record<string, string | undefined>): EnvResult<T>;
29
+
30
+ declare class Config<T extends EnvSchema> {
31
+ private readonly config;
32
+ private constructor();
33
+ static fromEnv<S extends EnvSchema>(schema: S, options?: LoadOptions | Record<string, string | undefined>): Config<S>;
34
+ static from<S extends EnvSchema>(config: EnvResult<S>): Config<S>;
35
+ get<K extends keyof T>(key: K): EnvResult<T>[K] | undefined;
36
+ get<K extends keyof T>(key: K, defaultValue: EnvResult<T>[K]): EnvResult<T>[K];
37
+ getOrThrow<K extends keyof T>(key: K): EnvResult<T>[K];
38
+ has(key: keyof T): boolean;
39
+ toSafeLog(): Record<string, string | number | boolean | undefined>;
40
+ getRaw(): EnvResult<T>;
41
+ }
42
+
43
+ export { Config, type EnvResult, type EnvSchema, type EnvVarSchema, type EnvVarType, type LoadOptions, load, parseEnvFile };
package/dist/index.js ADDED
@@ -0,0 +1,214 @@
1
+ // src/env/parse.ts
2
+ function parseBoolean(raw) {
3
+ const lower = raw.toLowerCase().trim();
4
+ if (lower === "true" || lower === "1" || lower === "yes") return true;
5
+ if (lower === "false" || lower === "0" || lower === "no" || lower === "")
6
+ return false;
7
+ throw new Error(`Invalid boolean value: "${raw}"`);
8
+ }
9
+ function parseNumber(raw) {
10
+ const n = Number(raw);
11
+ if (!Number.isFinite(n)) {
12
+ throw new Error(`Invalid number value: "${raw}"`);
13
+ }
14
+ return n;
15
+ }
16
+ function parseEnvFile(content) {
17
+ const result = {};
18
+ const lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
19
+ for (const line of lines) {
20
+ const trimmed = line.trim();
21
+ if (!trimmed || trimmed.startsWith("#")) continue;
22
+ const eqIndex = trimmed.indexOf("=");
23
+ if (eqIndex === -1) continue;
24
+ const key = trimmed.slice(0, eqIndex).trim();
25
+ let value = trimmed.slice(eqIndex + 1).trim();
26
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
27
+ value = value.slice(1, -1).replace(/\\(.)/g, "$1");
28
+ }
29
+ result[key] = value;
30
+ }
31
+ return result;
32
+ }
33
+
34
+ // src/env/file.ts
35
+ import { readFileSync, existsSync } from "fs";
36
+ import { resolve } from "path";
37
+ function loadEnvFile(filePath, cwd) {
38
+ const resolved = resolve(cwd, filePath);
39
+ if (!existsSync(resolved)) {
40
+ return {};
41
+ }
42
+ const content = readFileSync(resolved, "utf-8");
43
+ return parseEnvFile(content);
44
+ }
45
+ function getCwd() {
46
+ return typeof globalThis.process?.cwd === "function" ? globalThis.process.cwd() : ".";
47
+ }
48
+ function mergeEnv(base, overlay) {
49
+ const merged = { ...base };
50
+ for (const [k, v] of Object.entries(overlay)) {
51
+ merged[k] = v;
52
+ }
53
+ return merged;
54
+ }
55
+ function getEnvSource() {
56
+ const env = globalThis.process?.env;
57
+ if (env && typeof env === "object") {
58
+ return env;
59
+ }
60
+ return {};
61
+ }
62
+
63
+ // src/env/load.ts
64
+ var MASK = "***";
65
+ function load(schema, options) {
66
+ const opts = options ?? {};
67
+ const isLegacySource = opts && typeof opts === "object" && !Array.isArray(opts) && !("source" in opts) && !("fromFile" in opts) && !("strict" in opts);
68
+ const normalized = isLegacySource ? { source: opts } : opts;
69
+ const { source, fromFile, strict = false } = normalized;
70
+ let env = source ?? getEnvSource();
71
+ if (fromFile) {
72
+ const cwd = getCwd();
73
+ const files = Array.isArray(fromFile) ? fromFile : [fromFile];
74
+ for (const f of files) {
75
+ const loaded = loadEnvFile(f, cwd);
76
+ env = mergeEnv(env, loaded);
77
+ }
78
+ }
79
+ if (strict) {
80
+ const schemaKeys2 = new Set(Object.keys(schema));
81
+ const filtered = {};
82
+ for (const [k, v] of Object.entries(env)) {
83
+ if (schemaKeys2.has(k)) filtered[k] = v;
84
+ }
85
+ env = filtered;
86
+ }
87
+ const schemaKeys = Object.keys(schema);
88
+ const errors = [];
89
+ const result = {};
90
+ for (const key of schemaKeys) {
91
+ const def = schema[key];
92
+ const raw = env[key];
93
+ const { type, required = false, default: defaultValue } = def;
94
+ if (raw === void 0 || raw === "") {
95
+ if (required && defaultValue === void 0) {
96
+ errors.push(`Missing required env var: ${key}`);
97
+ continue;
98
+ }
99
+ result[key] = defaultValue ?? void 0;
100
+ continue;
101
+ }
102
+ try {
103
+ let value;
104
+ if (def.transform) {
105
+ value = def.transform(raw);
106
+ } else {
107
+ switch (type) {
108
+ case "string":
109
+ value = raw;
110
+ break;
111
+ case "number":
112
+ value = parseNumber(raw);
113
+ break;
114
+ case "boolean":
115
+ value = parseBoolean(raw);
116
+ break;
117
+ default:
118
+ value = raw;
119
+ }
120
+ }
121
+ if (type === "number" && typeof value === "number") {
122
+ if (def.min !== void 0 && value < def.min) {
123
+ errors.push(`${key}: must be >= ${def.min}`);
124
+ continue;
125
+ }
126
+ if (def.max !== void 0 && value > def.max) {
127
+ errors.push(`${key}: must be <= ${def.max}`);
128
+ continue;
129
+ }
130
+ }
131
+ if (type === "string" && typeof value === "string") {
132
+ if (def.regex && !def.regex.test(value)) {
133
+ errors.push(`${key}: must match ${def.regex}`);
134
+ continue;
135
+ }
136
+ if (def.oneOf && !def.oneOf.includes(value)) {
137
+ errors.push(`${key}: must be one of [${def.oneOf.join(", ")}]`);
138
+ continue;
139
+ }
140
+ }
141
+ result[key] = value;
142
+ } catch (err) {
143
+ errors.push(
144
+ `${key}: ${err instanceof Error ? err.message : String(err)}`
145
+ );
146
+ }
147
+ }
148
+ if (errors.length > 0) {
149
+ throw new Error(
150
+ `Env validation failed:
151
+ ${errors.map((e) => ` - ${e}`).join("\n")}`
152
+ );
153
+ }
154
+ const toSafeLog = () => {
155
+ const safe = {};
156
+ for (const key of schemaKeys) {
157
+ const def = schema[key];
158
+ const val = result[key];
159
+ safe[key] = def.secret && val !== void 0 ? MASK : val;
160
+ }
161
+ return safe;
162
+ };
163
+ return Object.assign(result, { toSafeLog });
164
+ }
165
+
166
+ // src/config.ts
167
+ var Config = class _Config {
168
+ constructor(config) {
169
+ this.config = config;
170
+ }
171
+ /**
172
+ * Create Config from a schema and env source.
173
+ * @param schema - Env variable definitions
174
+ * @param options - Source, fromFile, or strict. Legacy: plain object as source.
175
+ */
176
+ static fromEnv(schema, options) {
177
+ const config = load(schema, options);
178
+ return new _Config(config);
179
+ }
180
+ /** Create Config from an existing load() result. */
181
+ static from(config) {
182
+ return new _Config(config);
183
+ }
184
+ get(key, defaultValue) {
185
+ const val = this.config[key];
186
+ if (defaultValue !== void 0 && val === void 0) return defaultValue;
187
+ return val;
188
+ }
189
+ /** Get value by key, or throw if not set. */
190
+ getOrThrow(key) {
191
+ const val = this.config[key];
192
+ if (val === void 0) {
193
+ throw new Error(`Config key "${String(key)}" is not set`);
194
+ }
195
+ return val;
196
+ }
197
+ /** Check if key is set. */
198
+ has(key) {
199
+ return this.config[key] !== void 0;
200
+ }
201
+ /** Return a copy with secret values masked as '***'. */
202
+ toSafeLog() {
203
+ return this.config.toSafeLog();
204
+ }
205
+ /** Get the raw env result (no masking). */
206
+ getRaw() {
207
+ return this.config;
208
+ }
209
+ };
210
+ export {
211
+ Config,
212
+ load,
213
+ parseEnvFile
214
+ };
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@systemix/env",
3
+ "version": "0.2.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "private": false,
8
+ "type": "module",
9
+ "main": "./dist/index.cjs",
10
+ "module": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/shahadathhs/systemix.git",
22
+ "directory": "packages/env"
23
+ },
24
+ "homepage": "https://github.com/shahadathhs/systemix/tree/main/packages/env#readme",
25
+ "keywords": [
26
+ "systemix",
27
+ "env",
28
+ "environment",
29
+ "environment-variables",
30
+ "validation",
31
+ "typed-env",
32
+ "typescript",
33
+ "node",
34
+ "utility"
35
+ ],
36
+ "author": "Shahadath Hossen Sajib <shahadathhossensajib732@gmail.com> (https://github.com/shahadathhs)",
37
+ "license": "MIT",
38
+ "description": "Typed environment variable loading and validation. Part of the Systemix toolkit.",
39
+ "devDependencies": {
40
+ "@types/node": "^25.3.0",
41
+ "eslint": "^10.0.1",
42
+ "tsup": "^8.5.1",
43
+ "typescript": "^5.9.3",
44
+ "@systemix/eslint": "0.4.0",
45
+ "@systemix/runner": "0.2.0",
46
+ "@systemix/typescript": "0.4.0"
47
+ },
48
+ "directories": {
49
+ "test": "tests"
50
+ },
51
+ "sideEffects": false,
52
+ "bugs": {
53
+ "url": "https://github.com/shahadathhs/systemix/issues"
54
+ },
55
+ "files": [
56
+ "dist",
57
+ "README.md",
58
+ "LICENSE",
59
+ "package.json"
60
+ ],
61
+ "scripts": {
62
+ "build": "tsup src/index.ts --format cjs,esm --dts",
63
+ "test": "pnpm build && node tests/run.mjs",
64
+ "typecheck": "tsc --noEmit",
65
+ "lint": "eslint .",
66
+ "lint:fix": "eslint . --fix",
67
+ "format": "prettier --check . --ignore-path .prettierignore",
68
+ "format:fix": "prettier --write . --ignore-path .prettierignore",
69
+ "clean": "rimraf dist node_modules",
70
+ "clean:turbo": "rimraf .turbo dist node_modules"
71
+ }
72
+ }