Object.defineProperty(exports, '__esModule', { value: true });
const require_chunk = require('./chunk-CNVrAnJR.cjs');
const require_runtime = require('./runtime-g0TEIoZK.cjs');
const require_plugin = require('./plugin-CM1TSv1B.cjs');
require('./types-o3zWarRp.cjs');
const require_join_paths = require('./join-paths-Bc4rM2TX.cjs');
const require_persistence = require('./persistence-D_clXRxP.cjs');
const require_template_helpers = require('./template-helpers-YVcwxmoF.cjs');
const require_source_file_env = require('./source-file-env-4Vdtzc5-.cjs');
const require_defu = require('./defu-CrqNIh1A.cjs');
const require_load = require('./load-DPB0maqs.cjs');
require('./confbox.DA7CpUDY-r6FXRsI6.cjs');
require('./confbox.DnMsyigM-C13n3X-S.cjs');
const require_create_reflection_resource = require('./create-reflection-resource-d2zdTyOE.cjs');
require('./helpers-DgYP3uej.cjs');
const require_docs_helper = require('./docs-helper-4MoQ5-R3.cjs');
const require_automd_generator = require('./automd-generator-BNg74tyV.cjs');
const require_docs = require('./docs-ClXTdyjQ.cjs');
const require_env = require('./env-iQh74nl2.cjs');
require('./components-BUo6Koax.cjs');
const require_plugin$1 = require('./plugin-CSVnrdpE.cjs');
require('./babel-BZqmdVF4.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_chunk.__toESM(__powerlines_plugin_alloy);
let __powerlines_plugin_automd = require("@powerlines/plugin-automd");
__powerlines_plugin_automd = require_chunk.__toESM(__powerlines_plugin_automd);
let __powerlines_plugin_babel = require("@powerlines/plugin-babel");
__powerlines_plugin_babel = require_chunk.__toESM(__powerlines_plugin_babel);
let __stryke_fs_exists = require("@stryke/fs/exists");
let __stryke_string_format_constant_case = require("@stryke/string-format/constant-case");

//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/type-checks/src/get-object-tag.mjs
/**
* Gets the `toStringTag` of `obj`.
*
* @param value - The obj to query.
* @returns Returns the `toStringTag`.
*/
const getObjectTag = (value) => {
	if (value == null) return value === void 0 ? "[object Undefined]" : "[object Null]";
	return Object.prototype.toString.call(value);
};

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/type-checks/src/is-plain-object.mjs
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @example
* ```typescript
* isObjectLike({})
* // => true
*
* isObjectLike([1, 2, 3])
* // => true
*
* isObjectLike(Function)
* // => false
*
* isObjectLike(null)
* // => false
* ```
*
* @param value - The value to check.
* @returns Returns `true` if `value` is object-like, else `false`.
*/
const isObjectLike = (obj) => {
	return typeof obj === "object" && obj !== null;
};
/**
* Checks if `obj` is a plain object, that is, an object created by the `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @example
* ```typescript
* function Foo() {
*   this.a = 1
* }
*
* isPlainObject(new Foo)
* // => false
*
* isPlainObject([1, 2, 3])
* // => false
*
* isPlainObject({ 'x': 0, 'y': 0 })
* // => true
*
* isPlainObject(Object.create(null))
* // => true
* ```
*
* @param obj - The value to check.
* @returns Returns `true` if `obj` is a plain object, else `false`.
*/
const isPlainObject = (obj) => {
	if (!isObjectLike(obj) || getObjectTag(obj) !== "[object Object]") return false;
	if (Object.getPrototypeOf(obj) === null) return true;
	let proto = obj;
	while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
	return Object.getPrototypeOf(obj) === proto;
};

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/type-checks/src/is-object.mjs
/**
* Check if the provided value's type is `Object`
*
* @param value - The value to type check
* @returns An indicator specifying if the value provided is of type `Object`
*/
const isObject = (value) => {
	try {
		return typeof value === "object" || Boolean(value) && value?.constructor === Object || isPlainObject(value);
	} catch {
		return false;
	}
};

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/type-checks/src/is-string.mjs
const isString = (value) => {
	try {
		return typeof value === "string";
	} catch {
		return false;
	}
};

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/type-checks/src/is-buffer.mjs
const isBufferExists = typeof Buffer !== "undefined";
isBufferExists && Buffer.isBuffer.bind(Buffer);

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/type-checks/src/type-detect.mjs
((Obj) => {
	if (typeof globalThis === "object") return globalThis;
	Object.defineProperty(Obj, "typeDetectGlobalObject", {
		get() {
			return this;
		},
		configurable: true
	});
	return globalThis;
})(Object.prototype);

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/parse-type-definition.mjs
/**
* Parse a type definition parameter into a {@link TypeDefinition} object
*
* @param param - The parameter to parse
* @returns The parsed type definition
*/
const parseTypeDefinition = (param) => {
	if (isString(param)) {
		if (param.includes(":")) {
			const params = param.split(":");
			if (params.length > 1 && params[0]) return {
				file: params[0],
				name: params[1]
			};
		}
		if (param.includes("#")) {
			const params = param.split("#");
			if (params.length > 1 && params[0]) return {
				file: params[0],
				name: params[1]
			};
		}
		return { file: param };
	}
	if (isObject(param)) return {
		file: param.file,
		name: param.name
	};
};

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/to-array.mjs
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* @param array - The `Arrayable<T>` to convert
* @returns An `Array<T>` containing the elements of the input
*/
function toArray(array) {
	array = array ?? [];
	return Array.isArray(array) ? array : [array];
}

//#endregion
//#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: {},
						prefix: []
					}),
					transform: { babel: { plugins: [require_plugin$1.envBabelPlugin] } }
				};
				if (config.env.types) config.env.types = parseTypeDefinition(config.env.types);
				else {
					this.warn("The `env.types` configuration parameter was not provided. Please ensure this is expected.");
					const envDefaultTypeDefinition = await require_persistence.getEnvDefaultTypeDefinition(this);
					config.env.types = parseTypeDefinition(`${envDefaultTypeDefinition.file}#${envDefaultTypeDefinition.name}`);
				}
				if (config.env.secrets) config.env.secrets = parseTypeDefinition(config.env.secrets);
				else {
					const secretsDefaultTypeDefinition = await require_persistence.getSecretsDefaultTypeDefinition(this);
					config.env.secrets = parseTypeDefinition(`${secretsDefaultTypeDefinition.file}#${secretsDefaultTypeDefinition.name}`);
				}
				config.env.prefix = 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 = 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_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_persistence.getEnvTypeReflectionsPath(this, "env"))) {
					this.debug(`Skipping reflection initialization as the meta checksum has not changed.`);
					this.env.types.env = await require_persistence.readEnvTypeReflection(this, "env");
					if ((0, __stryke_fs_exists.existsSync)(require_persistence.getEnvReflectionsPath(this, "env"))) this.env.used.env = await require_persistence.readEnvReflection(this);
					if ((0, __stryke_fs_exists.existsSync)(require_persistence.getEnvTypeReflectionsPath(this, "secrets"))) this.env.types.secrets = await require_persistence.readEnvTypeReflection(this, "secrets");
					if ((0, __stryke_fs_exists.existsSync)(require_persistence.getEnvReflectionsPath(this, "secrets"))) this.env.used.secrets = await require_persistence.readSecretsReflection(this);
				} else {
					this.debug(`Starting environment configuration reflection initialization.`);
					this.env.types.env = await require_persistence.reflectEnv(this, this.config.env.types?.file ? require_persistence.isParentPath(this.config.env.types?.file, this.workspaceConfig.workspaceRoot) ? this.config.env.types?.file : require_join_paths.joinPaths(this.config.projectRoot, this.config.env.types?.file) : void 0, 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_persistence.writeEnvTypeReflection(this, this.env.types.env, "env");
					this.env.types.secrets = await require_persistence.reflectSecrets(this, this.config.env.secrets?.file ? require_persistence.isParentPath(this.config.env.secrets?.file, this.workspaceConfig.workspaceRoot) ? this.config.env.secrets?.file : require_join_paths.joinPaths(this.config.projectRoot, this.config.env.secrets?.file) : void 0, 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_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_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_persistence.writeEnvReflection(this, this.env.used.env, "env");
					if (this.env.types.secrets) {
						await require_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_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_persistence.readEnvTypeReflection(this, "env");
				return this.render((0, __alloy_js_core_jsx_runtime.createComponent)(require_env.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_persistence.getEnvReflectionsPath(this, "env")}.`);
						await require_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_persistence.getEnvReflectionsPath(this, "secrets")}.`);
						await require_persistence.writeEnvReflection(this, this.env.used.secrets, "secrets");
					}
				}
			},
			async docs() {
				this.debug(`Documenting environment variables configuration values in "${require_join_paths.joinPaths(require_docs_helper.getDocsOutputPath(this), "env.md")}"`);
				const result = await require_persistence.readEnvTypeReflection(this, "env");
				await this.render((0, __alloy_js_core_jsx_runtime.createComponent)(require_docs.EnvDocsFile, {
					levelOffset: 0,
					reflection: result
				}));
			},
			async buildEnd() {
				const reflectionPath = require_persistence.getEnvReflectionsPath(this, "env");
				this.debug(`Writing env reflection types to ${reflectionPath}.`);
				await require_persistence.writeEnvReflection(this, this.env.used.env, "env");
			}
		},
		{
			name: "env:automd-generator",
			config() {
				return { automd: require_defu.defu(options.automd ?? {}, { generators: { env: require_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.BaseEnv = require_persistence.BaseEnv;
exports.BaseSecrets = require_persistence.BaseSecrets;
exports.EnvBuiltin = require_env.EnvBuiltin;
exports.EnvDocsFile = require_docs.EnvDocsFile;
exports.EnvTypeDefinition = require_env.EnvTypeDefinition;
exports.__ΩCreateEnvReflectionOptions = require_persistence.__ΩCreateEnvReflectionOptions;
exports.__ΩEnvInterface = require_runtime.__ΩEnvInterface;
exports.__ΩEnvPluginContext = require_plugin.__ΩEnvPluginContext;
exports.__ΩEnvPluginOptions = require_plugin.__ΩEnvPluginOptions;
exports.__ΩEnvPluginResolvedConfig = require_plugin.__ΩEnvPluginResolvedConfig;
exports.__ΩEnvPluginUserConfig = require_plugin.__ΩEnvPluginUserConfig;
exports.__ΩEnvType = require_plugin.__ΩEnvType;
exports.__ΩSecretsInterface = require_runtime.__ΩSecretsInterface;
exports.createEnvReflection = require_persistence.createEnvReflection;
exports.createReflection = require_create_reflection_resource.createReflection;
exports.createSecretsReflection = require_persistence.createSecretsReflection;
exports.createTemplateReflection = require_template_helpers.createTemplateReflection;
exports.default = src_default;
exports.envBabelPlugin = require_plugin$1.envBabelPlugin;
exports.formatEnvField = require_source_file_env.formatEnvField;
exports.getEnvDefaultTypeDefinition = require_persistence.getEnvDefaultTypeDefinition;
exports.getEnvReflectionsPath = require_persistence.getEnvReflectionsPath;
exports.getEnvTypeReflectionsPath = require_persistence.getEnvTypeReflectionsPath;
exports.getSecretsDefaultTypeDefinition = require_persistence.getSecretsDefaultTypeDefinition;
exports.loadEnv = require_load.loadEnv;
exports.loadEnvFromContext = require_load.loadEnvFromContext;
exports.mergeEnvReflections = require_persistence.mergeEnvReflections;
exports.mergeSecretsReflections = require_persistence.mergeSecretsReflections;
exports.plugin = plugin;
exports.readEnvReflection = require_persistence.readEnvReflection;
exports.readEnvTypeReflection = require_persistence.readEnvTypeReflection;
exports.readSecretsReflection = require_persistence.readSecretsReflection;
exports.reflectEnv = require_persistence.reflectEnv;
exports.reflectSecrets = require_persistence.reflectSecrets;
exports.removeEnvPrefix = require_source_file_env.removeEnvPrefix;
exports.resolveRuntimeTypeFile = require_persistence.resolveRuntimeTypeFile;
exports.writeEnvReflection = require_persistence.writeEnvReflection;
exports.writeEnvReflectionSync = require_persistence.writeEnvReflectionSync;
exports.writeEnvTypeReflection = require_persistence.writeEnvTypeReflection;