import { writeDotenvProperties } from './chunk-CBI6CPYK.js';
import { resolveDotenvReflection, resolveDotenvProperties } from './chunk-HRPQF34B.js';
import { __name } from './chunk-6AXVLTU5.js';
import { parseAsync, Lang } from '@ast-grep/napi';
import { LogLevelLabel } from '@storm-software/config-tools/types';
import { Mutex } from '@stryke/helpers/mutex';

var mutex = new Mutex();
async function transformEnv(log, source, context) {
  const varsReflection = await resolveDotenvReflection(context, "variables");
  const dotenvProperties = await resolveDotenvProperties(log, context, "variables");
  const originalLength = dotenvProperties.length;
  const ast = await parseAsync(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(LogLevelLabel.INFO, `Adding environment variables from ${source.id} to variables.json.`);
    await mutex.acquire();
    try {
      await writeDotenvProperties(log, context, "variables", dotenvProperties);
    } catch (e) {
      console.error(e);
    } finally {
      mutex.release();
    }
  }
  return source;
}
__name(transformEnv, "transformEnv");

export { transformEnv };
//# sourceMappingURL=chunk-7SMZV7EV.js.map
//# sourceMappingURL=chunk-7SMZV7EV.js.map