Object.defineProperty(exports, '__esModule', { value: true });
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
const require_join_paths = require('./node_modules/.pnpm/@stryke_path@0.26.17/node_modules/@stryke/path/dist/join-paths.cjs');
const require_helpers_reflect = require('./helpers/reflect.cjs');
const require_helpers_persistence = require('./helpers/persistence.cjs');
const require_defu = require('./node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.cjs');
const require_helpers_load = require('./helpers/load.cjs');
const require_helpers_docs_helper = require('./helpers/docs-helper.cjs');
const require_helpers_automd_generator = require('./helpers/automd-generator.cjs');
const require_components_docs = require('./components/docs.cjs');
const require_components_env_builtin = require('./components/env-builtin.cjs');
const require_babel_plugin = require('./babel/plugin.cjs');
const require_parse_type_definition = require('./node_modules/.pnpm/@stryke_convert@0.6.51/node_modules/@stryke/convert/dist/parse-type-definition.cjs');
const require_to_array = require('./node_modules/.pnpm/@stryke_convert@0.6.51/node_modules/@stryke/convert/dist/to-array.cjs');
let __powerlines_deepkit_vendor_type = require("@powerlines/deepkit/vendor/type");
let __stryke_env_types = require("@stryke/env/types");
let __alloy_js_core_jsx_runtime = require("@alloy-js/core/jsx-runtime");
let __powerlines_plugin_alloy = require("@powerlines/plugin-alloy");
__powerlines_plugin_alloy = require_rolldown_runtime.__toESM(__powerlines_plugin_alloy);
let __powerlines_plugin_alloy_render = require("@powerlines/plugin-alloy/render");
let __powerlines_plugin_automd = require("@powerlines/plugin-automd");
__powerlines_plugin_automd = require_rolldown_runtime.__toESM(__powerlines_plugin_automd);
let __powerlines_plugin_babel = require("@powerlines/plugin-babel");
__powerlines_plugin_babel = require_rolldown_runtime.__toESM(__powerlines_plugin_babel);
let __stryke_fs_exists = require("@stryke/fs/exists");
let __stryke_string_format_constant_case = require("@stryke/string-format/constant-case");
let __stryke_type_checks_is_set_string = require("@stryke/type-checks/is-set-string");

