import { J as e, L as t, X as n, Y as r, d as i, q as a } from "./vue.runtime.esm-bundler-Bxqkjqhc.js";
import { r as o, u as s } from "./dist-DJmnUmW9.js";
//#region ../core/dist/cloud/index.js
var c = class e {
	static DEFAULT_BASE_URL = "https://templatical.com";
	accessToken = null;
	expiresAt = null;
	_projectId = null;
	_tenantId = null;
	_tenantSlug = null;
	_testEmailConfig = null;
	_userConfig = null;
	url;
	baseUrl;
	requestOptions;
	onError;
	refreshPromise = null;
	static REFRESH_THRESHOLD_MS = 60 * 1e3;
	constructor(t) {
		this.url = t.url, this.baseUrl = (t.baseUrl ?? e.DEFAULT_BASE_URL).replace(/\/$/, ""), this.requestOptions = t.requestOptions ?? {}, this.onError = t.onError;
	}
	resolveUrl(e) {
		if (e.startsWith("http://") || e.startsWith("https://")) return e;
		let t = e.startsWith("/") ? e : `/${e}`;
		return `${this.baseUrl}${t}`;
	}
	get projectId() {
		if (!this._projectId) throw Error("Project ID not available. Call initialize() first.");
		return this._projectId;
	}
	get tenantId() {
		if (!this._tenantId) throw Error("Tenant ID not available. Call initialize() first.");
		return this._tenantId;
	}
	get tenantSlug() {
		if (!this._tenantSlug) throw Error("Tenant slug not available. Call initialize() first.");
		return this._tenantSlug;
	}
	get testEmailConfig() {
		return this._testEmailConfig;
	}
	get userConfig() {
		return this._userConfig;
	}
	get accessTokenValue() {
		return this.accessToken;
	}
	async initialize() {
		await this.ensureToken();
	}
	async ensureToken() {
		return this.accessToken && !this.isTokenExpiringSoon() ? this.accessToken : this.refreshToken();
	}
	isTokenExpiringSoon() {
		return this.expiresAt ? this.expiresAt.getTime() - Date.now() < e.REFRESH_THRESHOLD_MS : !0;
	}
	async refreshToken() {
		if (this.refreshPromise) return this.refreshPromise;
		this.refreshPromise = this.performRefresh();
		try {
			return await this.refreshPromise;
		} finally {
			this.refreshPromise = null;
		}
	}
	async performRefresh() {
		try {
			let e = this.requestOptions.method ?? "POST", t = {
				Accept: "application/json",
				...this.requestOptions.headers
			}, n = {
				method: e,
				headers: t,
				credentials: this.requestOptions.credentials ?? "include"
			};
			e === "POST" && this.requestOptions.body && (t["Content-Type"] = "application/json", n.body = JSON.stringify(this.requestOptions.body));
			let r = await fetch(this.url, n);
			if (!r.ok) throw new o(`Token refresh failed: ${r.status}`, r.status);
			let i = await r.json();
			if (!i.token || !i.expires_at || !i.project_id || !i.tenant) throw Error("Invalid token response: missing token, expires_at, project_id, or tenant");
			return this.accessToken = i.token, this.expiresAt = /* @__PURE__ */ new Date(i.expires_at * 1e3), this._projectId = i.project_id, this._tenantSlug = i.tenant, i.test_email?.allowed_emails && i.test_email?.signature ? this._testEmailConfig = {
				allowedEmails: i.test_email.allowed_emails,
				signature: i.test_email.signature
			} : this._testEmailConfig = null, i.user?.id && i.user?.name && i.user?.signature ? this._userConfig = {
				id: i.user.id,
				name: i.user.name,
				signature: i.user.signature
			} : this._userConfig = null, this.accessToken;
		} catch (e) {
			let t = e instanceof Error ? e : Error("Token refresh failed", { cause: e });
			throw this.onError?.(t), t;
		}
	}
	async authenticatedFetch(e, t = {}) {
		let n = await this.ensureToken(), r = this.resolveUrl(e), i = async (e) => fetch(r, {
			...t,
			headers: {
				...t.headers,
				Authorization: `Bearer ${e}`
			}
		}), a = await i(n);
		return a.status === 401 && (a = await i(await this.refreshToken())), a;
	}
};
function l(e, t) {
	return e.replace(/\{(\w+)\}/g, (e, n) => encodeURIComponent(t[n] ?? ""));
}
var u = "/api/v1/projects/{project}/tenants/{tenant}", d = `${u}/templates/{template}`, f = `${d}/ai`, p = `${u}/media`, m = `${p}/folders`, h = `${u}/saved-modules`, g = {
	health: "/api/v1/health",
	"projects.config": `${u}/config`,
	"broadcasting.auth": `${u}/broadcasting/auth`,
	"templates.store": `${u}/templates`,
	"templates.show": `${d}`,
	"templates.update": `${d}`,
	"templates.destroy": `${d}`,
	"templates.export": `${d}/export`,
	"templates.importFromBeefree": `${u}/templates/import/from-beefree`,
	"templates.sendTestEmail": `${d}/send-test-email`,
	"snapshots.index": `${d}/snapshots`,
	"snapshots.store": `${d}/snapshots`,
	"snapshots.show": `${d}/snapshots/{snapshot}`,
	"snapshots.restore": `${d}/snapshots/{snapshot}/restore`,
	"comments.index": `${d}/comments`,
	"comments.store": `${d}/comments`,
	"comments.update": `${d}/comments/{comment}`,
	"comments.destroy": `${d}/comments/{comment}`,
	"comments.resolve": `${d}/comments/{comment}/resolve`,
	"ai.generate": `${f}/generate`,
	"ai.conversationMessages": `${f}/conversation-messages`,
	"ai.suggestions": `${f}/suggestions`,
	"ai.rewriteText": `${f}/rewrite-text`,
	"ai.score": `${f}/score`,
	"ai.fixFinding": `${f}/fix-finding`,
	"ai.generateFromDesign": `${f}/generate-from-design`,
	"media.upload": `${p}/upload`,
	"media.browse": `${p}/browse`,
	"media.delete": `${p}/delete`,
	"media.move": `${p}/move`,
	"media.update": `${p}/{media}`,
	"media.replace": `${p}/{media}/replace`,
	"media.checkUsage": `${p}/check-usage`,
	"media.frequentlyUsed": `${p}/frequently-used`,
	"media.importFromUrl": `${p}/import-from-url`,
	"folders.index": `${m}`,
	"folders.store": `${m}`,
	"folders.update": `${m}/{mediaFolder}`,
	"folders.destroy": `${m}/{mediaFolder}`,
	"savedModules.index": `${h}`,
	"savedModules.store": `${h}`,
	"savedModules.update": `${h}/{savedModule}`,
	"savedModules.destroy": `${h}/{savedModule}`
}, _ = class {
	constructor(e) {
		this.authManager = e;
	}
	authManager;
	get projectId() {
		return this.authManager.projectId;
	}
	get tenantSlug() {
		return this.authManager.tenantSlug;
	}
	get baseParams() {
		return {
			project: this.projectId,
			tenant: this.tenantSlug
		};
	}
	async request(e, t = {}) {
		let n = await this.authManager.authenticatedFetch(e, {
			...t,
			headers: {
				"Content-Type": "application/json",
				Accept: "application/json",
				...t.headers
			}
		});
		if (!n.ok) {
			let e = await n.json().catch(() => ({ message: `HTTP error ${n.status}` }));
			throw new o(this.extractFirstValidationError(e), n.status);
		}
		if (n.status !== 204) return (await n.json()).data;
	}
	extractFirstValidationError(e) {
		if (e.errors) {
			let t = Object.keys(e.errors)[0];
			if (t && e.errors[t]?.length > 0) return e.errors[t][0];
		}
		return e.message;
	}
	async createTemplate(e) {
		return this.request(l(g["templates.store"], this.baseParams), {
			method: "POST",
			body: JSON.stringify({ content: e })
		});
	}
	async getTemplate(e) {
		return this.request(l(g["templates.show"], {
			...this.baseParams,
			template: e
		}));
	}
	async updateTemplate(e, t) {
		return this.request(l(g["templates.update"], {
			...this.baseParams,
			template: e
		}), {
			method: "PUT",
			body: JSON.stringify({ content: t })
		});
	}
	async createSnapshot(e, t) {
		return this.request(l(g["snapshots.store"], {
			...this.baseParams,
			template: e
		}), {
			method: "POST",
			body: JSON.stringify({ content: t })
		});
	}
	async deleteTemplate(e) {
		return this.request(l(g["templates.destroy"], {
			...this.baseParams,
			template: e
		}), { method: "DELETE" });
	}
	async getSnapshots(e) {
		return this.request(l(g["snapshots.index"], {
			...this.baseParams,
			template: e
		}));
	}
	async restoreSnapshot(e, t) {
		return this.request(l(g["snapshots.restore"], {
			...this.baseParams,
			template: e,
			snapshot: t
		}), { method: "POST" });
	}
	async exportTemplate(e, t) {
		let n = t ? JSON.stringify({
			custom_fonts: t.customFonts,
			default_fallback: t.defaultFallback
		}) : void 0;
		return this.request(l(g["templates.export"], {
			...this.baseParams,
			template: e
		}), {
			method: "POST",
			body: n
		});
	}
	async sendTestEmail(e, t) {
		await this.request(l(g["templates.sendTestEmail"], {
			...this.baseParams,
			template: e
		}), {
			method: "POST",
			body: JSON.stringify(t)
		});
	}
	commentsUrl(e, t) {
		return t ? l(g["comments.update"], {
			...this.baseParams,
			template: e,
			comment: t
		}) : l(g["comments.index"], {
			...this.baseParams,
			template: e
		});
	}
	async getComments(e) {
		return this.request(this.commentsUrl(e));
	}
	async createComment(e, t, n) {
		return this.request(this.commentsUrl(e), {
			method: "POST",
			body: JSON.stringify(t),
			headers: n
		});
	}
	async updateComment(e, t, n, r) {
		return this.request(this.commentsUrl(e, t), {
			method: "PUT",
			body: JSON.stringify(n),
			headers: r
		});
	}
	async deleteComment(e, t, n, r) {
		return this.request(this.commentsUrl(e, t), {
			method: "DELETE",
			body: JSON.stringify(n),
			headers: r
		});
	}
	async resolveComment(e, t, n, r) {
		return this.request(l(g["comments.resolve"], {
			...this.baseParams,
			template: e,
			comment: t
		}), {
			method: "POST",
			body: JSON.stringify(n),
			headers: r
		});
	}
	async fetchConfig() {
		return this.request(l(g["projects.config"], this.baseParams));
	}
	async listModules(e) {
		let t = l(g["savedModules.index"], this.baseParams), n = e ? `?search=${encodeURIComponent(e)}` : "";
		return this.request(`${t}${n}`);
	}
	async createModule(e) {
		return this.request(l(g["savedModules.store"], this.baseParams), {
			method: "POST",
			body: JSON.stringify(e)
		});
	}
	async updateModule(e, t) {
		return this.request(l(g["savedModules.update"], {
			...this.baseParams,
			savedModule: e
		}), {
			method: "PUT",
			body: JSON.stringify(t)
		});
	}
	async deleteModule(e) {
		return this.request(l(g["savedModules.destroy"], {
			...this.baseParams,
			savedModule: e
		}), { method: "DELETE" });
	}
};
function v(e) {
	return {
		host: e.host,
		port: e.port,
		appKey: e.app_key
	};
}
var y = class {
	pusher = null;
	authManager;
	config;
	onError;
	constructor(e) {
		this.authManager = e.authManager, this.config = e.config, this.onError = e.onError;
	}
	async connect() {
		if (this.pusher) return;
		let e;
		try {
			({default: e} = await import("pusher-js"));
		} catch {
			throw Error("Cloud features require the optional peer dependency 'pusher-js'. Install it with: npm install pusher-js");
		}
		let { host: t, port: n, appKey: r } = this.config, i = this.authManager.resolveUrl(l(g["broadcasting.auth"], {
			project: this.authManager.projectId,
			tenant: this.authManager.tenantSlug
		}));
		this.pusher = new e(r, {
			wsHost: t,
			wsPort: n,
			wssPort: n,
			forceTLS: !0,
			disableStats: !0,
			enabledTransports: ["ws", "wss"],
			cluster: "",
			channelAuthorization: {
				transport: "ajax",
				endpoint: i,
				headers: {
					Authorization: `Bearer ${this.authManager.accessTokenValue}`,
					Accept: "application/json"
				},
				params: {
					user_id: this.authManager.userConfig?.id ?? "",
					user_name: this.authManager.userConfig?.name ?? "",
					user_signature: this.authManager.userConfig?.signature ?? ""
				}
			}
		}), this.pusher.connection.bind("error", (e) => {
			this.onError?.(e instanceof Error ? e : /* @__PURE__ */ Error("WebSocket connection error"));
		});
	}
	subscribePresence(e) {
		if (!this.pusher) throw Error("WebSocketClient not connected. Call connect() first.");
		return this.pusher.subscribe(e);
	}
	unsubscribe(e) {
		this.pusher?.unsubscribe(e);
	}
	getChannel(e) {
		return this.pusher?.channel(e);
	}
	disconnect() {
		this.pusher &&= (this.pusher.disconnect(), null);
	}
	getSocketId() {
		return this.pusher?.connection.socket_id ?? null;
	}
	get isConnected() {
		return this.pusher?.connection.state === "connected";
	}
};
function b(e, t) {
	let { operation: n, data: r } = t;
	switch (n) {
		case "add_block":
			e.addBlock(r.block, r.section_id, r.column_index, r.index);
			break;
		case "update_block":
			e.updateBlock(r.block_id, r.updates);
			break;
		case "delete_block":
			e.removeBlock(r.block_id);
			break;
		case "move_block":
			e.moveBlock(r.block_id, r.index, r.section_id, r.column_index);
			break;
		case "update_settings":
			e.updateSettings(r.updates);
			break;
		case "set_content":
			e.setContent(r.content);
			break;
		case "update_block_style":
			e.updateBlock(r.block_id, { styles: r.styles });
			break;
	}
}
function x(t) {
	let n = new _(t.authManager), a = e({
		template: null,
		content: s(t.defaultFontFamily, t.templateDefaults),
		selectedBlockId: null,
		viewport: "desktop",
		darkMode: !1,
		previewMode: !1,
		isDirty: !1,
		isSaving: !1,
		isLoading: !1,
		uiTheme: "auto"
	}), c = i({
		get: () => a.content,
		set: (e) => {
			a.content = e, a.isDirty = !0;
		}
	}), l = i(() => a.selectedBlockId ? d(a.content.blocks, a.selectedBlockId) : null), u = i(() => {
		let e = /* @__PURE__ */ new Set(), t = a.template?.content?.blocks;
		if (!t) return e;
		for (let n of t) if (e.add(n.id), n.type === "section") for (let t of n.children) for (let n of t) e.add(n.id);
		return e;
	});
	function d(e, t) {
		for (let n of e) {
			if (n.id === t) return n;
			if (n.type === "section") for (let e of n.children) {
				let n = d(e, t);
				if (n) return n;
			}
		}
		return null;
	}
	function f(e, t, n = { blocks: e }) {
		for (let r = 0; r < e.length; r++) {
			let i = e[r];
			if (i.id === t) return n;
			if (i.type === "section") for (let e = 0; e < i.children.length; e++) {
				let n = f(i.children[e], t, {
					blocks: i.children[e],
					sectionId: i.id,
					columnIndex: e
				});
				if (n) return n;
			}
		}
		return null;
	}
	function p(e) {
		return t.lockedBlocks?.value.has(e) ?? !1;
	}
	function m(e, t = !0) {
		a.content = e, t && (a.isDirty = !0);
	}
	function h(e) {
		e && p(e) || (a.selectedBlockId = e);
	}
	function g(e) {
		a.viewport = e;
	}
	function v(e) {
		a.darkMode = e;
	}
	function y(e) {
		a.uiTheme = e;
	}
	function b(e) {
		a.previewMode = e, e && (a.selectedBlockId = null);
	}
	function x(e, t) {
		if (p(e)) return;
		let n = d(a.content.blocks, e);
		n && (Object.assign(n, t), a.isDirty = !0);
	}
	function S(e) {
		a.content.settings = {
			...a.content.settings,
			...e
		}, a.isDirty = !0;
	}
	function C(e, t, n = 0, r) {
		if (t) {
			let i = d(a.content.blocks, t);
			if (i && i.type === "section") {
				i.children[n] = i.children[n] || [];
				let t = i.children[n];
				r !== void 0 && r < t.length ? t.splice(r, 0, e) : t.push(e);
			}
		} else r !== void 0 && r < a.content.blocks.length ? a.content.blocks.splice(r, 0, e) : a.content.blocks.push(e);
		a.isDirty = !0;
	}
	function w(e) {
		if (p(e)) return;
		let t = f(a.content.blocks, e);
		if (t) {
			let n = t.blocks.findIndex((t) => t.id === e);
			n !== -1 && (t.blocks.splice(n, 1), a.selectedBlockId === e && (a.selectedBlockId = null), a.isDirty = !0);
		}
	}
	function T(e, t, n, r = 0) {
		let i = f(a.content.blocks, e);
		if (!i) return;
		let o = i.blocks.findIndex((t) => t.id === e);
		if (o === -1) return;
		let [s] = i.blocks.splice(o, 1);
		if (n) {
			let e = d(a.content.blocks, n);
			e && e.type === "section" && (e.children[r] = e.children[r] || [], e.children[r].splice(t, 0, s));
		} else a.content.blocks.splice(t, 0, s);
		a.isDirty = !0;
	}
	async function E(e) {
		a.isLoading = !0;
		try {
			e && (a.content = e);
			let t = await n.createTemplate(a.content);
			return a.template = t, a.isDirty = !1, t;
		} catch (e) {
			throw t.onError?.(e), e;
		} finally {
			a.isLoading = !1;
		}
	}
	async function D(e) {
		a.isLoading = !0;
		try {
			let t = await n.getTemplate(e);
			return a.template = t, a.content = t.content, a.isDirty = !1, t;
		} catch (e) {
			throw t.onError?.(e), e;
		} finally {
			a.isLoading = !1;
		}
	}
	async function O() {
		if (!a.template?.id) throw new o("No template loaded. Call create() or load() before saving.");
		a.isSaving = !0;
		try {
			let e = await n.updateTemplate(a.template.id, a.content);
			return a.template = e, a.isDirty = !1, e;
		} catch (e) {
			throw t.onError?.(e), e;
		} finally {
			a.isSaving = !1;
		}
	}
	async function k() {
		if (a.template?.id) try {
			await n.createSnapshot(a.template.id, a.content);
		} catch (e) {
			throw t.onError?.(e), e;
		}
	}
	function A() {
		return a.template?.id !== void 0;
	}
	function j() {
		a.isDirty = !0;
	}
	function M(e) {
		let t = f(a.content.blocks, e);
		if (!t) return null;
		let n = t.blocks.findIndex((t) => t.id === e);
		return n === -1 ? null : {
			targetSectionId: t.sectionId,
			columnIndex: t.columnIndex,
			index: n
		};
	}
	return {
		state: r(a),
		content: c,
		selectedBlock: l,
		savedBlockIds: u,
		isBlockLocked: p,
		findBlockLocation: M,
		setContent: m,
		selectBlock: h,
		setViewport: g,
		setDarkMode: v,
		setUiTheme: y,
		setPreviewMode: b,
		updateBlock: x,
		updateSettings: S,
		addBlock: C,
		removeBlock: w,
		moveBlock: T,
		create: E,
		load: D,
		save: O,
		createSnapshot: k,
		hasTemplate: A,
		markDirty: j
	};
}
var S = 0;
function C() {
	return `msg_${Date.now()}_${++S}`;
}
function w(e) {
	let { authManager: t, getTemplateId: r, onApply: i, onError: a } = e, o = n([]), s = n(!1), c = n(!1), u = n(null), d = n(null), f = n(null), p = n(null), m = n(null), h = n(null), _ = n(!1), v = n([]), y = n(!1);
	function b(e, t) {
		let n = o.value.findIndex((t) => t.id === e);
		if (n === -1) return;
		let r = {
			...o.value[n],
			...t
		};
		o.value = [
			...o.value.slice(0, n),
			r,
			...o.value.slice(n + 1)
		];
	}
	async function x() {
		let e = r();
		if (e) {
			c.value = !0;
			try {
				let n = l(g["ai.conversationMessages"], {
					project: t.projectId,
					tenant: t.tenantSlug,
					template: e
				}), r = await t.authenticatedFetch(n, {
					method: "GET",
					headers: { Accept: "application/json" }
				});
				if (!r.ok) return;
				let i = await r.json();
				i.conversation_id && (f.value = i.conversation_id), Array.isArray(i.data) && i.data.length > 0 && (o.value = i.data.map((e) => ({
					id: e.id,
					role: e.role,
					content: e.content,
					timestamp: new Date(e.created_at).getTime()
				})));
			} catch {} finally {
				c.value = !1;
			}
		}
	}
	async function S(e, n) {
		let i = r();
		if (i) {
			y.value = !0;
			try {
				let r = l(g["ai.suggestions"], {
					project: t.projectId,
					tenant: t.tenantSlug,
					template: i
				}), a = await t.authenticatedFetch(r, {
					method: "POST",
					headers: {
						"Content-Type": "application/json",
						Accept: "text/event-stream"
					},
					body: JSON.stringify({
						current_content: e,
						merge_tags: n.map((e) => ({
							label: e.label,
							value: e.value
						}))
					})
				});
				if (!a.ok) return;
				let o = a.body?.getReader();
				if (!o) return;
				let s = new TextDecoder(), c = "";
				for (;;) {
					let { done: e, value: t } = await o.read();
					if (e) break;
					c += s.decode(t, { stream: !0 });
					let n = c.split("\n");
					c = n.pop() ?? "";
					for (let e of n) {
						if (!e.startsWith("data: ")) continue;
						let t;
						try {
							t = JSON.parse(e.slice(6));
						} catch {
							continue;
						}
						t.type === "done" && Array.isArray(t.suggestions) && (v.value = t.suggestions.slice(0, 3));
					}
				}
			} catch {} finally {
				y.value = !1;
			}
		}
	}
	async function w(e, n, c) {
		let y = r();
		if (!y) throw Error("Template must be saved before using AI generation");
		s.value = !0, u.value = null, d.value = null, v.value = [];
		let x = C();
		o.value = [...o.value, {
			id: x,
			role: "user",
			content: e,
			timestamp: Date.now()
		}];
		let S = C();
		o.value = [...o.value, {
			id: S,
			role: "assistant",
			content: "",
			timestamp: Date.now()
		}];
		try {
			let r = l(g["ai.generate"], {
				project: t.projectId,
				tenant: t.tenantSlug,
				template: y
			}), a = await t.authenticatedFetch(r, {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					Accept: "text/event-stream"
				},
				body: JSON.stringify({
					prompt: e,
					current_content: n,
					merge_tags: c.map((e) => ({
						label: e.label,
						value: e.value
					})),
					conversation_id: f.value
				})
			});
			if (!a.ok) {
				let e = await a.json().catch(() => null);
				throw a.status === 403 ? Error("ai_generation_not_available") : Error(e?.message || "Failed to generate template");
			}
			let s = a.body?.getReader();
			if (!s) throw Error("Failed to read stream");
			let d = new TextDecoder(), v = "", x = null;
			try {
				for (;;) {
					let { done: e, value: t } = await s.read();
					if (e) break;
					v += d.decode(t, { stream: !0 });
					let r = v.split("\n");
					v = r.pop() ?? "";
					for (let e of r) {
						if (!e.startsWith("data: ")) continue;
						let t = e.slice(6), r;
						try {
							r = JSON.parse(t);
						} catch {
							continue;
						}
						if (r.type === "text") b(S, { content: (o.value.find((e) => e.id === S)?.content ?? "") + r.text });
						else if (r.type === "error") throw Error(r.message || "Failed to generate template");
						else r.type === "done" && (r.conversation_id && (f.value = r.conversation_id), b(S, { content: r.text }), x = r.content ?? null, x ? (m.value = n, h.value = x, p.value = S, _.value = !1, i?.(x)) : u.value = "ai_apply_failed");
					}
				}
			} finally {
				s.cancel().catch(() => {});
			}
			return x;
		} catch (t) {
			let n = t instanceof Error ? t : Error("Failed to generate template", { cause: t });
			return u.value = n.message, d.value = e, a?.(n), o.value = o.value.filter((e) => e.id !== x && e.id !== S), null;
		} finally {
			s.value = !1;
		}
	}
	function T() {
		_.value ? (h.value && i?.(h.value), _.value = !1) : (m.value && i?.(m.value), _.value = !0);
	}
	function E() {
		o.value = [], f.value = null, u.value = null, p.value = null, m.value = null, h.value = null, _.value = !1;
	}
	return {
		messages: o,
		isGenerating: s,
		isLoadingHistory: c,
		isLastChangeReverted: _,
		lastApplyMessageId: p,
		error: u,
		failedPrompt: d,
		suggestions: v,
		isLoadingSuggestions: y,
		sendPrompt: w,
		toggleLastRevert: T,
		loadConversation: x,
		loadSuggestions: S,
		clearChat: E
	};
}
function T(e) {
	function t(t) {
		return e === !1 ? !1 : e?.[t] !== !1;
	}
	return {
		isFeatureEnabled: t,
		hasAnyMenuFeature: i(() => t("chat") || t("scoring") || t("designToTemplate"))
	};
}
function E(e) {
	let { authManager: t, getTemplateId: r } = e, i = n(!1), a = n(null), o = n(null), s = n(null), c = n(""), u = n(null);
	async function d(e, n) {
		let s = r();
		if (!s) return null;
		i.value = !0, o.value = null, a.value = null;
		try {
			let r = l(g["ai.score"], {
				project: t.projectId,
				tenant: t.tenantSlug,
				template: s
			}), i = await t.authenticatedFetch(r, {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					Accept: "text/event-stream"
				},
				body: JSON.stringify({
					current_content: e,
					merge_tags: n.map((e) => ({
						label: e.label,
						value: e.value
					}))
				})
			});
			if (!i.ok) {
				if (i.status === 403) throw Error("ai_generation_not_available");
				let e = await i.json().catch(() => null);
				throw Error(e?.message || "Failed to score template");
			}
			let o = i.body?.getReader();
			if (!o) throw Error("Failed to read stream");
			let c = new TextDecoder(), u = "", d = null;
			for (;;) {
				let { done: e, value: t } = await o.read();
				if (e) break;
				u += c.decode(t, { stream: !0 });
				let n = u.split("\n");
				u = n.pop() ?? "";
				for (let e of n) {
					if (!e.startsWith("data: ")) continue;
					let t;
					try {
						t = JSON.parse(e.slice(6));
					} catch {
						continue;
					}
					if (t.type === "error") throw Error(t.message || "Failed to score template");
					t.type === "done" && (d = t.result ?? null);
				}
			}
			if (d) for (let [e, t] of Object.entries(d.categories)) for (let n of t.findings) n.category = e;
			return a.value = d, d;
		} catch (e) {
			return o.value = e instanceof Error ? e.message : "Failed to score template", null;
		} finally {
			i.value = !1;
		}
	}
	async function f(e, n, i) {
		let a = r();
		if (!a) return null;
		s.value = n.id, c.value = "", u.value = null;
		try {
			let r = l(g["ai.fixFinding"], {
				project: t.projectId,
				tenant: t.tenantSlug,
				template: a
			}), o = await t.authenticatedFetch(r, {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					Accept: "text/event-stream"
				},
				body: JSON.stringify({
					content: e,
					finding: {
						id: n.id,
						message: n.message,
						suggestion: n.suggestion,
						category: n.category
					},
					merge_tags: i.map((e) => ({
						label: e.label,
						value: e.value
					}))
				})
			});
			if (!o.ok) {
				if (o.status === 403) throw Error("ai_generation_not_available");
				let e = await o.json().catch(() => null);
				throw Error(e?.message || "Failed to fix finding");
			}
			let s = o.body?.getReader();
			if (!s) throw Error("Failed to read stream");
			let u = new TextDecoder(), d = "", f = null;
			for (;;) {
				let { done: e, value: t } = await s.read();
				if (e) break;
				d += u.decode(t, { stream: !0 });
				let n = d.split("\n");
				d = n.pop() ?? "";
				for (let e of n) {
					if (!e.startsWith("data: ")) continue;
					let t;
					try {
						t = JSON.parse(e.slice(6));
					} catch {
						continue;
					}
					if (t.type === "text") c.value += t.text;
					else if (t.type === "error") throw Error(t.message || "Failed to fix finding");
					else t.type === "done" && (f = t.content ?? null);
				}
			}
			return f;
		} catch (e) {
			return u.value = e instanceof Error ? e.message : "Failed to fix finding", null;
		} finally {
			s.value = null;
		}
	}
	function p(e, t) {
		if (!a.value) return;
		let n = a.value.categories[e];
		n && (n.findings = n.findings.filter((e) => e.id !== t));
	}
	function m() {
		i.value = !1, a.value = null, o.value = null, s.value = null, c.value = "", u.value = null;
	}
	return {
		isScoring: i,
		scoringResult: a,
		error: o,
		fixingFindingId: s,
		fixStreamingText: c,
		fixError: u,
		score: d,
		fixFinding: f,
		removeFinding: p,
		reset: m
	};
}
function D(e) {
	let { authManager: t, getTemplateId: r, onApply: i, onError: a } = e, o = n(!1), s = n(null);
	async function c(e) {
		let n = r();
		if (!n) throw Error("Template must be saved before using design reference");
		o.value = !0, s.value = null;
		try {
			let r = new FormData();
			e.prompt && r.append("prompt", e.prompt), e.imageUpload && r.append("image_upload", e.imageUpload), e.pdfUpload && r.append("pdf_upload", e.pdfUpload);
			let a = l(g["ai.generateFromDesign"], {
				project: t.projectId,
				tenant: t.tenantSlug,
				template: n
			}), o = await t.authenticatedFetch(a, {
				method: "POST",
				headers: { Accept: "text/event-stream" },
				body: r
			});
			if (!o.ok) {
				let e = await o.json().catch(() => null);
				throw o.status === 403 ? Error("ai_generation_not_available") : Error(e?.message || "Failed to generate template from design");
			}
			let s = o.body?.getReader();
			if (!s) throw Error("Failed to read stream");
			let c = new TextDecoder(), u = "", d = null;
			for (;;) {
				let { done: e, value: t } = await s.read();
				if (e) break;
				u += c.decode(t, { stream: !0 });
				let n = u.split("\n");
				u = n.pop() ?? "";
				for (let e of n) {
					if (!e.startsWith("data: ")) continue;
					let t = e.slice(6), n;
					try {
						n = JSON.parse(t);
					} catch {
						continue;
					}
					if (n.type === "error") throw Error(n.message || "Failed to generate template from design");
					n.type === "done" && (d = n.content ?? null, d && i?.(d));
				}
			}
			return d;
		} catch (e) {
			let t = e instanceof Error ? e : Error("Failed to generate template from design", { cause: e });
			return s.value = t.message, a?.(t), null;
		} finally {
			o.value = !1;
		}
	}
	function u() {
		o.value = !1, s.value = null;
	}
	return {
		isGenerating: o,
		error: s,
		generate: c,
		reset: u
	};
}
function O(e) {
	let { authManager: t, getTemplateId: r, getSocketId: a, onComment: o, onError: s, hasCommentingFeature: c } = e, l = new _(t), u = n([]), d = n(!1), f = n(!1), p = i(() => (c?.() ?? !1) && t.userConfig !== null), m = i(() => {
		let e = 0;
		for (let t of u.value) e += 1 + (t.replies?.length ?? 0);
		return e;
	}), h = i(() => u.value.filter((e) => !e.resolved_at).length), g = i(() => {
		let e = /* @__PURE__ */ new Map();
		for (let t of u.value) t.block_id && e.set(t.block_id, (e.get(t.block_id) ?? 0) + 1 + (t.replies?.length ?? 0));
		return e;
	});
	function v() {
		let e = t.userConfig;
		if (!e) throw Error("User config not available");
		return {
			user_id: e.id,
			user_name: e.name,
			user_signature: e.signature
		};
	}
	function y() {
		let e = a?.();
		if (e) return { "X-Socket-ID": e };
	}
	function b(e, t) {
		o?.({
			type: e,
			comment: t
		});
	}
	function x(e) {
		for (let t of u.value) {
			if (t.id === e) return t;
			for (let n of t.replies ?? []) if (n.id === e) return n;
		}
		return null;
	}
	async function S() {
		let e = r();
		if (e) {
			d.value = !0;
			try {
				u.value = await l.getComments(e);
			} catch (e) {
				let t = e instanceof Error ? e : Error("Failed to load comments", { cause: e });
				s?.(t);
			} finally {
				d.value = !1;
			}
		}
	}
	async function C(e, t, n) {
		let i = r();
		if (!i) return null;
		f.value = !0;
		try {
			let r = await l.createComment(i, {
				body: e,
				block_id: t,
				parent_id: n,
				...v()
			}, y());
			if (n) {
				let e = x(n);
				e && (e.replies = [...e.replies ?? [], r]);
			} else u.value = [...u.value, r];
			return b("created", r), r;
		} catch (e) {
			let t = e instanceof Error ? e : Error("Failed to create comment", { cause: e });
			return s?.(t), null;
		} finally {
			f.value = !1;
		}
	}
	async function w(e, t) {
		let n = r();
		if (!n) return null;
		f.value = !0;
		try {
			let r = await l.updateComment(n, e, {
				body: t,
				...v()
			}, y());
			return A(e, r), b("updated", r), r;
		} catch (e) {
			let t = e instanceof Error ? e : Error("Failed to update comment", { cause: e });
			return s?.(t), null;
		} finally {
			f.value = !1;
		}
	}
	async function T(e) {
		let t = r();
		if (!t) return !1;
		let n = x(e);
		if (!n) return !1;
		let i = {
			...n,
			replies: [...n.replies ?? []]
		};
		f.value = !0;
		try {
			if (await l.deleteComment(t, e, v(), y()), n.parent_id) {
				let t = x(n.parent_id);
				t && (t.replies = (t.replies ?? []).filter((t) => t.id !== e));
			} else u.value = u.value.filter((t) => t.id !== e);
			return b("deleted", i), !0;
		} catch (e) {
			let t = e instanceof Error ? e : Error("Failed to delete comment", { cause: e });
			return s?.(t), !1;
		} finally {
			f.value = !1;
		}
	}
	async function E(e) {
		let t = r();
		if (!t) return null;
		f.value = !0;
		try {
			let n = await l.resolveComment(t, e, v(), y());
			return A(e, n), b(n.resolved_at ? "resolved" : "unresolved", n), n;
		} catch (e) {
			let t = e instanceof Error ? e : Error("Failed to toggle comment resolution", { cause: e });
			return s?.(t), null;
		} finally {
			f.value = !1;
		}
	}
	function D(e) {
		if (e.parent_id) {
			let t = x(e.parent_id);
			t && (t.replies = [...t.replies ?? [], e]);
		} else u.value = [...u.value, e];
		b("created", e);
	}
	function O(e) {
		A(e.id, e), b("updated", e);
	}
	function k(e, t) {
		let n = x(e), r = n ? {
			...n,
			replies: [...n.replies ?? []]
		} : null;
		if (t) {
			let n = x(t);
			n && (n.replies = (n.replies ?? []).filter((t) => t.id !== e));
		} else u.value = u.value.filter((t) => t.id !== e);
		r && b("deleted", r);
	}
	function A(e, t) {
		for (let n = 0; n < u.value.length; n++) {
			if (u.value[n].id === e) {
				u.value = [
					...u.value.slice(0, n),
					{
						...t,
						replies: u.value[n].replies
					},
					...u.value.slice(n + 1)
				];
				return;
			}
			let r = u.value[n].replies ?? [];
			for (let i = 0; i < r.length; i++) if (r[i].id === e) {
				let e = [
					...r.slice(0, i),
					t,
					...r.slice(i + 1)
				];
				u.value = [
					...u.value.slice(0, n),
					{
						...u.value[n],
						replies: e
					},
					...u.value.slice(n + 1)
				];
				return;
			}
		}
	}
	return {
		comments: u,
		isLoading: d,
		isSubmitting: f,
		isEnabled: p,
		commentCountByBlock: g,
		totalCount: m,
		unresolvedCount: h,
		loadComments: S,
		addComment: C,
		editComment: w,
		removeComment: T,
		toggleResolve: E,
		applyRemoteCreate: D,
		applyRemoteUpdate: O,
		applyRemoteDelete: k
	};
}
function k(e) {
	let { comments: n, channel: r } = e;
	t(r, (e, t) => {
		t && t.unbind("comment-broadcast"), e && e.bind("comment-broadcast", (e) => {
			A(n, e);
		});
	}), a(() => {
		r.value?.unbind("comment-broadcast");
	});
}
function A(e, t) {
	switch (t.action) {
		case "comment_created":
			e.applyRemoteCreate(t.comment);
			break;
		case "comment_updated":
			e.applyRemoteUpdate(t.comment);
			break;
		case "comment_deleted":
			e.applyRemoteDelete(t.comment.id, t.comment.parent_id);
			break;
		case "comment_resolved":
		case "comment_unresolved":
			e.applyRemoteUpdate(t.comment);
			break;
	}
}
var j = [
	"pusher:member_added",
	"pusher:member_removed",
	"client-block_locked",
	"client-block_unlocked",
	"client-operation",
	"mcp-operation"
];
function M(e) {
	for (let t of j) e.unbind(t);
}
var N = [
	"#3b82f6",
	"#ef4444",
	"#10b981",
	"#f59e0b",
	"#8b5cf6",
	"#ec4899",
	"#06b6d4",
	"#f97316",
	"#6366f1",
	"#14b8a6"
];
function P(e) {
	let { authManager: r, editor: o, channel: s } = e, c = n([]), l = n(/* @__PURE__ */ new Map()), u = 0, d = !1, f = i(() => r.userConfig?.id ?? "");
	function p() {
		let e = N[u % N.length];
		return u++, e;
	}
	function m(e) {
		if (e.id === f.value || c.value.some((t) => t.id === e.id)) return;
		let t = {
			id: e.id,
			name: e.name,
			color: p(),
			selectedBlockId: null
		};
		return c.value = [...c.value, t], t;
	}
	function h(e) {
		let t = new Map(l.value);
		for (let [n, r] of t) r.id === e && t.delete(n);
		l.value = t, c.value = c.value.filter((t) => t.id !== e);
	}
	function g(e) {
		let t = c.value.find((t) => t.id === e.userId);
		if (!t) return;
		c.value = c.value.map((t) => t.id === e.userId ? {
			...t,
			selectedBlockId: e.blockId
		} : t);
		let n = new Map(l.value);
		for (let [t, r] of n) r.id === e.userId && n.delete(t);
		n.set(e.blockId, {
			...t,
			selectedBlockId: e.blockId
		}), l.value = n, o.state.selectedBlockId === e.blockId && o.selectBlock(null);
	}
	function _(e) {
		let t = new Map(l.value), n = t.get(e.blockId);
		t.delete(e.blockId), l.value = t, n && (c.value = c.value.map((e) => e.id === n.id ? {
			...e,
			selectedBlockId: null
		} : e));
	}
	function v(e) {
		d = !0;
		try {
			b(o, e);
		} finally {
			d = !1;
		}
	}
	function y(e) {
		!s.value || d || s.value.trigger("client-operation", e);
	}
	function x(e) {
		s.value && s.value.trigger("client-block_locked", {
			blockId: e,
			userId: f.value
		});
	}
	function S(e) {
		s.value && s.value.trigger("client-block_unlocked", { blockId: e });
	}
	return t(() => o.state.selectedBlockId, (e, t) => {
		d || (t && S(t), e && x(e));
	}), t(s, (t, n) => {
		if (n && M(n), !t) {
			c.value = [], l.value = /* @__PURE__ */ new Map(), u = 0;
			return;
		}
		let r = t.members;
		r && r.each((e) => {
			m(e.info);
		}), t.bind("pusher:member_added", (t) => {
			let n = m(t.info);
			n && e.onCollaboratorJoined?.(n);
		}), t.bind("pusher:member_removed", (t) => {
			let n = c.value.find((e) => e.id === t.id);
			h(t.id), n && e.onCollaboratorLeft?.(n);
		}), t.bind("client-block_locked", (t) => {
			g(t);
			let n = c.value.find((e) => e.id === t.userId);
			n && e.onBlockLocked?.({
				blockId: t.blockId,
				collaborator: n
			});
		}), t.bind("client-block_unlocked", (t) => {
			let n = l.value.get(t.blockId);
			_(t), n && e.onBlockUnlocked?.({
				blockId: t.blockId,
				collaborator: n
			});
		}), t.bind("client-operation", (e) => {
			v(e);
		}), t.bind("mcp-operation", (e) => {
			v(e);
		});
	}), a(() => {
		s.value && M(s.value);
	}), {
		collaborators: c,
		lockedBlocks: l,
		_broadcastOperation: y,
		_isProcessingRemoteOperation: () => d
	};
}
function F(e, t) {
	let n = e.addBlock, r = e.updateBlock, i = e.removeBlock, a = e.moveBlock, o = e.updateSettings, s = e.setContent;
	e.addBlock = (e, r, i) => {
		n(e, r, i), t._broadcastOperation({
			operation: "add_block",
			data: {
				block: e,
				section_id: r,
				column_index: i
			},
			timestamp: Date.now()
		});
	}, e.updateBlock = (e, n) => {
		r(e, n), t._broadcastOperation({
			operation: "update_block",
			data: {
				block_id: e,
				updates: n
			},
			timestamp: Date.now()
		});
	}, e.removeBlock = (e) => {
		i(e), t._broadcastOperation({
			operation: "delete_block",
			data: { block_id: e },
			timestamp: Date.now()
		});
	}, e.moveBlock = (e, n, r, i) => {
		a(e, n, r, i), t._broadcastOperation({
			operation: "move_block",
			data: {
				block_id: e,
				index: n,
				section_id: r,
				column_index: i
			},
			timestamp: Date.now()
		});
	}, e.updateSettings = (e) => {
		o(e), t._broadcastOperation({
			operation: "update_settings",
			data: { updates: e },
			timestamp: Date.now()
		});
	}, e.setContent = (e, n) => {
		s(e, n), t._broadcastOperation({
			operation: "set_content",
			data: { content: e },
			timestamp: Date.now()
		});
	};
}
function I(e) {
	let { authManager: t, onError: r } = e, i = n(null), a = n(!1), o = null, s = null;
	async function c(e, n) {
		if (o) return;
		o = new y({
			authManager: t,
			config: n,
			onError: r
		}), await o.connect(), s = `presence-template.${e}`;
		let c = o.subscribePresence(s);
		c.bind("pusher:subscription_succeeded", () => {
			a.value = !0, i.value = c;
		}), c.bind("pusher:subscription_error", (e) => {
			a.value = !1, i.value = null, r?.(e instanceof Error ? e : /* @__PURE__ */ Error("Failed to subscribe to template channel"));
		});
	}
	function l() {
		s && o && o.unsubscribe(s), o?.disconnect(), o = null, s = null, i.value = null, a.value = !1;
	}
	function u() {
		return o?.getSocketId() ?? null;
	}
	return {
		channel: i,
		isConnected: a,
		connect: c,
		disconnect: l,
		getSocketId: u
	};
}
function L(e) {
	let t = new _(e.authManager), r = n([]), i = n(!1);
	async function a(n) {
		i.value = !0;
		try {
			r.value = await t.listModules(n);
		} catch (t) {
			throw e.onError?.(t), t;
		} finally {
			i.value = !1;
		}
	}
	async function o(n, i) {
		try {
			let e = await t.createModule({
				name: n,
				content: i
			});
			return r.value = [e, ...r.value], e;
		} catch (t) {
			throw e.onError?.(t), t;
		}
	}
	async function s(n, i) {
		try {
			let e = await t.updateModule(n, i);
			return r.value = r.value.map((t) => t.id === n ? e : t), e;
		} catch (t) {
			throw e.onError?.(t), t;
		}
	}
	async function c(n) {
		try {
			await t.deleteModule(n), r.value = r.value.filter((e) => e.id !== n);
		} catch (t) {
			throw e.onError?.(t), t;
		}
	}
	return {
		modules: r,
		isLoading: i,
		loadModules: a,
		createModule: o,
		updateModule: s,
		deleteModule: c
	};
}
function R(e) {
	let t = new _(e.authManager), r = n([]), i = n(!1), a = n(!1);
	async function o() {
		i.value = !0;
		try {
			r.value = await t.getSnapshots(e.templateId);
		} catch (t) {
			throw e.onError?.(t), t;
		} finally {
			i.value = !1;
		}
	}
	async function s(n) {
		a.value = !0;
		try {
			let r = await t.restoreSnapshot(e.templateId, n);
			return e.onRestore?.(r), r;
		} catch (t) {
			throw e.onError?.(t), t;
		} finally {
			a.value = !1;
		}
	}
	return {
		snapshots: r,
		isLoading: i,
		isRestoring: a,
		loadSnapshots: o,
		restoreSnapshot: s
	};
}
function z(e) {
	let { authManager: r, getTemplateId: a, save: o, exportHtml: s, onError: c, isAuthReady: l, onBeforeTestEmail: u } = e, d = new _(r), f = n(!1), p = n(null), m = n(null);
	l && t(l, (e) => {
		e && (m.value = r.testEmailConfig);
	}, { immediate: !0 });
	let h = i(() => m.value !== null), g = i(() => m.value?.allowedEmails ?? []);
	async function v(e) {
		if (!m.value) throw Error("Test email is not enabled for this project");
		let t = a();
		if (!t) throw Error("Template must be saved before sending a test email");
		f.value = !0, p.value = null;
		try {
			await o();
			let { html: n } = await s(t);
			u && (n = await u(n)), await d.sendTestEmail(t, {
				recipient: e,
				html: n,
				allowed_emails: m.value.allowedEmails,
				signature: m.value.signature
			});
		} catch (e) {
			let t = e instanceof Error ? e : Error("Failed to send test email", { cause: e });
			throw p.value = t.message, c?.(t), t;
		} finally {
			f.value = !1;
		}
	}
	return {
		isEnabled: h,
		allowedEmails: g,
		isSending: f,
		error: p,
		sendTestEmail: v
	};
}
function B(e) {
	let { authManager: t, getFontsConfig: n, canUseCustomFonts: r } = e, i = new _(t);
	function a() {
		let e = n?.();
		return {
			customFonts: (r?.() ?? !0) && e?.customFonts ? e.customFonts : [],
			defaultFallback: e?.defaultFallback ?? "Arial, sans-serif"
		};
	}
	async function o(e) {
		let t = a(), n = await i.exportTemplate(e, t);
		return {
			html: n.html,
			mjml: n.mjml
		};
	}
	async function s(e) {
		let t = a();
		return (await i.exportTemplate(e, t)).mjml;
	}
	return {
		exportHtml: o,
		getMjmlSource: s
	};
}
function V(e) {
	let { authManager: t, onError: r } = e, a = n(null), o = n(!1), s = new _(t), c = i(() => a.value?.features ?? null);
	function l(e) {
		return a.value?.features[e] ?? !1;
	}
	async function u() {
		if (!o.value) {
			o.value = !0;
			try {
				a.value = await s.fetchConfig();
			} catch (e) {
				r?.(e instanceof Error ? e : Error("Failed to fetch config", { cause: e }));
			} finally {
				o.value = !1;
			}
		}
	}
	return {
		config: a,
		isLoading: o,
		hasFeature: l,
		features: c,
		fetchConfig: u
	};
}
var H = 5e3;
function U(e) {
	return e.authManager ? e.authManager.resolveUrl(g.health) : `${(e.baseUrl ?? "https://templatical.com").replace(/\/$/, "")}${g.health}`;
}
async function W(e, t) {
	let n = performance.now();
	try {
		let r = t ? await t.authenticatedFetch(g.health, {
			method: "GET",
			headers: { Accept: "application/json" }
		}) : await fetch(e, {
			method: "GET",
			headers: { Accept: "application/json" }
		}), i = Math.round(performance.now() - n);
		if (r.status === 401) return {
			api: {
				ok: !0,
				latency: i
			},
			auth: {
				ok: !1,
				error: "HTTP 401"
			}
		};
		if (!r.ok) return {
			api: {
				ok: !1,
				latency: i
			},
			auth: {
				ok: !t,
				error: t ? `HTTP ${r.status}` : void 0
			}
		};
		let a = await r.json();
		return {
			api: {
				ok: a.status === "ok",
				latency: i
			},
			auth: { ok: !0 },
			wsConfig: a.websocket
		};
	} catch (e) {
		return {
			api: {
				ok: !1,
				latency: Math.round(performance.now() - n)
			},
			auth: {
				ok: !t,
				error: t ? e instanceof Error ? e.message : "Authentication check failed" : void 0
			}
		};
	}
}
async function G(e) {
	if (!e?.host || !e?.app_key) return {
		ok: !1,
		error: "WebSocket configuration not available"
	};
	if (typeof WebSocket > "u") return {
		ok: !1,
		error: "WebSocket not supported in this environment"
	};
	let t = `${e.port === 443 ? "wss" : "ws"}://${e.host}:${e.port}/app/${e.app_key}?protocol=7&client=js&version=8.4.0-rc2&flash=false`;
	return new Promise((e) => {
		let n = null, r = setTimeout(() => {
			n?.close(), e({
				ok: !1,
				error: "WebSocket connection timed out"
			});
		}, H);
		try {
			n = new WebSocket(t);
		} catch (t) {
			clearTimeout(r), e({
				ok: !1,
				error: t instanceof Error ? t.message : "WebSocket connection failed"
			});
			return;
		}
		n.onopen = () => {
			clearTimeout(r), n?.close(), e({ ok: !0 });
		}, n.onerror = () => {
			clearTimeout(r), e({
				ok: !1,
				error: "WebSocket connection failed"
			});
		};
	});
}
async function K(e = {}) {
	let t = await W(U(e), e.authManager), n = await G(t.wsConfig);
	return {
		api: t.api,
		websocket: n,
		auth: t.auth,
		overall: t.api.ok && t.auth.ok
	};
}
function q(e) {
	let { editor: n, channel: r, onOperation: i } = e;
	t(r, (e, t) => {
		t && t.unbind("mcp-operation"), e && e.bind("mcp-operation", (e) => {
			b(n, e), i?.(e);
		});
	});
}
//#endregion
export { E as _, T as a, k as c, x as d, B as f, R as g, L as h, w as i, O as l, V as m, K as n, P as o, q as p, v as r, F as s, c as t, D as u, z as v, I as y };
