import { encode } from "js-base64";
import { isDefined } from "@scalar/helpers/array/is-defined";
import { objectKeys } from "@scalar/helpers/object/object-keys";
import { replaceEnvVariables } from "@scalar/helpers/regex/replace-variables";
import { getResolvedRef } from "@scalar/workspace-store/helpers/get-resolved-ref";
import { xScalarCookieSchema } from "@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies";
import { coerceValue } from "@scalar/workspace-store/schemas/typebox-coerce";
//#region src/v2/blocks/operation-block/helpers/build-request-security.ts
/**
* Get the selected security schemes from security requirements.
* Takes security requirement objects and resolves them to actual security scheme objects.
*/
var getSecuritySchemes = (securitySchemes, selectedSecurity) => selectedSecurity.flatMap((scheme) => objectKeys(scheme).flatMap((key) => {
	const scheme = getResolvedRef(securitySchemes?.[key]);
	if (scheme) return scheme;
	return [];
})) ?? [];
/**
* Generates the headers, cookies and query params for selected security schemes
* In the future we can add customization for where the security is applied
*/
var buildRequestSecurity = (selectedSecuritySchemes, env = {}, emptyTokenPlaceholder = "") => {
	const headers = {};
	const cookies = [];
	const urlParams = new URLSearchParams();
	selectedSecuritySchemes.forEach((scheme) => {
		if (scheme.type === "apiKey") {
			const name = replaceEnvVariables(scheme.name, env);
			const value = replaceEnvVariables(scheme["x-scalar-secret-token"], env) || emptyTokenPlaceholder;
			if (scheme.in === "header") headers[name] = value;
			if (scheme.in === "query") urlParams.append(name, value);
			if (scheme.in === "cookie") cookies.push(coerceValue(xScalarCookieSchema, {
				name,
				value,
				path: "/"
			}));
		}
		if (scheme.type === "http") if (scheme.scheme === "basic") {
			const value = `${replaceEnvVariables(scheme["x-scalar-secret-username"], env)}:${replaceEnvVariables(scheme["x-scalar-secret-password"], env)}`;
			headers["Authorization"] = `Basic ${value === ":" ? "username:password" : encode(value)}`;
		} else headers["Authorization"] = `Bearer ${replaceEnvVariables(scheme["x-scalar-secret-token"], env) || emptyTokenPlaceholder}`;
		if (scheme.type === "oauth2") headers["Authorization"] = `Bearer ${replaceEnvVariables(Object.values(scheme?.flows ?? {}).filter(isDefined).find((f) => f["x-scalar-secret-token"])?.["x-scalar-secret-token"] ?? "", env) || emptyTokenPlaceholder}`;
	});
	return {
		headers,
		cookies,
		urlParams
	};
};
//#endregion
export { buildRequestSecurity, getSecuritySchemes };

//# sourceMappingURL=build-request-security.js.map