All files / lib env.js

98.23% Statements 111/113
89.65% Branches 26/29
100% Functions 3/3
98.23% Lines 111/113

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 8x 8x 8x 8x 8x 31x 31x 19x 19x 19x 8x 8x 8x 7x 7x 8x 8x 19x 9x 9x 9x 19x 19x 31x 8x 8x 533x 533x 533x 533x 533x 533x 533x 785x 785x 785x 782x 782x 3x 3x 3x 3x 7x 6x 6x 7x 3x     785x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 1574x 1574x 1574x 1574x 1574x 24x 24x 24x 24x 24x 1574x 1574x 1574x 1574x 1193x 1193x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1192x 1573x 1573x 1574x  
import fs from 'fs';
import path from 'path';
import { getClosestKey } from './config.js';
import { AvenxErrorCodes } from './core/runtime/AvenxError.js';
import { BuildError } from './compiler/errors/BuildError.js';
import { reportWarning } from './compiler/utils/warningReporter.js';
 
/**
 * Parses the content of a .env file and returns an object of key-value pairs.
 * Matches dotenv behavior including single/double quotes and inline comments.
 * @param {string|Buffer} src
 * @returns {Object}
 */
export function parseEnv(src) {
  const obj = {};
  // Match standard env entries: KEY = VAL
  const regex = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*|:\s*)\s*(?:("|')((?:\\\2|.)*?)\2|([^#\r\n]+?))?\s*(?:#.*)?$/;
  const lines = src.toString().split(/\r?\n/);
  for (const line of lines) {
    const match = line.match(regex);
    if (match) {
      const key = match[1];
      let val = '';
      if (match[2]) {
        // Quoted value
        val = match[3];
        if (match[2] === '"') {
          val = val.replace(/\\n/g, '\n').replace(/\\r/g, '\r');
        }
        // Unescape escaped quote character
        val = val.replace(new RegExp(`\\\\${match[2]}`, 'g'), match[2]);
      } else if (match[4]) {
        // Unquoted value
        val = match[4].trim();
      }
      obj[key] = val;
    }
  }
  return obj;
}
 
/**
 * Loads environment variables from the `.env` file in rootDir into process.env.
 * Does not overwrite existing environment variables.
 * @param {string} rootDir
 */
export function loadEnv(rootDir) {
  if (!rootDir) return;
  const envPath = path.join(rootDir, '.env');
  if (!fs.existsSync(envPath)) {
    return;
  }
  try {
    const content = fs.readFileSync(envPath, 'utf-8');
    const parsed = parseEnv(content);
    for (const key of Object.keys(parsed)) {
      if (process.env[key] === undefined) {
        process.env[key] = parsed[key];
      }
    }
  } catch {
    // Fail silently if reading fails
  }
}
 
/**
 * Replaces process.env.AVX_PUBLIC_... and process.env['AVX_PUBLIC_...']
 * occurrences in the content with their stringified values from process.env.
 *
 * A reference to a variable that has no value is inlined as `undefined`. When
 * `file` is given, each such variable is reported once as AVX_W60, naming the
 * file, because a misspelled name or a missing `.env` entry in CI otherwise
 * builds cleanly and fails only at runtime. Callers that re-read a file the
 * build already processed (a cache key, the Atlas model) omit `file`, so the
 * same reference is not reported twice.
 * @param {string} content
 * @param {string} [file] - The file the content came from, as it should appear in the warning.
 * @param {object} [config] - The application configuration, for `warnings` overrides.
 * @returns {string}
 */
export function replaceEnvVariables(content, file, config) {
  if (!content) return content;
  const unset = new Set();
  const replaced = content.replace(
    /process\.env\.AVX_PUBLIC_([a-zA-Z0-9_]+)|process\.env\[\s*(['"])AVX_PUBLIC_([a-zA-Z0-9_]+)\2\s*\]/g,
    (match, dottedKey, quote, bracketKey) => {
      const key = dottedKey || bracketKey;
      const fullKey = 'AVX_PUBLIC_' + key;
      const val = process.env[fullKey];
      if (val === undefined) unset.add(fullKey);
      return val !== undefined ? JSON.stringify(val) : 'undefined';
    },
  );
 
  if (file) {
    const known = Object.keys(process.env).filter((key) => key.startsWith('AVX_PUBLIC_'));
    for (const name of unset) {
      const closest = getClosestKey(name, known);
      reportWarning(
        AvenxErrorCodes.COMPILER_UNDEFINED_PUBLIC_ENV,
        new BuildError(
          AvenxErrorCodes.COMPILER_UNDEFINED_PUBLIC_ENV,
          name,
          file,
          closest ? ` Did you mean "${closest}"?` : '',
        ),
        config,
      );
    }
  }
 
  return replaced;
}