import { m as isUrl$1, r as useWorkspace, w as useActiveEntities } from "./store-DpSUVhjp.js";
import { t as WatchModeToggle_default } from "./WatchModeToggle-D_eAiTWJ.js";
import { t as IntegrationLogo_default } from "./IntegrationLogo-B9EDW8db.js";
import { Fragment, Transition, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, nextTick, normalizeClass, onBeforeUnmount, onMounted, onUnmounted, openBlock, reactive, ref, renderList, renderSlot, toDisplayString, unref, vModelText, watch, withCtx, withDirectives, withModifiers } from "vue";
import { ScalarButton, ScalarDropdown, ScalarDropdownDivider, ScalarDropdownItem, ScalarIcon, ScalarModal, useModal } from "@scalar/components";
import { getThemeStyles, themeIds } from "@scalar/themes";
import { useColorMode } from "@scalar/use-hooks/useColorMode";
import { useToasts } from "@scalar/use-toasts";
import { useRouter } from "vue-router";
import { fetchWithProxyFallback, isLocalUrl } from "@scalar/oas-utils/helpers";
import { redirectToProxy } from "@scalar/helpers/url/redirect-to-proxy";
import { normalize } from "@scalar/openapi-parser";
import { resolve } from "@scalar/import";
import { parse } from "yaml";
//#region src/components/ImportCollection/utils/workspace-store-is-empty.ts
/**
* Checks whether the store is empty.
*/
function workspaceStoreIsEmpty(store) {
	const hasSingleWorkspace = Object.keys(store.workspaces).length === 1;
	const hasSingleCollection = Object.keys(store.collections).length === 1;
	return hasSingleWorkspace && hasSingleCollection;
}
//#endregion
//#region src/components/ImportCollection/DropEventListener.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$3 = {
	key: 0,
	class: "bg-b-2 fixed right-1/2 bottom-1/2 z-50 h-64 w-64 translate-x-1/2 translate-y-1/2 rounded-xl border transition-opacity duration-200 md:right-10 md:bottom-10 md:translate-x-0 md:translate-y-0"
};
var _hoisted_2$3 = { class: "flex h-full flex-col items-center justify-center" };
//#endregion
//#region src/components/ImportCollection/DropEventListener.vue
var DropEventListener_default = /* @__PURE__ */ defineComponent({
	__name: "DropEventListener",
	emits: ["input"],
	setup(__props, { emit: __emit }) {
		const emit = __emit;
		const isDragging = ref(false);
		let dragCounter = 0;
		onMounted(() => {
			document.addEventListener("dragenter", handleDragEnter);
			document.addEventListener("dragleave", handleDragLeave);
			document.addEventListener("dragover", handleDragOver);
			document.addEventListener("drop", handleDrop);
		});
		onBeforeUnmount(() => {
			document.removeEventListener("dragenter", handleDragEnter);
			document.removeEventListener("dragover", handleDragOver);
			document.removeEventListener("dragleave", handleDragLeave);
			document.removeEventListener("drop", handleDrop);
		});
		function isFromApp(event) {
			return event.dataTransfer?.types.includes("text/html") ?? false;
		}
		function handleDrop(event) {
			event.preventDefault();
			isDragging.value = false;
			dragCounter = 0;
			if (isFromApp(event)) return;
			if (event.dataTransfer) {
				const droppedText = event.dataTransfer.getData("text").replace(/^blob:/, "");
				if (droppedText) emit("input", droppedText, null, "drop");
				else if (event.dataTransfer.files.length > 0) {
					const file = event.dataTransfer.files[0];
					if (!file) return;
					const reader = new FileReader();
					reader.onload = (e) => {
						if (e.target && typeof e.target.result === "string") emit("input", e.target.result, null, "drop");
					};
					reader.readAsText(file);
				}
			}
		}
		function handleDragOver(event) {
			event.preventDefault();
		}
		function handleDragLeave(event) {
			event.preventDefault();
			dragCounter--;
			if (dragCounter === 0) isDragging.value = false;
		}
		function handleDragEnter(event) {
			event.preventDefault();
			dragCounter++;
			if (isFromApp(event)) return;
			if (event.dataTransfer) {
				const items = event.dataTransfer.items;
				for (const item of items) if (item?.kind === "string" || item?.type?.includes("json") || item?.type?.includes("yml") || item?.type?.includes("yaml")) {
					isDragging.value = true;
					return;
				}
			}
			isDragging.value = false;
		}
		return (_ctx, _cache) => {
			return openBlock(), createBlock(Transition, {
				enterActiveClass: "transition-opacity duration-200",
				enterFromClass: "opacity-0",
				leaveActiveClass: "transition-opacity duration-200",
				leaveToClass: "opacity-0"
			}, {
				default: withCtx(() => [isDragging.value ? (openBlock(), createElementBlock("div", _hoisted_1$3, [createElementVNode("div", _hoisted_2$3, [createElementVNode("div", null, [createVNode(unref(ScalarIcon), {
					icon: "Download",
					size: "xl",
					thickness: "2"
				})]), _cache[0] || (_cache[0] = createElementVNode("div", { class: "text-c-1 m-4 text-center" }, " Drop your OpenAPI document here ", -1))])])) : createCommentVNode("", true)]),
				_: 1
			});
		};
	}
});
//#endregion
//#region src/components/ImportCollection/hooks/useUrlPrefetcher.ts
/**
* Vue composable for URL prefetching
*/
function useUrlPrefetcher() {
	const prefetchResult = reactive({
		state: "idle",
		content: null,
		url: null,
		input: null,
		error: null
	});
	function resetPrefetchResult() {
		Object.assign(prefetchResult, {
			state: "idle",
			content: null,
			url: null,
			input: null,
			error: null
		});
	}
	async function prefetchUrl(input, proxyUrl) {
		if (!input) return {
			state: "idle",
			content: null,
			url: null,
			input,
			error: null
		};
		try {
			const urlOrDocument = await resolve(input, { fetch: (url) => {
				return fetch(proxyUrl ? redirectToProxy(proxyUrl, url) : url, { cache: "no-cache" });
			} });
			if (typeof urlOrDocument === "object" && urlOrDocument !== null) return {
				state: "idle",
				content: JSON.stringify(urlOrDocument, null, 2),
				url: null,
				error: null
			};
			if (urlOrDocument === void 0) return {
				state: "idle",
				content: null,
				url: null,
				input,
				error: `Could not find an OpenAPI document in ${input}`
			};
			if (!isUrl$1(urlOrDocument)) return {
				state: "idle",
				content: null,
				url: null,
				input,
				error: "Oops, we got invalid content for the given URL."
			};
			const url = urlOrDocument;
			const result = await fetchWithProxyFallback(url, {
				proxyUrl,
				cache: "no-cache"
			});
			if (!result.ok) return {
				state: "idle",
				content: null,
				url: null,
				input,
				error: `Couldn't fetch ${url}, got error ${[result.status, result.statusText].join(" ").trim()}.`
			};
			return {
				state: "idle",
				content: await result.text(),
				url,
				error: null
			};
		} catch (error) {
			console.error("[prefetchDocument]", error);
			return {
				state: "idle",
				content: null,
				url: null,
				input,
				error: error.message
			};
		}
	}
	async function prefetchUrlAndUpdateState(input, proxyUrl) {
		Object.assign(prefetchResult, {
			state: "loading",
			content: null,
			url: null,
			input,
			error: null
		});
		const result = await prefetchUrl(input, proxyUrl);
		Object.assign(prefetchResult, result);
		return result;
	}
	return {
		prefetchResult,
		prefetchUrl: prefetchUrlAndUpdateState,
		resetPrefetchResult
	};
}
//#endregion
//#region src/components/ImportCollection/utils/is-url.ts
/**
* Checks whether the given string is an URL
**/
function isUrl(input) {
	if (!input) return false;
	const trimmed = input.trim();
	if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) return false;
	return trimmed.replace(/^https?:\/\//, "").length > 0;
}
//#endregion
//#region src/components/ImportCollection/utils/import-collection.ts
async function importCollection({ store, workspace, source, watchMode, onSuccess, onError }) {
	try {
		if (source && workspace) {
			if (isUrl(source)) {
				const [error, entities] = await store.importSpecFromUrl(source, workspace.uid, {
					proxyUrl: workspace.proxyUrl,
					watchMode
				});
				if (!error) onSuccess(entities?.collection);
				return;
			}
			onSuccess((await store.importSpecFile(source, workspace.uid))?.collection);
		}
	} catch (error) {
		onError(error);
	}
}
//#endregion
//#region src/components/ImportCollection/ImportNowButton.vue
var ImportNowButton_default = /* @__PURE__ */ defineComponent({
	__name: "ImportNowButton",
	props: {
		source: {},
		variant: {},
		watchMode: {
			type: Boolean,
			default: true
		}
	},
	emits: ["importFinished"],
	setup(__props, { emit: __emit }) {
		const emit = __emit;
		const router = useRouter();
		const store = useWorkspace();
		const { activeWorkspace } = useActiveEntities();
		const { toast } = useToasts();
		function handleImportCollection() {
			importCollection({
				store,
				workspace: activeWorkspace.value,
				source: __props.source,
				watchMode: __props.watchMode,
				onSuccess(collection) {
					if (collection) {
						redirectToFirstRequestInCollection(collection);
						toast("Import successful", "info");
						emit("importFinished");
					}
				},
				onError(error) {
					console.error("[importCollection]", error);
					toast(`Import failed: ${error?.message || "Unknown error"}`, "error");
				}
			});
		}
		function redirectToFirstRequestInCollection(collection) {
			if (!collection) return;
			router.push({
				name: "request",
				params: {
					workspace: activeWorkspace.value?.uid,
					request: collection?.requests[0]
				}
			});
		}
		return (_ctx, _cache) => {
			return __props.source ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [__props.variant === "button" ? (openBlock(), createBlock(unref(ScalarButton), {
				key: 0,
				class: "mt-3 h-fit w-full rounded-lg px-6 py-2.5 font-bold",
				size: "md",
				type: "button",
				onClick: handleImportCollection
			}, {
				default: withCtx(() => [..._cache[0] || (_cache[0] = [createTextVNode(" Import Collection ", -1)])]),
				_: 1
			})) : (openBlock(), createBlock(unref(ScalarButton), {
				key: 1,
				class: "h-fit rounded-lg px-6 py-2.5 text-[21px] font-bold",
				size: "md",
				type: "button",
				variant: "ghost",
				onClick: handleImportCollection
			}, {
				default: withCtx(() => [..._cache[1] || (_cache[1] = [createTextVNode(" Try it in the browser ", -1)])]),
				_: 1
			}))], 64)) : createCommentVNode("", true);
		};
	}
});
//#endregion
//#region src/components/ImportCollection/PrefetchError.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$2 = { class: "w-full text-center text-sm font-medium break-words" };
var _hoisted_2$2 = ["href"];
var _hoisted_3$2 = {
	key: 1,
	textContent: "OpenAPI document manually"
};
//#endregion
//#region src/components/ImportCollection/PrefetchError.vue
var PrefetchError_default = /* @__PURE__ */ defineComponent({
	__name: "PrefetchError",
	props: { url: {} },
	setup(__props) {
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock("div", _hoisted_1$2, [
				_cache[0] || (_cache[0] = createTextVNode(" We couldn't find an OpenAPI document at the provided URL. Please download and import the ", -1)),
				__props.url && unref(isUrl$1)(__props.url) ? (openBlock(), createElementBlock("a", {
					key: 0,
					href: __props.url,
					rel: "noopener nofollow",
					target: "_blank",
					textContent: "OpenAPI document manually"
				}, null, 8, _hoisted_2$2)) : (openBlock(), createElementBlock("span", _hoisted_3$2)),
				_cache[1] || (_cache[1] = createTextVNode(". ", -1))
			]);
		};
	}
});
//#endregion
//#region src/components/ImportCollection/utils/is-document.ts
/** Checks whether the given string could be an OpenAPI document */
function isDocument(input) {
	if (!input || input.trim().length === 0) return false;
	const trimmed = input.trim();
	if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) return false;
	return true;
}
//#endregion
//#region src/components/ImportCollection/utils/get-openapi-version.ts
/**
* Get the Swagger/OpenAPI version and format from the given string
*/
function getOpenApiVersion(input) {
	if (!isDocument(input)) return false;
	try {
		const result = JSON.parse(input ?? "");
		if (typeof result?.openapi === "string") return `OpenAPI ${result.openapi} JSON`;
		if (typeof result?.swagger === "string") return `Swagger ${result.swagger} JSON`;
		return false;
	} catch {}
	try {
		const result = parse(input ?? "");
		if (typeof result?.openapi === "string") return `OpenAPI ${result.openapi} YAML`;
		if (typeof result?.swagger === "string") return `Swagger ${result.swagger} YAML`;
		return false;
	} catch {}
	return false;
}
//#endregion
//#region src/components/ImportCollection/WorkspaceSelector.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$1 = { class: "flex w-[inherit] items-center text-base" };
var _hoisted_2$1 = { class: "m-0 flex items-center gap-1 text-sm font-medium" };
var _hoisted_3$1 = { class: "line-clamp-1 w-[calc(100%-10px)] text-left text-xs" };
var _hoisted_4$1 = { class: "overflow-hidden text-ellipsis" };
var _hoisted_5$1 = { class: "flex h-4 w-4 items-center justify-center" };
//#endregion
//#region src/components/ImportCollection/WorkspaceSelector.vue
var WorkspaceSelector_default = /* @__PURE__ */ defineComponent({
	__name: "WorkspaceSelector",
	setup(__props) {
		const { activeWorkspace } = useActiveEntities();
		const { workspaces, workspaceMutators } = useWorkspace();
		const { push } = useRouter();
		const modal = useModal();
		const { toast } = useToasts();
		const workspaceName = ref("");
		const updateSelected = (uid) => {
			if (uid === activeWorkspace.value?.uid) return;
			push({
				name: "workspace",
				params: { workspace: uid }
			});
		};
		const handleCreateWorkspace = () => {
			if (!workspaceName.value.trim()) {
				toast("Please enter a name before creating a workspace.", "error");
				return;
			}
			const newWorkspace = workspaceMutators.add({ name: workspaceName.value });
			toast(`Created new workspace '${newWorkspace.name}'`);
			push({
				name: "workspace",
				params: { workspace: newWorkspace.uid }
			});
			workspaceName.value = "";
			modal.hide();
		};
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock(Fragment, null, [createElementVNode("div", _hoisted_1$1, [createVNode(unref(ScalarDropdown), null, {
				items: withCtx(() => [
					(openBlock(true), createElementBlock(Fragment, null, renderList(unref(workspaces), (workspace, uid) => {
						return openBlock(), createBlock(unref(ScalarDropdownItem), {
							key: uid,
							class: "group/item flex w-full items-center gap-1.5 overflow-hidden text-ellipsis whitespace-nowrap",
							onClick: withModifiers(($event) => updateSelected(uid), ["stop"])
						}, {
							default: withCtx(() => [createElementVNode("div", { class: normalizeClass(["flex h-4 w-4 items-center justify-center rounded-full p-[3px]", unref(activeWorkspace)?.uid === uid ? "bg-c-accent text-b-1" : "shadow-border text-transparent"]) }, [createVNode(unref(ScalarIcon), {
								class: "size-2.5",
								icon: "Checkmark",
								thickness: "3"
							})], 2), createElementVNode("span", _hoisted_4$1, toDisplayString(workspace.name), 1)]),
							_: 2
						}, 1032, ["onClick"]);
					}), 128)),
					createVNode(unref(ScalarDropdownDivider)),
					createVNode(unref(ScalarDropdownItem), {
						class: "flex items-center gap-1.5",
						onClick: _cache[0] || (_cache[0] = ($event) => unref(modal).show())
					}, {
						default: withCtx(() => [createElementVNode("div", _hoisted_5$1, [createVNode(unref(ScalarIcon), {
							icon: "Add",
							size: "sm"
						})]), _cache[2] || (_cache[2] = createElementVNode("span", null, "New Workspace", -1))]),
						_: 1
					})
				]),
				default: withCtx(() => [createVNode(unref(ScalarButton), {
					class: "hover:bg-b-2 text-c-3 line-clamp-1 h-full w-fit justify-start px-1.5 py-1 font-normal",
					variant: "ghost"
				}, {
					default: withCtx(() => [createElementVNode("div", _hoisted_2$1, [createElementVNode("h2", _hoisted_3$1, toDisplayString(unref(activeWorkspace)?.name), 1), createVNode(unref(ScalarIcon), {
						icon: "ChevronDown",
						size: "md"
					})])]),
					_: 1
				})]),
				_: 1
			})]), createVNode(unref(ScalarModal), {
				bodyClass: "m-0 p-1 rounded-lg border-t-0",
				class: "z-overlay absolute",
				size: "xxs",
				state: unref(modal),
				variant: "form"
			}, {
				default: withCtx(() => [createElementVNode("form", {
					class: "flex gap-1",
					onSubmit: withModifiers(handleCreateWorkspace, ["prevent"])
				}, [withDirectives(createElementVNode("input", {
					"onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => workspaceName.value = $event),
					class: "min-h-8 w-full flex-1 border-none p-1.5 text-sm outline-none",
					placeholder: "New Workspace",
					type: "text"
				}, null, 512), [[vModelText, workspaceName.value]]), createVNode(unref(ScalarButton), {
					class: "max-h-8 p-0 px-3 text-xs",
					disabled: !workspaceName.value.trim(),
					type: "submit"
				}, {
					default: withCtx(() => [..._cache[3] || (_cache[3] = [createTextVNode(" Continue ", -1)])]),
					_: 1
				}, 8, ["disabled"])], 32)]),
				_: 1
			}, 8, ["state"])], 64);
		};
	}
});
//#endregion
//#region src/components/ImportCollection/ImportCollectionModal.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = ["innerHTML"];
var _hoisted_2 = { class: "relative flex h-screen flex-col justify-center overflow-hidden px-6 md:px-0" };
var _hoisted_3 = {
	key: 0,
	class: "mb-2 flex items-center justify-center p-1"
};
var _hoisted_4 = { class: "size-10 rounded-xl" };
var _hoisted_5 = ["src"];
var _hoisted_6 = {
	key: 2,
	class: "text-md mb-2 line-clamp-1 text-center font-bold"
};
var _hoisted_7 = { class: "z-10 inline-flex w-full flex-col items-center gap-2" };
var _hoisted_8 = { class: "flex justify-center" };
var _hoisted_9 = { class: "text-c-3 inline-flex items-center px-4 py-1 text-xs font-medium" };
var _hoisted_10 = {
	key: 0,
	class: "mt-5 overflow-hidden border-t pt-4 text-sm"
};
var _hoisted_11 = { class: "flex items-center justify-center" };
var _hoisted_12 = { class: "flex flex-col items-center justify-center pb-8" };
var _hoisted_13 = { class: "flex flex-col items-center text-center" };
var _hoisted_14 = { class: "mb-2 flex h-10 w-10 items-center justify-center rounded-[10px] border" };
var _hoisted_15 = {
	href: "https://scalar.com/download",
	target: "_blank"
};
//#endregion
//#region src/components/ImportCollection/ImportCollectionModal.vue
var ImportCollectionModal_default = /* @__PURE__ */ defineComponent({
	__name: "ImportCollectionModal",
	props: {
		source: {},
		integration: {},
		eventType: {}
	},
	emits: ["importFinished"],
	setup(__props, { emit: __emit }) {
		const props = __props;
		const emits = __emit;
		const { activeWorkspace } = useActiveEntities();
		const { workspaceMutators, events } = useWorkspace();
		const { prefetchResult, prefetchUrl, resetPrefetchResult } = useUrlPrefetcher();
		const modalState = useModal();
		const watchMode = ref(true);
		/** Close modal when a keyboard shortcut is pressed */
		events.hotKeys.on(() => modalState.hide());
		/** Try to make the retrieved content an OpenAPI document */
		const openApiDocument = computed(() => {
			try {
				return normalize(prefetchResult.content || props.source || "");
			} catch {
				return;
			}
		});
		/** Title from the OpenAPI document */
		const title = computed(() => openApiDocument.value?.info?.title);
		/** The OpenAPI/Swagger version */
		const version = computed(() => getOpenApiVersion(prefetchResult.content || props.source || ""));
		const { darkLightMode } = useColorMode();
		const { currentRoute } = useRouter();
		/** Grab light and dark logos from the url query params */
		const companyLogo = computed(() => {
			try {
				const query = currentRoute.value.query;
				const logo = darkLightMode.value === "dark" ? query.dark_logo : query.light_logo;
				if (logo) return decodeURIComponent(logo);
			} catch {}
			return null;
		});
		/** Open/close modal on events  */
		watch(() => props.source, async (value) => {
			resetPrefetchResult();
			if (isUrl(value)) {
				if (props.eventType && ["paste", "drop"].includes(props.eventType)) {
					const { error } = await prefetchUrl(value, activeWorkspace.value?.proxyUrl);
					if (error) modalState.hide();
					else modalState.show();
					return;
				}
				prefetchUrl(value, activeWorkspace.value?.proxyUrl);
				modalState.show();
				return;
			}
			if (!value) modalState.hide();
			else if (isDocument(value) && getOpenApiVersion(value)) modalState.show();
			else modalState.hide();
		});
		const hasUrl = computed(() => !!props.source && isUrl(props.source));
		const hasContent = computed(() => !!props.source && isDocument(props.source));
		/** Show the integration icon only for local URLs */
		const shouldShowIntegrationIcon = computed(() => {
			return prefetchResult.url && isLocalUrl(prefetchResult.url);
		});
		const toggleBodyClass = (add) => {
			document.body.classList.remove("has-no-import-url");
			if (add && (hasUrl.value || hasContent.value) && modalState.open) document.body.classList.add("has-import-url");
			else document.body.classList.remove("has-import-url");
		};
		/** Toggles the 'has-import-url' class on the body element */
		const closeModal = () => {
			document.body.classList.remove("has-import-url");
			document.body.classList.add("has-no-import-url");
		};
		watch(() => modalState.open, (isOpen) => {
			if (isOpen) toggleBodyClass(true);
			else closeModal();
		});
		watch(() => props.source, () => {
			toggleBodyClass(true);
		});
		onMounted(() => {
			toggleBodyClass(true);
		});
		onUnmounted(() => {
			document.body.classList.remove("has-import-url");
			document.body.classList.remove("has-no-import-url");
		});
		const themeStyleTag = computed(() => activeWorkspace.value && shouldShowIntegrationIcon.value && props.integration && `<style>${getThemeStyles(props.integration)}</style>`);
		function handleImportFinished() {
			const isIntegrationThemeId = (value) => themeIds.includes(value);
			const integrationThemeId = props.integration && isIntegrationThemeId(props.integration) ? props.integration : "default";
			if (shouldShowIntegrationIcon.value) workspaceMutators.edit(activeWorkspace.value?.uid, "themeId", integrationThemeId);
			emits("importFinished");
		}
		return (_ctx, _cache) => {
			return openBlock(), createBlock(unref(ScalarModal), {
				size: "full",
				state: unref(modalState)
			}, {
				default: withCtx(() => [themeStyleTag.value ? (openBlock(), createElementBlock("div", {
					key: 0,
					innerHTML: themeStyleTag.value
				}, null, 8, _hoisted_1)) : createCommentVNode("", true), createElementVNode("div", _hoisted_2, [
					_cache[6] || (_cache[6] = createElementVNode("div", { class: "section-flare" }, [
						createElementVNode("div", { class: "section-flare-item" }),
						createElementVNode("div", { class: "section-flare-item" }),
						createElementVNode("div", { class: "section-flare-item" }),
						createElementVNode("div", { class: "section-flare-item" }),
						createElementVNode("div", { class: "section-flare-item" }),
						createElementVNode("div", { class: "section-flare-item" }),
						createElementVNode("div", { class: "section-flare-item" }),
						createElementVNode("div", { class: "section-flare-item" })
					], -1)),
					createElementVNode("div", { class: normalizeClass(["m-auto flex w-full max-w-[380px] flex-col items-center rounded-xl border px-8 py-8 transition-opacity", { "opacity-0": unref(prefetchResult).state === "loading" }]) }, [unref(prefetchResult).error && unref(prefetchResult).state === "idle" && !version.value ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [_cache[1] || (_cache[1] = createElementVNode("div", { class: "text-md mb-2 line-clamp-1 text-center font-bold" }, " No OpenAPI document found ", -1)), createVNode(PrefetchError_default, { url: unref(prefetchResult)?.input || props.source }, null, 8, ["url"])], 64)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
						shouldShowIntegrationIcon.value ? (openBlock(), createElementBlock("div", _hoisted_3, [createElementVNode("div", _hoisted_4, [createVNode(IntegrationLogo_default, { integration: __props.integration }, null, 8, ["integration"])])])) : companyLogo.value ? (openBlock(), createElementBlock("img", {
							key: 1,
							alt: "Logo",
							class: "mb-2 w-full object-contain",
							src: companyLogo.value
						}, null, 8, _hoisted_5)) : createCommentVNode("", true),
						!companyLogo.value ? (openBlock(), createElementBlock("div", _hoisted_6, toDisplayString(title.value || "Untitled Collection"), 1)) : createCommentVNode("", true),
						_cache[4] || (_cache[4] = createElementVNode("div", { class: "text-c-1 text-center text-sm font-medium text-balance" }, " Import the OpenAPI document to instantly send API requests. No signup required. ", -1)),
						version.value ? (openBlock(), createElementBlock(Fragment, { key: 3 }, [
							createElementVNode("div", _hoisted_7, [createVNode(ImportNowButton_default, {
								source: unref(prefetchResult)?.url ?? unref(prefetchResult)?.content ?? __props.source,
								variant: "button",
								watchMode: watchMode.value,
								onImportFinished: handleImportFinished
							}, null, 8, ["source", "watchMode"])]),
							createElementVNode("div", _hoisted_8, [createElementVNode("div", _hoisted_9, [_cache[2] || (_cache[2] = createTextVNode(" Import to: ", -1)), createVNode(WorkspaceSelector_default)])]),
							unref(prefetchResult)?.url ? (openBlock(), createElementBlock("div", _hoisted_10, [createElementVNode("div", _hoisted_11, [createVNode(WatchModeToggle_default, {
								modelValue: watchMode.value,
								"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => watchMode.value = $event),
								disableToolTip: true
							}, null, 8, ["modelValue"])]), _cache[3] || (_cache[3] = createElementVNode("div", { class: "text-c-3 pt-0 text-center text-xs font-medium text-balance" }, " Automatically update your API client when the OpenAPI document content changes. ", -1))])) : createCommentVNode("", true)
						], 64)) : createCommentVNode("", true)
					], 64))], 2),
					createElementVNode("div", _hoisted_12, [createElementVNode("div", _hoisted_13, [createElementVNode("div", _hoisted_14, [createElementVNode("a", _hoisted_15, [createVNode(unref(ScalarIcon), {
						icon: "Logo",
						size: "xl"
					})])]), _cache[5] || (_cache[5] = createElementVNode("span", { class: "text-c-2 text-sm leading-snug font-medium" }, [
						createElementVNode("a", {
							class: "hover:text-c-1 mb-1 inline-block underline-offset-2",
							href: "https://scalar.com/download",
							target: "_blank"
						}, " Download Desktop App "),
						createElementVNode("br"),
						createTextVNode(" free · open-source · offline first ")
					], -1))])])
				])]),
				_: 1
			}, 8, ["state"]);
		};
	}
});
//#endregion
//#region src/components/ImportCollection/PasteEventListener.vue
var PasteEventListener_default = /* @__PURE__ */ defineComponent({
	__name: "PasteEventListener",
	emits: ["input"],
	setup(__props, { emit: __emit }) {
		const emit = __emit;
		onMounted(() => {
			document.addEventListener("paste", handlePaste);
		});
		onBeforeUnmount(() => {
			document.removeEventListener("paste", handlePaste);
		});
		function handlePaste(event) {
			const target = event.target;
			const isCodeMirror = Boolean(document.activeElement?.classList.contains("cm-content"));
			if (target && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable || isCodeMirror)) return;
			if (event.clipboardData) {
				const pastedText = event.clipboardData.getData("text");
				if (pastedText) emit("input", pastedText, null, "paste");
			}
		}
		return (_ctx, _cache) => {
			return null;
		};
	}
});
//#endregion
//#region src/components/ImportCollection/UrlQueryParameterChecker.vue
var UrlQueryParameterChecker_default = /* @__PURE__ */ defineComponent({
	__name: "UrlQueryParameterChecker",
	emits: ["input"],
	setup(__props, { emit: __emit }) {
		const emit = __emit;
		onMounted(() => {
			const queryParameters = new URLSearchParams(window.location.search);
			const urlQueryParameter = queryParameters.get("url");
			if (urlQueryParameter) emit("input", urlQueryParameter, queryParameters.get("integration"), "query");
		});
		return (_ctx, _cache) => {
			return null;
		};
	}
});
//#endregion
//#region src/components/ImportCollection/ImportCollectionListener.vue
var ImportCollectionListener_default = /* @__PURE__ */ defineComponent({
	__name: "ImportCollectionListener",
	setup(__props) {
		const store = useWorkspace();
		/** Source to import from */
		const source = ref(null);
		const integration = ref(null);
		const eventType = ref(null);
		/** Reset the data when the modal was closed */
		async function resetData() {
			source.value = null;
			integration.value = null;
			eventType.value = null;
			await nextTick();
		}
		/** Receive data from the paste event listener */
		async function handleInput(newSource, newIntegration = null, newEventType) {
			await resetData();
			if (workspaceStoreIsEmpty(store)) {
				console.info("Workspace store is empty, directly importing:", newSource);
				if (await handleImportCollection(newSource)) return;
				console.warn("Failed to import the collection from:", newSource);
			}
			source.value = newSource;
			integration.value = newIntegration;
			eventType.value = newEventType;
		}
		const router = useRouter();
		const { activeWorkspace } = useActiveEntities();
		const { toast } = useToasts();
		function handleImportCollection(source) {
			if (!source) return Promise.resolve(false);
			return new Promise((resolve) => {
				importCollection({
					store,
					workspace: activeWorkspace.value,
					source,
					watchMode: true,
					onSuccess(collection) {
						if (collection) {
							redirectToFirstRequestInCollection(collection);
							toast("Import successful", "info");
							resolve(true);
							return;
						}
						toast("Import failed: No collection was created", "error");
						resolve(false);
					},
					onError(error) {
						console.error("[importCollection]", error);
						toast(`Import failed: ${error?.message || "Unknown error"}`, "error");
						resolve(false);
					}
				});
			});
		}
		function redirectToFirstRequestInCollection(collection) {
			if (!collection) return;
			router.push({
				name: "request",
				params: {
					workspace: activeWorkspace.value?.uid,
					request: collection?.requests[0]
				}
			});
		}
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock(Fragment, null, [
				createVNode(ImportCollectionModal_default, {
					eventType: eventType.value,
					integration: integration.value,
					source: source.value,
					onImportFinished: resetData
				}, null, 8, [
					"eventType",
					"integration",
					"source"
				]),
				createVNode(PasteEventListener_default, { onInput: handleInput }),
				createVNode(DropEventListener_default, { onInput: handleInput }),
				createVNode(UrlQueryParameterChecker_default, { onInput: handleInput }),
				renderSlot(_ctx.$slots, "default")
			], 64);
		};
	}
});
//#endregion
export { ImportCollectionListener_default as t };

//# sourceMappingURL=ImportCollection-DfX1UQ5u.js.map