//#region src/index.tsx
/**
* A Powerlines plugin to inject environment variables into the source code.
*/
const plugin = (options = {}) => {
	return [
		(0, __powerlines_plugin_alloy.default)(options.alloy),
		(0, __powerlines_plugin_babel.default)(options.babel),
		{
			name: "env",
			async config() {
				this.debug("Providing default configuration for the Powerlines `env` build plugin.");
				const config = {
					env: require_defu.defu(options, {
						types: {},
						validate: false,
						inject: false,
						prefix: []
					}),
					transform: { babel: { plugins: [require_babel_plugin.envBabelPlugin] } }
				};
				if ((0, __stryke_type_checks_is_set_string.isSetString)(config.env.types) || config.env.types && (0, __stryke_type_checks_is_set_string.isSetString)(config.env.types.file)) {
					config.env.types = require_parse_type_definition.parseTypeDefinition(config.env.types);
					const file = await this.fs.resolve(config.env.types.file);
					if (file) config.env.types.file = file;
				} else {
					this.warn("The `env.types` configuration parameter was not provided. Please ensure this is expected.");
					const envDefaultTypeDefinition = await require_helpers_persistence.getEnvDefaultTypeDefinition(this);
					const file = await this.fs.resolve(envDefaultTypeDefinition.file);
					if (file) config.env.types = require_parse_type_definition.parseTypeDefinition(`${file}#${envDefaultTypeDefinition.name}`);
				}
				if ((0, __stryke_type_checks_is_set_string.isSetString)(config.env.secrets) || config.env.secrets && (0, __stryke_type_checks_is_set_string.isSetString)(config.env.secrets.file)) {
					config.env.secrets = require_parse_type_definition.parseTypeDefinition(config.env.secrets);
					const file = await this.fs.resolve(config.env.secrets.file);
					if (file) config.env.secrets.file = file;
				} else {
					const secretsDefaultTypeDefinition = await require_helpers_persistence.getSecretsDefaultTypeDefinition(this);
					const file = await this.fs.resolve(secretsDefaultTypeDefinition.file);
					if (file) config.env.secrets = require_parse_type_definition.parseTypeDefinition(`${file}#${secretsDefaultTypeDefinition.name}`);
				}
				config.env.prefix = require_to_array.toArray(config.env.prefix ?? []).reduce((ret, prefix) => {
					const formattedPrefix = (0, __stryke_string_format_constant_case.constantCase)(prefix);
					if (!ret.includes(formattedPrefix)) ret.push(formattedPrefix);
					return ret;
				}, [
					...__stryke_env_types.ENV_PREFIXES,
					"POWERLINES_",
					this.config.framework && this.config.framework !== "powerlines" && `${(0, __stryke_string_format_constant_case.constantCase)(this.config.framework)}_`
				].filter(Boolean));
				config.env.prefix = require_to_array.toArray(config.env.prefix).reduce((ret, prefix) => {
					if (!ret.includes(prefix.replace(/_$/g, ""))) ret.push(prefix.replace(/_$/g, ""));
					return ret;
				}, []);
				return config;
			},
			async configResolved() {
				this.debug(`Environment plugin configuration has been resolved for the Powerlines project.`);
				this.env = require_defu.defu({ parsed: await require_helpers_load.loadEnv(this, this.config.env) }, this.env ?? {}, {
					types: { env: {} },
					used: {
						env: {},
						secrets: {}
					},
					parsed: {},
					injected: {}
				});
				if (this.config.command !== "prepare" && !this.config.skipCache && this.persistedMeta?.checksum === this.meta.checksum && (0, __stryke_fs_exists.existsSync)(require_helpers_persistence.getEnvTypeReflectionsPath(this, "env"))) {
					this.debug(`Skipping reflection initialization as the meta checksum has not changed.`);
					this.env.types.env = await require_helpers_persistence.readEnvTypeReflection(this, "env");
					if ((0, __stryke_fs_exists.existsSync)(require_helpers_persistence.getEnvReflectionsPath(this, "env"))) this.env.used.env = await require_helpers_persistence.readEnvReflection(this);
					if ((0, __stryke_fs_exists.existsSync)(require_helpers_persistence.getEnvTypeReflectionsPath(this, "secrets"))) this.env.types.secrets = await require_helpers_persistence.readEnvTypeReflection(this, "secrets");
					if ((0, __stryke_fs_exists.existsSync)(require_helpers_persistence.getEnvReflectionsPath(this, "secrets"))) this.env.used.secrets = await require_helpers_persistence.readSecretsReflection(this);
				} else {
					this.debug(`Starting environment configuration reflection initialization.`);
					this.env.types.env = await require_helpers_reflect.reflectEnv(this, this.config.env.types?.file, this.config.env.types?.name);
					if (!this.env.types.env) throw new Error("Failed to find the environment configuration type reflection in the context.");
					await require_helpers_persistence.writeEnvTypeReflection(this, this.env.types.env, "env");
					this.env.types.secrets = await require_helpers_reflect.reflectSecrets(this, this.config.env.secrets?.file, this.config.env.secrets?.name);
					if (!this.env.types.secrets) throw new Error("Failed to find the secrets configuration type reflection in the context.");
					await require_helpers_persistence.writeEnvTypeReflection(this, this.env.types.secrets, "secrets");
					this.debug(`Resolved ${this.env.types.env.getProperties().length ?? 0} environment configuration parameters and ${this.env.types.secrets?.getProperties().length ?? 0} secret configuration parameters`);
					const envWithAlias = this.env.types.env.getProperties().filter((prop) => prop.getAlias().length > 0);
					Object.entries(await require_helpers_load.loadEnv(this, this.config.env)).forEach(([key, value]) => {
						const unprefixedKey = this.config.env.prefix.reduce((ret, prefix) => {
							if (key.replace(/_$/g, "").startsWith(prefix)) return key.replace(/_$/g, "").slice(prefix.length);
							return ret;
						}, key);
						const aliasKey = envWithAlias.find((prop) => prop?.getAlias().reverse().includes(unprefixedKey));
						if (this.env.types.env?.hasProperty(unprefixedKey) || aliasKey) this.env.types.env.getProperty(unprefixedKey).setDefaultValue(value);
					});
					this.env.used.env = new __powerlines_deepkit_vendor_type.ReflectionClass({
						kind: __powerlines_deepkit_vendor_type.ReflectionKind.objectLiteral,
						typeName: "Env",
						description: `An object containing the environment configuration parameters used by the ${this.config.name ? `${this.config.name} application` : "application"}.`,
						types: []
					}, this.env.types.env);
					await require_helpers_persistence.writeEnvReflection(this, this.env.used.env, "env");
					if (this.env.types.secrets) {
						await require_helpers_persistence.writeEnvTypeReflection(this, this.env.types.secrets, "secrets");
						this.env.used.secrets = new __powerlines_deepkit_vendor_type.ReflectionClass({
							kind: __powerlines_deepkit_vendor_type.ReflectionKind.objectLiteral,
							typeName: "Secrets",
							description: `An object containing the secret configuration parameters used by the ${this.config.name ? `${this.config.name} application` : "application"}.`,
							types: []
						}, this.env.types.secrets);
						await require_helpers_persistence.writeEnvReflection(this, this.env.used.secrets, "secrets");
					}
				}
			},
			async prepare() {
				const _self$ = this;
				this.debug(`Preparing the Environment runtime artifacts for the Powerlines project.`);
				const result = await require_helpers_persistence.readEnvTypeReflection(this, "env");
				return (0, __powerlines_plugin_alloy_render.render)(this, (0, __alloy_js_core_jsx_runtime.createComponent)(require_components_env_builtin.EnvBuiltin, {
					get defaultConfig() {
						return _self$.config.env.defaultConfig;
					},
					reflection: result
				}));
			},
			transform: {
				order: "post",
				async handler() {
					if (this.env.used.env.getProperties().length > 0) {
						this.trace(`Persisting used environment configuration reflections to ${require_helpers_persistence.getEnvReflectionsPath(this, "env")}.`);
						await require_helpers_persistence.writeEnvReflection(this, this.env.used.env, "env");
					}
					if (this.env.used.secrets.getProperties().length > 0) {
						this.trace(`Persisting used secret configuration reflections to ${require_helpers_persistence.getEnvReflectionsPath(this, "secrets")}.`);
						await require_helpers_persistence.writeEnvReflection(this, this.env.used.secrets, "secrets");
					}
				}
			},
			async docs() {
				this.debug(`Documenting environment variables configuration values in "${require_join_paths.joinPaths(require_helpers_docs_helper.getDocsOutputPath(this), "env.md")}"`);
				const result = await require_helpers_persistence.readEnvTypeReflection(this, "env");
				return (0, __powerlines_plugin_alloy_render.render)(this, (0, __alloy_js_core_jsx_runtime.createComponent)(require_components_docs.EnvDocsFile, {
					levelOffset: 0,
					reflection: result
				}));
			},
			async buildEnd() {
				const reflectionPath = require_helpers_persistence.getEnvReflectionsPath(this, "env");
				this.debug(`Writing env reflection types to ${reflectionPath}.`);
				await require_helpers_persistence.writeEnvReflection(this, this.env.used.env, "env");
			}
		},
		{
			name: "env:automd-generator",
			config() {
				return { automd: require_defu.defu(options.automd ?? {}, { generators: { env: require_helpers_automd_generator.env(this) } }) };
			}
		},
		{
			name: "env:vite",
			vite: { configResolved() {
				return { envPrefix: this.config?.env?.prefix };
			} }
		},
		(0, __powerlines_plugin_automd.default)(options.automd)
	];
};
var src_default = plugin;

//#endregion
exports.default = src_default;
exports.plugin = plugin;