import { useActiveEntities } from "../../store/active-entities.js";
import { useClientConfig } from "../../hooks/useClientConfig.js";
import { useLayout } from "../../hooks/useLayout.js";
import { useSidebar } from "../../hooks/useSidebar.js";
import { usePluginManager } from "../../plugins/hooks/usePluginManager.js";
import { ERRORS } from "../../libs/errors.js";
import { createRequestOperation } from "../../libs/send-request/create-request-operation.js";
import { useWorkspace } from "../../store/store.js";
import SidebarToggle_default from "../../components/Sidebar/SidebarToggle.vue.js";
import { validateParameters } from "../../libs/validate-parameters.js";
import { useOpenApiWatcher } from "./hooks/useOpenApiWatcher.js";
import RequestSidebar_default from "./RequestSidebar.vue.js";
import { computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createVNode, defineComponent, isRef, normalizeClass, onBeforeUnmount, onMounted, openBlock, ref, unref, watch } from "vue";
import { useToasts } from "@scalar/use-toasts";
import { RouterView } from "vue-router";
import { isDefined } from "@scalar/helpers/array/is-defined";
import { safeJSON } from "@scalar/object-utils/parse";
//#region src/views/Request/RequestRoot.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = { class: "flex h-full" };
var _hoisted_2 = { class: "flex h-full flex-1 flex-col" };
var RequestRoot_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	__name: "RequestRoot",
	emits: ["newTab"],
	setup(__props) {
		const workspaceContext = useWorkspace();
		const { toast } = useToasts();
		const { layout } = useLayout();
		const config = useClientConfig();
		const { isSidebarOpen } = useSidebar();
		const { activeCollection, activeExample, activeEnvironment, activeRequest, activeWorkspace, activeServer } = useActiveEntities();
		const { cookies, requestHistory, showSidebar, securitySchemes, modalState, events } = workspaceContext;
		const pluginManager = usePluginManager();
		/** Root element (bound in template via ref="_element") */
		const _element = ref();
		_element.value;
		const requestAbortController = ref();
		/** Computed Validation State Update on Example Change */
		const validation = computed(() => validateParameters(activeExample.value ?? null));
		const requestResult = ref(null);
		/**
		* Selected scheme UIDs
		*
		* In the modal we use collection.selectedSecuritySchemes and in the
		* standalone client we use request.selectedSecuritySchemeUids
		*
		* These are centralized here so they can be drilled down AND used in send-request
		*/
		const selectedSecuritySchemeUids = computed(() => (activeCollection.value?.useCollectionSecurity ? activeCollection.value?.selectedSecuritySchemeUids : activeRequest.value?.selectedSecuritySchemeUids) ?? []);
		/**
		* Execute the request
		* called from the send button as well as keyboard shortcuts
		*/
		const executeRequest = async () => {
			if (!activeRequest.value || !activeExample.value || !activeCollection.value) return;
			if (validation.value.hasBlockingErrors) {
				toast("Path parameters must have values.", "error");
				events.requestStatus.emit("abort");
				return;
			}
			const environmentValue = typeof activeEnvironment.value === "object" ? activeEnvironment.value.value : "{}";
			const e = safeJSON.parse(environmentValue);
			if (e.error) console.error("INVALID ENVIRONMENT!");
			const environment = e.error || typeof e.data !== "object" ? {} : e.data ?? {};
			const globalCookies = activeWorkspace.value?.cookies.map((c) => cookies[c]).filter(isDefined) ?? [];
			const server = activeCollection.value?.info?.title === "Drafts" ? void 0 : activeServer.value;
			const [error, requestOperation] = createRequestOperation({
				request: activeRequest.value,
				example: activeExample.value,
				selectedSecuritySchemeUids: selectedSecuritySchemeUids.value,
				proxyUrl: activeWorkspace.value?.proxyUrl ?? "",
				environment,
				globalCookies,
				status: events.requestStatus,
				securitySchemes,
				server,
				pluginManager
			});
			config.value?.onRequestSent?.(activeRequest.value.path ?? "");
			if (error) {
				toast(error.message, "error");
				return;
			}
			requestAbortController.value = requestOperation.controller;
			const [sendRequestError, result] = await requestOperation.sendRequest();
			requestResult.value = result;
			if (sendRequestError) toast(sendRequestError.message, "error");
			else requestHistory.push(cloneRequestResult(result));
		};
		/** Cancel a live request */
		const cancelRequest = async () => requestAbortController.value?.abort(ERRORS.REQUEST_ABORTED);
		/** Subscribed to executeRequest, used for logging / analytics. */
		function logRequest() {}
		/**
		* Cancel request when closing the modal
		* @see https://github.com/scalar/scalar/issues/7115
		*/
		watch(modalState, ({ open }) => {
			if (!open) cancelRequest();
		});
		onMounted(() => {
			events.executeRequest.on(executeRequest);
			events.executeRequest.on(logRequest);
			events.cancelRequest.on(cancelRequest);
		});
		useOpenApiWatcher();
		/**
		* Need to manually remove listener on unmount due to vueuse memory leak
		*
		* @see https://github.com/vueuse/vueuse/issues/3498#issuecomment-2055546566
		*/
		onBeforeUnmount(() => {
			events.executeRequest.off(executeRequest);
			events.executeRequest.off(logRequest);
			events.cancelRequest.off(cancelRequest);
		});
		const cloneRequestResult = (result) => {
			try {
				return structuredClone(result);
			} catch {
				const clone = { ...result };
				if (result.response?.data) if (result.response.data instanceof Blob || result.response.data instanceof ArrayBuffer) clone.response.data = result.response.data;
				else clone.response.data = JSON.parse(JSON.stringify(result.response.data));
				return clone;
			}
		};
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock("div", {
				ref_key: "_element",
				ref: _element,
				class: normalizeClass(["bg-b-1 relative z-0 flex h-full flex-1 flex-col overflow-hidden pt-0", { "!mr-0 !mb-0 !border-0": unref(layout) === "modal" }])
			}, [unref(showSidebar) ? (openBlock(), createBlock(SidebarToggle_default, {
				key: 0,
				modelValue: unref(isSidebarOpen),
				"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => isRef(isSidebarOpen) ? isSidebarOpen.value = $event : null),
				class: normalizeClass(["absolute top-2 left-3 z-50", [
					{ hidden: unref(isSidebarOpen) },
					{ "xl:!flex": !unref(isSidebarOpen) },
					{ "!flex": unref(layout) === "modal" }
				]])
			}, null, 8, ["modelValue", "class"])) : createCommentVNode("", true), createElementVNode("div", _hoisted_1, [unref(showSidebar) ? (openBlock(), createBlock(RequestSidebar_default, {
				key: 0,
				onNewTab: _cache[1] || (_cache[1] = ($event) => _ctx.$emit("newTab", $event))
			})) : createCommentVNode("", true), createElementVNode("div", _hoisted_2, [createVNode(unref(RouterView), {
				invalidParams: validation.value.invalidParams,
				requestResult: requestResult.value,
				selectedSecuritySchemeUids: selectedSecuritySchemeUids.value
			}, null, 8, [
				"invalidParams",
				"requestResult",
				"selectedSecuritySchemeUids"
			])])])], 2);
		};
	}
});
//#endregion
export { RequestRoot_vue_vue_type_script_setup_true_lang_default as default };

//# sourceMappingURL=RequestRoot.vue.script.js.map