import { n as e } from "../sanitize-uWpY18N9.js";
import { t } from "../navigation-DihI8dfX.js";
//#region src/services/router.ts
function n(e) {
	return ((e.split("?")[0] ?? "").split("#")[0] ?? "").replace(/^\/+|\/+$/g, "").split("/").filter(Boolean);
}
function r(e, t) {
	let r = t;
	return r.startsWith(e) && (r = r.slice(e.length)), r.startsWith("/") || (r = "/" + r), n(`${e}${r}`).map((e) => e.startsWith(":") ? {
		kind: "param",
		name: e.slice(1)
	} : e.startsWith("*") ? {
		kind: "wildcard",
		name: e.slice(1)
	} : {
		kind: "static",
		value: e
	});
}
function i(e) {
	try {
		return decodeURIComponent(e);
	} catch {
		return null;
	}
}
function a(e, t, n) {
	e[t] = n;
}
function o(e, t) {
	let r = n(t), o = {}, s = e.segments.findIndex((e) => e.kind === "wildcard");
	if (s === -1 && r.length !== e.segments.length || s !== -1 && r.length < s) return null;
	for (let t = 0; t < e.segments.length; t++) {
		let n = e.segments[t];
		if (n.kind === "wildcard") {
			let e = i(r.slice(t).join("/"));
			return e === null ? null : (a(o, n.name, e), o);
		}
		let s = r.slice(t, t + 1)[0] ?? "";
		if (n.kind === "static") {
			if (n.value !== s) return null;
			continue;
		}
		let c = i(s);
		if (c === null) return null;
		a(o, n.name, c);
	}
	return o;
}
function s(e) {
	return Array.from(e.childNodes).map((e) => e.cloneNode(!0));
}
function c(e) {
	let t = new XMLSerializer();
	return Array.from(e.childNodes).map((e) => t.serializeToString(e)).join("");
}
var l = class {
	apps = /* @__PURE__ */ new Map();
	compiledRoutes = [];
	moduleLoaders = /* @__PURE__ */ new Map();
	loadedModules = /* @__PURE__ */ new Map();
	currentRoute = null;
	currentAppPrefix = null;
	config;
	listeners = /* @__PURE__ */ new Map();
	clickHandler = null;
	popstateHandler = null;
	started = !1;
	constructor(e) {
		this.config = {
			contentSelector: e?.contentSelector ?? "#app-content",
			interceptLinks: e?.interceptLinks ?? !0,
			onAuthError: e?.onAuthError ?? ((e) => {
				t("/login");
			}),
			transitionClass: e?.transitionClass ?? "page__content--transitioning",
			sanitizeFetchedHtml: e?.sanitizeFetchedHtml ?? !1,
			onAfterSwap: e?.onAfterSwap ?? (() => {})
		};
	}
	registerApp(e) {
		this.apps.set(e.prefix, e);
		let t = e.routes.map((t) => ({
			definition: t,
			segments: r(e.prefix, t.pattern),
			appPrefix: e.prefix
		}));
		t.sort((e, t) => {
			let n = e.definition.pattern.split("/").length;
			return t.definition.pattern.split("/").length - n;
		}), this.compiledRoutes.push(...t), this.compiledRoutes.sort((e, t) => t.appPrefix.length === e.appPrefix.length ? t.definition.pattern.split("/").length - e.definition.pattern.split("/").length : t.appPrefix.length - e.appPrefix.length);
	}
	registerModule(e, t) {
		this.moduleLoaders.set(e, t);
	}
	matchRoute(e) {
		for (let t of this.compiledRoutes) {
			let n = o(t, e);
			if (n) return {
				pattern: t.definition.pattern,
				params: n,
				path: e,
				appPrefix: t.appPrefix,
				view: t.definition.view,
				navSection: t.definition.navSection
			};
		}
		for (let [t, n] of this.apps) if (e === t || e === t + "/") return {
			pattern: t,
			params: {},
			path: e,
			appPrefix: t,
			view: n.defaultView ?? "dashboard",
			navSection: void 0
		};
		return null;
	}
	getCurrentRoute() {
		return this.currentRoute;
	}
	async navigate(e, n) {
		let r = n?.pushState ?? !0, i = n?.replace ?? !1, a = this.matchRoute(e);
		if (!a) {
			t(e);
			return;
		}
		let o = this.currentRoute;
		o !== null && o.appPrefix === a.appPrefix ? await this.navigateIntraApp(a, r, i) : await this.navigateCrossApp(a, r, i), this.setCurrentRoute(a), this.emit("navigate", {
			from: o,
			to: a,
			path: e
		});
	}
	async navigateIntraApp(e, t, n) {
		let r = this.apps.get(e.appPrefix);
		r && this.showAppView(r, e.view, e.navSection), t && this.pushOrReplace(e.path, n), this.setCurrentRoute(e);
		let i = this.loadedModules.get(e.appPrefix);
		i && await i.init(e.params), window.scrollTo(0, 0);
	}
	async navigateCrossApp(e, n, r) {
		let i = document.querySelector(this.config.contentSelector);
		if (!i) {
			t(e.path);
			return;
		}
		let a = this.currentAppPrefix ? this.loadedModules.get(this.currentAppPrefix) : null;
		if (a?.destroy && await a.destroy(), i.classList.add(this.config.transitionClass), !this.isSameOriginPath(e.path)) {
			i.classList.remove(this.config.transitionClass), t(e.path);
			return;
		}
		let o;
		try {
			let n = await fetch(e.path, { credentials: "same-origin" });
			if (n.status === 401 || n.status === 403) {
				i.classList.remove(this.config.transitionClass), this.config.onAuthError(n.status);
				return;
			}
			if (n.redirected) {
				i.classList.remove(this.config.transitionClass), t(n.url);
				return;
			}
			if (!n.ok) {
				i.classList.remove(this.config.transitionClass), t(e.path);
				return;
			}
			o = await n.text();
		} catch {
			i.classList.remove(this.config.transitionClass), t(e.path);
			return;
		}
		let s = new DOMParser().parseFromString(o, "text/html"), c = s.querySelector(this.config.contentSelector);
		if (!c) {
			i.classList.remove(this.config.transitionClass), t(e.path);
			return;
		}
		let l = document.querySelector(".page__shell");
		if (l) {
			let e = l.querySelector(":scope > aside[data-sidebar]"), t = l.querySelector(":scope > .sidebar__backdrop");
			e && e.remove(), t && t.remove();
			let n = s.querySelector(".page__shell");
			if (n) {
				let e = n.querySelector(":scope > aside[data-sidebar]"), t = n.querySelector(":scope > .sidebar__backdrop"), r = l.querySelector("main");
				if (e && r) {
					let t = this.prepareFetchedElement(e);
					t && l.insertBefore(t, r);
				}
				if (t && r) {
					let e = this.prepareFetchedElement(t);
					e && l.insertBefore(e, r);
				}
			}
		}
		this.replaceFetchedContent(i, c), i.className = c.className, document.body.className = s.body.className, document.title = s.title;
		let u = document.getElementById("web-config"), d = s.getElementById("web-config");
		u && d && (u.textContent = d.textContent), n && this.pushOrReplace(e.path, r), this.setCurrentRoute(e), await this.loadAndInitModule(e), await this.config.onAfterSwap(), i.classList.remove(this.config.transitionClass), window.scrollTo(0, 0);
	}
	async loadAndInitModule(e) {
		let t = this.loadedModules.get(e.appPrefix);
		if (!t) {
			let n = this.moduleLoaders.get(e.appPrefix);
			n && (t = await n(), this.loadedModules.set(e.appPrefix, t));
		}
		if (t) {
			let n = this.apps.get(e.appPrefix);
			n && this.showAppView(n, e.view, e.navSection), await t.init(e.params);
		}
	}
	showAppView(e, t, n) {
		let r = e.viewAttribute, i = e.navAttribute, a = e.activeViewClass ?? `${e.prefix.slice(1)}-view--active`, o = e.activeNavClass ?? "sidebar__item--active";
		document.querySelectorAll(`[${r}]`).forEach((e) => {
			let n = e.getAttribute(r) === t;
			e.classList.toggle(a, n), n ? e.removeAttribute("hidden") : e.setAttribute("hidden", "true");
		});
		let s = n ?? t;
		document.querySelectorAll(`[${i}]`).forEach((e) => {
			e.classList.toggle(o, e.getAttribute(i) === s);
		});
	}
	start() {
		if (this.started) return;
		this.started = !0, this.config.interceptLinks && (this.clickHandler = (e) => {
			if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || e.button !== 0) return;
			let t = e.target.closest("a[href]");
			if (!t || t.origin !== window.location.origin || t.target === "_blank" || t.target === "_parent" || t.target === "_top" || t.hasAttribute("data-no-router") || t.hasAttribute("download")) return;
			let n = t.pathname;
			this.matchRoute(n) && (e.preventDefault(), this.navigate(n, { pushState: !0 }));
		}, document.addEventListener("click", this.clickHandler)), this.popstateHandler = () => {
			this.navigate(window.location.pathname, { pushState: !1 });
		}, window.addEventListener("popstate", this.popstateHandler);
		let e = this.matchRoute(window.location.pathname);
		e && (this.currentRoute = e, this.currentAppPrefix = e.appPrefix, this.loadAndInitModule(e));
	}
	destroy() {
		this.clickHandler &&= (document.removeEventListener("click", this.clickHandler), null), this.popstateHandler &&= (window.removeEventListener("popstate", this.popstateHandler), null), this.started = !1, this.listeners.clear();
	}
	on(e, t) {
		let n = this.listeners.get(e);
		return n || (n = /* @__PURE__ */ new Set(), this.listeners.set(e, n)), n.add(t), () => {
			n.delete(t);
		};
	}
	emit(e, t) {
		let n = this.listeners.get(e);
		if (n) for (let e of n) e(t);
	}
	pushOrReplace(e, t) {
		let n = {
			scrollX: window.scrollX,
			scrollY: window.scrollY
		};
		window.history.replaceState({
			...window.history.state,
			...n
		}, "", window.location.href), t ? window.history.replaceState({}, "", e) : window.history.pushState({}, "", e);
	}
	setCurrentRoute(e) {
		this.currentRoute = e, this.currentAppPrefix = e.appPrefix;
	}
	isSameOriginPath(e) {
		try {
			return new URL(e, window.location.origin).origin === window.location.origin;
		} catch {
			return !1;
		}
	}
	replaceFetchedContent(t, n) {
		if (this.config.sanitizeFetchedHtml) {
			t.replaceChildren(e(c(n), { allowSvg: !0 }));
			return;
		}
		t.replaceChildren(...s(n));
	}
	prepareFetchedElement(t) {
		if (!this.config.sanitizeFetchedHtml) return t;
		let n = document.createElement("template");
		return n.content.replaceChildren(e(t.outerHTML, { allowSvg: !0 })), n.content.firstElementChild;
	}
	clearModuleCache() {
		this.loadedModules.clear();
	}
};
function u(e) {
	return new l(e);
}
//#endregion
export { l as Router, u as createRouter };

//# sourceMappingURL=router.js.map