node-env-resolver 2.0.0 → 2.0.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/README.md CHANGED
@@ -1,9 +1,11 @@
1
1
  # node-env-resolver
2
2
 
3
- Type-safe environment variable resolution with zero dependencies.
3
+ Type-safe environment variable resolution with zero dependencies and ultra-small bundle size.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/node-env-resolver)](https://www.npmjs.com/package/node-env-resolver)
6
6
 
7
+ **Bundle Size:** ~6KB gzipped (includes all validators)
8
+
7
9
  ## Install
8
10
 
9
11
  ```bash
@@ -100,30 +102,111 @@ config.NODE_ENV; // 'development' | 'production' | 'test'
100
102
  config.LOG_LEVEL; // 'debug' | 'info' | 'warn' | 'error'
101
103
  ```
102
104
 
105
+ ## Performance & Bundle Size
106
+
107
+ **Ultra-lightweight and optimized.** The library uses intelligent validation strategies to minimize bundle size:
108
+
109
+ ### Inline validation for basic types
110
+
111
+ Common types use **inline validation** with zero external dependencies:
112
+ - `string`, `number`, `boolean` (with min/max validation)
113
+ - `enum` (array validation)
114
+ - `pattern` (regex validation)
115
+ - `custom` (validator functions)
116
+
117
+ ```ts
118
+ // Minimal overhead for basic validation
119
+ const config = resolve({
120
+ PORT: 3000,
121
+ DEBUG: false,
122
+ NODE_ENV: ['development', 'production'] as const,
123
+ API_KEY: 'string'
124
+ });
125
+ ```
126
+
127
+ ### All types work synchronously
128
+
129
+ All validator types (including advanced ones) work in both synchronous and asynchronous contexts:
130
+
131
+ ```ts
132
+ // Synchronous - works with all types
133
+ const config = resolve({
134
+ DATABASE_URL: 'postgres',
135
+ API_URL: 'url',
136
+ PORT: 'port:3000'
137
+ });
138
+
139
+ // Also works with async resolvers
140
+ const config = await resolve.with([
141
+ awsSecrets(),
142
+ { DATABASE_URL: 'postgres', API_URL: 'url' }
143
+ ]);
144
+ ```
145
+
146
+ ### Audit Logging (Lazy Loaded)
147
+
148
+ Audit logging is **only loaded when enabled**:
149
+
150
+ ```ts
151
+ // Audit module not loaded
152
+ const config = resolve({ PORT: 3000 });
153
+
154
+ // Audit loaded when enabled
155
+ const config = resolve({ PORT: 3000 }, { enableAudit: true });
156
+ ```
157
+
158
+ ### Tree-Shaking Friendly
159
+
160
+ The library uses ES modules for optimal tree-shaking:
161
+
162
+ ```ts
163
+ // Your bundle only includes what you import
164
+ import { resolve } from 'node-env-resolver'; // ✅ Core functionality
165
+
166
+ import { resolveZod } from 'node-env-resolver/zod'; // ✅ Separate chunk
167
+ import { awsSecrets } from 'node-env-resolver-aws'; // ✅ Separate package
168
+ ```
169
+
103
170
  ## Built-in validators
104
171
 
172
+ All validator types work synchronously and asynchronously.
173
+
105
174
  ### Basic types
106
175
 
107
- - `'string'` - Any string value
108
- - `'number'` - Numeric value (coerced from string)
176
+ These types use inline validation with **zero external dependencies**:
177
+
178
+ - `'string'` - Any string value (with optional `min`/`max` length)
179
+ - `'number'` - Numeric value (coerced from string, with optional `min`/`max`)
109
180
  - `'boolean'` - Boolean value (`'true'`/`'false'` coerced to boolean)
110
- - `'json'` - JSON value (parsed automatically)
111
- - `'port'` - Port number (1-65535)
181
+ - `'enum'` - Array of allowed values
182
+ - `'pattern'` - Regex pattern validation
183
+ - `'custom'` - Custom validator function
184
+
185
+ ### Advanced types
112
186
 
113
- ### Network types
187
+ Advanced validators provide specialized validation and parsing:
114
188
 
115
- - `'url'` - Valid URL
116
- - `'http'` - HTTP URL
117
- - `'https'` - HTTPS URL
189
+ **Network types:**
190
+
191
+ - `'url'` - Valid URL (returns URL object)
192
+ - `'http'` - HTTP or HTTPS URL
193
+ - `'https'` - HTTPS-only URL (strict)
118
194
  - `'email'` - Email address
119
195
 
120
- ### Database connection strings
196
+ **Database connection strings:**
121
197
 
122
198
  - `'postgres'` or `'postgresql'` - PostgreSQL connection string
123
199
  - `'mysql'` - MySQL connection string
124
200
  - `'mongodb'` - MongoDB connection string
125
201
  - `'redis'` - Redis connection string
126
202
 
203
+ **Format types:**
204
+
205
+ - `'json'` - JSON value (parsed automatically)
206
+ - `'port'` - Port number (1-65535)
207
+ - `'date'` - ISO 8601 date string
208
+ - `'timestamp'` - Unix timestamp
209
+
127
210
  All validators automatically handle type coercion from environment variable strings.
128
211
 
129
212
  ## Custom validators
@@ -194,6 +277,57 @@ const config = await resolve.with(
194
277
 
195
278
  This is useful for development workflows where local overrides should take precedence over cloud secrets.
196
279
 
280
+ ### Performance optimizations
281
+
282
+ The library includes two automatic performance optimizations:
283
+
284
+ #### 1. Early termination with `priority: 'first'`
285
+
286
+ When using `priority: 'first'`, resolvers are called sequentially, but execution **stops early** once all required environment variables are satisfied:
287
+
288
+ ```ts
289
+ const config = await resolve.with(
290
+ [dotenv(), { DATABASE_URL: 'url', API_KEY: 'string', PORT: 3000 }],
291
+ [awsSecrets(), { DATABASE_URL: 'url', API_KEY: 'string', PORT: 3000 }],
292
+ [gcpSecrets(), { DATABASE_URL: 'url', API_KEY: 'string', PORT: 3000 }],
293
+ { priority: 'first' }
294
+ );
295
+ // If dotenv() provides all required keys, awsSecrets() and gcpSecrets() are never called!
296
+ ```
297
+
298
+ This is particularly valuable in development where:
299
+
300
+ - Local `.env` file contains all needed variables
301
+ - Expensive remote resolver calls (AWS Secrets Manager, Parameter Store, GCP Secret Manager) are skipped
302
+ - Startup time is significantly reduced
303
+
304
+ **What counts as "satisfied"?**
305
+
306
+ - Only **required** keys (no `optional: true`, no `default` value) trigger early termination
307
+ - Optional variables and variables with defaults do **not** prevent calling remaining resolvers
308
+
309
+ #### 2. Parallel execution with `priority: 'last'`
310
+
311
+ When using `priority: 'last'` (the default), all resolvers are called **in parallel** for maximum performance:
312
+
313
+ ```ts
314
+ const config = await resolve.with(
315
+ [awsSecrets(), { DATABASE_URL: 'url' }], // 100ms
316
+ [awsParameterStore(), { API_KEY: 'string' }], // 100ms
317
+ [gcpSecrets(), { JWT_SECRET: 'string' }] // 100ms
318
+ // Default: priority: 'last'
319
+ );
320
+ // Total time: ~100ms (parallel) instead of ~300ms (sequential)
321
+ ```
322
+
323
+ Since `priority: 'last'` means "last write wins", the order doesn't matter for conflict resolution, so all resolvers can run concurrently.
324
+
325
+ **Use cases:**
326
+
327
+ - Production environments loading from multiple remote secret stores
328
+ - Fetching different variables from different sources
329
+ - Significant speedup when resolvers have network latency
330
+
197
331
  ## Safe error handling
198
332
 
199
333
  Like Zod's `safeParse()`, use `safeResolve()` to get a result object instead of throwing:
@@ -228,25 +362,27 @@ All functions have safe variants:
228
362
  ```ts
229
363
  import { resolve } from 'node-env-resolver';
230
364
 
231
- // Synchronous - no await needed
365
+ // Synchronous - no await needed, works with ALL types
232
366
  const config = resolve({
233
367
  PORT: 3000,
234
- NODE_ENV: ['development', 'production'] as const
368
+ NODE_ENV: ['development', 'production'] as const,
369
+ API_KEY: 'string',
370
+ API_URL: 'url', // Advanced types work synchronously!
371
+ DATABASE_URL: 'postgres',
372
+ DEBUG: false
235
373
  });
236
374
  ```
237
375
 
238
- However, `resolve.with()` is **async** when using custom resolvers (like loading from files or APIs):
376
+ `resolve.with()` is **async** when using custom resolvers:
239
377
 
240
378
  ```ts
241
- // Async - await required
379
+ // Async - await required when using custom resolvers
242
380
  const config = await resolve.with(
243
381
  [processEnv(), { PORT: 3000 }],
244
- [dotenv(), { DATABASE_URL: 'url' }]
382
+ [dotenv(), { DATABASE_URL: 'postgres', API_URL: 'url' }]
245
383
  );
246
384
  ```
247
385
 
248
- Synchronous resolution works with shorthand syntax and Zod schemas (see Zod integration below).
249
-
250
386
  ## Advanced features
251
387
 
252
388
  ### Zod integration
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Tests for performance optimizations:
3
+ * 1. Early termination for priority: 'first'
4
+ * 2. Parallel resolver execution for priority: 'last'
5
+ */
6
+ export {};
7
+ //# sourceMappingURL=performance.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"performance.test.d.ts","sourceRoot":"","sources":["../src/performance.test.ts"],"names":[],"mappings":"AAAA;;;;GAIG"}
@@ -1 +1 @@
1
- {"version":3,"file":"resolver.d.ts","sourceRoot":"","sources":["../src/resolver.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EACV,QAAQ,EACR,SAAS,EAET,eAAe,EACf,cAAc,EAGf,MAAM,SAAS,CAAC;AA8CjB;;GAEG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,eAAe,GAAG,SAAS,CAsBlE;AAiMD;;GAEG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,SAAS,SAAS,EAC1D,MAAM,EAAE,CAAC,EACT,SAAS,EAAE,QAAQ,EAAE,EACrB,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAwHlC;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,SAAS,EACxD,MAAM,EAAE,CAAC,EACT,SAAS,EAAE,QAAQ,EAAE,EACrB,OAAO,EAAE,cAAc,GACtB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAoDzB"}
1
+ {"version":3,"file":"resolver.d.ts","sourceRoot":"","sources":["../src/resolver.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EACV,QAAQ,EACR,SAAS,EAET,eAAe,EACf,cAAc,EAGf,MAAM,SAAS,CAAC;AAsEjB;;GAEG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,eAAe,GAAG,SAAS,CAsBlE;AAscD;;GAEG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,SAAS,SAAS,EAC1D,MAAM,EAAE,CAAC,EACT,SAAS,EAAE,QAAQ,EAAE,EACrB,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAgIlC;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,SAAS,EACxD,MAAM,EAAE,CAAC,EACT,SAAS,EAAE,QAAQ,EAAE,EACrB,OAAO,EAAE,cAAc,GACtB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAiEzB"}
package/dist/resolver.js CHANGED
@@ -1,9 +1,9 @@
1
- import {toStandardSchema}from'./standard-schema';import {logAuditEvent}from'./audit';function O(e){const s=e.match(/^(\w+):(\/.*\/)$/);if(s){const[,i,r]=s;return {type:i,pattern:r?.slice(1,-1)??""}}const o=e.indexOf(":");if(o>0&&o<e.length-1){const i=e.slice(0,o).replace(/[?]/g,""),r=e.slice(o+1),t=e.includes("?");let l=r;return i==="number"||i==="port"||i==="timestamp"?l=Number(r):i==="boolean"&&(l=r==="true"),{type:i,default:l,...t&&{optional:true}}}const n=e.endsWith("?");return {type:e.replace(/[?]/g,"")||"string",...n&&{optional:true}}}function k(e){const s={};for(const[o,n]of Object.entries(e))typeof n=="string"?s[o]=O(n):typeof n=="number"?s[o]={type:"number",default:n}:typeof n=="boolean"?s[o]={type:"boolean",default:n}:Array.isArray(n)?s[o]={type:"string",enum:n}:typeof n=="function"?s[o]={type:"custom",validator:n}:s[o]=n;return s}function D(e,s){return e.replace(/\$\{([^}]+)\}/g,(o,n)=>s[n]||o)}async function j(e,s,o,n="last"){const c={},i={};for(const r of e)try{const t=await r.load();for(const[l,f]of Object.entries(t))if(f!==void 0){if(n==="first"&&c[l]!==void 0)continue;c[l]=f,i[l]={source:r.name,timestamp:Date.now(),...r.metadata?.cached!==void 0&&{cached:r.metadata.cached}};}}catch(t){if(logAuditEvent({type:"resolver_error",timestamp:Date.now(),source:r.name,error:t instanceof Error?t.message:String(t)}),o)throw new Error(`Resolver ${r.name} failed: ${t instanceof Error?t.message:t}`)}if(s)for(const[r,t]of Object.entries(c))c[r]=D(t,c);return {mergedEnv:c,provenance:i}}function V(e,s,o,n="last"){const c={},i={};for(const r of e)try{if(!r.loadSync){if(o)throw new Error(`Resolver ${r.name} has no loadSync() method`);continue}const t=r.loadSync();for(const[l,f]of Object.entries(t))if(f!==void 0){if(n==="first"&&c[l]!==void 0)continue;c[l]=f,i[l]={source:r.name,timestamp:Date.now(),...r.metadata?.cached!==void 0&&{cached:r.metadata.cached}};}}catch(t){if(logAuditEvent({type:"resolver_error",timestamp:Date.now(),source:r.name,error:t instanceof Error?t.message:String(t)}),o)throw new Error(`Resolver ${r.name} failed: ${t instanceof Error?t.message:t}`)}if(s)for(const[r,t]of Object.entries(c))c[r]=D(t,c);return {mergedEnv:c,provenance:i}}function R(e,s,o,n){if(!n)return null;if((process.env.NODE_ENV||"").toLowerCase()==="production"&&o&&o.source.startsWith("dotenv(")){const i=n.allowDotenvInProduction;return i===true?null:Array.isArray(i)?i.includes(e)?null:`${e} cannot be sourced from .env files in production. Use process.env or cloud resolvers. To allow: policies.allowDotenvInProduction: ['${e}'] or set to true for all.`:`${e} cannot be sourced from .env files in production (secure default). Production platforms (Vercel, AWS, etc.) use process.env. To allow .env in production: policies.allowDotenvInProduction: true`}if(n.enforceAllowedSources&&n.enforceAllowedSources[e]&&o){const i=n.enforceAllowedSources[e];if(!i.includes(o.source))return `${e} must be sourced from one of: ${i.join(", ")} (actual: ${o.source})`}return null}function S(e){const s=[],o=/^[A-Z_][A-Z0-9_]*$/;for(const n of Object.keys(e))o.test(n)||s.push(`Invalid environment variable name: "${n}". Environment variable names must contain only uppercase letters, numbers, and underscores, and cannot start with a number.`);return s}async function x(e,s,o){const n=(process.env.NODE_ENV||"").toLowerCase()==="production",{interpolate:c=false,strict:i=true,policies:r,enableAudit:t=n,priority:l="last"}=o,f=S(e);if(f.length>0)throw t&&logAuditEvent({type:"validation_failure",timestamp:Date.now(),error:`Invalid environment variable names: ${f.join(", ")}`}),new Error(`Environment validation failed:
2
- ${f.map(a=>` - ${a}`).join(`
3
- `)}`);const{mergedEnv:b,provenance:m}=await j(s,c,i,l),u={},d=[];for(const[a,E]of Object.entries(e)){const h=b[a],p=R(a,E,m[a],r);if(p){d.push(p),t&&logAuditEvent({type:"policy_violation",timestamp:Date.now(),key:a,source:m[a]?.source??"unknown",error:p});continue}try{const v=toStandardSchema(a,E)["~standard"].validate(h);if(v instanceof Promise){const y=await v;y.issues?d.push(...y.issues.map(P=>P.message)):u[a]=y.value;}else v.issues?(d.push(...v.issues.map(y=>y.message)),t&&logAuditEvent({type:"validation_failure",timestamp:Date.now(),key:a,error:v.issues.map(y=>y.message).join("; ")})):(u[a]=v.value,t&&logAuditEvent({type:"env_loaded",timestamp:Date.now(),key:a,source:m[a]?.source??"unknown",metadata:{cached:m[a]?.cached}}));}catch(w){const v=w instanceof Error?w.message:String(w);d.push(`${a}: ${v}`),t&&logAuditEvent({type:"validation_failure",timestamp:Date.now(),key:a,error:v});}}if(d.length>0)throw t&&logAuditEvent({type:"validation_failure",timestamp:Date.now(),error:`${d.length} validation error(s)`,metadata:{errorCount:d.length}}),new Error(`Environment validation failed:
4
- ${d.map(a=>` - ${a}`).join(`
5
- `)}`);return t&&logAuditEvent({type:"validation_success",timestamp:Date.now(),metadata:{variableCount:Object.keys(e).length}}),u}function I(e,s,o){const n=S(e);if(n.length>0)throw new Error(`Environment validation failed:
6
- ${n.map(u=>` - ${u}`).join(`
7
- `)}`);const{interpolate:c=false,strict:i=true,policies:r,priority:t="last"}=o,{mergedEnv:l,provenance:f}=V(s,c,i,t),b={},m=[];for(const[u,d]of Object.entries(e)){const a=l[u],E=R(u,d,f[u],r);if(E){m.push(E);continue}try{const p=toStandardSchema(u,d)["~standard"].validate(a);if(p instanceof Promise)throw new Error(`resolveSync cannot validate '${u}' because validation is async`);p.issues?m.push(...p.issues.map(w=>w.message)):b[u]=p.value;}catch(h){const p=h instanceof Error?h.message:String(h);m.push(`${u}: ${p}`);}}if(m.length>0)throw new Error(`Environment validation failed:
8
- ${m.map(u=>` - ${u}`).join(`
9
- `)}`);return b}export{k as normalizeSchema,x as resolveEnvInternal,I as resolveEnvInternalSync};
1
+ import {toStandardSchema}from'./standard-schema';let $=null;async function h(e){$||($=(await import('./audit')).logAuditEvent),$(e);}function O(e){$&&$(e);}function x(e){const n=e.match(/^(\w+):(\/.*\/)$/);if(n){const[,r,l]=n;return {type:r,pattern:l?.slice(1,-1)??""}}const t=e.indexOf(":");if(t>0&&t<e.length-1){const r=e.slice(0,t).replace(/[?]/g,""),l=e.slice(t+1),a=e.includes("?");let s=l;return r==="number"||r==="port"||r==="timestamp"?s=Number(l):r==="boolean"&&(s=l==="true"),{type:r,default:s,...a&&{optional:true}}}const o=e.endsWith("?");return {type:e.replace(/[?]/g,"")||"string",...o&&{optional:true}}}function C(e){const n={};for(const[t,o]of Object.entries(e))typeof o=="string"?n[t]=x(o):typeof o=="number"?n[t]={type:"number",default:o}:typeof o=="boolean"?n[t]={type:"boolean",default:o}:Array.isArray(o)?n[t]={type:"string",enum:o}:typeof o=="function"?n[t]={type:"custom",validator:o}:n[t]=o;return n}function D(e,n){return e.replace(/\$\{([^}]+)\}/g,(t,o)=>n[o]||t)}function S(e,n,t){const o=n.type||"string";if(t===void 0||t==="")return n.default!==void 0?{success:true,value:n.default}:n.optional?{success:true,value:void 0}:{success:false,error:`Missing required environment variable: ${e}`};if(n.enum)return n.enum.includes(t)?{success:true,value:t}:{success:false,error:`${e} must be one of: ${n.enum.join(", ")}`};if(n.pattern&&!new RegExp(n.pattern).test(t))return {success:false,error:`${e} does not match required pattern: ${n.pattern}`};switch(o){case "string":return n.min!==void 0&&t.length<n.min?{success:false,error:`${e} must be at least ${n.min} characters`}:n.max!==void 0&&t.length>n.max?{success:false,error:`${e} must be at most ${n.max} characters`}:{success:true,value:t};case "number":{const i=Number(t);return isNaN(i)?{success:false,error:`${e}: Invalid number`}:n.min!==void 0&&i<n.min?{success:false,error:`${e} must be at least ${n.min}`}:n.max!==void 0&&i>n.max?{success:false,error:`${e} must be at most ${n.max}`}:{success:true,value:i}}case "boolean":{const i=t.toLowerCase();return ["true","1","yes","on","false","0","no","off",""].includes(i)?{success:true,value:["true","1","yes","on"].includes(i)}:{success:false,error:`${e}: Invalid boolean`}}case "custom":{if(!n.validator)return {success:false,error:"Custom validator function is required for type 'custom'"};try{return {success:!0,value:n.validator(t)}}catch(i){return {success:false,error:i instanceof Error?i.message:`Custom validation failed for ${e}`}}}default:return {success:false,error:"NEEDS_ADVANCED_VALIDATION"}}}function A(e){return ["postgres","postgresql","mysql","mongodb","redis","http","https","url","email","port","json","date","timestamp"].includes(e)}function _(e,n,t){const i=toStandardSchema(e,n)["~standard"].validate(t);if(i instanceof Promise)throw new Error(`Cannot validate '${e}' synchronously because the validator returned a Promise. This shouldn't happen with standard types. Please file a bug report.`);return i.issues?{success:false,error:i.issues.map(r=>r.message).join("; ")}:{success:true,value:i.value}}async function V(e,n,t){const i=toStandardSchema(e,n)["~standard"].validate(t),r=i instanceof Promise?await i:i;return r.issues?{success:false,error:r.issues.map(l=>l.message).join("; ")}:{success:true,value:r.value}}async function T(e,n,t,o="last",i){const r={},l={};if(o==="last"){const a=await Promise.allSettled(e.map(async s=>({resolver:s,env:await s.load()})));for(const s of a){if(s.status==="rejected"){const f=s.reason;if(await h({type:"resolver_error",timestamp:Date.now(),source:"unknown",error:f instanceof Error?f.message:String(f)}),t)throw new Error(`Resolver failed: ${f instanceof Error?f.message:f}`);continue}const{resolver:u,env:d}=s.value;for(const[f,v]of Object.entries(d))v!==void 0&&(r[f]=v,l[f]={source:u.name,timestamp:Date.now(),...u.metadata?.cached!==void 0&&{cached:u.metadata.cached}});}}else for(const a of e)try{const s=await a.load();for(const[u,d]of Object.entries(s))if(d!==void 0){if(r[u]!==void 0)continue;r[u]=d,l[u]={source:a.name,timestamp:Date.now(),...a.metadata?.cached!==void 0&&{cached:a.metadata.cached}};}if(i&&i.size>0&&Array.from(i).every(d=>r[d]!==void 0))break}catch(s){if(await h({type:"resolver_error",timestamp:Date.now(),source:a.name,error:s instanceof Error?s.message:String(s)}),t)throw new Error(`Resolver ${a.name} failed: ${s instanceof Error?s.message:s}`)}if(n)for(const[a,s]of Object.entries(r))r[a]=D(s,r);return {mergedEnv:r,provenance:l}}function I(e,n,t,o="last",i){const r={},l={};for(const a of e)try{if(!a.loadSync){if(t)throw new Error(`Resolver ${a.name} has no loadSync() method`);continue}const s=a.loadSync();for(const[u,d]of Object.entries(s))if(d!==void 0){if(o==="first"&&r[u]!==void 0)continue;r[u]=d,l[u]={source:a.name,timestamp:Date.now(),...a.metadata?.cached!==void 0&&{cached:a.metadata.cached}};}if(o==="first"&&i&&i.size>0&&Array.from(i).every(d=>r[d]!==void 0))break}catch(s){if(O({type:"resolver_error",timestamp:Date.now(),source:a.name,error:s instanceof Error?s.message:String(s)}),t)throw new Error(`Resolver ${a.name} failed: ${s instanceof Error?s.message:s}`)}if(n)for(const[a,s]of Object.entries(r))r[a]=D(s,r);return {mergedEnv:r,provenance:l}}function P(e,n,t,o){if(!o)return null;if((process.env.NODE_ENV||"").toLowerCase()==="production"&&t&&t.source.startsWith("dotenv(")){const r=o.allowDotenvInProduction;return r===true?null:Array.isArray(r)?r.includes(e)?null:`${e} cannot be sourced from .env files in production. Use process.env or cloud resolvers. To allow: policies.allowDotenvInProduction: ['${e}'] or set to true for all.`:`${e} cannot be sourced from .env files in production (secure default). Production platforms (Vercel, AWS, etc.) use process.env. To allow .env in production: policies.allowDotenvInProduction: true`}if(o.enforceAllowedSources&&o.enforceAllowedSources[e]&&t){const r=o.enforceAllowedSources[e];if(!r.includes(t.source))return `${e} must be sourced from one of: ${r.join(", ")} (actual: ${t.source})`}return null}function j(e){const n=[],t=/^[A-Z_][A-Z0-9_]*$/;for(const o of Object.keys(e))t.test(o)||n.push(`Invalid environment variable name: "${o}". Environment variable names must contain only uppercase letters, numbers, and underscores, and cannot start with a number.`);return n}async function k(e,n,t){const o=(process.env.NODE_ENV||"").toLowerCase()==="production",{interpolate:i=false,strict:r=true,policies:l,enableAudit:a=o,priority:s="last"}=t,u=j(e);if(u.length>0)throw a&&await h({type:"validation_failure",timestamp:Date.now(),error:`Invalid environment variable names: ${u.join(", ")}`}),new Error(`Environment validation failed:
2
+ ${u.map(c=>` - ${c}`).join(`
3
+ `)}`);const d=new Set(Object.keys(e)),{mergedEnv:f,provenance:v}=await T(n,i,r,s,d),m={},p=[];for(const[c,w]of Object.entries(e)){const E=f[c],g=P(c,w,v[c],l);if(g){p.push(g),a&&h({type:"policy_violation",timestamp:Date.now(),key:c,source:v[c]?.source??"unknown",error:g});continue}try{const b=w.type||"string";let y;A(b)?y=await V(c,w,E):y=S(c,w,E),y.success?(m[c]=y.value,a&&await h({type:"env_loaded",timestamp:Date.now(),key:c,source:v[c]?.source??"unknown",metadata:{cached:v[c]?.cached}})):(p.push(y.error),a&&await h({type:"validation_failure",timestamp:Date.now(),key:c,error:y.error}));}catch(b){const y=b instanceof Error?b.message:String(b);p.push(`${c}: ${y}`),a&&await h({type:"validation_failure",timestamp:Date.now(),key:c,error:y});}}if(p.length>0)throw a&&await h({type:"validation_failure",timestamp:Date.now(),error:`${p.length} validation error(s)`,metadata:{errorCount:p.length}}),new Error(`Environment validation failed:
4
+ ${p.map(c=>` - ${c}`).join(`
5
+ `)}`);return a&&await h({type:"validation_success",timestamp:Date.now(),metadata:{variableCount:Object.keys(e).length}}),m}function q(e,n,t){const o=j(e);if(o.length>0)throw new Error(`Environment validation failed:
6
+ ${o.map(m=>` - ${m}`).join(`
7
+ `)}`);const{interpolate:i=false,strict:r=true,policies:l,priority:a="last"}=t,s=new Set(Object.keys(e)),{mergedEnv:u,provenance:d}=I(n,i,r,a,s),f={},v=[];for(const[m,p]of Object.entries(e)){const c=u[m],w=P(m,p,d[m],l);if(w){v.push(w);continue}try{const E=p.type||"string";let g;A(E)?g=_(m,p,c):g=S(m,p,c),g.success?f[m]=g.value:v.push(g.error);}catch(E){const g=E instanceof Error?E.message:String(E);v.push(`${m}: ${g}`);}}if(v.length>0)throw new Error(`Environment validation failed:
8
+ ${v.map(m=>` - ${m}`).join(`
9
+ `)}`);return f}export{C as normalizeSchema,k as resolveEnvInternal,q as resolveEnvInternalSync};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-env-resolver",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "Type-safe environment variable resolver with async resolvers - lightweight, tree-shakeable, no dependencies",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -99,7 +99,7 @@
99
99
  "build": "NODE_ENV=production tsup && tsc --emitDeclarationOnly",
100
100
  "build:dev": "tsup",
101
101
  "build:dts": "tsc --emitDeclarationOnly",
102
- "typecheck": "tsc -p tsconfig.json --noEmit",
102
+ "type-check": "tsc -p tsconfig.json --noEmit",
103
103
  "lint": "eslint src/",
104
104
  "test": "vitest run",
105
105
  "format": "prettier --write \"**/*.{ts,tsx,md}\""