import { joinPaths } from "./node_modules/.pnpm/@stryke_path@0.26.19/node_modules/@stryke/path/dist/join-paths.mjs";
import { reflectEnv, reflectSecrets } from "./helpers/reflect.mjs";
import { getEnvDefaultTypeDefinition, getEnvReflectionsPath, getEnvTypeReflectionsPath, getSecretsDefaultTypeDefinition, readEnvReflection, readEnvTypeReflection, readSecretsReflection, writeEnvReflection, writeEnvTypeReflection } from "./helpers/persistence.mjs";
import { defu } from "./node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs";
import { loadEnv } from "./helpers/load.mjs";
import { getDocsOutputPath } from "./helpers/docs-helper.mjs";
import { env } from "./helpers/automd-generator.mjs";
import { EnvDocsFile } from "./components/docs.mjs";
import { EnvBuiltin } from "./components/env-builtin.mjs";
import { envBabelPlugin } from "./babel/plugin.mjs";
import { parseTypeDefinition } from "./node_modules/.pnpm/@stryke_convert@0.6.53/node_modules/@stryke/convert/dist/parse-type-definition.mjs";
import { toArray } from "./node_modules/.pnpm/@stryke_convert@0.6.53/node_modules/@stryke/convert/dist/to-array.mjs";
import { ReflectionClass, ReflectionKind } from "@powerlines/deepkit/vendor/type";
import { ENV_PREFIXES } from "@stryke/env/types";
import { createComponent } from "@alloy-js/core/jsx-runtime";
import alloy from "@powerlines/plugin-alloy";
import { render } from "@powerlines/plugin-alloy/render";
import automd from "@powerlines/plugin-automd";
import babel from "@powerlines/plugin-babel";
import { existsSync } from "@stryke/fs/exists";
import { constantCase } from "@stryke/string-format/constant-case";
import { isSetString } from "@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 [
		alloy(options.alloy),
		babel(options.babel),
		{
			name: "env",
			async config() {
				this.debug("Providing default configuration for the Powerlines `env` build plugin.");
				const config = {
					env: defu(options, {
						types: {},
						validate: false,
						inject: false,
						prefix: []
					}),
					transform: { babel: { plugins: [envBabelPlugin] } }
				};
				if (isSetString(config.env.types) || config.env.types && isSetString(config.env.types.file)) {
					config.env.types = 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 getEnvDefaultTypeDefinition(this);
					const file = await this.fs.resolve(envDefaultTypeDefinition.file);
					if (file) config.env.types = parseTypeDefinition(`${file}#${envDefaultTypeDefinition.name}`);
				}
				if (isSetString(config.env.secrets) || config.env.secrets && isSetString(config.env.secrets.file)) {
					config.env.secrets = 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 getSecretsDefaultTypeDefinition(this);
					const file = await this.fs.resolve(secretsDefaultTypeDefinition.file);
					if (file) config.env.secrets = parseTypeDefinition(`${file}#${secretsDefaultTypeDefinition.name}`);
				}
				config.env.prefix = toArray(config.env.prefix ?? []).reduce((ret, prefix) => {
					const formattedPrefix = constantCase(prefix);
					if (!ret.includes(formattedPrefix)) ret.push(formattedPrefix);
					return ret;
				}, [
					...ENV_PREFIXES,
					"POWERLINES_",
					this.config.framework && this.config.framework !== "powerlines" && `${constantCase(this.config.framework)}_`
				].filter(Boolean));
				config.env.prefix = 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 = defu({ parsed: await 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 && existsSync(getEnvTypeReflectionsPath(this, "env"))) {
					this.debug(`Skipping reflection initialization as the meta checksum has not changed.`);
					this.env.types.env = await readEnvTypeReflection(this, "env");
					if (existsSync(getEnvReflectionsPath(this, "env"))) this.env.used.env = await readEnvReflection(this);
					if (existsSync(getEnvTypeReflectionsPath(this, "secrets"))) this.env.types.secrets = await readEnvTypeReflection(this, "secrets");
					if (existsSync(getEnvReflectionsPath(this, "secrets"))) this.env.used.secrets = await readSecretsReflection(this);
				} else {
					this.debug(`Starting environment configuration reflection initialization.`);
					this.env.types.env = await 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 writeEnvTypeReflection(this, this.env.types.env, "env");
					this.env.types.secrets = await 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 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 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 ReflectionClass({
						kind: 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 writeEnvReflection(this, this.env.used.env, "env");
					if (this.env.types.secrets) {
						await writeEnvTypeReflection(this, this.env.types.secrets, "secrets");
						this.env.used.secrets = new ReflectionClass({
							kind: 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 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 readEnvTypeReflection(this, "env");
				return render(this, createComponent(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 ${getEnvReflectionsPath(this, "env")}.`);
						await writeEnvReflection(this, this.env.used.env, "env");
					}
					if (this.env.used.secrets.getProperties().length > 0) {
						this.trace(`Persisting used secret configuration reflections to ${getEnvReflectionsPath(this, "secrets")}.`);
						await writeEnvReflection(this, this.env.used.secrets, "secrets");
					}
				}
			},
			async docs() {
				this.debug(`Documenting environment variables configuration values in "${joinPaths(getDocsOutputPath(this), "env.md")}"`);
				const result = await readEnvTypeReflection(this, "env");
				return render(this, createComponent(EnvDocsFile, {
					levelOffset: 0,
					reflection: result
				}));
			},
			async buildEnd() {
				const reflectionPath = getEnvReflectionsPath(this, "env");
				this.debug(`Writing env reflection types to ${reflectionPath}.`);
				await writeEnvReflection(this, this.env.used.env, "env");
			}
		},
		{
			name: "env:automd-generator",
			config() {
				return { automd: defu(options.automd ?? {}, { generators: { env: env(this) } }) };
			}
		},
		{
			name: "env:vite",
			vite: { configResolved() {
				return { envPrefix: this.config?.env?.prefix };
			} }
		},
		automd(options.automd)
	];
};
var src_default = plugin;

//#endregion
export { src_default as default, plugin };
//# sourceMappingURL=index.mjs.map