'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var nodejs_fs = require('../nodejs/fs.js');

function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function getKeyValue(key, sourceLine) {
  var result;
  var ma;
  var re = new RegExp("".concat(key, "\\s*=\\s*(.*?)(\\s|$)"));
  var _iterator = _createForOfIteratorHelper(sourceLine),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var line = _step.value;
      if (line.startsWith('#')) {
        // 忽略注释行
        continue;
      }
      ma = line.match(re);
      if (ma) {
        result = ma[1] || '';
        break;
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return result;
}
/**
 * 获取文件中所有环境变量的键值对映射
 * 支持解析 KEY=VALUE 格式的环境变量文件，忽略以 # 开头的注释行
 * @param {string} filepath 文件路径，如果文件不存在则将参数作为字符串直接解析
 * @returns {Record<string, any>} 环境变量的键值对映射
 * @example
 * ```ts
 * // 解析 .env 文件
 * const envMap = getEnvVariableMap('.env.local');
 * // { NODE_ENV: 'production', API_URL: 'https://api.example.com' }
 *
 * // 直接解析字符串
 * const envMap2 = getEnvVariableMap('KEY1=value1\nKEY2=value2');
 * // { KEY1: 'value1', KEY2: 'value2' }
 * ```
 */
function getEnvVariableMap(filepath) {
  var sourceStr = '';
  var re = new RegExp('(.*?)\\s*=\\s*(.*?)(\\s|$)');
  if (nodejs_fs.getFs().existsSync(filepath)) {
    sourceStr = nodejs_fs.getFs().readFileSync(filepath, 'utf-8');
  } else {
    sourceStr = filepath;
  }
  var sourceLine = sourceStr.split('\n');
  var result = {};
  var _iterator2 = _createForOfIteratorHelper(sourceLine),
    _step2;
  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var line = _step2.value;
      if (line.startsWith('#')) {
        // 忽略注释行
        continue;
      }
      var match = line.match(re);
      if (match === null || match === void 0 ? void 0 : match[1]) {
        result[match[1]] = match[2] || '';
      }
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  return result;
}
/**
 * 读取文件中环境变量的值，支持：
 * - NPM_TOKEN=xxx
 * - NPM_TOKEN = xxx
 * @param {string} key 环境变量的key
 * @param {string} filepath 保存环境变量的文件路径
 * @returns {string} 环境变量的值
 * @example
 * ```ts
 * const token = readEnvVariable('NPM_TOKEN', '.env.local');
 * console.log(token); // 'npm_xxxxxxxxxxxxxxxx'
 * ```
 */
function readEnvVariable(key, filepath) {
  if (!nodejs_fs.getFs().existsSync(filepath)) {
    console.log('[readEnvVariable] 文件不存在:', filepath, '，请先创建文件');
    return '';
  }
  try {
    var sourceStr = nodejs_fs.getFs().readFileSync(filepath, 'utf-8');
    var sourceLine = sourceStr.split('\n');
    return getKeyValue(key, sourceLine);
  } catch (e) {
    console.log('[readEnvVariable] 打开文件失败:', filepath);
    process.exit(1);
  }
}

exports.getEnvVariableMap = getEnvVariableMap;
exports.readEnvVariable = readEnvVariable;
