'use strict';

var chunkDNBPSJZB_cjs = require('./chunk-DNBPSJZB.cjs');
var chunkD5HE46WD_cjs = require('./chunk-D5HE46WD.cjs');
var chunkAF3E2D32_cjs = require('./chunk-AF3E2D32.cjs');
var napi = require('@ast-grep/napi');
var types = require('@storm-software/config-tools/types');
var mutex$1 = require('@stryke/helpers/mutex');

var mutex = new mutex$1.Mutex();
async function transformEnv(log, source, context) {
  const varsReflection = await chunkD5HE46WD_cjs.resolveDotenvReflection(context, "variables");
  const dotenvProperties = await chunkD5HE46WD_cjs.resolveDotenvProperties(log, context, "variables");
  const originalLength = dotenvProperties.length;
  const ast = await napi.parseAsync(napi.Lang.TypeScript, source.code.toString());
  const root = ast.root();
  const nodes = root.findAll({
    rule: {
      kind: "member_expression",
      any: [
        {
          pattern: "$storm.vars.$ENV_VALUE"
        },
        {
          pattern: "useStorm().vars.$ENV_VALUE"
        },
        {
          pattern: "process.env.$ENV_VALUE"
        }
      ]
    }
  });
  if (!nodes) {
    return source;
  }
  for (const node of nodes) {
    const name = node.getMatch("ENV_VALUE")?.text()?.replace("STORM_", "");
    if (name && varsReflection.hasProperty(name)) {
      const reflectionProperty = varsReflection.getProperty(name);
      if (context.dotenv.replace && !node.text().startsWith("process.env.")) {
        const value = context.dotenv.values?.[name] ?? context.dotenv.values?.[`STORM_${name}`] ?? reflectionProperty.getDefaultValue();
        if (reflectionProperty.isValueRequired() && value === void 0) {
          throw new Error(`Environment variable \`${name}\` is not defined in the .env configuration files`);
        }
        source.code = source.code.replaceAll(node.text(), String(value));
      }
      dotenvProperties.push(reflectionProperty);
    } else {
      throw new Error(`Environment variable \`${name}\` is not defined in the dotenv type definition but is used in the code. 

The following variable names are defined in the dotenv type definition: 
${varsReflection.getPropertyNames().map((typeDef) => ` - ${String(typeDef)} `).join("\n")} 

Please check your \`dotenv\` configuration option. If you are using a custom dotenv type definition, please make sure that the variable names match the ones in the code. 

`);
    }
  }
  if (dotenvProperties.length !== originalLength) {
    log(types.LogLevelLabel.INFO, `Adding environment variables from ${source.id} to variables.json.`);
    await mutex.acquire();
    try {
      await chunkDNBPSJZB_cjs.writeDotenvProperties(log, context, "variables", dotenvProperties);
    } catch (e) {
      console.error(e);
    } finally {
      mutex.release();
    }
  }
  return source;
}
chunkAF3E2D32_cjs.__name(transformEnv, "transformEnv");

exports.transformEnv = transformEnv;
//# sourceMappingURL=chunk-YRPB2JS5.cjs.map
//# sourceMappingURL=chunk-YRPB2JS5.cjs.map