@stacksjs/env 0.75.629 → 0.75.630

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/dist/plugin.d.ts CHANGED
@@ -49,6 +49,22 @@ export declare function envPlugin(options?: EnvPluginOptions): BunPlugin;
49
49
  * Auto-detect and load .env files based on environment
50
50
  */
51
51
  export declare function autoLoadEnv(options?: Omit<EnvPluginOptions, 'path'>): { loaded: number, errors: string[] };
52
+ /**
53
+ * The env files {@link autoLoadEnv} reads for an environment, least specific
54
+ * first: `.env`, `.env.local`, `.env.<env>`, `.env.<env>.local`, each only if
55
+ * it exists in `cwd`.
56
+ *
57
+ * A later file's value replaces an earlier one's (loadEnv preserves what was
58
+ * set before the call, and lets later files in the list override earlier
59
+ * ones), so the last file here that sets a key, and that this process can
60
+ * read, is where the app's value for it comes from.
61
+ *
62
+ * Exported so a tool that edits env files edits the ones the app loads. The
63
+ * dashboard's Mail settings page edited `.env` alone, and a key set again in
64
+ * `.env.<env>` kept that file's value however often it was saved
65
+ * (stacksjs/stacks#3340).
66
+ */
67
+ export declare function environmentFiles(env: string, cwd?: string): string[];
52
68
  export declare interface EnvPluginOptions {
53
69
  path?: string | string[]
54
70
  overload?: boolean
package/dist/plugin.js CHANGED
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{readFileSync}from"node:fs";import{resolve}from"node:path";import{decryptValue,getPrivateKey}from"./crypto";import{parse}from"./parser";import{isEncryptedValue}from"./encrypted-value";import{plaintextEnv}from"./plaintext-env";import{applyWithheldEnv,withheldEnvKeys}from"./withheld";function normalizeEnvName(value){if(!value||isEncryptedValue(value))return;const normalized=value.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(normalized))return;if(normalized==="prod")return"production";if(normalized==="stage")return"staging";if(normalized==="dev")return"development";return normalized}let cachedKeyEnv=null;let cachedKeyCwd=null;let cachedPrivateKey;let loadedEnvName;function keyFromKeysFile(envName,cwd,keysFile=".env.keys"){const keysPath=resolve(cwd,keysFile);if(!existsSync(keysPath))return;try{const{parsed}=parse(readFileSync(keysPath,"utf-8"));if(envName){const specific=parsed[`DOTENV_PRIVATE_KEY_${envName.toUpperCase()}`];if(specific)return specific}return parsed.DOTENV_PRIVATE_KEY}catch{return}}export function activeEnvName(options={}){return normalizeEnvName(options.env)||loadedEnvName||normalizeEnvName(process.env.NODE_ENV)||normalizeEnvName(process.env.DOTENV_ENV)||normalizeEnvName(process.env.APP_ENV)||"development"}export function resolvePrivateKey(options={}){const envName=activeEnvName(options);const cwd=resolve(options.cwd||process.cwd());if(cachedKeyEnv===envName&&cachedKeyCwd===cwd)return cachedPrivateKey;let key=getPrivateKey(envName);if(!key)key=process.env.DOTENV_PRIVATE_KEY;if(!key)key=keyFromKeysFile(envName,cwd);cachedKeyEnv=envName;cachedKeyCwd=cwd;cachedPrivateKey=key;return key}export function resetPrivateKeyCache(){cachedKeyEnv=null;cachedKeyCwd=null;cachedPrivateKey=undefined;loadedEnvName=undefined}export function decryptEnvValue(value,options={}){if(!isEncryptedValue(value))return value;const key=resolvePrivateKey(options);if(!key)return;try{const normalized=value.startsWith("enc:")?`encrypted:${value.slice(4)}`:value;return decryptValue(normalized,key)}catch{return}}export function loadEnv(options={}){const{path:envPaths=[".env"],overload=false,env:envName,privateKey:customPrivateKey,keysFile=".env.keys",quiet=false,cwd=process.cwd()}=options;const paths=Array.isArray(envPaths)?envPaths:[envPaths];const errors=[];let loaded=0;const withheld=withheldEnvKeys();const externalOverrides=new Map(Object.entries(plaintextEnv(process.env)).filter((entry)=>entry[1]!==undefined));let privateKey=customPrivateKey;if(!privateKey&&keysFile){const keysPath=resolve(cwd,keysFile);if(existsSync(keysPath)){try{const keysContent=readFileSync(keysPath,"utf-8");const{parsed}=parse(keysContent);if(envName){const keyName=`DOTENV_PRIVATE_KEY_${envName.toUpperCase()}`;privateKey=parsed[keyName]||parsed.DOTENV_PRIVATE_KEY}else{privateKey=parsed.DOTENV_PRIVATE_KEY}}catch(error){errors.push(`Failed to load keys file: ${error instanceof Error?error.message:"Unknown error"}`)}}}if(!privateKey){privateKey=getPrivateKey(envName||"")||getPrivateKey()}for(const envPath of paths){const fullPath=resolve(cwd,envPath);if(!existsSync(fullPath)){if(!quiet){errors.push(`File not found: ${fullPath}`)}continue}try{const content=readFileSync(fullPath,"utf-8");const{parsed,errors:parseErrors,skippedEncrypted}=parse(content,{privateKey,processEnv:process.env});errors.push(...parseErrors);if(skippedEncrypted.length>0){const usable=plaintextEnv(process.env,skippedEncrypted);for(const key of Object.keys(process.env)){if(!Object.hasOwn(usable,key))delete process.env[key]}const keyName=envName?`DOTENV_PRIVATE_KEY_${envName.toUpperCase()}`:"DOTENV_PRIVATE_KEY";const reason=privateKey?"decryption failed":`${keyName} not set`;const preview=skippedEncrypted.slice(0,5).join(", ");const rest=skippedEncrypted.length>5?`, … +${skippedEncrypted.length-5} more`:"";console.warn(`[env] warning: skipped ${skippedEncrypted.length} encrypted value(s) in ${envPath} (${reason}; existing plaintext or defaults apply): ${preview}${rest}`)}let applied=0;for(const[key,value]of Object.entries(parsed)){if(key==="DOTENV_PUBLIC_KEY"||withheld.has(key)){continue}const existing=process.env[key];const isStaleCiphertext=isEncryptedValue(existing)&&value!==existing;if(externalOverrides.get(key)===value)externalOverrides.delete(key);if(overload||!externalOverrides.has(key)||isStaleCiphertext){process.env[key]=value;loaded++;applied++}}if(!quiet&&!process.env.__ENV_LOADED__){console.error(`[env] loaded ${applied}/${Object.keys(parsed).length} variables from ${envPath}`);process.env.__ENV_LOADED__="1"}}catch(error){errors.push(`Failed to load ${fullPath}: ${error instanceof Error?error.message:"Unknown error"}`)}}scrubForeignCiphertext(privateKey);applyWithheldEnv();return{loaded,errors}}const reportedForeignCiphertext=new Set;function scrubForeignCiphertext(privateKey){const undecryptable=[];for(const[key,value]of Object.entries(process.env)){if(!isEncryptedValue(value))continue;let plaintext;if(privateKey){try{plaintext=decryptValue(value.startsWith("enc:")?`encrypted:${value.slice(4)}`:value,privateKey)}catch{}}if(plaintext===undefined)undecryptable.push(key);else process.env[key]=plaintext}if(!undecryptable.length)return;const usable=plaintextEnv(process.env,undecryptable);for(const key of Object.keys(process.env)){if(!Object.hasOwn(usable,key))delete process.env[key]}const fresh=undecryptable.filter((key)=>!reportedForeignCiphertext.has(key));if(!fresh.length)return;for(const key of fresh)reportedForeignCiphertext.add(key);const preview=fresh.slice(0,5).join(", ");const rest=fresh.length>5?`, … +${fresh.length-5} more`:"";console.warn(`[env] warning: unset ${fresh.length} encrypted value(s) no loaded env file could decrypt (Bun preloads .env.<NODE_ENV> on its own): ${preview}${rest}`)}export function envPlugin(options={}){return{name:"env-plugin",setup(build){loadEnv(options)}}}export function autoLoadEnv(options={}){const env=normalizeEnvName(options.env)||normalizeEnvName(process.env.NODE_ENV)||normalizeEnvName(process.env.DOTENV_ENV)||normalizeEnvName(process.env.APP_ENV)||"development";const cwd=options.cwd||process.cwd();if(loadedEnvName!==env){loadedEnvName=env;cachedKeyEnv=null;cachedKeyCwd=null;cachedPrivateKey=undefined}const paths=[];const addIfPresent=(file)=>{if(!paths.includes(file)&&existsSync(resolve(cwd,file)))paths.push(file)};addIfPresent(".env");addIfPresent(".env.local");const envFile=`.env.${env}`;const envLocalFile=`.env.${env}.local`;addIfPresent(envFile);addIfPresent(envLocalFile);return loadEnv({...options,path:paths,env})}export default envPlugin;
1
+ import{existsSync}from"node:fs";import{readFileSync}from"node:fs";import{resolve}from"node:path";import{decryptValue,getPrivateKey}from"./crypto";import{parse}from"./parser";import{isEncryptedValue}from"./encrypted-value";import{plaintextEnv}from"./plaintext-env";import{applyWithheldEnv,withheldEnvKeys}from"./withheld";function normalizeEnvName(value){if(!value||isEncryptedValue(value))return;const normalized=value.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(normalized))return;if(normalized==="prod")return"production";if(normalized==="stage")return"staging";if(normalized==="dev")return"development";return normalized}let cachedKeyEnv=null;let cachedKeyCwd=null;let cachedPrivateKey;let loadedEnvName;function keyFromKeysFile(envName,cwd,keysFile=".env.keys"){const keysPath=resolve(cwd,keysFile);if(!existsSync(keysPath))return;try{const{parsed}=parse(readFileSync(keysPath,"utf-8"));if(envName){const specific=parsed[`DOTENV_PRIVATE_KEY_${envName.toUpperCase()}`];if(specific)return specific}return parsed.DOTENV_PRIVATE_KEY}catch{return}}export function activeEnvName(options={}){return normalizeEnvName(options.env)||loadedEnvName||normalizeEnvName(process.env.NODE_ENV)||normalizeEnvName(process.env.DOTENV_ENV)||normalizeEnvName(process.env.APP_ENV)||"development"}export function resolvePrivateKey(options={}){const envName=activeEnvName(options);const cwd=resolve(options.cwd||process.cwd());if(cachedKeyEnv===envName&&cachedKeyCwd===cwd)return cachedPrivateKey;let key=getPrivateKey(envName);if(!key)key=process.env.DOTENV_PRIVATE_KEY;if(!key)key=keyFromKeysFile(envName,cwd);cachedKeyEnv=envName;cachedKeyCwd=cwd;cachedPrivateKey=key;return key}export function resetPrivateKeyCache(){cachedKeyEnv=null;cachedKeyCwd=null;cachedPrivateKey=undefined;loadedEnvName=undefined}export function decryptEnvValue(value,options={}){if(!isEncryptedValue(value))return value;const key=resolvePrivateKey(options);if(!key)return;try{const normalized=value.startsWith("enc:")?`encrypted:${value.slice(4)}`:value;return decryptValue(normalized,key)}catch{return}}export function loadEnv(options={}){const{path:envPaths=[".env"],overload=false,env:envName,privateKey:customPrivateKey,keysFile=".env.keys",quiet=false,cwd=process.cwd()}=options;const paths=Array.isArray(envPaths)?envPaths:[envPaths];const errors=[];let loaded=0;const withheld=withheldEnvKeys();const externalOverrides=new Map(Object.entries(plaintextEnv(process.env)).filter((entry)=>entry[1]!==undefined));let privateKey=customPrivateKey;if(!privateKey&&keysFile){const keysPath=resolve(cwd,keysFile);if(existsSync(keysPath)){try{const keysContent=readFileSync(keysPath,"utf-8");const{parsed}=parse(keysContent);if(envName){const keyName=`DOTENV_PRIVATE_KEY_${envName.toUpperCase()}`;privateKey=parsed[keyName]||parsed.DOTENV_PRIVATE_KEY}else{privateKey=parsed.DOTENV_PRIVATE_KEY}}catch(error){errors.push(`Failed to load keys file: ${error instanceof Error?error.message:"Unknown error"}`)}}}if(!privateKey){privateKey=getPrivateKey(envName||"")||getPrivateKey()}for(const envPath of paths){const fullPath=resolve(cwd,envPath);if(!existsSync(fullPath)){if(!quiet){errors.push(`File not found: ${fullPath}`)}continue}try{const content=readFileSync(fullPath,"utf-8");const{parsed,errors:parseErrors,skippedEncrypted}=parse(content,{privateKey,processEnv:process.env});errors.push(...parseErrors);if(skippedEncrypted.length>0){const usable=plaintextEnv(process.env,skippedEncrypted);for(const key of Object.keys(process.env)){if(!Object.hasOwn(usable,key))delete process.env[key]}const keyName=envName?`DOTENV_PRIVATE_KEY_${envName.toUpperCase()}`:"DOTENV_PRIVATE_KEY";const reason=privateKey?"decryption failed":`${keyName} not set`;const preview=skippedEncrypted.slice(0,5).join(", ");const rest=skippedEncrypted.length>5?`, … +${skippedEncrypted.length-5} more`:"";console.warn(`[env] warning: skipped ${skippedEncrypted.length} encrypted value(s) in ${envPath} (${reason}; existing plaintext or defaults apply): ${preview}${rest}`)}let applied=0;for(const[key,value]of Object.entries(parsed)){if(key==="DOTENV_PUBLIC_KEY"||withheld.has(key)){continue}const existing=process.env[key];const isStaleCiphertext=isEncryptedValue(existing)&&value!==existing;if(externalOverrides.get(key)===value)externalOverrides.delete(key);if(overload||!externalOverrides.has(key)||isStaleCiphertext){process.env[key]=value;loaded++;applied++}}if(!quiet&&!process.env.__ENV_LOADED__){console.error(`[env] loaded ${applied}/${Object.keys(parsed).length} variables from ${envPath}`);process.env.__ENV_LOADED__="1"}}catch(error){errors.push(`Failed to load ${fullPath}: ${error instanceof Error?error.message:"Unknown error"}`)}}scrubForeignCiphertext(privateKey);applyWithheldEnv();return{loaded,errors}}const reportedForeignCiphertext=new Set;function scrubForeignCiphertext(privateKey){const undecryptable=[];for(const[key,value]of Object.entries(process.env)){if(!isEncryptedValue(value))continue;let plaintext;if(privateKey){try{plaintext=decryptValue(value.startsWith("enc:")?`encrypted:${value.slice(4)}`:value,privateKey)}catch{}}if(plaintext===undefined)undecryptable.push(key);else process.env[key]=plaintext}if(!undecryptable.length)return;const usable=plaintextEnv(process.env,undecryptable);for(const key of Object.keys(process.env)){if(!Object.hasOwn(usable,key))delete process.env[key]}const fresh=undecryptable.filter((key)=>!reportedForeignCiphertext.has(key));if(!fresh.length)return;for(const key of fresh)reportedForeignCiphertext.add(key);const preview=fresh.slice(0,5).join(", ");const rest=fresh.length>5?`, … +${fresh.length-5} more`:"";console.warn(`[env] warning: unset ${fresh.length} encrypted value(s) no loaded env file could decrypt (Bun preloads .env.<NODE_ENV> on its own): ${preview}${rest}`)}export function envPlugin(options={}){return{name:"env-plugin",setup(build){loadEnv(options)}}}export function autoLoadEnv(options={}){const env=normalizeEnvName(options.env)||normalizeEnvName(process.env.NODE_ENV)||normalizeEnvName(process.env.DOTENV_ENV)||normalizeEnvName(process.env.APP_ENV)||"development";const cwd=options.cwd||process.cwd();if(loadedEnvName!==env){loadedEnvName=env;cachedKeyEnv=null;cachedKeyCwd=null;cachedPrivateKey=undefined}return loadEnv({...options,path:environmentFiles(env,cwd),env})}export function environmentFiles(env,cwd=process.cwd()){const files=[];for(const file of[".env",".env.local",`.env.${env}`,`.env.${env}.local`]){if(!files.includes(file)&&existsSync(resolve(cwd,file)))files.push(file)}return files}export default envPlugin;
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/env",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.629",
5
+ "version": "0.75.630",
6
6
  "description": "Stacks env helper methods.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -56,11 +56,11 @@
56
56
  "prepublishOnly": "bun run build"
57
57
  },
58
58
  "dependencies": {
59
- "@stacksjs/path": "0.75.629",
59
+ "@stacksjs/path": "0.75.630",
60
60
  "@stacksjs/ts-validation": "^0.5.7"
61
61
  },
62
62
  "devDependencies": {
63
63
  "better-dx": "^0.2.39",
64
- "@stacksjs/validation": "0.75.629"
64
+ "@stacksjs/validation": "0.75.630"
65
65
  }
66
66
  }