import { package_default } from "./chunks/mermaid.core/chunk-DR5Q36YT.js";
import { __name, log, setLogLevel } from "./chunks/mermaid.core/chunk-AGHRB4JF.js";
import { purify } from "../../dompurify/dist/purify.es.js";
import { UnknownDiagramError, addDirective, assignWithDepth_default, configureSvgSize, defaultConfig, detectType, detectors, evaluate, frontMatterRegex, getConfig, getDiagram, getDiagramLoader, getSiteConfig, registerDiagram, registerLazyLoadedDiagrams, reset, saveConfigFromInitialize, setConfig, setSiteConfig, styles_default, themes_default, updateSiteConfig } from "./chunks/mermaid.core/chunk-ABZYJK2D.js";
import select_default from "../../d3-selection/src/select.js";
import "../../d3/src/index.js";
import { selectSvgElement } from "./chunks/mermaid.core/chunk-EXTU4WIE.js";
import { JSON_SCHEMA, load } from "./chunks/mermaid.core/chunk-MI3HLSF2.js";
import "./chunks/mermaid.core/chunk-HN2XXSSU.js";
import "./chunks/mermaid.core/chunk-CVBHYZKI.js";
import "./chunks/mermaid.core/chunk-ATLVNIR6.js";
import { cleanAndMerge, decodeEntities, encodeEntities, isDetailedError, removeDirectives, utils_default } from "./chunks/mermaid.core/chunk-S3R3BYOJ.js";
import { dedent } from "../../ts-dedent/esm/index.js";
import { registerIconPacks } from "./chunks/mermaid.core/chunk-JA3XYJ7Z.js";
import "./chunks/mermaid.core/chunk-JZLCHNYA.js";
import "./chunks/mermaid.core/chunk-QXUST7PY.js";
import { registerLayoutLoaders } from "./chunks/mermaid.core/chunk-N4CR4FBY.js";
import { compile } from "../../stylis/src/Parser.js";
import { serialize, stringify } from "../../stylis/src/Serializer.js";
import isEmpty_default from "../../lodash-es/isEmpty.js";
var id = "c4", c4Detector_default = {
	id,
	detector: /* @__PURE__ */ __name((e) => /^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/c4Diagram-YG6GDRKO.js");
		return {
			id,
			diagram: e
		};
	}, "loader")
}, id2 = "flowchart", flowDetector_default = {
	id: id2,
	detector: /* @__PURE__ */ __name((e, C) => C?.flowchart?.defaultRenderer === "dagre-wrapper" || C?.flowchart?.defaultRenderer === "elk" ? !1 : /^\s*graph/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/flowDiagram-NV44I4VS.js");
		return {
			id: id2,
			diagram: e
		};
	}, "loader")
}, id3 = "flowchart-v2", flowDetector_v2_default = {
	id: id3,
	detector: /* @__PURE__ */ __name((e, C) => C?.flowchart?.defaultRenderer === "dagre-d3" ? !1 : (C?.flowchart?.defaultRenderer === "elk" && (C.layout = "elk"), /^\s*graph/.test(e) && C?.flowchart?.defaultRenderer === "dagre-wrapper" ? !0 : /^\s*flowchart/.test(e)), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/flowDiagram-NV44I4VS.js");
		return {
			id: id3,
			diagram: e
		};
	}, "loader")
}, id4 = "er", erDetector_default = {
	id: id4,
	detector: /* @__PURE__ */ __name((e) => /^\s*erDiagram/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/erDiagram-Q2GNP2WA.js");
		return {
			id: id4,
			diagram: e
		};
	}, "loader")
}, id5 = "gitGraph", gitGraphDetector_default = {
	id: id5,
	detector: /* @__PURE__ */ __name((e) => /^\s*gitGraph/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/gitGraphDiagram-V2S2FVAM.js");
		return {
			id: id5,
			diagram: e
		};
	}, "loader")
}, id6 = "gantt", ganttDetector_default = {
	id: id6,
	detector: /* @__PURE__ */ __name((e) => /^\s*gantt/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/ganttDiagram-JELNMOA3.js");
		return {
			id: id6,
			diagram: e
		};
	}, "loader")
}, id7 = "info", info = {
	id: id7,
	detector: /* @__PURE__ */ __name((e) => /^\s*info/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/infoDiagram-HS3SLOUP.js");
		return {
			id: id7,
			diagram: e
		};
	}, "loader")
}, id8 = "pie", pie = {
	id: id8,
	detector: /* @__PURE__ */ __name((e) => /^\s*pie/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/pieDiagram-ADFJNKIX.js");
		return {
			id: id8,
			diagram: e
		};
	}, "loader")
}, id9 = "quadrantChart", quadrantDetector_default = {
	id: id9,
	detector: /* @__PURE__ */ __name((e) => /^\s*quadrantChart/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/quadrantDiagram-AYHSOK5B.js");
		return {
			id: id9,
			diagram: e
		};
	}, "loader")
}, id10 = "xychart", xychartDetector_default = {
	id: id10,
	detector: /* @__PURE__ */ __name((e) => /^\s*xychart(-beta)?/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/xychartDiagram-PRI3JC2R.js");
		return {
			id: id10,
			diagram: e
		};
	}, "loader")
}, id11 = "requirement", requirementDetector_default = {
	id: id11,
	detector: /* @__PURE__ */ __name((e) => /^\s*requirement(Diagram)?/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/requirementDiagram-UZGBJVZJ.js");
		return {
			id: id11,
			diagram: e
		};
	}, "loader")
}, id12 = "sequence", sequenceDetector_default = {
	id: id12,
	detector: /* @__PURE__ */ __name((e) => /^\s*sequenceDiagram/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/sequenceDiagram-WL72ISMW.js");
		return {
			id: id12,
			diagram: e
		};
	}, "loader")
}, id13 = "class", classDetector_default = {
	id: id13,
	detector: /* @__PURE__ */ __name((e, C) => C?.class?.defaultRenderer === "dagre-wrapper" ? !1 : /^\s*classDiagram/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/classDiagram-2ON5EDUG.js");
		return {
			id: id13,
			diagram: e
		};
	}, "loader")
}, id14 = "classDiagram", classDetector_V2_default = {
	id: id14,
	detector: /* @__PURE__ */ __name((e, C) => /^\s*classDiagram/.test(e) && C?.class?.defaultRenderer === "dagre-wrapper" ? !0 : /^\s*classDiagram-v2/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/classDiagram-v2-WZHVMYZB.js");
		return {
			id: id14,
			diagram: e
		};
	}, "loader")
}, id15 = "state", stateDetector_default = {
	id: id15,
	detector: /* @__PURE__ */ __name((e, C) => C?.state?.defaultRenderer === "dagre-wrapper" ? !1 : /^\s*stateDiagram/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/stateDiagram-FKZM4ZOC.js");
		return {
			id: id15,
			diagram: e
		};
	}, "loader")
}, id16 = "stateDiagram", stateDetector_V2_default = {
	id: id16,
	detector: /* @__PURE__ */ __name((e, C) => !!(/^\s*stateDiagram-v2/.test(e) || /^\s*stateDiagram/.test(e) && C?.state?.defaultRenderer === "dagre-wrapper"), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/stateDiagram-v2-4FDKWEC3.js");
		return {
			id: id16,
			diagram: e
		};
	}, "loader")
}, id17 = "journey", journeyDetector_default = {
	id: id17,
	detector: /* @__PURE__ */ __name((e) => /^\s*journey/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/journeyDiagram-XKPGCS4Q.js");
		return {
			id: id17,
			diagram: e
		};
	}, "loader")
}, renderer = { draw: /* @__PURE__ */ __name((e, C, T) => {
	log.debug("rendering svg for syntax error\n");
	let E = selectSvgElement(C), D = E.append("g");
	E.attr("viewBox", "0 0 2412 512"), configureSvgSize(E, 100, 512, !0), D.append("path").attr("class", "error-icon").attr("d", "m411.313,123.313c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32-9.375,9.375-20.688-20.688c-12.484-12.5-32.766-12.5-45.25,0l-16,16c-1.261,1.261-2.304,2.648-3.31,4.051-21.739-8.561-45.324-13.426-70.065-13.426-105.867,0-192,86.133-192,192s86.133,192 192,192 192-86.133 192-192c0-24.741-4.864-48.327-13.426-70.065 1.402-1.007 2.79-2.049 4.051-3.31l16-16c12.5-12.492 12.5-32.758 0-45.25l-20.688-20.688 9.375-9.375 32.001-31.999zm-219.313,100.687c-52.938,0-96,43.063-96,96 0,8.836-7.164,16-16,16s-16-7.164-16-16c0-70.578 57.422-128 128-128 8.836,0 16,7.164 16,16s-7.164,16-16,16z"), D.append("path").attr("class", "error-icon").attr("d", "m459.02,148.98c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l16,16c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16.001-16z"), D.append("path").attr("class", "error-icon").attr("d", "m340.395,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16-16c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l15.999,16z"), D.append("path").attr("class", "error-icon").attr("d", "m400,64c8.844,0 16-7.164 16-16v-32c0-8.836-7.156-16-16-16-8.844,0-16,7.164-16,16v32c0,8.836 7.156,16 16,16z"), D.append("path").attr("class", "error-icon").attr("d", "m496,96.586h-32c-8.844,0-16,7.164-16,16 0,8.836 7.156,16 16,16h32c8.844,0 16-7.164 16-16 0-8.836-7.156-16-16-16z"), D.append("path").attr("class", "error-icon").attr("d", "m436.98,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688l32-32c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32c-6.251,6.25-6.251,16.375-0.001,22.625z"), D.append("text").attr("class", "error-text").attr("x", 1440).attr("y", 250).attr("font-size", "150px").style("text-anchor", "middle").text("Syntax error in text"), D.append("text").attr("class", "error-text").attr("x", 1250).attr("y", 400).attr("font-size", "100px").style("text-anchor", "middle").text(`mermaid version ${T}`);
}, "draw") }, errorRenderer_default = renderer, errorDiagram_default = {
	db: {},
	renderer,
	parser: { parse: /* @__PURE__ */ __name(() => {}, "parse") }
}, id18 = "flowchart-elk", detector_default = {
	id: id18,
	detector: /* @__PURE__ */ __name((e, C = {}) => /^\s*flowchart-elk/.test(e) || /^\s*(flowchart|graph)/.test(e) && C?.flowchart?.defaultRenderer === "elk" ? (C.layout = "elk", !0) : !1, "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/flowDiagram-NV44I4VS.js");
		return {
			id: id18,
			diagram: e
		};
	}, "loader")
}, id19 = "timeline", detector_default2 = {
	id: id19,
	detector: /* @__PURE__ */ __name((e) => /^\s*timeline/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/timeline-definition-IT6M3QCI.js");
		return {
			id: id19,
			diagram: e
		};
	}, "loader")
}, id20 = "mindmap", detector_default3 = {
	id: id20,
	detector: /* @__PURE__ */ __name((e) => /^\s*mindmap/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/mindmap-definition-VGOIOE7T.js");
		return {
			id: id20,
			diagram: e
		};
	}, "loader")
}, id21 = "kanban", detector_default4 = {
	id: id21,
	detector: /* @__PURE__ */ __name((e) => /^\s*kanban/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/kanban-definition-3W4ZIXB7.js");
		return {
			id: id21,
			diagram: e
		};
	}, "loader")
}, id22 = "sankey", sankeyDetector_default = {
	id: id22,
	detector: /* @__PURE__ */ __name((e) => /^\s*sankey(-beta)?/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/sankeyDiagram-TZEHDZUN.js");
		return {
			id: id22,
			diagram: e
		};
	}, "loader")
}, id23 = "packet", packet = {
	id: id23,
	detector: /* @__PURE__ */ __name((e) => /^\s*packet(-beta)?/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/diagram-S2PKOQOG.js");
		return {
			id: id23,
			diagram: e
		};
	}, "loader")
}, id24 = "radar", radar = {
	id: id24,
	detector: /* @__PURE__ */ __name((e) => /^\s*radar-beta/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/diagram-QEK2KX5R.js");
		return {
			id: id24,
			diagram: e
		};
	}, "loader")
}, id25 = "block", blockDetector_default = {
	id: id25,
	detector: /* @__PURE__ */ __name((e) => /^\s*block(-beta)?/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/blockDiagram-VD42YOAC.js");
		return {
			id: id25,
			diagram: e
		};
	}, "loader")
}, id26 = "architecture", architectureDetector_default = {
	id: id26,
	detector: /* @__PURE__ */ __name((e) => /^\s*architecture/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/architectureDiagram-VXUJARFQ.js");
		return {
			id: id26,
			diagram: e
		};
	}, "loader")
}, id27 = "treemap", treemap = {
	id: id27,
	detector: /* @__PURE__ */ __name((e) => /^\s*treemap/.test(e), "detector"),
	loader: /* @__PURE__ */ __name(async () => {
		let { diagram: e } = await import("./chunks/mermaid.core/diagram-PSM6KHXK.js");
		return {
			id: id27,
			diagram: e
		};
	}, "loader")
}, hasLoadedDiagrams = !1, addDiagrams = /* @__PURE__ */ __name(() => {
	hasLoadedDiagrams || (hasLoadedDiagrams = !0, registerDiagram("error", errorDiagram_default, (e) => e.toLowerCase().trim() === "error"), registerDiagram("---", {
		db: { clear: /* @__PURE__ */ __name(() => {}, "clear") },
		styles: {},
		renderer: { draw: /* @__PURE__ */ __name(() => {}, "draw") },
		parser: { parse: /* @__PURE__ */ __name(() => {
			throw Error("Diagrams beginning with --- are not valid. If you were trying to use a YAML front-matter, please ensure that you've correctly opened and closed the YAML front-matter with un-indented `---` blocks");
		}, "parse") },
		init: /* @__PURE__ */ __name(() => null, "init")
	}, (e) => e.toLowerCase().trimStart().startsWith("---")), registerLazyLoadedDiagrams(detector_default, detector_default3, architectureDetector_default), registerLazyLoadedDiagrams(c4Detector_default, detector_default4, classDetector_V2_default, classDetector_default, erDetector_default, ganttDetector_default, info, pie, requirementDetector_default, sequenceDetector_default, flowDetector_v2_default, flowDetector_default, detector_default2, gitGraphDetector_default, stateDetector_V2_default, stateDetector_default, journeyDetector_default, quadrantDetector_default, sankeyDetector_default, packet, xychartDetector_default, blockDetector_default, radar, treemap));
}, "addDiagrams"), loadRegisteredDiagrams = /* @__PURE__ */ __name(async () => {
	log.debug("Loading registered diagrams");
	let e = (await Promise.allSettled(Object.entries(detectors).map(async ([e, { detector: C, loader: T }]) => {
		if (T) try {
			getDiagram(e);
		} catch {
			try {
				let { diagram: e, id: w } = await T();
				registerDiagram(w, e, C);
			} catch (C) {
				throw log.error(`Failed to load external diagram with key ${e}. Removing from detectors.`), delete detectors[e], C;
			}
		}
	}))).filter((e) => e.status === "rejected");
	if (e.length > 0) {
		log.error(`Failed to load ${e.length} external diagrams`);
		for (let C of e) log.error(C);
		throw Error(`Failed to load ${e.length} external diagrams`);
	}
}, "loadRegisteredDiagrams"), SVG_ROLE = "graphics-document document";
function setA11yDiagramInfo(e, C) {
	e.attr("role", SVG_ROLE), C !== "" && e.attr("aria-roledescription", C);
}
__name(setA11yDiagramInfo, "setA11yDiagramInfo");
function addSVGa11yTitleDescription(e, C, w, T) {
	if (e.insert !== void 0) {
		if (w) {
			let C = `chart-desc-${T}`;
			e.attr("aria-describedby", C), e.insert("desc", ":first-child").attr("id", C).text(w);
		}
		if (C) {
			let w = `chart-title-${T}`;
			e.attr("aria-labelledby", w), e.insert("title", ":first-child").attr("id", w).text(C);
		}
	}
}
__name(addSVGa11yTitleDescription, "addSVGa11yTitleDescription");
var Diagram = class e {
	constructor(e, C, w, T, E) {
		this.type = e, this.text = C, this.db = w, this.parser = T, this.renderer = E;
	}
	static #e = __name(this, "Diagram");
	static async fromText(C, w = {}) {
		let T = getConfig(), E = detectType(C, T);
		C = encodeEntities(C) + "\n";
		try {
			getDiagram(E);
		} catch {
			let e = getDiagramLoader(E);
			if (!e) throw new UnknownDiagramError(`Diagram ${E} not found.`);
			let { id: C, diagram: w } = await e();
			registerDiagram(C, w);
		}
		let { db: O, parser: k, renderer: A, init: j } = getDiagram(E);
		return k.parser && (k.parser.yy = O), O.clear?.(), j?.(T), w.title && O.setDiagramTitle?.(w.title), await k.parse(C), new e(E, C, O, k, A);
	}
	async render(e, C) {
		await this.renderer.draw(this.text, e, C, this);
	}
	getParser() {
		return this.parser;
	}
	getType() {
		return this.type;
	}
}, interactionFunctions = [], attachFunctions = /* @__PURE__ */ __name(() => {
	interactionFunctions.forEach((e) => {
		e();
	}), interactionFunctions = [];
}, "attachFunctions"), cleanupComments = /* @__PURE__ */ __name((e) => e.replace(/^\s*%%(?!{)[^\n]+\n?/gm, "").trimStart(), "cleanupComments");
function extractFrontMatter(e) {
	let C = e.match(frontMatterRegex);
	if (!C) return {
		text: e,
		metadata: {}
	};
	let w = load(C[1], { schema: JSON_SCHEMA }) ?? {};
	w = typeof w == "object" && !Array.isArray(w) ? w : {};
	let T = {};
	return w.displayMode && (T.displayMode = w.displayMode.toString()), w.title && (T.title = w.title.toString()), w.config && (T.config = w.config), {
		text: e.slice(C[0].length),
		metadata: T
	};
}
__name(extractFrontMatter, "extractFrontMatter");
var cleanupText = /* @__PURE__ */ __name((e) => e.replace(/\r\n?/g, "\n").replace(/<(\w+)([^>]*)>/g, (e, C, w) => "<" + C + w.replace(/="([^"]*)"/g, "='$1'") + ">"), "cleanupText"), processFrontmatter = /* @__PURE__ */ __name((e) => {
	let { text: C, metadata: w } = extractFrontMatter(e), { displayMode: T, title: E, config: D = {} } = w;
	return T && (D.gantt ||= {}, D.gantt.displayMode = T), {
		title: E,
		config: D,
		text: C
	};
}, "processFrontmatter"), processDirectives = /* @__PURE__ */ __name((e) => {
	let C = utils_default.detectInit(e) ?? {}, w = utils_default.detectDirective(e, "wrap");
	return Array.isArray(w) ? C.wrap = w.some(({ type: e }) => e === "wrap") : w?.type === "wrap" && (C.wrap = !0), {
		text: removeDirectives(e),
		directive: C
	};
}, "processDirectives");
function preprocessDiagram(e) {
	let C = processFrontmatter(cleanupText(e)), w = processDirectives(C.text), T = cleanAndMerge(C.config, w.directive);
	return e = cleanupComments(w.text), {
		code: e,
		title: C.title,
		config: T
	};
}
__name(preprocessDiagram, "preprocessDiagram");
function toBase64(e) {
	let C = new TextEncoder().encode(e), w = Array.from(C, (e) => String.fromCodePoint(e)).join("");
	return btoa(w);
}
__name(toBase64, "toBase64");
var MAX_TEXTLENGTH = 5e4, MAX_TEXTLENGTH_EXCEEDED_MSG = "graph TB;a[Maximum text size in diagram exceeded];style a fill:#faa", SECURITY_LVL_SANDBOX = "sandbox", SECURITY_LVL_LOOSE = "loose", XMLNS_SVG_STD = "http://www.w3.org/2000/svg", XMLNS_XLINK_STD = "http://www.w3.org/1999/xlink", XMLNS_XHTML_STD = "http://www.w3.org/1999/xhtml", IFRAME_WIDTH = "100%", IFRAME_HEIGHT = "100%", IFRAME_STYLES = "border:0;margin:0;", IFRAME_BODY_STYLE = "margin:0", IFRAME_SANDBOX_OPTS = "allow-top-navigation-by-user-activation allow-popups", IFRAME_NOT_SUPPORTED_MSG = "The \"iframe\" tag is not supported by your browser.", DOMPURIFY_TAGS = ["foreignobject"], DOMPURIFY_ATTR = ["dominant-baseline"];
function processAndSetConfigs(e) {
	let C = preprocessDiagram(e);
	return reset(), addDirective(C.config ?? {}), C;
}
__name(processAndSetConfigs, "processAndSetConfigs");
async function parse(e, C) {
	addDiagrams();
	try {
		let { code: C, config: w } = processAndSetConfigs(e);
		return {
			diagramType: (await getDiagramFromText(C)).type,
			config: w
		};
	} catch (e) {
		if (C?.suppressErrors) return !1;
		throw e;
	}
}
__name(parse, "parse");
var cssImportantStyles = /* @__PURE__ */ __name((e, C, w = []) => `
.${e} ${C} { ${w.join(" !important; ")} !important; }`, "cssImportantStyles"), createCssStyles = /* @__PURE__ */ __name((e, C = /* @__PURE__ */ new Map()) => {
	let w = "";
	if (e.themeCSS !== void 0 && (w += `
${e.themeCSS}`), e.fontFamily !== void 0 && (w += `
:root { --mermaid-font-family: ${e.fontFamily}}`), e.altFontFamily !== void 0 && (w += `
:root { --mermaid-alt-font-family: ${e.altFontFamily}}`), C instanceof Map) {
		let T = e.htmlLabels ?? e.flowchart?.htmlLabels ? ["> *", "span"] : [
			"rect",
			"polygon",
			"ellipse",
			"circle",
			"path"
		];
		C.forEach((e) => {
			isEmpty_default(e.styles) || T.forEach((C) => {
				w += cssImportantStyles(e.id, C, e.styles);
			}), isEmpty_default(e.textStyles) || (w += cssImportantStyles(e.id, "tspan", (e?.textStyles || []).map((e) => e.replace("color", "fill"))));
		});
	}
	return w;
}, "createCssStyles"), createUserStyles = /* @__PURE__ */ __name((e, C, w, T) => serialize(compile(`${T}{${styles_default(C, createCssStyles(e, w), e.themeVariables)}}`), stringify), "createUserStyles"), cleanUpSvgCode = /* @__PURE__ */ __name((e = "", C, w) => {
	let T = e;
	return !w && !C && (T = T.replace(/marker-end="url\([\d+./:=?A-Za-z-]*?#/g, "marker-end=\"url(#")), T = decodeEntities(T), T = T.replace(/<br>/g, "<br/>"), T;
}, "cleanUpSvgCode"), putIntoIFrame = /* @__PURE__ */ __name((e = "", C) => `<iframe style="width:${IFRAME_WIDTH};height:${C?.viewBox?.baseVal?.height ? C.viewBox.baseVal.height + "px" : IFRAME_HEIGHT};${IFRAME_STYLES}" src="data:text/html;charset=UTF-8;base64,${toBase64(`<body style="${IFRAME_BODY_STYLE}">${e}</body>`)}" sandbox="${IFRAME_SANDBOX_OPTS}">
  ${IFRAME_NOT_SUPPORTED_MSG}
</iframe>`, "putIntoIFrame"), appendDivSvgG = /* @__PURE__ */ __name((e, C, w, T, E) => {
	let D = e.append("div");
	D.attr("id", w), T && D.attr("style", T);
	let O = D.append("svg").attr("id", C).attr("width", "100%").attr("xmlns", XMLNS_SVG_STD);
	return E && O.attr("xmlns:xlink", E), O.append("g"), e;
}, "appendDivSvgG");
function sandboxedIframe(e, C) {
	return e.append("iframe").attr("id", C).attr("style", "width: 100%; height: 100%;").attr("sandbox", "");
}
__name(sandboxedIframe, "sandboxedIframe");
var removeExistingElements = /* @__PURE__ */ __name((e, C, w, T) => {
	e.getElementById(C)?.remove(), e.getElementById(w)?.remove(), e.getElementById(T)?.remove();
}, "removeExistingElements"), render = /* @__PURE__ */ __name(async function(T, D, O) {
	addDiagrams();
	let k = processAndSetConfigs(D);
	D = k.code;
	let A = getConfig();
	log.debug(A), D.length > (A?.maxTextSize ?? MAX_TEXTLENGTH) && (D = MAX_TEXTLENGTH_EXCEEDED_MSG);
	let j = "#" + T, M = "i" + T, N = "#" + M, P = "d" + T, F = "#" + P, I = /* @__PURE__ */ __name(() => {
		let e = select_default(R ? N : F).node();
		e && "remove" in e && e.remove();
	}, "removeTempElements"), L = select_default("body"), R = A.securityLevel === SECURITY_LVL_SANDBOX, z = A.securityLevel === SECURITY_LVL_LOOSE, B = A.fontFamily;
	O === void 0 ? (removeExistingElements(document, T, P, M), R ? (L = select_default(sandboxedIframe(select_default("body"), M).nodes()[0].contentDocument.body), L.node().style.margin = 0) : L = select_default("body"), appendDivSvgG(L, T, P)) : (O && (O.innerHTML = ""), R ? (L = select_default(sandboxedIframe(select_default(O), M).nodes()[0].contentDocument.body), L.node().style.margin = 0) : L = select_default(O), appendDivSvgG(L, T, P, `font-family: ${B}`, XMLNS_XLINK_STD));
	let V, H;
	try {
		V = await Diagram.fromText(D, { title: k.title });
	} catch (e) {
		if (A.suppressErrorRendering) throw I(), e;
		V = await Diagram.fromText("error"), H = e;
	}
	let U = L.select(F).node(), W = V.type, G = U.firstChild, K = G.firstChild, q = V.renderer.getClasses?.(D, V), J = createUserStyles(A, W, q, j), Y = document.createElement("style");
	Y.innerHTML = J, G.insertBefore(Y, K);
	try {
		await V.renderer.draw(D, T, package_default.version, V);
	} catch (C) {
		throw A.suppressErrorRendering ? I() : errorRenderer_default.draw(D, T, package_default.version), C;
	}
	let X = L.select(`${F} svg`), Z = V.db.getAccTitle?.(), Q = V.db.getAccDescription?.();
	addA11yInfo(W, X, Z, Q), L.select(`[id="${T}"]`).selectAll("foreignobject > *").attr("xmlns", XMLNS_XHTML_STD);
	let $ = L.select(F).node().innerHTML;
	if (log.debug("config.arrowMarkerAbsolute", A.arrowMarkerAbsolute), $ = cleanUpSvgCode($, R, evaluate(A.arrowMarkerAbsolute)), R) {
		let e = L.select(F + " svg").node();
		$ = putIntoIFrame($, e);
	} else z || ($ = purify.sanitize($, {
		ADD_TAGS: DOMPURIFY_TAGS,
		ADD_ATTR: DOMPURIFY_ATTR,
		HTML_INTEGRATION_POINTS: { foreignobject: !0 }
	}));
	if (attachFunctions(), H) throw H;
	return I(), {
		diagramType: W,
		svg: $,
		bindFunctions: V.db.bindFunctions
	};
}, "render");
function initialize(e = {}) {
	let C = assignWithDepth_default({}, e);
	C?.fontFamily && !C.themeVariables?.fontFamily && (C.themeVariables ||= {}, C.themeVariables.fontFamily = C.fontFamily), saveConfigFromInitialize(C), C?.theme && C.theme in themes_default ? C.themeVariables = themes_default[C.theme].getThemeVariables(C.themeVariables) : C && (C.themeVariables = themes_default.default.getThemeVariables(C.themeVariables)), setLogLevel((typeof C == "object" ? setSiteConfig(C) : getSiteConfig()).logLevel), addDiagrams();
}
__name(initialize, "initialize");
var getDiagramFromText = /* @__PURE__ */ __name((e, C = {}) => {
	let { code: w } = preprocessDiagram(e);
	return Diagram.fromText(w, C);
}, "getDiagramFromText");
function addA11yInfo(e, C, w, T) {
	setA11yDiagramInfo(C, e), addSVGa11yTitleDescription(C, w, T, C.attr("id"));
}
__name(addA11yInfo, "addA11yInfo");
var mermaidAPI = Object.freeze({
	render,
	parse,
	getDiagramFromText,
	initialize,
	getConfig,
	setConfig,
	getSiteConfig,
	updateSiteConfig,
	reset: /* @__PURE__ */ __name(() => {
		reset();
	}, "reset"),
	globalReset: /* @__PURE__ */ __name(() => {
		reset(defaultConfig);
	}, "globalReset"),
	defaultConfig
});
setLogLevel(getConfig().logLevel), reset(getConfig());
var handleError = /* @__PURE__ */ __name((e, C, T) => {
	log.warn(e), isDetailedError(e) ? (T && T(e.str, e.hash), C.push({
		...e,
		message: e.str,
		error: e
	})) : (T && T(e), e instanceof Error && C.push({
		str: e.message,
		message: e.message,
		hash: e.name,
		error: e
	}));
}, "handleError"), run = /* @__PURE__ */ __name(async function(e = { querySelector: ".mermaid" }) {
	try {
		await runThrowsErrors(e);
	} catch (C) {
		if (isDetailedError(C) && log.error(C.str), mermaid.parseError && mermaid.parseError(C), !e.suppressErrors) throw log.error("Use the suppressErrors option to suppress these errors"), C;
	}
}, "run"), runThrowsErrors = /* @__PURE__ */ __name(async function({ postRenderCallback: e, querySelector: C, nodes: T } = { querySelector: ".mermaid" }) {
	let E = mermaidAPI.getConfig();
	log.debug(`${e ? "" : "No "}Callback function found`);
	let D;
	if (T) D = T;
	else if (C) D = document.querySelectorAll(C);
	else throw Error("Nodes and querySelector are both undefined");
	log.debug(`Found ${D.length} diagrams`), E?.startOnLoad !== void 0 && (log.debug("Start On Load: " + E?.startOnLoad), mermaidAPI.updateSiteConfig({ startOnLoad: E?.startOnLoad }));
	let O = new utils_default.InitIDGenerator(E.deterministicIds, E.deterministicIDSeed), k, A = [];
	for (let C of Array.from(D)) {
		if (log.info("Rendering diagram: " + C.id), C.getAttribute("data-processed")) continue;
		C.setAttribute("data-processed", "true");
		let T = `mermaid-${O.next()}`;
		k = C.innerHTML, k = dedent(utils_default.entityDecode(k)).trim().replace(/<br\s*\/?>/gi, "<br/>");
		let E = utils_default.detectInit(k);
		E && log.debug("Detected early reinit: ", E);
		try {
			let { svg: w, bindFunctions: E } = await render2(T, k, C);
			C.innerHTML = w, e && await e(T), E && E(C);
		} catch (e) {
			handleError(e, A, mermaid.parseError);
		}
	}
	if (A.length > 0) throw A[0];
}, "runThrowsErrors"), initialize2 = /* @__PURE__ */ __name(function(e) {
	mermaidAPI.initialize(e);
}, "initialize"), init = /* @__PURE__ */ __name(async function(e, C, T) {
	log.warn("mermaid.init is deprecated. Please use run instead."), e && initialize2(e);
	let E = {
		postRenderCallback: T,
		querySelector: ".mermaid"
	};
	typeof C == "string" ? E.querySelector = C : C && (C instanceof HTMLElement ? E.nodes = [C] : E.nodes = C), await run(E);
}, "init"), registerExternalDiagrams = /* @__PURE__ */ __name(async (e, { lazyLoad: C = !0 } = {}) => {
	addDiagrams(), registerLazyLoadedDiagrams(...e), C === !1 && await loadRegisteredDiagrams();
}, "registerExternalDiagrams"), contentLoaded = /* @__PURE__ */ __name(function() {
	if (mermaid.startOnLoad) {
		let { startOnLoad: e } = mermaidAPI.getConfig();
		e && mermaid.run().catch((e) => log.error("Mermaid failed to initialize", e));
	}
}, "contentLoaded");
typeof document < "u" && window.addEventListener("load", contentLoaded, !1);
var setParseErrorHandler = /* @__PURE__ */ __name(function(e) {
	mermaid.parseError = e;
}, "setParseErrorHandler"), executionQueue = [], executionQueueRunning = !1, executeQueue = /* @__PURE__ */ __name(async () => {
	if (!executionQueueRunning) {
		for (executionQueueRunning = !0; executionQueue.length > 0;) {
			let e = executionQueue.shift();
			if (e) try {
				await e();
			} catch (e) {
				log.error("Error executing queue", e);
			}
		}
		executionQueueRunning = !1;
	}
}, "executeQueue"), parse2 = /* @__PURE__ */ __name(async (e, T) => new Promise((E, D) => {
	let O = /* @__PURE__ */ __name(() => new Promise((C, O) => {
		mermaidAPI.parse(e, T).then((e) => {
			C(e), E(e);
		}, (e) => {
			log.error("Error parsing", e), mermaid.parseError?.(e), O(e), D(e);
		});
	}), "performCall");
	executionQueue.push(O), executeQueue().catch(D);
}), "parse"), render2 = /* @__PURE__ */ __name((e, T, E) => new Promise((D, O) => {
	let k = /* @__PURE__ */ __name(() => new Promise((C, k) => {
		mermaidAPI.render(e, T, E).then((e) => {
			C(e), D(e);
		}, (e) => {
			log.error("Error parsing", e), mermaid.parseError?.(e), k(e), O(e);
		});
	}), "performCall");
	executionQueue.push(k), executeQueue().catch(O);
}), "render"), mermaid = {
	startOnLoad: !0,
	mermaidAPI,
	parse: parse2,
	render: render2,
	init,
	run,
	registerExternalDiagrams,
	registerLayoutLoaders,
	initialize: initialize2,
	parseError: void 0,
	contentLoaded,
	setParseErrorHandler,
	detectType,
	registerIconPacks,
	getRegisteredDiagramsMetadata: /* @__PURE__ */ __name(() => Object.keys(detectors).map((e) => ({ id: e })), "getRegisteredDiagramsMetadata")
}, mermaid_default = mermaid;
export { mermaid_default };
