import { n as replaceTemplateVariables } from "./string-template-sS5PtY6T.js";
import { t as buildRequestSecurity } from "./build-request-security-BQjNr2MD.js";
import { t as getSnippet } from "./get-snippet-DBRUSfZ2.js";
import { computed, createBlock, createCommentVNode, createElementBlock, defineComponent, openBlock, toDisplayString, unref } from "vue";
import { ScalarCodeBlock } from "@scalar/components";
import { REGEX, isDefined, mergeUrls } from "@scalar/oas-utils/helpers";
import { encode } from "js-base64";
//#region src/views/Components/CodeSnippet/CodeSnippet.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = {
	key: 0,
	class: "text-c-3 flex min-h-16 items-center justify-center px-4 text-sm"
};
//#endregion
//#region src/views/Components/CodeSnippet/CodeSnippet.vue
var CodeSnippet_default = /* @__PURE__ */ defineComponent({
	__name: "CodeSnippet",
	props: {
		target: {},
		client: {},
		operation: {},
		server: {},
		example: {},
		securitySchemes: { default: () => [] },
		environment: {}
	},
	setup(__props) {
		/**  Block secrets from being shown in the code block */
		const secretCredentials = computed(() => __props.securitySchemes.flatMap((scheme) => {
			if (scheme.type === "apiKey") return scheme.value;
			if (scheme?.type === "http") return [
				scheme.token,
				scheme.password,
				encode(`${scheme.username}:${scheme.password}`)
			];
			if (scheme.type === "oauth2") return Object.values(scheme.flows).map((flow) => flow?.token).filter(isDefined);
			return [];
		}));
		/** Generated code example */
		const content = computed(() => {
			const harRequest = getHarRequest({
				operation: __props.operation,
				example: __props.example,
				server: __props.server,
				securitySchemes: __props.securitySchemes,
				environment: __props.environment
			});
			const [error, payload] = getSnippet(__props.target, __props.client, harRequest);
			return {
				error,
				payload
			};
		});
		/** CodeMirror syntax highlighting language */
		const language = computed(() => {
			if (__props.target === "shell" && __props.client === "curl") return "curl";
			return __props.target ?? "plaintext";
		});
		return (_ctx, _cache) => {
			return content.value.error ? (openBlock(), createElementBlock("div", _hoisted_1, toDisplayString(content.value.error.message), 1)) : content.value.payload ? (openBlock(), createBlock(unref(ScalarCodeBlock), {
				key: 1,
				class: "w-full",
				content: content.value.payload,
				hideCredentials: secretCredentials.value,
				lang: language.value,
				lineNumbers: ""
			}, null, 8, [
				"content",
				"hideCredentials",
				"lang"
			])) : createCommentVNode("", true);
		};
	}
});
//#endregion
//#region src/views/Components/CodeSnippet/helpers/convert-to-har-request.ts
/**
* Takes in a regular request object and returns a HAR request
* We also Titlecase the headers and remove accept header if it's *
*/
var convertToHarRequest = ({ baseUrl = "", method, body, path, cookies, headers, query }) => {
	const url = mergeUrls(baseUrl, path, void 0, true);
	const harRequest = {
		method: method.toUpperCase(),
		url: url.toString(),
		httpVersion: "HTTP/1.1",
		headers: [],
		queryString: [],
		cookies: [],
		headersSize: -1,
		bodySize: -1
	};
	if (cookies.length) harRequest.cookies = cookies.filter((c) => c.enabled).map(({ key, value }) => ({
		name: key,
		value
	}));
	if (headers.length) harRequest.headers = headers.filter((h) => h.enabled && !(h.key.toLowerCase() === "accept" && h.value === "*/*")).map(({ key, value }) => ({
		name: key.replace(/\b\w/g, (letter) => letter.toUpperCase()),
		value
	}));
	if (query.length) harRequest.queryString = query.filter((q) => q.enabled).map(({ key, value }) => ({
		name: key,
		value
	}));
	if (body) try {
		const contentType = headers.find((h) => h.key.toLowerCase() === "content-type")?.value;
		if (body.activeBody === "formData" && body.formData) {
			const params = [];
			body.formData.value.forEach(({ key, value, file, enabled }) => {
				if (!enabled) return;
				if (file) params.push({
					name: key || "blob",
					value: "BINARY",
					fileName: file.name,
					contentType: file.type || "application/octet-stream"
				});
				else params.push({
					name: key,
					value
				});
			});
			if (body.formData?.encoding === "urlencoded") harRequest.postData = {
				mimeType: contentType || "application/x-www-form-urlencoded",
				params
			};
			else harRequest.postData = {
				mimeType: contentType || "multipart/form-data",
				params
			};
		} else if (body.activeBody === "raw" && body.raw) harRequest.postData = {
			mimeType: contentType || "application/json",
			text: body.raw?.value ?? ""
		};
	} catch (_e) {}
	return harRequest;
};
//#endregion
//#region src/views/Components/CodeSnippet/helpers/get-har-request.ts
var EMPTY_TOKEN_PLACEHOLDER = "YOUR_SECRET_TOKEN";
/**
* Creates a snippetz-compatible HarRequest from OpenAPI-like store entities
*
* @deprecated, can be removed once we've migrated to the new code snippet component
*/
var getHarRequest = ({ operation, example, server, securitySchemes = [], environment }) => {
	const env = environment && Array.isArray(environment) ? Object.fromEntries(environment.map((v) => [v.key, v.value])) : environment || {};
	const encodedPathVars = (example?.parameters?.path ?? []).reduce((vars, param) => {
		if (param.enabled) {
			const substitutedValue = replaceTemplateVariables(param.value, env);
			vars[param.key] = encodeURIComponent(substitutedValue);
		}
		return vars;
	}, {});
	const serverString = (() => {
		if (server?.url && (REGEX.VARIABLES.test(server.url) || REGEX.PATH.test(server.url))) {
			const serverParams = Object.entries(server?.variables || {}).reduce((acc, [key, variable]) => {
				if (encodedPathVars[key]) acc[key] = encodedPathVars[key];
				else if (variable.default) acc[key] = replaceTemplateVariables(variable.default, env);
				return acc;
			}, {});
			return replaceTemplateVariables(replaceTemplateVariables(server.url, env), serverParams);
		}
		return server?.url;
	})();
	const pathString = (() => {
		const path = operation?.path ?? "/";
		if (path && (REGEX.VARIABLES.test(path) || REGEX.PATH.test(path))) return replaceTemplateVariables(replaceTemplateVariables(path, env), encodedPathVars);
		return path;
	})();
	const security = buildRequestSecurity(securitySchemes, env, EMPTY_TOKEN_PLACEHOLDER);
	const headers = [...(example?.parameters.headers ?? []).map((h) => ({
		...h,
		value: REGEX.VARIABLES.test(h.value) || REGEX.PATH.test(h.value) ? replaceTemplateVariables(h.value, env) : h.value
	})) ?? [], ...Object.entries(security.headers).map(([key, value]) => ({
		key,
		value,
		enabled: true
	}))];
	const cookies = [...(example?.parameters.cookies ?? []).map((c) => ({
		...c,
		value: REGEX.VARIABLES.test(c.value) || REGEX.PATH.test(c.value) ? replaceTemplateVariables(c.value, env) : c.value
	})) ?? [], ...security.cookies.map((cookie) => ({
		key: cookie.name,
		value: cookie.value,
		enabled: true
	}))];
	const query = [...(example?.parameters.query ?? []).map((q) => ({
		...q,
		value: REGEX.VARIABLES.test(q.value) || REGEX.PATH.test(q.value) ? replaceTemplateVariables(q.value, env) : q.value
	})) ?? [], ...Array.from(security.urlParams.entries()).map(([key, value]) => ({
		key,
		value,
		enabled: true
	}))];
	const body = (() => {
		const body = example?.body;
		if (body?.raw?.value && (REGEX.VARIABLES.test(body.raw.value) || REGEX.PATH.test(body.raw.value))) return {
			...body,
			raw: {
				...body.raw,
				value: replaceTemplateVariables(body.raw.value, env)
			}
		};
		return body;
	})();
	return convertToHarRequest({
		baseUrl: serverString,
		method: operation?.method ?? "get",
		path: pathString,
		body,
		cookies,
		headers,
		query
	});
};
//#endregion
export { convertToHarRequest as n, CodeSnippet_default as r, getHarRequest as t };

//# sourceMappingURL=CodeSnippet-D7Heh1nd.js.map