import { eventBus as e } from "../services/eventEmitter.js";
import "../services/index.js";
import { useStudio as t } from "./StudioProvider.js";
import { useMe as n } from "../hooks/useAuth.js";
import { useEffect as r, useRef as i } from "react";
//#region src/providers/SseProvider.tsx
function a() {
	let { environment: a } = t(), { data: o, isSuccess: s } = n(), c = i(null);
	return r(() => {
		if (a.url && s && o) {
			c.current &&= (c.current.close(), null);
			let t = `${a.url}/api/v1/sse/stream`, n = new EventSource(t, { withCredentials: !0 });
			return c.current = n, n.onopen = () => {
				console.log("SSE connection established");
			}, n.onerror = () => {
				n.readyState === EventSource.CLOSED && console.warn("SSE connection closed. Refresh the page if it does not recover.");
			}, [
				"workflow.created",
				"workflow.updated",
				"document.created",
				"workspace.updated"
			].forEach((t) => {
				n.addEventListener(t, (n) => {
					try {
						let t = JSON.parse(n.data);
						e.emit(t.type, t);
					} catch (e) {
						console.error(`Error parsing SSE event [${t}]:`, e);
					}
				});
			}), () => {
				n.close(), c.current = null;
			};
		}
	}, [
		a.url,
		s,
		o
	]), null;
}
//#endregion
export { a as SseProvider };
