node-env-resolver 6.4.0 → 6.5.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 +73 -0
- package/binding.gyp +9 -0
- package/dist/builder.cjs +1 -1
- package/dist/builder.js +1 -1
- package/dist/chunk-2IQQVAXA.cjs +9 -0
- package/dist/chunk-46CBATKM.js +1 -0
- package/dist/{chunk-4TODB2KY.js → chunk-C34FGZOG.js} +1 -1
- package/dist/chunk-FNF55TN4.cjs +1 -0
- package/dist/chunk-G36OESVW.cjs +1 -0
- package/dist/chunk-I5UKYTX6.js +1 -0
- package/dist/chunk-MFFH2ZXS.js +17 -0
- package/dist/chunk-QCKMQEJP.cjs +17 -0
- package/dist/{chunk-OX54K5J5.cjs → chunk-S7AB6UX7.cjs} +3 -3
- package/dist/chunk-TGIYWWDY.js +9 -0
- package/dist/chunk-VUUPIWFJ.js +9 -0
- package/dist/chunk-ZDRU3RSU.cjs +9 -0
- package/dist/cli-main.cjs +4 -0
- package/dist/cli-main.d.cts +1 -0
- package/dist/cli-main.d.ts +1 -0
- package/dist/cli-main.js +4 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/redaction.cjs +1 -0
- package/dist/redaction.d.cts +54 -0
- package/dist/redaction.d.ts +54 -0
- package/dist/redaction.js +1 -0
- package/dist/resolver.cjs +1 -1
- package/dist/resolver.js +1 -1
- package/dist/resolvers.cjs +1 -1
- package/dist/resolvers.d.cts +26 -1
- package/dist/resolvers.d.ts +26 -1
- package/dist/resolvers.js +1 -1
- package/dist/typegen.cjs +1 -0
- package/dist/typegen.d.cts +52 -0
- package/dist/typegen.d.ts +52 -0
- package/dist/typegen.js +1 -0
- package/dist/types.cjs +1 -1
- package/dist/types.d.cts +16 -2
- package/dist/types.d.ts +16 -2
- package/dist/types.js +1 -1
- package/dist/utils.cjs +1 -1
- package/dist/utils.d.cts +12 -2
- package/dist/utils.d.ts +12 -2
- package/dist/utils.js +1 -1
- package/dist/valibot.cjs +1 -1
- package/dist/valibot.js +1 -1
- package/dist/validators.cjs +2 -2
- package/dist/validators.d.cts +47 -24
- package/dist/validators.d.ts +47 -24
- package/dist/validators.js +2 -2
- package/dist/web.cjs +3 -3
- package/dist/web.js +1 -1
- package/dist/zod.cjs +1 -1
- package/dist/zod.js +1 -1
- package/index.js +1 -0
- package/package.json +31 -7
- package/dist/chunk-4KFQR5TJ.js +0 -9
- package/dist/chunk-6D5APQIG.cjs +0 -1
- package/dist/chunk-DCAD54W2.js +0 -15
- package/dist/chunk-GMN7ADP3.cjs +0 -9
- package/dist/chunk-HHOS5S5T.js +0 -1
- package/dist/chunk-UQW24J5O.cjs +0 -15
package/README.md
CHANGED
|
@@ -148,6 +148,7 @@ const config = await resolveAsync({
|
|
|
148
148
|
- [Safe error handling](#safe-error-handling)
|
|
149
149
|
- [Synchronous resolution](#synchronous-resolution)
|
|
150
150
|
- [Advanced features](#advanced-features)
|
|
151
|
+
- [CLI tool](#cli-tool-node-env-resolver)
|
|
151
152
|
- [API Reference](#api-reference)
|
|
152
153
|
- [Configuration Options](#configuration-options)
|
|
153
154
|
- [Framework examples](#framework-examples)
|
|
@@ -730,6 +731,78 @@ const config = await resolveAsync({
|
|
|
730
731
|
|
|
731
732
|
**Bundle size:** ~500 bytes (lazy-loaded)
|
|
732
733
|
|
|
734
|
+
### CLI tool (`node-env-resolver`)
|
|
735
|
+
|
|
736
|
+
This package also ships a standalone CLI binary for working with an `EnvConfig` file.
|
|
737
|
+
|
|
738
|
+
#### 1. Create an `env.config` file
|
|
739
|
+
|
|
740
|
+
Create `env.config.mjs` or `env.config.js` in your project root:
|
|
741
|
+
|
|
742
|
+
```ts
|
|
743
|
+
// env.config.mjs
|
|
744
|
+
import { processEnv, dotenv } from 'node-env-resolver/resolvers';
|
|
745
|
+
import { string, number, json } from 'node-env-resolver/validators';
|
|
746
|
+
|
|
747
|
+
/** @type {import('node-env-resolver').ResolveAsyncConfig<any>} */
|
|
748
|
+
export const config = {
|
|
749
|
+
schema: {
|
|
750
|
+
NODE_ENV: ['development', 'production', 'test'] as const,
|
|
751
|
+
PORT: number({ default: 3000 }),
|
|
752
|
+
API_KEY: string({ optional: true, sensitive: true }),
|
|
753
|
+
FEATURE_FLAGS: json(), // parsed JSON → unknown
|
|
754
|
+
},
|
|
755
|
+
resolvers: [
|
|
756
|
+
[processEnv(), {}],
|
|
757
|
+
[dotenv(), {}],
|
|
758
|
+
],
|
|
759
|
+
};
|
|
760
|
+
|
|
761
|
+
export default config;
|
|
762
|
+
```
|
|
763
|
+
|
|
764
|
+
The CLI loads this file using native `import()` (no ts-node/jiti) and expects a default export (or `config` / `env`) with a `schema` field.
|
|
765
|
+
|
|
766
|
+
#### 2. Commands
|
|
767
|
+
|
|
768
|
+
- **`load`** – resolve and print config
|
|
769
|
+
- Pretty table (default):
|
|
770
|
+
```bash
|
|
771
|
+
node-env-resolver load
|
|
772
|
+
node-env-resolver load --config ./env.config.mjs
|
|
773
|
+
```
|
|
774
|
+
- JSON output (honours sensitive redaction):
|
|
775
|
+
```bash
|
|
776
|
+
node-env-resolver load --format=json
|
|
777
|
+
node-env-resolver load --format=json --reveal # show secrets in plaintext
|
|
778
|
+
```
|
|
779
|
+
- `.env`-style output (good for scripting):
|
|
780
|
+
```bash
|
|
781
|
+
node-env-resolver load --format=env > .env.local
|
|
782
|
+
```
|
|
783
|
+
|
|
784
|
+
- **`run`** – resolve config and run a child process with injected env:
|
|
785
|
+
```bash
|
|
786
|
+
node-env-resolver run -- npm run migrate
|
|
787
|
+
node-env-resolver run --config ./env.config.mjs -- npm run start
|
|
788
|
+
node-env-resolver run --no-redact -- node scripts/print-env.ts
|
|
789
|
+
```
|
|
790
|
+
|
|
791
|
+
- Merges resolved values on top of `process.env`.
|
|
792
|
+
- By default, stdout/stderr are **redacted** using the same sensitive key detection as the library.
|
|
793
|
+
- Use `--no-redact` to disable stream redaction when you need raw logs.
|
|
794
|
+
|
|
795
|
+
- **`typegen`** – generate `EnvSchema` and `process.env` / `import.meta.env` types:
|
|
796
|
+
```bash
|
|
797
|
+
node-env-resolver typegen --output env.d.ts
|
|
798
|
+
node-env-resolver typegen --config ./env.config.mjs --output ./src/env.d.ts
|
|
799
|
+
```
|
|
800
|
+
|
|
801
|
+
This uses the same generator as `node-env-resolver/typegen`, including:
|
|
802
|
+
- `json()` → `unknown` in `EnvSchema` (parsed JSON)
|
|
803
|
+
- Correct optional flags based on `{ optional: true }`
|
|
804
|
+
- String-oriented types for `process.env`/`import.meta.env` augmentation
|
|
805
|
+
|
|
733
806
|
### Computed fields
|
|
734
807
|
|
|
735
808
|
Derive properties from resolved configuration:
|
package/binding.gyp
ADDED
package/dist/builder.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk2IQQVAXA_cjs=require('./chunk-2IQQVAXA.cjs');require('./chunk-O7NR4K6A.cjs'),require('./chunk-G36OESVW.cjs');var chunkQCKMQEJP_cjs=require('./chunk-QCKMQEJP.cjs'),chunk4QOKRJ3F_cjs=require('./chunk-4QOKRJ3F.cjs');require('./chunk-D6WM53FN.cjs');var i=class{constructor(e,s={}){this.localSchema=e;this.options=s;}layers=[];from(e,s){return this.layers.push({resolver:e,schema:s}),this}resolve(){let e=chunk2IQQVAXA_cjs.a(this.localSchema);for(let l of this.layers){let m=chunk2IQQVAXA_cjs.a(l.schema);Object.assign(e,m);}let s=this.buildDefaultResolvers(),r=this.layers.map(l=>l.resolver),a=this.options.extend||[],c=[...s,...r,...a],u=this.options.policies??{};return chunk2IQQVAXA_cjs.c(e,c,{...this.options,policies:u,interpolate:this.options.interpolate??true,strict:this.options.strict??true})}buildDefaultResolvers(){let e=process.env.NODE_ENV==="production",s=[];return e||s.push(chunkQCKMQEJP_cjs.a({expand:true})),s.push(chunk4QOKRJ3F_cjs.a()),s}},n=class{constructor(e,s={}){this.localSchema=e;this.options=s;}layers=[];from(e,s){return this.layers.push({resolver:e,schema:s}),this}resolveSync(){let e=chunk2IQQVAXA_cjs.a(this.localSchema);for(let l of this.layers){let m=chunk2IQQVAXA_cjs.a(l.schema);Object.assign(e,m);}let s=this.buildDefaultResolvers(),r=this.layers.map(l=>l.resolver),a=this.options.extend||[],c=[...s,...r,...a],u=this.options.policies??{};return chunk2IQQVAXA_cjs.c(e,c,{...this.options,policies:u,interpolate:this.options.interpolate??true,strict:this.options.strict??true})}buildDefaultResolvers(){let e=process.env.NODE_ENV==="production",s=[];return e||s.push(chunkQCKMQEJP_cjs.a({expand:true})),s.push(chunk4QOKRJ3F_cjs.a()),s}};function y(t,e){return new i(t,e)}function b(t,e){return new n(t,e)}var d=class{builder;simpleResolve=null;constructor(e,s={}){this.builder=new i(e,s);}from(e,s){return this.builder.from(e,s),this}async compose(){return this.builder.resolve()}then(e,s){return this.simpleResolve||(this.simpleResolve=Promise.resolve(this.builder.resolve())),this.simpleResolve.then(e,s)}catch(e){return this.simpleResolve||(this.simpleResolve=Promise.resolve(this.builder.resolve())),this.simpleResolve.catch(e)}finally(e){return this.simpleResolve||(this.simpleResolve=Promise.resolve(this.builder.resolve())),this.simpleResolve.finally(e)}},S=class{builder;_resolved=null;_hasComposition=false;constructor(e,s={}){Object.defineProperty(this,"builder",{value:new n(e,s),enumerable:false,writable:true}),Object.defineProperty(this,"_hasComposition",{value:false,enumerable:false,writable:true});let r=this.builder.resolveSync();Object.defineProperty(this,"_resolved",{value:r,enumerable:false,writable:true}),Object.assign(this,r);}from(e,s){return Object.defineProperty(this,"_hasComposition",{value:true,enumerable:false,writable:true}),this.builder.from(e,s),this}compose(){return this._hasComposition&&(this._resolved=this.builder.resolveSync(),Object.assign(this,this._resolved)),this._resolved}valueOf(){return this._resolved}toJSON(){return this._resolved}};exports.EnvBuilder=i;exports.EnvBuilderSync=n;exports.ResolvableBuilder=d;exports.ResolvableBuilderSync=S;exports.env=y;exports.envSync=b;
|
package/dist/builder.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a
|
|
1
|
+
import {a,c}from'./chunk-VUUPIWFJ.js';import'./chunk-6EWR3WHU.js';import'./chunk-46CBATKM.js';import {a as a$1}from'./chunk-MFFH2ZXS.js';import {a as a$2}from'./chunk-WKIPEKF6.js';import'./chunk-I7AUKTXE.js';var i=class{constructor(e,s={}){this.localSchema=e;this.options=s;}layers=[];from(e,s){return this.layers.push({resolver:e,schema:s}),this}resolve(){let e=a(this.localSchema);for(let l of this.layers){let m=a(l.schema);Object.assign(e,m);}let s=this.buildDefaultResolvers(),r=this.layers.map(l=>l.resolver),a$1=this.options.extend||[],c$1=[...s,...r,...a$1],u=this.options.policies??{};return c(e,c$1,{...this.options,policies:u,interpolate:this.options.interpolate??true,strict:this.options.strict??true})}buildDefaultResolvers(){let e=process.env.NODE_ENV==="production",s=[];return e||s.push(a$1({expand:true})),s.push(a$2()),s}},n=class{constructor(e,s={}){this.localSchema=e;this.options=s;}layers=[];from(e,s){return this.layers.push({resolver:e,schema:s}),this}resolveSync(){let e=a(this.localSchema);for(let l of this.layers){let m=a(l.schema);Object.assign(e,m);}let s=this.buildDefaultResolvers(),r=this.layers.map(l=>l.resolver),a$1=this.options.extend||[],c$1=[...s,...r,...a$1],u=this.options.policies??{};return c(e,c$1,{...this.options,policies:u,interpolate:this.options.interpolate??true,strict:this.options.strict??true})}buildDefaultResolvers(){let e=process.env.NODE_ENV==="production",s=[];return e||s.push(a$1({expand:true})),s.push(a$2()),s}};function y(t,e){return new i(t,e)}function b(t,e){return new n(t,e)}var d=class{builder;simpleResolve=null;constructor(e,s={}){this.builder=new i(e,s);}from(e,s){return this.builder.from(e,s),this}async compose(){return this.builder.resolve()}then(e,s){return this.simpleResolve||(this.simpleResolve=Promise.resolve(this.builder.resolve())),this.simpleResolve.then(e,s)}catch(e){return this.simpleResolve||(this.simpleResolve=Promise.resolve(this.builder.resolve())),this.simpleResolve.catch(e)}finally(e){return this.simpleResolve||(this.simpleResolve=Promise.resolve(this.builder.resolve())),this.simpleResolve.finally(e)}},S=class{builder;_resolved=null;_hasComposition=false;constructor(e,s={}){Object.defineProperty(this,"builder",{value:new n(e,s),enumerable:false,writable:true}),Object.defineProperty(this,"_hasComposition",{value:false,enumerable:false,writable:true});let r=this.builder.resolveSync();Object.defineProperty(this,"_resolved",{value:r,enumerable:false,writable:true}),Object.assign(this,r);}from(e,s){return Object.defineProperty(this,"_hasComposition",{value:true,enumerable:false,writable:true}),this.builder.from(e,s),this}compose(){return this._hasComposition&&(this._resolved=this.builder.resolveSync(),Object.assign(this,this._resolved)),this._resolved}valueOf(){return this._resolved}toJSON(){return this._resolved}};export{i as EnvBuilder,n as EnvBuilderSync,d as ResolvableBuilder,S as ResolvableBuilderSync,y as env,b as envSync};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
'use strict';var chunkO7NR4K6A_cjs=require('./chunk-O7NR4K6A.cjs'),chunkG36OESVW_cjs=require('./chunk-G36OESVW.cjs'),path=require('path'),fs=require('fs');function L(i,u){try{let t=path.resolve(process.cwd(),i);return {valid:!0,value:fs.readFileSync(t,"utf8").trim()}}catch(t){return {valid:false,error:`Failed to read file${u?` for ${u}`:""}: ${t instanceof Error?t.message:String(t)}`}}}var E=chunkO7NR4K6A_cjs.b,h=chunkO7NR4K6A_cjs.b,T=chunkO7NR4K6A_cjs.a;function H(i){let u={};for(let[t,s]of Object.entries(i))if(typeof s=="function"){let a=s,r=a.__isFileValidator===true,f=a.__meta;u[t]={type:r?"file":"custom",validator:s,...a.default!==void 0&&{default:a.default},...a.optional!==void 0&&{optional:a.optional},...a.secretsDir!==void 0&&{secretsDir:a.secretsDir},...f?.sensitive!==void 0&&{sensitive:f.sensitive},...f?.description!==void 0&&{description:f.description}};}else if(typeof s=="string")u[t]={type:"string",default:s,validator:a=>{let r=u[t];if(a===""&&!r.allowEmpty)throw new Error("String cannot be empty");return a}};else if(typeof s=="number")u[t]={type:"number",default:s,validator:a=>{let r=Number(a);if(isNaN(r))throw new Error(`Invalid number: "${a}"`);return r}};else if(typeof s=="boolean")u[t]={type:"boolean",default:s,validator:a=>{let r=a.toLowerCase();if(["true","1","yes","on"].includes(r))return true;if(["false","0","no","off",""].includes(r))return false;throw new Error(`Invalid boolean: "${a}"`)}};else if(Array.isArray(s)){let a=s.map(String),r=s.__optional===true;u[t]={type:"string",enum:a,optional:r,validator:(f,n)=>{if(!a.includes(f)){let o=n||t;throw new Error(`${o} must be one of: ${a.join(", ")}`)}return f}};}else u[t]=s;return u}function x(i,u){return i.replace(/\$\{([^}]+)\}/g,(t,s)=>u[s]||t)}async function q(i,u,t,s="last",a){let r={},f={};if(s==="last"){let n=await Promise.allSettled(i.map(async o=>({resolver:o,env:o.load?await o.load():{}})));for(let o of n){if(o.status==="rejected"){let d=o.reason;if(E({type:"resolver_error",timestamp:Date.now(),source:"unknown",error:d instanceof Error?d.message:String(d)}),t)throw new Error(`Resolver failed: ${d instanceof Error?d.message:d}`);continue}let{resolver:m,env:c}=o.value;for(let[d,b]of Object.entries(c))b!==void 0&&(r[d]=b,f[d]={source:m.name||"unknown",timestamp:Date.now(),...m.metadata?.cached!==void 0&&{cached:!!m.metadata.cached}});}}else for(let n of i)try{let o=n.load?await n.load():{};for(let[m,c]of Object.entries(o))if(c!==void 0){if(r[m]!==void 0)continue;r[m]=c,f[m]={source:n.name||"unknown",timestamp:Date.now(),...n.metadata?.cached!==void 0&&{cached:!!n.metadata.cached}};}if(a&&a.size>0&&Array.from(a).every(c=>r[c]!==void 0))break}catch(o){if(E({type:"resolver_error",timestamp:Date.now(),source:n.name,error:o instanceof Error?o.message:String(o)}),t)throw new Error(`Resolver ${n.name} failed: ${o instanceof Error?o.message:o}`,{cause:o})}if(u)for(let[n,o]of Object.entries(r))r[n]=x(o,r);return {mergedEnv:r,provenance:f}}function W(i,u,t,s="last",a){let r={},f={};for(let n of i)try{if(!n.loadSync){if(t)throw new Error(`Resolver ${n.name} has no loadSync() method`);continue}let o=n.loadSync();for(let[m,c]of Object.entries(o))if(c!==void 0){if(s==="first"&&r[m]!==void 0)continue;r[m]=c,f[m]={source:n.name||"unknown",timestamp:Date.now(),...n.metadata?.cached!==void 0&&{cached:!!n.metadata.cached}};}if(s==="first"&&a&&a.size>0&&Array.from(a).every(c=>r[c]!==void 0))break}catch(o){if(h({type:"resolver_error",timestamp:Date.now(),source:n.name,error:o instanceof Error?o.message:String(o)}),t)throw new Error(`Resolver ${n.name} failed: ${o instanceof Error?o.message:o}`,{cause:o})}if(u)for(let[n,o]of Object.entries(r))r[n]=x(o,r);return {mergedEnv:r,provenance:f}}function z(i,u,t,s){if(!s)return null;if((process.env.NODE_ENV||"").toLowerCase()==="production"&&t&&t.source.startsWith("dotenv(")){let f=s.allowDotenvInProduction;return f===true?null:Array.isArray(f)?f.includes(i)?null:`${i} cannot be sourced from .env files in production. Use process.env or cloud resolvers. To allow: policies.allowDotenvInProduction: ['${i}'] or set to true for all.`:`${i} 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`}let r=s.enforceAllowedSources?.[i];return r&&t&&!r.includes(t.source)?`${i} must be sourced from one of: ${r.join(", ")} (actual: ${t.source})`:null}function M(i){let u=[],t=/^[A-Za-z_][A-Za-z0-9_]*$/;for(let s of Object.keys(i))t.test(s)||u.push(`Invalid environment variable name: "${s}". Environment variable names must contain only letters, numbers, and underscores, and cannot start with a number.`);return u}function B(i,u){let t={};for(let[s,a]of Object.entries(i)){if(!s.includes(u)){t[s]=a;continue}let r=s.split(u),f=t;for(let o=0;o<r.length-1;o++){let m=r[o].toLowerCase();m in f||(f[m]={}),f=f[m];}let n=r[r.length-1].toLowerCase();f[n]=a;}for(let s of Object.keys(i))delete i[s];return Object.assign(i,t),i}async function J(i,u,t){let s=(process.env.NODE_ENV||"").toLowerCase()==="production",{interpolate:a=false,strict:r=true,policies:f,enableAudit:n=s,priority:o="last",secretsDir:m}=t,c={},d;n&&(d=T(c));let b=M(i);if(b.length>0)throw n&&E({type:"validation_failure",timestamp:Date.now(),error:`Invalid environment variable names: ${b.join(", ")}`,sessionId:d}),new Error(`Environment validation failed:
|
|
2
|
+
${b.map(e=>` - ${e}`).join(`
|
|
3
|
+
`)}`);let O=new Set(Object.keys(i)),{mergedEnv:_,provenance:y}=await q(u,a,r,o,O),g=[];for(let[e,w]of Object.entries(i)){let v=w,D=_[e],S=z(e,v,y[e],f);if(S){g.push(S),n&&E({type:"policy_violation",timestamp:Date.now(),key:e,source:y[e]?.source??"unknown",error:S,sessionId:d});continue}try{let l;if(D===void 0){let p=v.secretsDir??m;if(v.type==="file"&&p){let j=e.toLowerCase().replace(/_/g,"-"),P=path.join(p,j),$=L(P,e);$.valid?(l={success:!0,value:$.value},y[e]={source:`secretsDir(${p})`,timestamp:Date.now()}):l={success:!1,error:$.error??`Failed to read secret for ${e}`};}else v.default!==void 0?l={success:!0,value:v.default}:v.optional?l={success:!0,value:void 0}:l={success:!1,error:`Missing required environment variable: ${e}`};}else if(v.validator)try{l={success:!0,value:v.validator(D,e)};}catch(p){l={success:!1,error:p instanceof Error?p.message:`Validation failed for ${e}`};}else l={success:!0,value:D};l.success?(c[e]=l.value,n&&E({type:"env_loaded",timestamp:Date.now(),key:e,source:y[e]?.source??"unknown",metadata:{cached:y[e]?.cached},sessionId:d})):(g.push(l.error),n&&E({type:"validation_failure",timestamp:Date.now(),key:e,error:l.error,sessionId:d}));}catch(l){let p=l instanceof Error?l.message:String(l);g.push(`${e}: ${p}`),n&&E({type:"validation_failure",timestamp:Date.now(),key:e,error:p,sessionId:d});}}if(g.length>0)throw n&&E({type:"validation_failure",timestamp:Date.now(),error:`${g.length} validation error(s)`,metadata:{errorCount:g.length},sessionId:d}),new Error(`Environment validation failed:
|
|
4
|
+
${g.map(e=>` - ${e}`).join(`
|
|
5
|
+
`)}`);n&&E({type:"validation_success",timestamp:Date.now(),metadata:{variableCount:Object.keys(i).length},sessionId:d});let R=new Set,k=new Map;for(let[e,w]of Object.entries(i))if(w.sensitive){R.add(e);let v=c[e];typeof v=="string"&&v.length>0&&k.set(e,v);}if(t.nestedDelimiter){B(c,t.nestedDelimiter);for(let[e,w]of k.entries())e in c||Object.defineProperty(c,e,{value:w,enumerable:false,configurable:false});}return Object.defineProperty(c,chunkG36OESVW_cjs.d,{value:R,enumerable:false,configurable:false}),Object.defineProperty(c,chunkG36OESVW_cjs.c,{value:y,enumerable:false,configurable:false}),c}function Q(i,u,t){let s=(process.env.NODE_ENV||"").toLowerCase()==="production",{interpolate:a=false,strict:r=true,policies:f,enableAudit:n=s,priority:o="last",secretsDir:m}=t,c={},d;n&&(d=T(c));let b=M(i);if(b.length>0)throw n&&h({type:"validation_failure",timestamp:Date.now(),error:`Invalid environment variable names: ${b.join(", ")}`,sessionId:d}),new Error(`Environment validation failed:
|
|
6
|
+
${b.map(e=>` - ${e}`).join(`
|
|
7
|
+
`)}`);let O=new Set(Object.keys(i)),{mergedEnv:_,provenance:y}=W(u,a,r,o,O),g=[];for(let[e,w]of Object.entries(i)){let v=w,D=_[e],S=z(e,v,y[e],f);if(S){g.push(S),n&&h({type:"policy_violation",timestamp:Date.now(),key:e,source:y[e]?.source??"unknown",error:S,sessionId:d});continue}try{let l;if(D===void 0){let p=v.secretsDir??m;if(v.type==="file"&&p){let j=e.toLowerCase().replace(/_/g,"-"),P=path.join(p,j),$=L(P,e);$.valid?(l={success:!0,value:$.value},y[e]={source:`secretsDir(${p})`,timestamp:Date.now()}):l={success:!1,error:$.error??`Failed to read secret for ${e}`};}else v.default!==void 0?l={success:!0,value:v.default}:v.optional?l={success:!0,value:void 0}:l={success:!1,error:`Missing required environment variable: ${e}`};}else if(v.validator)try{l={success:!0,value:v.validator(D,e)};}catch(p){l={success:!1,error:p instanceof Error?p.message:`Validation failed for ${e}`};}else l={success:!0,value:D};l.success?(c[e]=l.value,n&&h({type:"env_loaded",timestamp:Date.now(),key:e,source:y[e]?.source??"unknown",metadata:{cached:y[e]?.cached},sessionId:d})):(g.push(l.error),n&&h({type:"validation_failure",timestamp:Date.now(),key:e,error:l.error,sessionId:d}));}catch(l){let p=l instanceof Error?l.message:String(l);g.push(`${e}: ${p}`),n&&h({type:"validation_failure",timestamp:Date.now(),key:e,error:p,sessionId:d});}}if(g.length>0)throw n&&h({type:"validation_failure",timestamp:Date.now(),error:`${g.length} validation error(s)`,metadata:{errorCount:g.length},sessionId:d}),new Error(`Environment validation failed:
|
|
8
|
+
${g.map(e=>` - ${e}`).join(`
|
|
9
|
+
`)}`);n&&h({type:"validation_success",timestamp:Date.now(),metadata:{variableCount:Object.keys(i).length},sessionId:d});let R=new Set,k=new Map;for(let[e,w]of Object.entries(i))if(w.sensitive){R.add(e);let v=c[e];typeof v=="string"&&v.length>0&&k.set(e,v);}if(t.nestedDelimiter){B(c,t.nestedDelimiter);for(let[e,w]of k.entries())e in c||Object.defineProperty(c,e,{value:w,enumerable:false,configurable:false});}return Object.defineProperty(c,chunkG36OESVW_cjs.d,{value:R,enumerable:false,configurable:false}),Object.defineProperty(c,chunkG36OESVW_cjs.c,{value:y,enumerable:false,configurable:false}),c}exports.a=H;exports.b=J;exports.c=Q;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var n=e=>"loadSync"in e,r=e=>"load"in e&&!("loadSync"in e),o=Symbol.for("node-env-resolver:provenance"),t=Symbol.for("node-env-resolver:sensitiveKeys");export{n as a,r as b,o as c,t as d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a,c,b}from'./chunk-
|
|
1
|
+
import {a,c,b}from'./chunk-VUUPIWFJ.js';import {a as a$1}from'./chunk-WKIPEKF6.js';function v(){return [a$1()]}function h(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&("resolvers"in e||"schema"in e||"options"in e)}function S(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("resolvers"in e)&&!("schema"in e)&&!("options"in e)}function w(e,t){let o,l,i;if(h(e)){let s=e;if(s.schema)o=s.schema;else if(s.resolvers&&s.resolvers.length>0){o={};for(let[,n]of s.resolvers)Object.assign(o,n);}else throw new Error('resolve() config object must have either a "schema" property or "resolvers" array');l=s.resolvers?s.resolvers.map(([n])=>n):v(),i=s.options;}else if(S(e))o=e,l=v(),i=t;else throw new Error('resolve() expects either a schema object or a config object with "schema" or "resolvers" property');for(let[s,n]of Object.entries(o))if(n&&typeof n=="object"&&"~standard"in n)throw new Error(`\u274C resolve() cannot be used with async validators.
|
|
2
2
|
Variable '${s}' uses a Standard Schema validator (Zod, Valibot, etc.)
|
|
3
3
|
\u{1F4A1} Use resolveAsync() instead, or use shorthand syntax for sync validation.`);for(let s of l)if(!s.loadSync)throw new Error(`\u274C Resolver '${s.name}' does not support synchronous loading.
|
|
4
4
|
All resolvers passed to resolve() must have a loadSync() method.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkG36OESVW_cjs=require('./chunk-G36OESVW.cjs');var g=Symbol.for("node-env-resolver:revealed");function h(e){return {[g]:true,value:e}}function y(e){return typeof e=="object"&&e!==null&&g in e&&e[g]===true}function b(e){let n=e[chunkG36OESVW_cjs.d];return n instanceof Set?n:new Set}function w(e){let n=b(e),s=new Map,t=e;for(let o of n){let r=t[o];typeof r=="string"&&r.length>0&&s.set(o,r);}return s}function x(e,n=2){return e.length<=n?"*".repeat(e.length):e.slice(0,n)+"*".repeat(Math.min(e.length-n,5))}var f=new WeakMap;function k(e){let n=f.get(e);if(n)return n;let s=w(e),t=Array.from(s.entries()).sort((c,i)=>i[1].length-c[1].length),o=new Map,r=[];for(let[c,i]of t)i.length!==0&&(o.set(i,c),r.push(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")));return n={regex:r.length>0?new RegExp(r.join("|"),"g"):null,valueToKey:o},f.set(e,n),n}function p(e){let n=k(e);function s(t){if(y(t))return t.value;if(typeof t=="string")return d(t,n);if(Array.isArray(t))return t.map(s);if(typeof t=="object"&&t!==null)try{let o=JSON.stringify(t),r=d(o,n);return JSON.parse(r)}catch{return t}return t}return s}function d(e,n){return !n.regex||n.valueToKey.size===0?e:(n.regex.lastIndex=0,e.replace(n.regex,s=>x(s)))}function R(e,n){return p(n)(e)}var a=Symbol.for("node-env-resolver:consolePatchedBy");function m(e){if(globalThis[a])return ()=>{};let n=p(e),s=["log","warn","error","info","debug","trace"],t=new Map;for(let o of s){let r=console[o].bind(console);t.set(o,r),console[o]=(...l)=>{r(...l.map(n));};}return globalThis[a]=true,()=>{for(let o of s){let r=t.get(o);r&&(console[o]=r);}delete globalThis[a];}}exports.a=g;exports.b=h;exports.c=b;exports.d=w;exports.e=x;exports.f=p;exports.g=R;exports.h=m;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var n=e=>"loadSync"in e,r=e=>"load"in e&&!("loadSync"in e),o=Symbol.for("node-env-resolver:provenance"),t=Symbol.for("node-env-resolver:sensitiveKeys");exports.a=n;exports.b=r;exports.c=o;exports.d=t;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {d as d$1}from'./chunk-46CBATKM.js';var g=Symbol.for("node-env-resolver:revealed");function h(e){return {[g]:true,value:e}}function y(e){return typeof e=="object"&&e!==null&&g in e&&e[g]===true}function b(e){let n=e[d$1];return n instanceof Set?n:new Set}function w(e){let n=b(e),s=new Map,t=e;for(let o of n){let r=t[o];typeof r=="string"&&r.length>0&&s.set(o,r);}return s}function x(e,n=2){return e.length<=n?"*".repeat(e.length):e.slice(0,n)+"*".repeat(Math.min(e.length-n,5))}var f=new WeakMap;function k(e){let n=f.get(e);if(n)return n;let s=w(e),t=Array.from(s.entries()).sort((c,i)=>i[1].length-c[1].length),o=new Map,r=[];for(let[c,i]of t)i.length!==0&&(o.set(i,c),r.push(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")));return n={regex:r.length>0?new RegExp(r.join("|"),"g"):null,valueToKey:o},f.set(e,n),n}function p(e){let n=k(e);function s(t){if(y(t))return t.value;if(typeof t=="string")return d(t,n);if(Array.isArray(t))return t.map(s);if(typeof t=="object"&&t!==null)try{let o=JSON.stringify(t),r=d(o,n);return JSON.parse(r)}catch{return t}return t}return s}function d(e,n){return !n.regex||n.valueToKey.size===0?e:(n.regex.lastIndex=0,e.replace(n.regex,s=>x(s)))}function R(e,n){return p(n)(e)}var a=Symbol.for("node-env-resolver:consolePatchedBy");function m(e){if(globalThis[a])return ()=>{};let n=p(e),s=["log","warn","error","info","debug","trace"],t=new Map;for(let o of s){let r=console[o].bind(console);t.set(o,r),console[o]=(...l)=>{r(...l.map(n));};}return globalThis[a]=true,()=>{for(let o of s){let r=t.get(o);r&&(console[o]=r);}delete globalThis[a];}}export{g as a,h as b,b as c,w as d,x as e,p as f,R as g,m as h};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import {a}from'./chunk-I7AUKTXE.js';import {existsSync,readFileSync}from'fs';import {resolve,join}from'path';import {execSync,exec}from'child_process';var $=l=>{let c={},r=l.split(`
|
|
2
|
+
`);for(let e=0;e<r.length;e++){let f=r[e]?.trim()??"";if(!f||f[0]==="#")continue;let a=f.indexOf("=");if(a<=0)continue;let s=f.slice(0,a).trim();if(!/^[A-Z_][A-Z0-9_]*$/i.test(s))continue;let t=f.slice(a+1).trim();if(t.length>=2){let n=t[0];(n==='"'||n==="'")&&t[t.length-1]===n&&(t=t.slice(1,-1),n==='"'&&(t=t.replace(/\\n/g,`
|
|
3
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\\/g,"\\").replace(/\\"/g,'"').replace(/\\'/g,"'")));}else {let n=t.indexOf("#");n>=0&&(t=t.slice(0,n).trim());}c[s]=t;}return c};function U(l){let c=typeof l=="string"?{path:l,expand:false}:{path:l?.path??".env",expand:l?.expand??false};return {name:c.expand?`dotenv-expand(${c.path})`:`dotenv(${c.path})`,async load(){if(!c.expand){let s=resolve(process.cwd(),c.path);return existsSync(s)?$(readFileSync(s,"utf8")):{}}let r=c.path,e=process.env.NODE_ENV||"development",f=[`${r}.defaults`,r,`${r}.local`,`${r}.${e}`,`${r}.${e}.local`],a={};for(let s of f){let t=resolve(process.cwd(),s);if(existsSync(t))try{a={...a,...$(readFileSync(t,"utf8"))};}catch{}}return a},loadSync(){if(!c.expand){let s=resolve(process.cwd(),c.path);return existsSync(s)?$(readFileSync(s,"utf8")):{}}let r=c.path,e=process.env.NODE_ENV||"development",f=[`${r}.defaults`,r,`${r}.local`,`${r}.${e}`,`${r}.${e}.local`],a={};for(let s of f){let t=resolve(process.cwd(),s);if(existsSync(t))try{a={...a,...$(readFileSync(t,"utf8"))};}catch{}}return a}}}function _(l){let c={path:l?.path??"package.json",fields:l?.fields??["version","name","config"]};return {name:"package.json",async load(){let r=resolve(process.cwd(),c.path);if(!existsSync(r))return {};try{let e=readFileSync(r,"utf8"),f=JSON.parse(e),a={};for(let s of c.fields){let t=f[s];if(t!==void 0)if(s==="config"&&typeof t=="object"){let n=(o,u)=>{if(o&&typeof o=="object"&&!Array.isArray(o))for(let[p,i]of Object.entries(o)){let d=`${u}_${p.toUpperCase()}`;i&&typeof i=="object"&&!Array.isArray(i)?n(i,d):a[d]=String(i);}};n(t,"CONFIG");}else a[s.toUpperCase()]=String(t);}return a}catch(e){throw new Error(`Failed to read package.json: ${e instanceof Error?e.message:String(e)}`,{cause:e})}},loadSync(){let r=resolve(process.cwd(),c.path);if(!existsSync(r))return {};try{let e=readFileSync(r,"utf8"),f=JSON.parse(e),a={};for(let s of c.fields){let t=f[s];if(t!==void 0)if(s==="config"&&typeof t=="object"){let n=(o,u)=>{if(o&&typeof o=="object"&&!Array.isArray(o))for(let[p,i]of Object.entries(o)){let d=`${u}_${p.toUpperCase()}`;i&&typeof i=="object"&&!Array.isArray(i)?n(i,d):a[d]=String(i);}};n(t,"CONFIG");}else a[s.toUpperCase()]=String(t);}return a}catch(e){throw new Error(`Failed to read package.json: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}}}function C(l,c){return {name:`http(${l})`,async load(){try{let r=new AbortController,e=c?.timeout??5e3,f=setTimeout(()=>r.abort(),e),a=await fetch(l,{...c,signal:r.signal});if(clearTimeout(f),!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);let s=await a.json(),t={},n=(o,u="")=>{if(o&&typeof o=="object"&&!Array.isArray(o))for(let[p,i]of Object.entries(o)){let d=u?`${u}_${p}`:p;i&&typeof i=="object"&&!Array.isArray(i)?n(i,d):t[d.toUpperCase()]=String(i);}};return n(s),t}catch(r){throw r.name==="AbortError"?new Error(`HTTP request timeout after ${c?.timeout??5e3}ms`,{cause:r}):new Error(`Failed to fetch config from ${l}: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}}}function F(l="config.json"){return {name:`json(${l})`,async load(){let c=resolve(process.cwd(),l);if(!existsSync(c))return {};try{let r=readFileSync(c,"utf8"),e=JSON.parse(r),f={},a=(s,t="")=>{if(s&&typeof s=="object"&&!Array.isArray(s))for(let[n,o]of Object.entries(s)){let u=t?`${t}_${n}`:n;o&&typeof o=="object"&&!Array.isArray(o)?a(o,u):f[u.toUpperCase()]=String(o);}};return a(e),f}catch(r){throw new Error(`Failed to parse JSON file ${l}: ${r instanceof Error?r.message:String(r)}`,{cause:r})}},loadSync(){let c=resolve(process.cwd(),l);if(!existsSync(c))return {};try{let r=readFileSync(c,"utf8"),e=JSON.parse(r),f={},a=(s,t="")=>{if(s&&typeof s=="object"&&!Array.isArray(s))for(let[n,o]of Object.entries(s)){let u=t?`${t}_${n}`:n;o&&typeof o=="object"&&!Array.isArray(o)?a(o,u):f[u.toUpperCase()]=String(o);}};return a(e),f}catch(r){throw new Error(`Failed to parse JSON file ${l}: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}}}function N(l="/run/secrets"){return {name:`secrets(${l})`,async load(){let{readdirSync:c,statSync:r}=await import('fs'),e=resolve(process.cwd(),l);if(!existsSync(e))return {};try{let f=c(e),a={};for(let s of f){let t=join(e,s);if(!r(t).isFile())continue;let o=s.toUpperCase().replace(/[.-]/g,"_"),u=readFileSync(t,"utf8").trim();a[o]=u;}return a}catch(f){throw new Error(`Failed to read secrets from ${l}: ${f instanceof Error?f.message:String(f)}`,{cause:f})}},loadSync(){let{readdirSync:c,statSync:r}=a("fs"),e=resolve(process.cwd(),l);if(!existsSync(e))return {};try{let f=c(e),a={};for(let s of f){let t=join(e,s);if(!r(t).isFile())continue;let o=s.toUpperCase().replace(/[.-]/g,"_"),u=readFileSync(t,"utf8").trim();a[o]=u;}return a}catch(f){throw new Error(`Failed to read secrets from ${l}: ${f instanceof Error?f.message:String(f)}`,{cause:f})}}}}function j(l){let c=typeof l=="string"?{path:l}:{path:l?.path??"config.yaml"};return {name:`yaml(${c.path})`,async load(){let r=join(process.cwd(),c.path);if(!existsSync(r))return {};try{let{load:e}=await import('js-yaml'),f=readFileSync(r,"utf8"),a=e(f),s={},t=(n,o="")=>{if(n&&typeof n=="object"&&!Array.isArray(n))for(let[u,p]of Object.entries(n)){let i=o?`${o}_${u}`:u;p&&typeof p=="object"&&!Array.isArray(p)?t(p,i):s[i.toUpperCase()]=String(p);}};return t(a),s}catch(e){throw e.code==="MODULE_NOT_FOUND"||e.message?.includes("Cannot find package")?new Error(`YAML resolver requires 'js-yaml' package. Install it with:
|
|
4
|
+
npm install js-yaml
|
|
5
|
+
# or
|
|
6
|
+
pnpm add js-yaml`,{cause:e}):new Error(`Failed to parse YAML file ${c.path}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}},loadSync(){let r=join(process.cwd(),c.path);if(!existsSync(r))return {};try{let{load:e}=a("js-yaml"),f=readFileSync(r,"utf8"),a$1=e(f),s={},t=(n,o="")=>{if(n&&typeof n=="object"&&!Array.isArray(n))for(let[u,p]of Object.entries(n)){let i=o?`${o}_${u}`:u;p&&typeof p=="object"&&!Array.isArray(p)?t(p,i):s[i.toUpperCase()]=String(p);}};return t(a$1),s}catch(e){throw e.code==="MODULE_NOT_FOUND"||e.message?.includes("Cannot find package")?new Error(`YAML resolver requires 'js-yaml' package. Install it with:
|
|
7
|
+
npm install js-yaml
|
|
8
|
+
# or
|
|
9
|
+
pnpm add js-yaml`,{cause:e}):new Error(`Failed to parse YAML file ${c.path}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}}}function D(l){let c=typeof l=="string"?{path:l}:{path:l?.path??"config.toml"};return {name:`toml(${c.path})`,async load(){let r=resolve(process.cwd(),c.path);if(!existsSync(r))return {};try{let{parse:e}=await import('smol-toml'),f=readFileSync(r,"utf8"),a=e(f),s={},t=(n,o="")=>{if(n&&typeof n=="object"&&!Array.isArray(n))for(let[u,p]of Object.entries(n)){let i=o?`${o}_${u}`:u;p&&typeof p=="object"&&!Array.isArray(p)?t(p,i):s[i.toUpperCase()]=String(p);}};return t(a),s}catch(e){throw e.code==="MODULE_NOT_FOUND"||e.message?.includes("Cannot find package")?new Error(`TOML resolver requires 'smol-toml' package. Install it with:
|
|
10
|
+
npm install smol-toml
|
|
11
|
+
# or
|
|
12
|
+
pnpm add smol-toml`,{cause:e}):new Error(`Failed to parse TOML file ${c.path}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}},loadSync(){let r=resolve(process.cwd(),c.path);if(!existsSync(r))return {};try{let{parse:e}=a("smol-toml"),f=readFileSync(r,"utf8"),a$1=e(f),s={},t=(n,o="")=>{if(n&&typeof n=="object"&&!Array.isArray(n))for(let[u,p]of Object.entries(n)){let i=o?`${o}_${u}`:u;p&&typeof p=="object"&&!Array.isArray(p)?t(p,i):s[i.toUpperCase()]=String(p);}};return t(a$1),s}catch(e){throw e.code==="MODULE_NOT_FOUND"||e.message?.includes("Cannot find package")?new Error(`TOML resolver requires 'smol-toml' package. Install it with:
|
|
13
|
+
npm install smol-toml
|
|
14
|
+
# or
|
|
15
|
+
pnpm add smol-toml`,{cause:e}):new Error(`Failed to parse TOML file ${c.path}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}}}function M(l,c={}){let r=c.format??"env",e=c.timeout??5e3,f=t=>{let n={},o=t.split(`
|
|
16
|
+
`);for(let u of o){let p=u.trim();if(!p||p.startsWith("#"))continue;let i=p.indexOf("=");if(i<=0)continue;let d=p.slice(0,i).trim(),w=p.slice(i+1).trim();d&&(n[d]=w);}return n},a=t=>{let n=t.trim();if(!n)return {};let o;try{o=JSON.parse(n);}catch(i){throw new Error(`Failed to parse JSON from exec(${l}): ${i instanceof Error?i.message:String(i)}`,{cause:i})}let u={},p=(i,d="")=>{if(i&&typeof i=="object"&&!Array.isArray(i))for(let[w,h]of Object.entries(i)){let O=d?`${d}_${w}`:w;h&&typeof h=="object"&&!Array.isArray(h)?p(h,O):u[O.toUpperCase()]=String(h);}};return p(o),u},s=t=>r==="json"?a(t):f(t);return {name:`exec(${l})`,async load(){try{let t=await new Promise((n,o)=>{exec(l,{timeout:e},(u,p,i)=>{if(u){let d=u instanceof Error?u.message:String(u),w=typeof i=="string"?i.trim():"";o(new Error(`Failed to execute command "${l}": ${d}${w?`
|
|
17
|
+
${w}`:""}`,{cause:u}));return}n(String(p??""));});});return s(t)}catch(t){throw t.code==="ETIMEDOUT"||t.message?.includes("ETIMEDOUT")?new Error(`Command "${l}" timed out after ${e}ms`,{cause:t}):t}},loadSync(){try{let t=execSync(l,{timeout:e,encoding:"utf8"});return s(t)}catch(t){if(t.code==="ETIMEDOUT"||t.message?.includes("ETIMEDOUT"))throw new Error(`Command "${l}" timed out after ${e}ms`,{cause:t});let n=t instanceof Error?t.message:String(t);throw new Error(`Failed to execute command "${l}" synchronously: ${n}`,{cause:t})}}}}export{U as a,_ as b,C as c,F as d,N as e,j as f,D as g,M as h};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
'use strict';var chunkD6WM53FN_cjs=require('./chunk-D6WM53FN.cjs'),fs=require('fs'),path=require('path'),child_process=require('child_process');var $=l=>{let c={},r=l.split(`
|
|
2
|
+
`);for(let e=0;e<r.length;e++){let f=r[e]?.trim()??"";if(!f||f[0]==="#")continue;let a=f.indexOf("=");if(a<=0)continue;let s=f.slice(0,a).trim();if(!/^[A-Z_][A-Z0-9_]*$/i.test(s))continue;let t=f.slice(a+1).trim();if(t.length>=2){let n=t[0];(n==='"'||n==="'")&&t[t.length-1]===n&&(t=t.slice(1,-1),n==='"'&&(t=t.replace(/\\n/g,`
|
|
3
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\\/g,"\\").replace(/\\"/g,'"').replace(/\\'/g,"'")));}else {let n=t.indexOf("#");n>=0&&(t=t.slice(0,n).trim());}c[s]=t;}return c};function U(l){let c=typeof l=="string"?{path:l,expand:false}:{path:l?.path??".env",expand:l?.expand??false};return {name:c.expand?`dotenv-expand(${c.path})`:`dotenv(${c.path})`,async load(){if(!c.expand){let s=path.resolve(process.cwd(),c.path);return fs.existsSync(s)?$(fs.readFileSync(s,"utf8")):{}}let r=c.path,e=process.env.NODE_ENV||"development",f=[`${r}.defaults`,r,`${r}.local`,`${r}.${e}`,`${r}.${e}.local`],a={};for(let s of f){let t=path.resolve(process.cwd(),s);if(fs.existsSync(t))try{a={...a,...$(fs.readFileSync(t,"utf8"))};}catch{}}return a},loadSync(){if(!c.expand){let s=path.resolve(process.cwd(),c.path);return fs.existsSync(s)?$(fs.readFileSync(s,"utf8")):{}}let r=c.path,e=process.env.NODE_ENV||"development",f=[`${r}.defaults`,r,`${r}.local`,`${r}.${e}`,`${r}.${e}.local`],a={};for(let s of f){let t=path.resolve(process.cwd(),s);if(fs.existsSync(t))try{a={...a,...$(fs.readFileSync(t,"utf8"))};}catch{}}return a}}}function _(l){let c={path:l?.path??"package.json",fields:l?.fields??["version","name","config"]};return {name:"package.json",async load(){let r=path.resolve(process.cwd(),c.path);if(!fs.existsSync(r))return {};try{let e=fs.readFileSync(r,"utf8"),f=JSON.parse(e),a={};for(let s of c.fields){let t=f[s];if(t!==void 0)if(s==="config"&&typeof t=="object"){let n=(o,u)=>{if(o&&typeof o=="object"&&!Array.isArray(o))for(let[p,i]of Object.entries(o)){let d=`${u}_${p.toUpperCase()}`;i&&typeof i=="object"&&!Array.isArray(i)?n(i,d):a[d]=String(i);}};n(t,"CONFIG");}else a[s.toUpperCase()]=String(t);}return a}catch(e){throw new Error(`Failed to read package.json: ${e instanceof Error?e.message:String(e)}`,{cause:e})}},loadSync(){let r=path.resolve(process.cwd(),c.path);if(!fs.existsSync(r))return {};try{let e=fs.readFileSync(r,"utf8"),f=JSON.parse(e),a={};for(let s of c.fields){let t=f[s];if(t!==void 0)if(s==="config"&&typeof t=="object"){let n=(o,u)=>{if(o&&typeof o=="object"&&!Array.isArray(o))for(let[p,i]of Object.entries(o)){let d=`${u}_${p.toUpperCase()}`;i&&typeof i=="object"&&!Array.isArray(i)?n(i,d):a[d]=String(i);}};n(t,"CONFIG");}else a[s.toUpperCase()]=String(t);}return a}catch(e){throw new Error(`Failed to read package.json: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}}}function C(l,c){return {name:`http(${l})`,async load(){try{let r=new AbortController,e=c?.timeout??5e3,f=setTimeout(()=>r.abort(),e),a=await fetch(l,{...c,signal:r.signal});if(clearTimeout(f),!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);let s=await a.json(),t={},n=(o,u="")=>{if(o&&typeof o=="object"&&!Array.isArray(o))for(let[p,i]of Object.entries(o)){let d=u?`${u}_${p}`:p;i&&typeof i=="object"&&!Array.isArray(i)?n(i,d):t[d.toUpperCase()]=String(i);}};return n(s),t}catch(r){throw r.name==="AbortError"?new Error(`HTTP request timeout after ${c?.timeout??5e3}ms`,{cause:r}):new Error(`Failed to fetch config from ${l}: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}}}function F(l="config.json"){return {name:`json(${l})`,async load(){let c=path.resolve(process.cwd(),l);if(!fs.existsSync(c))return {};try{let r=fs.readFileSync(c,"utf8"),e=JSON.parse(r),f={},a=(s,t="")=>{if(s&&typeof s=="object"&&!Array.isArray(s))for(let[n,o]of Object.entries(s)){let u=t?`${t}_${n}`:n;o&&typeof o=="object"&&!Array.isArray(o)?a(o,u):f[u.toUpperCase()]=String(o);}};return a(e),f}catch(r){throw new Error(`Failed to parse JSON file ${l}: ${r instanceof Error?r.message:String(r)}`,{cause:r})}},loadSync(){let c=path.resolve(process.cwd(),l);if(!fs.existsSync(c))return {};try{let r=fs.readFileSync(c,"utf8"),e=JSON.parse(r),f={},a=(s,t="")=>{if(s&&typeof s=="object"&&!Array.isArray(s))for(let[n,o]of Object.entries(s)){let u=t?`${t}_${n}`:n;o&&typeof o=="object"&&!Array.isArray(o)?a(o,u):f[u.toUpperCase()]=String(o);}};return a(e),f}catch(r){throw new Error(`Failed to parse JSON file ${l}: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}}}function N(l="/run/secrets"){return {name:`secrets(${l})`,async load(){let{readdirSync:c,statSync:r}=await import('fs'),e=path.resolve(process.cwd(),l);if(!fs.existsSync(e))return {};try{let f=c(e),a={};for(let s of f){let t=path.join(e,s);if(!r(t).isFile())continue;let o=s.toUpperCase().replace(/[.-]/g,"_"),u=fs.readFileSync(t,"utf8").trim();a[o]=u;}return a}catch(f){throw new Error(`Failed to read secrets from ${l}: ${f instanceof Error?f.message:String(f)}`,{cause:f})}},loadSync(){let{readdirSync:c,statSync:r}=chunkD6WM53FN_cjs.a("fs"),e=path.resolve(process.cwd(),l);if(!fs.existsSync(e))return {};try{let f=c(e),a={};for(let s of f){let t=path.join(e,s);if(!r(t).isFile())continue;let o=s.toUpperCase().replace(/[.-]/g,"_"),u=fs.readFileSync(t,"utf8").trim();a[o]=u;}return a}catch(f){throw new Error(`Failed to read secrets from ${l}: ${f instanceof Error?f.message:String(f)}`,{cause:f})}}}}function j(l){let c=typeof l=="string"?{path:l}:{path:l?.path??"config.yaml"};return {name:`yaml(${c.path})`,async load(){let r=path.join(process.cwd(),c.path);if(!fs.existsSync(r))return {};try{let{load:e}=await import('js-yaml'),f=fs.readFileSync(r,"utf8"),a=e(f),s={},t=(n,o="")=>{if(n&&typeof n=="object"&&!Array.isArray(n))for(let[u,p]of Object.entries(n)){let i=o?`${o}_${u}`:u;p&&typeof p=="object"&&!Array.isArray(p)?t(p,i):s[i.toUpperCase()]=String(p);}};return t(a),s}catch(e){throw e.code==="MODULE_NOT_FOUND"||e.message?.includes("Cannot find package")?new Error(`YAML resolver requires 'js-yaml' package. Install it with:
|
|
4
|
+
npm install js-yaml
|
|
5
|
+
# or
|
|
6
|
+
pnpm add js-yaml`,{cause:e}):new Error(`Failed to parse YAML file ${c.path}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}},loadSync(){let r=path.join(process.cwd(),c.path);if(!fs.existsSync(r))return {};try{let{load:e}=chunkD6WM53FN_cjs.a("js-yaml"),f=fs.readFileSync(r,"utf8"),a=e(f),s={},t=(n,o="")=>{if(n&&typeof n=="object"&&!Array.isArray(n))for(let[u,p]of Object.entries(n)){let i=o?`${o}_${u}`:u;p&&typeof p=="object"&&!Array.isArray(p)?t(p,i):s[i.toUpperCase()]=String(p);}};return t(a),s}catch(e){throw e.code==="MODULE_NOT_FOUND"||e.message?.includes("Cannot find package")?new Error(`YAML resolver requires 'js-yaml' package. Install it with:
|
|
7
|
+
npm install js-yaml
|
|
8
|
+
# or
|
|
9
|
+
pnpm add js-yaml`,{cause:e}):new Error(`Failed to parse YAML file ${c.path}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}}}function D(l){let c=typeof l=="string"?{path:l}:{path:l?.path??"config.toml"};return {name:`toml(${c.path})`,async load(){let r=path.resolve(process.cwd(),c.path);if(!fs.existsSync(r))return {};try{let{parse:e}=await import('smol-toml'),f=fs.readFileSync(r,"utf8"),a=e(f),s={},t=(n,o="")=>{if(n&&typeof n=="object"&&!Array.isArray(n))for(let[u,p]of Object.entries(n)){let i=o?`${o}_${u}`:u;p&&typeof p=="object"&&!Array.isArray(p)?t(p,i):s[i.toUpperCase()]=String(p);}};return t(a),s}catch(e){throw e.code==="MODULE_NOT_FOUND"||e.message?.includes("Cannot find package")?new Error(`TOML resolver requires 'smol-toml' package. Install it with:
|
|
10
|
+
npm install smol-toml
|
|
11
|
+
# or
|
|
12
|
+
pnpm add smol-toml`,{cause:e}):new Error(`Failed to parse TOML file ${c.path}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}},loadSync(){let r=path.resolve(process.cwd(),c.path);if(!fs.existsSync(r))return {};try{let{parse:e}=chunkD6WM53FN_cjs.a("smol-toml"),f=fs.readFileSync(r,"utf8"),a=e(f),s={},t=(n,o="")=>{if(n&&typeof n=="object"&&!Array.isArray(n))for(let[u,p]of Object.entries(n)){let i=o?`${o}_${u}`:u;p&&typeof p=="object"&&!Array.isArray(p)?t(p,i):s[i.toUpperCase()]=String(p);}};return t(a),s}catch(e){throw e.code==="MODULE_NOT_FOUND"||e.message?.includes("Cannot find package")?new Error(`TOML resolver requires 'smol-toml' package. Install it with:
|
|
13
|
+
npm install smol-toml
|
|
14
|
+
# or
|
|
15
|
+
pnpm add smol-toml`,{cause:e}):new Error(`Failed to parse TOML file ${c.path}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}}}function M(l,c={}){let r=c.format??"env",e=c.timeout??5e3,f=t=>{let n={},o=t.split(`
|
|
16
|
+
`);for(let u of o){let p=u.trim();if(!p||p.startsWith("#"))continue;let i=p.indexOf("=");if(i<=0)continue;let d=p.slice(0,i).trim(),w=p.slice(i+1).trim();d&&(n[d]=w);}return n},a=t=>{let n=t.trim();if(!n)return {};let o;try{o=JSON.parse(n);}catch(i){throw new Error(`Failed to parse JSON from exec(${l}): ${i instanceof Error?i.message:String(i)}`,{cause:i})}let u={},p=(i,d="")=>{if(i&&typeof i=="object"&&!Array.isArray(i))for(let[w,h]of Object.entries(i)){let O=d?`${d}_${w}`:w;h&&typeof h=="object"&&!Array.isArray(h)?p(h,O):u[O.toUpperCase()]=String(h);}};return p(o),u},s=t=>r==="json"?a(t):f(t);return {name:`exec(${l})`,async load(){try{let t=await new Promise((n,o)=>{child_process.exec(l,{timeout:e},(u,p,i)=>{if(u){let d=u instanceof Error?u.message:String(u),w=typeof i=="string"?i.trim():"";o(new Error(`Failed to execute command "${l}": ${d}${w?`
|
|
17
|
+
${w}`:""}`,{cause:u}));return}n(String(p??""));});});return s(t)}catch(t){throw t.code==="ETIMEDOUT"||t.message?.includes("ETIMEDOUT")?new Error(`Command "${l}" timed out after ${e}ms`,{cause:t}):t}},loadSync(){try{let t=child_process.execSync(l,{timeout:e,encoding:"utf8"});return s(t)}catch(t){if(t.code==="ETIMEDOUT"||t.message?.includes("ETIMEDOUT"))throw new Error(`Command "${l}" timed out after ${e}ms`,{cause:t});let n=t instanceof Error?t.message:String(t);throw new Error(`Failed to execute command "${l}" synchronously: ${n}`,{cause:t})}}}}exports.a=U;exports.b=_;exports.c=C;exports.d=F;exports.e=N;exports.f=j;exports.g=D;exports.h=M;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk2IQQVAXA_cjs=require('./chunk-2IQQVAXA.cjs'),chunk4QOKRJ3F_cjs=require('./chunk-4QOKRJ3F.cjs');function v(){return [chunk4QOKRJ3F_cjs.a()]}function h(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&("resolvers"in e||"schema"in e||"options"in e)}function S(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("resolvers"in e)&&!("schema"in e)&&!("options"in e)}function w(e,t){let o,l,i;if(h(e)){let s=e;if(s.schema)o=s.schema;else if(s.resolvers&&s.resolvers.length>0){o={};for(let[,n]of s.resolvers)Object.assign(o,n);}else throw new Error('resolve() config object must have either a "schema" property or "resolvers" array');l=s.resolvers?s.resolvers.map(([n])=>n):v(),i=s.options;}else if(S(e))o=e,l=v(),i=t;else throw new Error('resolve() expects either a schema object or a config object with "schema" or "resolvers" property');for(let[s,n]of Object.entries(o))if(n&&typeof n=="object"&&"~standard"in n)throw new Error(`\u274C resolve() cannot be used with async validators.
|
|
2
2
|
Variable '${s}' uses a Standard Schema validator (Zod, Valibot, etc.)
|
|
3
3
|
\u{1F4A1} Use resolveAsync() instead, or use shorthand syntax for sync validation.`);for(let s of l)if(!s.loadSync)throw new Error(`\u274C Resolver '${s.name}' does not support synchronous loading.
|
|
4
4
|
All resolvers passed to resolve() must have a loadSync() method.
|
|
5
|
-
\u{1F4A1} Use resolveAsync() for async resolvers, or use a sync-compatible resolver.`);let a=(process.env.NODE_ENV||"").toLowerCase()==="production",r=i?.policies??{},p={interpolate:true,strict:true,enableAudit:a,policies:r,...i},c=
|
|
5
|
+
\u{1F4A1} Use resolveAsync() for async resolvers, or use a sync-compatible resolver.`);let a=(process.env.NODE_ENV||"").toLowerCase()==="production",r=i?.policies??{},p={interpolate:true,strict:true,enableAudit:a,policies:r,...i},c=chunk2IQQVAXA_cjs.a(o);return chunk2IQQVAXA_cjs.c(c,l,p)}async function P(e){let t;if(e.schema)t=e.schema;else if(e.resolvers&&e.resolvers.length>0){t={};for(let[,c]of e.resolvers)Object.assign(t,c);}else throw new Error('resolveAsync() config object must have either a "schema" property or "resolvers" array');let o=e.resolvers?e.resolvers.map(([c])=>c):v(),l=(process.env.NODE_ENV||"").toLowerCase()==="production",i=e.options?.policies??{},a={interpolate:true,strict:true,enableAudit:l,policies:i,...e.options},r=chunk2IQQVAXA_cjs.a(t);return await chunk2IQQVAXA_cjs.b(r,o,a)}function g(e,t){let o,l,i;try{if(h(e)){let s=e;if(s.schema)o=s.schema;else if(s.resolvers&&s.resolvers.length>0){o={};for(let[,n]of s.resolvers)Object.assign(o,n);}else return {success:!1,error:'safeResolve() config object must have either a "schema" property or "resolvers" array'};l=s.resolvers?s.resolvers.map(([n])=>n):v(),i=s.options;}else if(S(e))o=e,l=v(),i=t;else return {success:!1,error:'safeResolve() expects either a schema object or a config object with "schema" or "resolvers" property'};for(let[s,n]of Object.entries(o))if(n&&typeof n=="object"&&"~standard"in n)return {success:!1,error:`\u274C safeResolve() cannot be used with async validators.
|
|
6
6
|
Variable '${s}' uses a Standard Schema validator (Zod, Valibot, etc.)
|
|
7
7
|
\u{1F4A1} Use safeResolveAsync() instead, or use shorthand syntax for sync validation.`};for(let s of l)if(!s.loadSync)return {success:!1,error:`\u274C Resolver '${s.name}' does not support synchronous loading.
|
|
8
8
|
All resolvers passed to safeResolve() must have a loadSync() method.
|
|
9
|
-
\u{1F4A1} Use safeResolveAsync() for async resolvers.`};let a=(process.env.NODE_ENV||"").toLowerCase()==="production",r=i?.policies??{},p={interpolate:!0,strict:!0,enableAudit:a,policies:r,...i},c=
|
|
9
|
+
\u{1F4A1} Use safeResolveAsync() for async resolvers.`};let a=(process.env.NODE_ENV||"").toLowerCase()==="production",r=i?.policies??{},p={interpolate:!0,strict:!0,enableAudit:a,policies:r,...i},c=chunk2IQQVAXA_cjs.a(o);return {success:!0,data:chunk2IQQVAXA_cjs.c(c,l,p)}}catch(a){return {success:false,error:a instanceof Error?a.message:String(a)}}}async function k(e){let t;if(e.schema)t=e.schema;else if(e.resolvers&&e.resolvers.length>0){t={};for(let[,r]of e.resolvers)Object.assign(t,r);}else return {success:false,error:'safeResolveAsync() config object must have either a "schema" property or "resolvers" array'};let o=e.resolvers?e.resolvers.map(([r])=>r):v(),l=(process.env.NODE_ENV||"").toLowerCase()==="production",i=e.options?.policies??{},a={interpolate:true,strict:true,enableAudit:l,policies:i,...e.options};try{let r=chunk2IQQVAXA_cjs.a(t);return {success:!0,data:await chunk2IQQVAXA_cjs.b(r,o,a)}}catch(r){return {success:false,error:r instanceof Error?r.message:String(r)}}}exports.a=w;exports.b=P;exports.c=g;exports.d=k;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import {writeFileSync}from'fs';var g=`// Auto-generated by node-env-resolver typegen. DO NOT EDIT.
|
|
2
|
+
// Regenerate with: npx node-env-resolver typegen
|
|
3
|
+
`;function y(t){if(!t?.type)return "string";switch(t.type){case "string":case "url":case "email":case "json":case "custom":return "string";case "number":case "port":return "number";case "boolean":return "boolean";case "string[]":return "string[]";case "number[]":return "number[]";case "oneOf":{let n=t.enumValues;return !n||n.length===0?"string":n.map(r=>JSON.stringify(String(r))).join(" | ")}default:return "string"}}function m(t){if(!t?.type)return "string";switch(t.type){case "boolean":return "'true' | 'false'";case "oneOf":{let n=t.enumValues;return !n||n.length===0?"string":n.map(r=>JSON.stringify(String(r))).join(" | ")}default:return "string"}}function h(t){let n=[];for(let[r,i]of Object.entries(t)){let a="string",p="string",e=false,s,o=false;if(typeof i=="function"){let u=i,c=u.__meta;a=y(c),p=m(c),e=u.optional===true,s=c?.description,o=c?.sensitive===true;}else if(typeof i=="number")a="number";else if(typeof i=="boolean")a="boolean",p="'true' | 'false'";else if(Array.isArray(i)){let u=i;if(u.length>0){let c=u.map(l=>JSON.stringify(String(l))).join(" | ");a=c,p=c;}e=i.__optional===true;}n.push({key:r,tsType:a,stringType:p,isOptional:e,description:s,isSensitive:o});}return n}function d(t){let n=[];return t.description&&n.push(t.description),t.isSensitive&&n.push("@sensitive"),n.length===0?"":n.length===1?` /** ${n[0]} */
|
|
4
|
+
`:` /**
|
|
5
|
+
${n.map(r=>` * ${r}`).join(`
|
|
6
|
+
`)}
|
|
7
|
+
*/
|
|
8
|
+
`}function v(t,n={}){let{augmentProcessEnv:r=true,augmentImportMetaEnv:i=true,banner:a=g}=n,p=h(t),e=[];a&&e.push(a),e.push("export interface EnvSchema {");for(let s of p){let o=d(s);o&&e.push(o.trimEnd());let u=s.isOptional?"?":"";e.push(` ${s.key}${u}: ${s.tsType};`);}if(e.push("}"),e.push(""),r){e.push("declare global {"),e.push(" namespace NodeJS {"),e.push(" interface ProcessEnv {");for(let s of p){let o=s.isOptional?"?":"";e.push(` ${s.key}${o}: ${s.stringType};`);}e.push(" }"),e.push(" }"),e.push("}"),e.push("");}if(i){e.push("interface ImportMetaEnv {");for(let s of p){let o=s.isOptional?"?":"";e.push(` ${s.key}${o}: ${s.stringType};`);}e.push("}"),e.push(""),e.push("interface ImportMeta {"),e.push(" readonly env: ImportMetaEnv;"),e.push("}"),e.push("");}return e.join(`
|
|
9
|
+
`)}function b(t,n,r){let i=v(t,r);writeFileSync(n,i,"utf8");}export{v as a,b};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import {a,b}from'./chunk-6EWR3WHU.js';import {d,c}from'./chunk-46CBATKM.js';import {join,resolve}from'path';import {readFileSync}from'fs';function L(i,u){try{let t=resolve(process.cwd(),i);return {valid:!0,value:readFileSync(t,"utf8").trim()}}catch(t){return {valid:false,error:`Failed to read file${u?` for ${u}`:""}: ${t instanceof Error?t.message:String(t)}`}}}var E=b,h=b,T=a;function H(i){let u={};for(let[t,s]of Object.entries(i))if(typeof s=="function"){let a=s,r=a.__isFileValidator===true,f=a.__meta;u[t]={type:r?"file":"custom",validator:s,...a.default!==void 0&&{default:a.default},...a.optional!==void 0&&{optional:a.optional},...a.secretsDir!==void 0&&{secretsDir:a.secretsDir},...f?.sensitive!==void 0&&{sensitive:f.sensitive},...f?.description!==void 0&&{description:f.description}};}else if(typeof s=="string")u[t]={type:"string",default:s,validator:a=>{let r=u[t];if(a===""&&!r.allowEmpty)throw new Error("String cannot be empty");return a}};else if(typeof s=="number")u[t]={type:"number",default:s,validator:a=>{let r=Number(a);if(isNaN(r))throw new Error(`Invalid number: "${a}"`);return r}};else if(typeof s=="boolean")u[t]={type:"boolean",default:s,validator:a=>{let r=a.toLowerCase();if(["true","1","yes","on"].includes(r))return true;if(["false","0","no","off",""].includes(r))return false;throw new Error(`Invalid boolean: "${a}"`)}};else if(Array.isArray(s)){let a=s.map(String),r=s.__optional===true;u[t]={type:"string",enum:a,optional:r,validator:(f,n)=>{if(!a.includes(f)){let o=n||t;throw new Error(`${o} must be one of: ${a.join(", ")}`)}return f}};}else u[t]=s;return u}function x(i,u){return i.replace(/\$\{([^}]+)\}/g,(t,s)=>u[s]||t)}async function q(i,u,t,s="last",a){let r={},f={};if(s==="last"){let n=await Promise.allSettled(i.map(async o=>({resolver:o,env:o.load?await o.load():{}})));for(let o of n){if(o.status==="rejected"){let d=o.reason;if(E({type:"resolver_error",timestamp:Date.now(),source:"unknown",error:d instanceof Error?d.message:String(d)}),t)throw new Error(`Resolver failed: ${d instanceof Error?d.message:d}`);continue}let{resolver:m,env:c}=o.value;for(let[d,b]of Object.entries(c))b!==void 0&&(r[d]=b,f[d]={source:m.name||"unknown",timestamp:Date.now(),...m.metadata?.cached!==void 0&&{cached:!!m.metadata.cached}});}}else for(let n of i)try{let o=n.load?await n.load():{};for(let[m,c]of Object.entries(o))if(c!==void 0){if(r[m]!==void 0)continue;r[m]=c,f[m]={source:n.name||"unknown",timestamp:Date.now(),...n.metadata?.cached!==void 0&&{cached:!!n.metadata.cached}};}if(a&&a.size>0&&Array.from(a).every(c=>r[c]!==void 0))break}catch(o){if(E({type:"resolver_error",timestamp:Date.now(),source:n.name,error:o instanceof Error?o.message:String(o)}),t)throw new Error(`Resolver ${n.name} failed: ${o instanceof Error?o.message:o}`,{cause:o})}if(u)for(let[n,o]of Object.entries(r))r[n]=x(o,r);return {mergedEnv:r,provenance:f}}function W(i,u,t,s="last",a){let r={},f={};for(let n of i)try{if(!n.loadSync){if(t)throw new Error(`Resolver ${n.name} has no loadSync() method`);continue}let o=n.loadSync();for(let[m,c]of Object.entries(o))if(c!==void 0){if(s==="first"&&r[m]!==void 0)continue;r[m]=c,f[m]={source:n.name||"unknown",timestamp:Date.now(),...n.metadata?.cached!==void 0&&{cached:!!n.metadata.cached}};}if(s==="first"&&a&&a.size>0&&Array.from(a).every(c=>r[c]!==void 0))break}catch(o){if(h({type:"resolver_error",timestamp:Date.now(),source:n.name,error:o instanceof Error?o.message:String(o)}),t)throw new Error(`Resolver ${n.name} failed: ${o instanceof Error?o.message:o}`,{cause:o})}if(u)for(let[n,o]of Object.entries(r))r[n]=x(o,r);return {mergedEnv:r,provenance:f}}function z(i,u,t,s){if(!s)return null;if((process.env.NODE_ENV||"").toLowerCase()==="production"&&t&&t.source.startsWith("dotenv(")){let f=s.allowDotenvInProduction;return f===true?null:Array.isArray(f)?f.includes(i)?null:`${i} cannot be sourced from .env files in production. Use process.env or cloud resolvers. To allow: policies.allowDotenvInProduction: ['${i}'] or set to true for all.`:`${i} 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`}let r=s.enforceAllowedSources?.[i];return r&&t&&!r.includes(t.source)?`${i} must be sourced from one of: ${r.join(", ")} (actual: ${t.source})`:null}function M(i){let u=[],t=/^[A-Za-z_][A-Za-z0-9_]*$/;for(let s of Object.keys(i))t.test(s)||u.push(`Invalid environment variable name: "${s}". Environment variable names must contain only letters, numbers, and underscores, and cannot start with a number.`);return u}function B(i,u){let t={};for(let[s,a]of Object.entries(i)){if(!s.includes(u)){t[s]=a;continue}let r=s.split(u),f=t;for(let o=0;o<r.length-1;o++){let m=r[o].toLowerCase();m in f||(f[m]={}),f=f[m];}let n=r[r.length-1].toLowerCase();f[n]=a;}for(let s of Object.keys(i))delete i[s];return Object.assign(i,t),i}async function J(i,u,t){let s=(process.env.NODE_ENV||"").toLowerCase()==="production",{interpolate:a=false,strict:r=true,policies:f,enableAudit:n=s,priority:o="last",secretsDir:m}=t,c$1={},d$1;n&&(d$1=T(c$1));let b=M(i);if(b.length>0)throw n&&E({type:"validation_failure",timestamp:Date.now(),error:`Invalid environment variable names: ${b.join(", ")}`,sessionId:d$1}),new Error(`Environment validation failed:
|
|
2
|
+
${b.map(e=>` - ${e}`).join(`
|
|
3
|
+
`)}`);let O=new Set(Object.keys(i)),{mergedEnv:_,provenance:y}=await q(u,a,r,o,O),g=[];for(let[e,w]of Object.entries(i)){let v=w,D=_[e],S=z(e,v,y[e],f);if(S){g.push(S),n&&E({type:"policy_violation",timestamp:Date.now(),key:e,source:y[e]?.source??"unknown",error:S,sessionId:d$1});continue}try{let l;if(D===void 0){let p=v.secretsDir??m;if(v.type==="file"&&p){let j=e.toLowerCase().replace(/_/g,"-"),P=join(p,j),$=L(P,e);$.valid?(l={success:!0,value:$.value},y[e]={source:`secretsDir(${p})`,timestamp:Date.now()}):l={success:!1,error:$.error??`Failed to read secret for ${e}`};}else v.default!==void 0?l={success:!0,value:v.default}:v.optional?l={success:!0,value:void 0}:l={success:!1,error:`Missing required environment variable: ${e}`};}else if(v.validator)try{l={success:!0,value:v.validator(D,e)};}catch(p){l={success:!1,error:p instanceof Error?p.message:`Validation failed for ${e}`};}else l={success:!0,value:D};l.success?(c$1[e]=l.value,n&&E({type:"env_loaded",timestamp:Date.now(),key:e,source:y[e]?.source??"unknown",metadata:{cached:y[e]?.cached},sessionId:d$1})):(g.push(l.error),n&&E({type:"validation_failure",timestamp:Date.now(),key:e,error:l.error,sessionId:d$1}));}catch(l){let p=l instanceof Error?l.message:String(l);g.push(`${e}: ${p}`),n&&E({type:"validation_failure",timestamp:Date.now(),key:e,error:p,sessionId:d$1});}}if(g.length>0)throw n&&E({type:"validation_failure",timestamp:Date.now(),error:`${g.length} validation error(s)`,metadata:{errorCount:g.length},sessionId:d$1}),new Error(`Environment validation failed:
|
|
4
|
+
${g.map(e=>` - ${e}`).join(`
|
|
5
|
+
`)}`);n&&E({type:"validation_success",timestamp:Date.now(),metadata:{variableCount:Object.keys(i).length},sessionId:d$1});let R=new Set,k=new Map;for(let[e,w]of Object.entries(i))if(w.sensitive){R.add(e);let v=c$1[e];typeof v=="string"&&v.length>0&&k.set(e,v);}if(t.nestedDelimiter){B(c$1,t.nestedDelimiter);for(let[e,w]of k.entries())e in c$1||Object.defineProperty(c$1,e,{value:w,enumerable:false,configurable:false});}return Object.defineProperty(c$1,d,{value:R,enumerable:false,configurable:false}),Object.defineProperty(c$1,c,{value:y,enumerable:false,configurable:false}),c$1}function Q(i,u,t){let s=(process.env.NODE_ENV||"").toLowerCase()==="production",{interpolate:a=false,strict:r=true,policies:f,enableAudit:n=s,priority:o="last",secretsDir:m}=t,c$1={},d$1;n&&(d$1=T(c$1));let b=M(i);if(b.length>0)throw n&&h({type:"validation_failure",timestamp:Date.now(),error:`Invalid environment variable names: ${b.join(", ")}`,sessionId:d$1}),new Error(`Environment validation failed:
|
|
6
|
+
${b.map(e=>` - ${e}`).join(`
|
|
7
|
+
`)}`);let O=new Set(Object.keys(i)),{mergedEnv:_,provenance:y}=W(u,a,r,o,O),g=[];for(let[e,w]of Object.entries(i)){let v=w,D=_[e],S=z(e,v,y[e],f);if(S){g.push(S),n&&h({type:"policy_violation",timestamp:Date.now(),key:e,source:y[e]?.source??"unknown",error:S,sessionId:d$1});continue}try{let l;if(D===void 0){let p=v.secretsDir??m;if(v.type==="file"&&p){let j=e.toLowerCase().replace(/_/g,"-"),P=join(p,j),$=L(P,e);$.valid?(l={success:!0,value:$.value},y[e]={source:`secretsDir(${p})`,timestamp:Date.now()}):l={success:!1,error:$.error??`Failed to read secret for ${e}`};}else v.default!==void 0?l={success:!0,value:v.default}:v.optional?l={success:!0,value:void 0}:l={success:!1,error:`Missing required environment variable: ${e}`};}else if(v.validator)try{l={success:!0,value:v.validator(D,e)};}catch(p){l={success:!1,error:p instanceof Error?p.message:`Validation failed for ${e}`};}else l={success:!0,value:D};l.success?(c$1[e]=l.value,n&&h({type:"env_loaded",timestamp:Date.now(),key:e,source:y[e]?.source??"unknown",metadata:{cached:y[e]?.cached},sessionId:d$1})):(g.push(l.error),n&&h({type:"validation_failure",timestamp:Date.now(),key:e,error:l.error,sessionId:d$1}));}catch(l){let p=l instanceof Error?l.message:String(l);g.push(`${e}: ${p}`),n&&h({type:"validation_failure",timestamp:Date.now(),key:e,error:p,sessionId:d$1});}}if(g.length>0)throw n&&h({type:"validation_failure",timestamp:Date.now(),error:`${g.length} validation error(s)`,metadata:{errorCount:g.length},sessionId:d$1}),new Error(`Environment validation failed:
|
|
8
|
+
${g.map(e=>` - ${e}`).join(`
|
|
9
|
+
`)}`);n&&h({type:"validation_success",timestamp:Date.now(),metadata:{variableCount:Object.keys(i).length},sessionId:d$1});let R=new Set,k=new Map;for(let[e,w]of Object.entries(i))if(w.sensitive){R.add(e);let v=c$1[e];typeof v=="string"&&v.length>0&&k.set(e,v);}if(t.nestedDelimiter){B(c$1,t.nestedDelimiter);for(let[e,w]of k.entries())e in c$1||Object.defineProperty(c$1,e,{value:w,enumerable:false,configurable:false});}return Object.defineProperty(c$1,d,{value:R,enumerable:false,configurable:false}),Object.defineProperty(c$1,c,{value:y,enumerable:false,configurable:false}),c$1}export{H as a,J as b,Q as c};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
'use strict';var fs=require('fs');var g=`// Auto-generated by node-env-resolver typegen. DO NOT EDIT.
|
|
2
|
+
// Regenerate with: npx node-env-resolver typegen
|
|
3
|
+
`;function y(t){if(!t?.type)return "string";switch(t.type){case "string":case "url":case "email":case "json":case "custom":return "string";case "number":case "port":return "number";case "boolean":return "boolean";case "string[]":return "string[]";case "number[]":return "number[]";case "oneOf":{let n=t.enumValues;return !n||n.length===0?"string":n.map(r=>JSON.stringify(String(r))).join(" | ")}default:return "string"}}function m(t){if(!t?.type)return "string";switch(t.type){case "boolean":return "'true' | 'false'";case "oneOf":{let n=t.enumValues;return !n||n.length===0?"string":n.map(r=>JSON.stringify(String(r))).join(" | ")}default:return "string"}}function h(t){let n=[];for(let[r,i]of Object.entries(t)){let a="string",p="string",e=false,s,o=false;if(typeof i=="function"){let u=i,c=u.__meta;a=y(c),p=m(c),e=u.optional===true,s=c?.description,o=c?.sensitive===true;}else if(typeof i=="number")a="number";else if(typeof i=="boolean")a="boolean",p="'true' | 'false'";else if(Array.isArray(i)){let u=i;if(u.length>0){let c=u.map(l=>JSON.stringify(String(l))).join(" | ");a=c,p=c;}e=i.__optional===true;}n.push({key:r,tsType:a,stringType:p,isOptional:e,description:s,isSensitive:o});}return n}function d(t){let n=[];return t.description&&n.push(t.description),t.isSensitive&&n.push("@sensitive"),n.length===0?"":n.length===1?` /** ${n[0]} */
|
|
4
|
+
`:` /**
|
|
5
|
+
${n.map(r=>` * ${r}`).join(`
|
|
6
|
+
`)}
|
|
7
|
+
*/
|
|
8
|
+
`}function v(t,n={}){let{augmentProcessEnv:r=true,augmentImportMetaEnv:i=true,banner:a=g}=n,p=h(t),e=[];a&&e.push(a),e.push("export interface EnvSchema {");for(let s of p){let o=d(s);o&&e.push(o.trimEnd());let u=s.isOptional?"?":"";e.push(` ${s.key}${u}: ${s.tsType};`);}if(e.push("}"),e.push(""),r){e.push("declare global {"),e.push(" namespace NodeJS {"),e.push(" interface ProcessEnv {");for(let s of p){let o=s.isOptional?"?":"";e.push(` ${s.key}${o}: ${s.stringType};`);}e.push(" }"),e.push(" }"),e.push("}"),e.push("");}if(i){e.push("interface ImportMetaEnv {");for(let s of p){let o=s.isOptional?"?":"";e.push(` ${s.key}${o}: ${s.stringType};`);}e.push("}"),e.push(""),e.push("interface ImportMeta {"),e.push(" readonly env: ImportMetaEnv;"),e.push("}"),e.push("");}return e.join(`
|
|
9
|
+
`)}function b(t,n,r){let i=v(t,r);fs.writeFileSync(n,i,"utf8");}exports.a=v;exports.b=b;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';var chunkZDRU3RSU_cjs=require('./chunk-ZDRU3RSU.cjs'),chunkS7AB6UX7_cjs=require('./chunk-S7AB6UX7.cjs'),chunkFNF55TN4_cjs=require('./chunk-FNF55TN4.cjs');require('./chunk-2IQQVAXA.cjs'),require('./chunk-O7NR4K6A.cjs');var chunkG36OESVW_cjs=require('./chunk-G36OESVW.cjs');require('./chunk-4QOKRJ3F.cjs'),require('./chunk-D6WM53FN.cjs');var b=require('ansis'),fs=require('fs'),path=require('path'),url=require('url'),child_process=require('child_process');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var b__default=/*#__PURE__*/_interopDefault(b);var U=["env.config.mjs","env.config.js"];function G(e){if(e){let n=path.resolve(process.cwd(),e);if(!fs.existsSync(n))throw new Error(`Config file not found at ${e}. Pass a valid --config path or create env.config.js/env.config.mjs in the current directory.`);return n}for(let n of U){let r=path.resolve(process.cwd(),n);if(fs.existsSync(r))return r}throw new Error("No config file found. Create env.config.js or env.config.mjs in the current directory, or pass --config <path>.")}function M(e){if(e.endsWith(".ts")||e.endsWith(".mts")||e.endsWith(".cts"))throw new Error(["TypeScript config files are not loaded automatically.","Use Node with a loader such as tsx, for example:",""," node --import tsx ./node_modules/node-env-resolver/dist/cli-main.js load --config env.config.ts"].join(`
|
|
3
|
+
`))}async function y(e={}){let n=G(e.configPath);M(n);let o=await import(url.pathToFileURL(n).href),t=(o&&(o.default??o.config??o.env))??void 0;if(!t||typeof t!="object")throw new Error(`Config file at ${n} does not export a valid EnvConfig. Export an object with a "schema" property.`);let a=t;if(!a.schema||typeof a.schema!="object")throw new Error(`EnvConfig from ${n} is missing a "schema" object. Ensure it matches { schema, resolvers?, options? }.`);return a}function _(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function S(e,n,r={}){let o=r.prefix??"",t={};for(let[a,s]of Object.entries(e)){let m=a.toUpperCase(),i=o?`${o}${n}${m}`:m;if(!o&&r.preserveTopLevelKeys?.has(i)){t[i]=s==null?"":typeof s=="string"?s:JSON.stringify(s);continue}_(s)?Object.assign(t,S(s,n,{...r,prefix:i})):t[i]=s==null?"":String(s);}return t}function F(e){let n="pretty",r=false,o;for(let t=0;t<e.length;t++){let a=e[t];if(a==="--format"&&e[t+1]){let s=e[t+1];if(s==="pretty"||s==="json"||s==="env")n=s;else throw new Error(`Invalid --format value "${s}". Expected one of: pretty, json, env.`);t++;}else if(a.startsWith("--format=")){let s=a.split("=",2)[1];if(s==="pretty"||s==="json"||s==="env")n=s;else throw new Error(`Invalid --format value "${s}". Expected one of: pretty, json, env.`)}else a==="--reveal"?r=true:(a==="--config"||a==="-c")&&e[t+1]&&(o=e[t+1],t++);}return {format:n,reveal:r,configPath:o}}function J(e){let n=e[chunkG36OESVW_cjs.c];if(n&&typeof n=="object")return n}function W(e,n){let r=Object.keys(e).sort(),o=chunkFNF55TN4_cjs.c(e),t=J(e),a=chunkFNF55TN4_cjs.f(e),s=[];for(let f of r){let d=e[f],p=n?d:a(d),C=d===null?"null":Array.isArray(d)?"array":typeof d=="object"?"object":typeof d,P=t?.[f]?.source??"unknown",I=o.has(f),R=typeof p=="string"?p:JSON.stringify(p);s.push([f,C,P,I&&!n?`${R}`:R]);}let m=["KEY","TYPE","SOURCE","VALUE"],i=[m,...s],c=i[0].map((f,d)=>Math.max(...i.map(p=>p[d].length))),[u,g,v,l]=m;console.log(b__default.default.bold(`${u.padEnd(c[0])} ${g.padEnd(c[1])} ${v.padEnd(c[2])} ${l}`));for(let[f,d,p,C]of s){let P=chunkFNF55TN4_cjs.c(e).has(f)?b__default.default.yellow(f):f;console.log(`${P.padEnd(c[0])} ${d.padEnd(c[1])} ${p.padEnd(c[2])} ${C}`);}}async function O(e){let n=F(e),r=await y({configPath:n.configPath}),o=await chunkS7AB6UX7_cjs.b(r);if(n.format==="pretty")return W(o,n.reveal),0;if(n.format==="json"){let i=chunkFNF55TN4_cjs.f(o),c=n.reveal?o:i(o);return console.log(JSON.stringify(c,null,2)),0}let t=r.options?.nestedDelimiter,a=t?(()=>{let i=new Set(Object.keys(r.schema).filter(c=>!c.includes(t)));return S(o,t,{preserveTopLevelKeys:i})})():Object.fromEntries(Object.entries(o).map(([i,c])=>[i,String(c??"")])),s=chunkFNF55TN4_cjs.f(o),m=Object.keys(a).sort();for(let i of m){let c=a[i]??"",u=n.reveal?c:s(c);console.log(`${i}=${typeof u=="string"?u:c}`);}return 0}function B(e){let n,r=false,o=e.indexOf("--");if(o===-1||o===e.length-1)throw new Error("Missing child command. Usage: node-env-resolver run [--config path] [--no-redact] -- <command>");let t=e.slice(0,o),a=e.slice(o+1);for(let i=0;i<t.length;i++){let c=t[i];(c==="--config"||c==="-c")&&t[i+1]?(n=t[i+1],i++):c==="--no-redact"&&(r=true);}let[s,...m]=a;if(!s)throw new Error('Missing child command after "--". Example: node-env-resolver run -- npm run migrate');return {configPath:n,noRedact:r,command:s,commandArgs:m}}async function L(e){let n=B(e),r=await y({configPath:n.configPath}),o=await chunkS7AB6UX7_cjs.b(r),t=r.options?.nestedDelimiter,a=t?new Set(Object.keys(r.schema).filter(l=>!l.includes(t))):null,s=t?S(o,t,{preserveTopLevelKeys:a??void 0}):Object.fromEntries(Object.entries(o).map(([l,f])=>[l,String(f??"")])),m={...process.env,...s};if(t&&a)for(let l of a){let f=`${l}${t}`;for(let d of Object.keys(m))d.startsWith(f)&&delete m[d];}let c=chunkFNF55TN4_cjs.c(o).size>0&&!n.noRedact,u=c?chunkFNF55TN4_cjs.f(o):null,g=child_process.spawn(n.command,n.commandArgs,{env:m,stdio:c?["inherit","pipe","pipe"]:"inherit"}),v=l=>{g.killed||g.kill(l);};return process.on("SIGINT",v),process.on("SIGTERM",v),c&&g.stdout&&g.stderr&&(g.stdout.on("data",l=>{let f=l.toString(),d=u?u(f):f,p=typeof d=="string"?d:f;process.stdout.write(p);}),g.stderr.on("data",l=>{let f=l.toString(),d=u?u(f):f,p=typeof d=="string"?d:f;process.stderr.write(p);})),await new Promise(l=>{g.on("exit",(f,d)=>{process.removeListener("SIGINT",v),process.removeListener("SIGTERM",v),d&&console.error(b__default.default.red(`Child process terminated with signal ${d}`)),l(f??0);});})}function z(e){let n,r="env.d.ts";for(let o=0;o<e.length;o++){let t=e[o];(t==="--config"||t==="-c")&&e[o+1]?(n=e[o+1],o++):(t==="--output"||t==="-o")&&e[o+1]?(r=e[o+1],o++):t.startsWith("--output=")&&(r=t.split("=",2)[1]);}return {configPath:n,outputPath:r}}async function N(e){let n=z(e),r=await y({configPath:n.configPath});return chunkZDRU3RSU_cjs.b(r.schema,n.outputPath),console.log(b__default.default.green(`Type definitions written to ${n.outputPath} based on EnvConfig schema.`)),0}function Z(){try{let e=url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-main.cjs', document.baseURI).href))),n=path.join(path.dirname(e),"../package.json");return JSON.parse(fs.readFileSync(n,"utf8")).version??"unknown"}catch{return "unknown"}}function j(){console.log([b__default.default.bold("node-env-resolver CLI"),"","Usage:"," node-env-resolver <command> [options]","","Commands:"," load Resolve config and print it (pretty | json | env)"," run Resolve config and run a child command with injected env"," typegen Generate TypeScript definitions from EnvConfig schema","","Global options:"," -h, --help Show this help message"," -v, --version Show CLI version","","Examples:"," node-env-resolver load"," node-env-resolver load --format=json"," node-env-resolver run -- npm run migrate"," node-env-resolver typegen --output env.d.ts"].join(`
|
|
4
|
+
`));}async function ee(){let[,,...e]=process.argv;if(e.includes("--help")||e.includes("-h"))return j(),0;if(e.includes("--version")||e.includes("-v"))return console.log(Z()),0;let[n,...r]=e;if(!n)return j(),1;try{switch(n){case "load":return await O(r);case "run":return await L(r);case "typegen":return await N(r);default:return console.error(b__default.default.red(`Unknown command: ${n}`)),j(),1}}catch(o){let t=o instanceof Error?o.message:String(o);return console.error(b__default.default.red(t)),1}}ee().then(e=>{process.exit(e);});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/cli-main.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {b as b$1}from'./chunk-TGIYWWDY.js';import {b as b$2}from'./chunk-C34FGZOG.js';import {c,f}from'./chunk-I5UKYTX6.js';import'./chunk-VUUPIWFJ.js';import'./chunk-6EWR3WHU.js';import {c as c$1}from'./chunk-46CBATKM.js';import'./chunk-WKIPEKF6.js';import'./chunk-I7AUKTXE.js';import b from'ansis';import {readFileSync,existsSync}from'fs';import {join,dirname,resolve}from'path';import {fileURLToPath,pathToFileURL}from'url';import {spawn}from'child_process';var U=["env.config.mjs","env.config.js"];function G(e){if(e){let n=resolve(process.cwd(),e);if(!existsSync(n))throw new Error(`Config file not found at ${e}. Pass a valid --config path or create env.config.js/env.config.mjs in the current directory.`);return n}for(let n of U){let r=resolve(process.cwd(),n);if(existsSync(r))return r}throw new Error("No config file found. Create env.config.js or env.config.mjs in the current directory, or pass --config <path>.")}function M(e){if(e.endsWith(".ts")||e.endsWith(".mts")||e.endsWith(".cts"))throw new Error(["TypeScript config files are not loaded automatically.","Use Node with a loader such as tsx, for example:",""," node --import tsx ./node_modules/node-env-resolver/dist/cli-main.js load --config env.config.ts"].join(`
|
|
3
|
+
`))}async function y(e={}){let n=G(e.configPath);M(n);let o=await import(pathToFileURL(n).href),t=(o&&(o.default??o.config??o.env))??void 0;if(!t||typeof t!="object")throw new Error(`Config file at ${n} does not export a valid EnvConfig. Export an object with a "schema" property.`);let a=t;if(!a.schema||typeof a.schema!="object")throw new Error(`EnvConfig from ${n} is missing a "schema" object. Ensure it matches { schema, resolvers?, options? }.`);return a}function _(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function S(e,n,r={}){let o=r.prefix??"",t={};for(let[a,s]of Object.entries(e)){let m=a.toUpperCase(),i=o?`${o}${n}${m}`:m;if(!o&&r.preserveTopLevelKeys?.has(i)){t[i]=s==null?"":typeof s=="string"?s:JSON.stringify(s);continue}_(s)?Object.assign(t,S(s,n,{...r,prefix:i})):t[i]=s==null?"":String(s);}return t}function F(e){let n="pretty",r=false,o;for(let t=0;t<e.length;t++){let a=e[t];if(a==="--format"&&e[t+1]){let s=e[t+1];if(s==="pretty"||s==="json"||s==="env")n=s;else throw new Error(`Invalid --format value "${s}". Expected one of: pretty, json, env.`);t++;}else if(a.startsWith("--format=")){let s=a.split("=",2)[1];if(s==="pretty"||s==="json"||s==="env")n=s;else throw new Error(`Invalid --format value "${s}". Expected one of: pretty, json, env.`)}else a==="--reveal"?r=true:(a==="--config"||a==="-c")&&e[t+1]&&(o=e[t+1],t++);}return {format:n,reveal:r,configPath:o}}function J(e){let n=e[c$1];if(n&&typeof n=="object")return n}function W(e,n){let r=Object.keys(e).sort(),o=c(e),t=J(e),a=f(e),s=[];for(let f of r){let d=e[f],p=n?d:a(d),C=d===null?"null":Array.isArray(d)?"array":typeof d=="object"?"object":typeof d,P=t?.[f]?.source??"unknown",I=o.has(f),R=typeof p=="string"?p:JSON.stringify(p);s.push([f,C,P,I&&!n?`${R}`:R]);}let m=["KEY","TYPE","SOURCE","VALUE"],i=[m,...s],c$1=i[0].map((f,d)=>Math.max(...i.map(p=>p[d].length))),[u,g,v,l]=m;console.log(b.bold(`${u.padEnd(c$1[0])} ${g.padEnd(c$1[1])} ${v.padEnd(c$1[2])} ${l}`));for(let[f,d,p,C]of s){let P=c(e).has(f)?b.yellow(f):f;console.log(`${P.padEnd(c$1[0])} ${d.padEnd(c$1[1])} ${p.padEnd(c$1[2])} ${C}`);}}async function O(e){let n=F(e),r=await y({configPath:n.configPath}),o=await b$2(r);if(n.format==="pretty")return W(o,n.reveal),0;if(n.format==="json"){let i=f(o),c=n.reveal?o:i(o);return console.log(JSON.stringify(c,null,2)),0}let t=r.options?.nestedDelimiter,a=t?(()=>{let i=new Set(Object.keys(r.schema).filter(c=>!c.includes(t)));return S(o,t,{preserveTopLevelKeys:i})})():Object.fromEntries(Object.entries(o).map(([i,c])=>[i,String(c??"")])),s=f(o),m=Object.keys(a).sort();for(let i of m){let c=a[i]??"",u=n.reveal?c:s(c);console.log(`${i}=${typeof u=="string"?u:c}`);}return 0}function B(e){let n,r=false,o=e.indexOf("--");if(o===-1||o===e.length-1)throw new Error("Missing child command. Usage: node-env-resolver run [--config path] [--no-redact] -- <command>");let t=e.slice(0,o),a=e.slice(o+1);for(let i=0;i<t.length;i++){let c=t[i];(c==="--config"||c==="-c")&&t[i+1]?(n=t[i+1],i++):c==="--no-redact"&&(r=true);}let[s,...m]=a;if(!s)throw new Error('Missing child command after "--". Example: node-env-resolver run -- npm run migrate');return {configPath:n,noRedact:r,command:s,commandArgs:m}}async function L(e){let n=B(e),r=await y({configPath:n.configPath}),o=await b$2(r),t=r.options?.nestedDelimiter,a=t?new Set(Object.keys(r.schema).filter(l=>!l.includes(t))):null,s=t?S(o,t,{preserveTopLevelKeys:a??void 0}):Object.fromEntries(Object.entries(o).map(([l,f])=>[l,String(f??"")])),m={...process.env,...s};if(t&&a)for(let l of a){let f=`${l}${t}`;for(let d of Object.keys(m))d.startsWith(f)&&delete m[d];}let c$1=c(o).size>0&&!n.noRedact,u=c$1?f(o):null,g=spawn(n.command,n.commandArgs,{env:m,stdio:c$1?["inherit","pipe","pipe"]:"inherit"}),v=l=>{g.killed||g.kill(l);};return process.on("SIGINT",v),process.on("SIGTERM",v),c$1&&g.stdout&&g.stderr&&(g.stdout.on("data",l=>{let f=l.toString(),d=u?u(f):f,p=typeof d=="string"?d:f;process.stdout.write(p);}),g.stderr.on("data",l=>{let f=l.toString(),d=u?u(f):f,p=typeof d=="string"?d:f;process.stderr.write(p);})),await new Promise(l=>{g.on("exit",(f,d)=>{process.removeListener("SIGINT",v),process.removeListener("SIGTERM",v),d&&console.error(b.red(`Child process terminated with signal ${d}`)),l(f??0);});})}function z(e){let n,r="env.d.ts";for(let o=0;o<e.length;o++){let t=e[o];(t==="--config"||t==="-c")&&e[o+1]?(n=e[o+1],o++):(t==="--output"||t==="-o")&&e[o+1]?(r=e[o+1],o++):t.startsWith("--output=")&&(r=t.split("=",2)[1]);}return {configPath:n,outputPath:r}}async function N(e){let n=z(e),r=await y({configPath:n.configPath});return b$1(r.schema,n.outputPath),console.log(b.green(`Type definitions written to ${n.outputPath} based on EnvConfig schema.`)),0}function Z(){try{let e=fileURLToPath(import.meta.url),n=join(dirname(e),"../package.json");return JSON.parse(readFileSync(n,"utf8")).version??"unknown"}catch{return "unknown"}}function j(){console.log([b.bold("node-env-resolver CLI"),"","Usage:"," node-env-resolver <command> [options]","","Commands:"," load Resolve config and print it (pretty | json | env)"," run Resolve config and run a child command with injected env"," typegen Generate TypeScript definitions from EnvConfig schema","","Global options:"," -h, --help Show this help message"," -v, --version Show CLI version","","Examples:"," node-env-resolver load"," node-env-resolver load --format=json"," node-env-resolver run -- npm run migrate"," node-env-resolver typegen --output env.d.ts"].join(`
|
|
4
|
+
`));}async function ee(){let[,,...e]=process.argv;if(e.includes("--help")||e.includes("-h"))return j(),0;if(e.includes("--version")||e.includes("-v"))return console.log(Z()),0;let[n,...r]=e;if(!n)return j(),1;try{switch(n){case "load":return await O(r);case "run":return await L(r);case "typegen":return await N(r);default:return console.error(b.red(`Unknown command: ${n}`)),j(),1}}catch(o){let t=o instanceof Error?o.message:String(o);return console.error(b.red(t)),1}}ee().then(e=>{process.exit(e);});
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkS7AB6UX7_cjs=require('./chunk-S7AB6UX7.cjs');require('./chunk-2IQQVAXA.cjs');var chunkO7NR4K6A_cjs=require('./chunk-O7NR4K6A.cjs'),chunkG36OESVW_cjs=require('./chunk-G36OESVW.cjs');require('./chunk-4QOKRJ3F.cjs'),require('./chunk-D6WM53FN.cjs');Object.defineProperty(exports,"resolve",{enumerable:true,get:function(){return chunkS7AB6UX7_cjs.a}});Object.defineProperty(exports,"resolveAsync",{enumerable:true,get:function(){return chunkS7AB6UX7_cjs.b}});Object.defineProperty(exports,"safeResolve",{enumerable:true,get:function(){return chunkS7AB6UX7_cjs.c}});Object.defineProperty(exports,"safeResolveAsync",{enumerable:true,get:function(){return chunkS7AB6UX7_cjs.d}});Object.defineProperty(exports,"clearAuditLog",{enumerable:true,get:function(){return chunkO7NR4K6A_cjs.d}});Object.defineProperty(exports,"getAuditLog",{enumerable:true,get:function(){return chunkO7NR4K6A_cjs.c}});Object.defineProperty(exports,"isAsyncOnlyResolver",{enumerable:true,get:function(){return chunkG36OESVW_cjs.b}});Object.defineProperty(exports,"isSyncResolver",{enumerable:true,get:function(){return chunkG36OESVW_cjs.a}});
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as resolve,b as resolveAsync,c as safeResolve,d as safeResolveAsync}from'./chunk-
|
|
1
|
+
export{a as resolve,b as resolveAsync,c as safeResolve,d as safeResolveAsync}from'./chunk-C34FGZOG.js';import'./chunk-VUUPIWFJ.js';export{d as clearAuditLog,c as getAuditLog}from'./chunk-6EWR3WHU.js';export{b as isAsyncOnlyResolver,a as isSyncResolver}from'./chunk-46CBATKM.js';import'./chunk-WKIPEKF6.js';import'./chunk-I7AUKTXE.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkFNF55TN4_cjs=require('./chunk-FNF55TN4.cjs');require('./chunk-G36OESVW.cjs'),require('./chunk-D6WM53FN.cjs');Object.defineProperty(exports,"REVEAL_SYMBOL",{enumerable:true,get:function(){return chunkFNF55TN4_cjs.a}});Object.defineProperty(exports,"createRedactor",{enumerable:true,get:function(){return chunkFNF55TN4_cjs.f}});Object.defineProperty(exports,"getSensitiveKeys",{enumerable:true,get:function(){return chunkFNF55TN4_cjs.c}});Object.defineProperty(exports,"getSensitiveValues",{enumerable:true,get:function(){return chunkFNF55TN4_cjs.d}});Object.defineProperty(exports,"patchGlobalConsole",{enumerable:true,get:function(){return chunkFNF55TN4_cjs.h}});Object.defineProperty(exports,"redactSensitiveConfig",{enumerable:true,get:function(){return chunkFNF55TN4_cjs.g}});Object.defineProperty(exports,"redactString",{enumerable:true,get:function(){return chunkFNF55TN4_cjs.e}});Object.defineProperty(exports,"reveal",{enumerable:true,get:function(){return chunkFNF55TN4_cjs.b}});
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Symbol used to mark a value as intentionally revealed, so the redactor skips it.
|
|
3
|
+
*/
|
|
4
|
+
declare const REVEAL_SYMBOL: unique symbol;
|
|
5
|
+
/**
|
|
6
|
+
* A value wrapped with REVEAL_SYMBOL so the redactor skips redaction.
|
|
7
|
+
*/
|
|
8
|
+
type Revealed<T> = {
|
|
9
|
+
readonly [REVEAL_SYMBOL]: true;
|
|
10
|
+
readonly value: T;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Wrap a value so the redactor intentionally skips it.
|
|
14
|
+
* Use this when you need to log a sensitive value for debugging.
|
|
15
|
+
*/
|
|
16
|
+
declare function reveal<T>(value: T): Revealed<T>;
|
|
17
|
+
/**
|
|
18
|
+
* Extract the set of keys marked as sensitive from a resolved config object.
|
|
19
|
+
*/
|
|
20
|
+
declare function getSensitiveKeys(config: object): Set<string>;
|
|
21
|
+
/**
|
|
22
|
+
* Extract a map of sensitive key → resolved string value from a resolved config.
|
|
23
|
+
* Only includes keys whose resolved values are non-empty strings.
|
|
24
|
+
*/
|
|
25
|
+
declare function getSensitiveValues(config: object): Map<string, string>;
|
|
26
|
+
/**
|
|
27
|
+
* Mask a string value for display. Shows the first `showChars` characters
|
|
28
|
+
* followed by asterisks.
|
|
29
|
+
*
|
|
30
|
+
* @param value - The string to mask
|
|
31
|
+
* @param showChars - Number of leading characters to show (default: 2)
|
|
32
|
+
*/
|
|
33
|
+
declare function redactString(value: string, showChars?: number): string;
|
|
34
|
+
/**
|
|
35
|
+
* Create a bound redaction function for a specific resolved config.
|
|
36
|
+
* The regex is built once and cached via WeakMap.
|
|
37
|
+
*
|
|
38
|
+
* @param config - A resolved config object (from resolve/resolveAsync)
|
|
39
|
+
* @returns A function that redacts sensitive values from any input
|
|
40
|
+
*/
|
|
41
|
+
declare function createRedactor(config: object): (value: unknown) => unknown;
|
|
42
|
+
declare function redactSensitiveConfig(value: unknown, config: object): unknown;
|
|
43
|
+
/**
|
|
44
|
+
* Patch global console methods to redact sensitive values.
|
|
45
|
+
* Returns an unpatch function to restore original behavior.
|
|
46
|
+
*
|
|
47
|
+
* Best-effort, Node-only. Not guaranteed for all logging pipelines.
|
|
48
|
+
*
|
|
49
|
+
* @param config - A resolved config object with sensitive keys attached
|
|
50
|
+
* @returns A function to unpatch (restore original console methods)
|
|
51
|
+
*/
|
|
52
|
+
declare function patchGlobalConsole(config: object): () => void;
|
|
53
|
+
|
|
54
|
+
export { REVEAL_SYMBOL, type Revealed, createRedactor, getSensitiveKeys, getSensitiveValues, patchGlobalConsole, redactSensitiveConfig, redactString, reveal };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Symbol used to mark a value as intentionally revealed, so the redactor skips it.
|
|
3
|
+
*/
|
|
4
|
+
declare const REVEAL_SYMBOL: unique symbol;
|
|
5
|
+
/**
|
|
6
|
+
* A value wrapped with REVEAL_SYMBOL so the redactor skips redaction.
|
|
7
|
+
*/
|
|
8
|
+
type Revealed<T> = {
|
|
9
|
+
readonly [REVEAL_SYMBOL]: true;
|
|
10
|
+
readonly value: T;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Wrap a value so the redactor intentionally skips it.
|
|
14
|
+
* Use this when you need to log a sensitive value for debugging.
|
|
15
|
+
*/
|
|
16
|
+
declare function reveal<T>(value: T): Revealed<T>;
|
|
17
|
+
/**
|
|
18
|
+
* Extract the set of keys marked as sensitive from a resolved config object.
|
|
19
|
+
*/
|
|
20
|
+
declare function getSensitiveKeys(config: object): Set<string>;
|
|
21
|
+
/**
|
|
22
|
+
* Extract a map of sensitive key → resolved string value from a resolved config.
|
|
23
|
+
* Only includes keys whose resolved values are non-empty strings.
|
|
24
|
+
*/
|
|
25
|
+
declare function getSensitiveValues(config: object): Map<string, string>;
|
|
26
|
+
/**
|
|
27
|
+
* Mask a string value for display. Shows the first `showChars` characters
|
|
28
|
+
* followed by asterisks.
|
|
29
|
+
*
|
|
30
|
+
* @param value - The string to mask
|
|
31
|
+
* @param showChars - Number of leading characters to show (default: 2)
|
|
32
|
+
*/
|
|
33
|
+
declare function redactString(value: string, showChars?: number): string;
|
|
34
|
+
/**
|
|
35
|
+
* Create a bound redaction function for a specific resolved config.
|
|
36
|
+
* The regex is built once and cached via WeakMap.
|
|
37
|
+
*
|
|
38
|
+
* @param config - A resolved config object (from resolve/resolveAsync)
|
|
39
|
+
* @returns A function that redacts sensitive values from any input
|
|
40
|
+
*/
|
|
41
|
+
declare function createRedactor(config: object): (value: unknown) => unknown;
|
|
42
|
+
declare function redactSensitiveConfig(value: unknown, config: object): unknown;
|
|
43
|
+
/**
|
|
44
|
+
* Patch global console methods to redact sensitive values.
|
|
45
|
+
* Returns an unpatch function to restore original behavior.
|
|
46
|
+
*
|
|
47
|
+
* Best-effort, Node-only. Not guaranteed for all logging pipelines.
|
|
48
|
+
*
|
|
49
|
+
* @param config - A resolved config object with sensitive keys attached
|
|
50
|
+
* @returns A function to unpatch (restore original console methods)
|
|
51
|
+
*/
|
|
52
|
+
declare function patchGlobalConsole(config: object): () => void;
|
|
53
|
+
|
|
54
|
+
export { REVEAL_SYMBOL, type Revealed, createRedactor, getSensitiveKeys, getSensitiveValues, patchGlobalConsole, redactSensitiveConfig, redactString, reveal };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as REVEAL_SYMBOL,f as createRedactor,c as getSensitiveKeys,d as getSensitiveValues,h as patchGlobalConsole,g as redactSensitiveConfig,e as redactString,b as reveal}from'./chunk-I5UKYTX6.js';import'./chunk-46CBATKM.js';import'./chunk-I7AUKTXE.js';
|
package/dist/resolver.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk2IQQVAXA_cjs=require('./chunk-2IQQVAXA.cjs');require('./chunk-O7NR4K6A.cjs'),require('./chunk-G36OESVW.cjs'),require('./chunk-D6WM53FN.cjs');Object.defineProperty(exports,"normalizeSchema",{enumerable:true,get:function(){return chunk2IQQVAXA_cjs.a}});Object.defineProperty(exports,"resolveEnvInternal",{enumerable:true,get:function(){return chunk2IQQVAXA_cjs.b}});Object.defineProperty(exports,"resolveEnvInternalSync",{enumerable:true,get:function(){return chunk2IQQVAXA_cjs.c}});
|
package/dist/resolver.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as normalizeSchema,b as resolveEnvInternal,c as resolveEnvInternalSync}from'./chunk-
|
|
1
|
+
export{a as normalizeSchema,b as resolveEnvInternal,c as resolveEnvInternalSync}from'./chunk-VUUPIWFJ.js';import'./chunk-6EWR3WHU.js';import'./chunk-46CBATKM.js';import'./chunk-I7AUKTXE.js';
|
package/dist/resolvers.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkQCKMQEJP_cjs=require('./chunk-QCKMQEJP.cjs'),chunk4QOKRJ3F_cjs=require('./chunk-4QOKRJ3F.cjs');require('./chunk-D6WM53FN.cjs');Object.defineProperty(exports,"dotenv",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.a}});Object.defineProperty(exports,"exec",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.h}});Object.defineProperty(exports,"http",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.c}});Object.defineProperty(exports,"json",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.d}});Object.defineProperty(exports,"packageJson",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.b}});Object.defineProperty(exports,"secrets",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.e}});Object.defineProperty(exports,"toml",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.g}});Object.defineProperty(exports,"yaml",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.f}});Object.defineProperty(exports,"processEnv",{enumerable:true,get:function(){return chunk4QOKRJ3F_cjs.a}});
|