import { ShikiError } from "../../types/dist/index.js";
import { EncodedTokenMetadata, FontStyle, INITIAL, Registry, Theme } from "../../vscode-textmate/dist/index.js";
import { toHtml } from "../../../hast-util-to-html/lib/index.js";
function resolveColorReplacements(a, P) {
	let F = typeof a == "string" ? {} : { ...a.colorReplacements }, I = typeof a == "string" ? a : a.name;
	for (let [a, L] of Object.entries(P?.colorReplacements || {})) typeof L == "string" ? F[a] = L : a === I && Object.assign(F, L);
	return F;
}
function applyColorReplacements(a, P) {
	return a && (P?.[a?.toLowerCase()] || a);
}
function toArray(a) {
	return Array.isArray(a) ? a : [a];
}
async function normalizeGetter(a) {
	return Promise.resolve(typeof a == "function" ? a() : a).then((a) => a.default || a);
}
function isPlainLang(a) {
	return !a || [
		"plaintext",
		"txt",
		"text",
		"plain"
	].includes(a);
}
function isSpecialLang(a) {
	return a === "ansi" || isPlainLang(a);
}
function isNoneTheme(a) {
	return a === "none";
}
function isSpecialTheme(a) {
	return isNoneTheme(a);
}
function addClassToHast(a, P) {
	if (!P) return a;
	a.properties ||= {}, a.properties.class ||= [], typeof a.properties.class == "string" && (a.properties.class = a.properties.class.split(/\s+/g)), Array.isArray(a.properties.class) || (a.properties.class = []);
	let F = Array.isArray(P) ? P : P.split(/\s+/g);
	for (let P of F) P && !a.properties.class.includes(P) && a.properties.class.push(P);
	return a;
}
function splitLines(a, P = !1) {
	if (a.length === 0) return [["", 0]];
	let F = a.split(/(\r?\n)/g), I = 0, L = [];
	for (let a = 0; a < F.length; a += 2) {
		let R = P ? F[a] + (F[a + 1] || "") : F[a];
		L.push([R, I]), I += F[a].length, I += F[a + 1]?.length || 0;
	}
	return L;
}
function createPositionConverter(a) {
	let P = splitLines(a, !0).map(([a]) => a);
	function F(F) {
		if (F === a.length) return {
			line: P.length - 1,
			character: P[P.length - 1].length
		};
		let I = F, L = 0;
		for (let a of P) {
			if (I < a.length) break;
			I -= a.length, L++;
		}
		return {
			line: L,
			character: I
		};
	}
	function I(a, F) {
		let I = 0;
		for (let F = 0; F < a; F++) I += P[F].length;
		return I += F, I;
	}
	return {
		lines: P,
		indexToPos: F,
		posToIndex: I
	};
}
function guessEmbeddedLanguages(a, P, F) {
	let I = /* @__PURE__ */ new Set();
	for (let P of a.matchAll(/:?lang=["']([^"']+)["']/g)) {
		let a = P[1].toLowerCase().trim();
		a && I.add(a);
	}
	for (let P of a.matchAll(/(?:```|~~~)([\w-]+)/g)) {
		let a = P[1].toLowerCase().trim();
		a && I.add(a);
	}
	for (let P of a.matchAll(/\\begin\{([\w-]+)\}/g)) {
		let a = P[1].toLowerCase().trim();
		a && I.add(a);
	}
	for (let P of a.matchAll(/<script\s+(?:type|lang)=["']([^"']+)["']/gi)) {
		let a = P[1].toLowerCase().trim(), F = a.includes("/") ? a.split("/").pop() : a;
		F && I.add(F);
	}
	if (!F) return Array.from(I);
	let L = F.getBundledLanguages();
	return Array.from(I).filter((a) => a && L[a]);
}
var DEFAULT_COLOR_LIGHT_DARK = "light-dark()", COLOR_KEYS = ["color", "background-color"];
function splitToken(a, P) {
	let F = 0, I = [];
	for (let L of P) L > F && I.push({
		...a,
		content: a.content.slice(F, L),
		offset: a.offset + F
	}), F = L;
	return F < a.content.length && I.push({
		...a,
		content: a.content.slice(F),
		offset: a.offset + F
	}), I;
}
function splitTokens(a, P) {
	let F = Array.from(P instanceof Set ? P : new Set(P)).sort((a, P) => a - P);
	return F.length ? a.map((a) => a.flatMap((a) => {
		let P = F.filter((P) => a.offset < P && P < a.offset + a.content.length).map((P) => P - a.offset).sort((a, P) => a - P);
		return P.length ? splitToken(a, P) : a;
	})) : a;
}
function flatTokenVariants(P, F, I, L, R = "css-vars") {
	let z = {
		content: P.content,
		explanation: P.explanation,
		offset: P.offset
	}, B = F.map((a) => getTokenStyleObject(P.variants[a])), V = new Set(B.flatMap((a) => Object.keys(a))), H = {}, U = (a, P) => {
		let L = P === "color" ? "" : P === "background-color" ? "-bg" : `-${P}`;
		return I + F[a] + (P === "color" ? "" : L);
	};
	return B.forEach((P, I) => {
		for (let z of V) {
			let V = P[z] || "inherit";
			if (I === 0 && L && COLOR_KEYS.includes(z)) if (L === DEFAULT_COLOR_LIGHT_DARK && B.length > 1) {
				let P = F.findIndex((a) => a === "light"), L = F.findIndex((a) => a === "dark");
				if (P === -1 || L === -1) throw new ShikiError("When using `defaultColor: \"light-dark()\"`, you must provide both `light` and `dark` themes");
				H[z] = `light-dark(${B[P][z] || "inherit"}, ${B[L][z] || "inherit"})`, R === "css-vars" && (H[U(I, z)] = V);
			} else H[z] = V;
			else R === "css-vars" && (H[U(I, z)] = V);
		}
	}), z.htmlStyle = H, z;
}
function getTokenStyleObject(a) {
	let P = {};
	if (a.color && (P.color = a.color), a.bgColor && (P["background-color"] = a.bgColor), a.fontStyle) {
		a.fontStyle & FontStyle.Italic && (P["font-style"] = "italic"), a.fontStyle & FontStyle.Bold && (P["font-weight"] = "bold");
		let I = [];
		a.fontStyle & FontStyle.Underline && I.push("underline"), a.fontStyle & FontStyle.Strikethrough && I.push("line-through"), I.length && (P["text-decoration"] = I.join(" "));
	}
	return P;
}
function stringifyTokenStyle(a) {
	return typeof a == "string" ? a : Object.entries(a).map(([a, P]) => `${a}:${P}`).join(";");
}
var _grammarStateMap = /* @__PURE__ */ new WeakMap();
function setLastGrammarStateToMap(a, P) {
	_grammarStateMap.set(a, P);
}
function getLastGrammarStateFromMap(a) {
	return _grammarStateMap.get(a);
}
var GrammarState = class a {
	_stacks = {};
	lang;
	get themes() {
		return Object.keys(this._stacks);
	}
	get theme() {
		return this.themes[0];
	}
	get _stack() {
		return this._stacks[this.theme];
	}
	static initial(P, F) {
		return new a(Object.fromEntries(toArray(F).map((a) => [a, INITIAL])), P);
	}
	constructor(...a) {
		if (a.length === 2) {
			let [P, F] = a;
			this.lang = F, this._stacks = P;
		} else {
			let [P, F, I] = a;
			this.lang = F, this._stacks = { [I]: P };
		}
	}
	getInternalStack(a = this.theme) {
		return this._stacks[a];
	}
	getScopes(a = this.theme) {
		return getScopes(this._stacks[a]);
	}
	toJSON() {
		return {
			lang: this.lang,
			theme: this.theme,
			themes: this.themes,
			scopes: this.getScopes()
		};
	}
};
function getScopes(a) {
	let P = [], F = /* @__PURE__ */ new Set();
	function I(a) {
		if (F.has(a)) return;
		F.add(a);
		let L = a?.nameScopesList?.scopeName;
		L && P.push(L), a.parent && I(a.parent);
	}
	return I(a), P;
}
function getGrammarStack(P, F) {
	if (!(P instanceof GrammarState)) throw new ShikiError("Invalid grammar state");
	return P.getInternalStack(F);
}
function transformerDecorations() {
	let P = /* @__PURE__ */ new WeakMap();
	function F(F) {
		if (!P.has(F.meta)) {
			let I = function(P) {
				if (typeof P == "number") {
					if (P < 0 || P > F.source.length) throw new ShikiError(`Invalid decoration offset: ${P}. Code length: ${F.source.length}`);
					return {
						...L.indexToPos(P),
						offset: P
					};
				} else {
					let F = L.lines[P.line];
					if (F === void 0) throw new ShikiError(`Invalid decoration position ${JSON.stringify(P)}. Lines length: ${L.lines.length}`);
					let I = P.character;
					if (I < 0 && (I = F.length + I), I < 0 || I > F.length) throw new ShikiError(`Invalid decoration position ${JSON.stringify(P)}. Line ${P.line} length: ${F.length}`);
					return {
						...P,
						character: I,
						offset: L.posToIndex(P.line, I)
					};
				}
			}, L = createPositionConverter(F.source), R = (F.options.decorations || []).map((a) => ({
				...a,
				start: I(a.start),
				end: I(a.end)
			}));
			verifyIntersections(R), P.set(F.meta, {
				decorations: R,
				converter: L,
				source: F.source
			});
		}
		return P.get(F.meta);
	}
	return {
		name: "shiki:decorations",
		tokens(a) {
			if (this.options.decorations?.length) return splitTokens(a, F(this).decorations.flatMap((a) => [a.start.offset, a.end.offset]));
		},
		code(P) {
			if (!this.options.decorations?.length) return;
			let I = F(this), L = Array.from(P.children).filter((a) => a.type === "element" && a.tagName === "span");
			if (L.length !== I.converter.lines.length) throw new ShikiError(`Number of lines in code element (${L.length}) does not match the number of lines in the source (${I.converter.lines.length}). Failed to apply decorations.`);
			function R(P, F, I, R) {
				let z = L[P], V = "", H = -1, U = -1;
				if (F === 0 && (H = 0), I === 0 && (U = 0), I === Infinity && (U = z.children.length), H === -1 || U === -1) for (let a = 0; a < z.children.length; a++) V += stringify(z.children[a]), H === -1 && V.length === F && (H = a + 1), U === -1 && V.length === I && (U = a + 1);
				if (H === -1) throw new ShikiError(`Failed to find start index for decoration ${JSON.stringify(R.start)}`);
				if (U === -1) throw new ShikiError(`Failed to find end index for decoration ${JSON.stringify(R.end)}`);
				let W = z.children.slice(H, U);
				if (!R.alwaysWrap && W.length === z.children.length) B(z, R, "line");
				else if (!R.alwaysWrap && W.length === 1 && W[0].type === "element") B(W[0], R, "token");
				else {
					let a = {
						type: "element",
						tagName: "span",
						properties: {},
						children: W
					};
					B(a, R, "wrapper"), z.children.splice(H, W.length, a);
				}
			}
			function z(a, P) {
				L[a] = B(L[a], P, "line");
			}
			function B(a, P, F) {
				let I = P.properties || {}, L = P.transform || ((a) => a);
				return a.tagName = P.tagName || "span", a.properties = {
					...a.properties,
					...I,
					class: a.properties.class
				}, P.properties?.class && addClassToHast(a, P.properties.class), a = L(a, F) || a, a;
			}
			let V = [], H = I.decorations.sort((a, P) => P.start.offset - a.start.offset || a.end.offset - P.end.offset);
			for (let a of H) {
				let { start: P, end: F } = a;
				if (P.line === F.line) R(P.line, P.character, F.character, a);
				else if (P.line < F.line) {
					R(P.line, P.character, Infinity, a);
					for (let I = P.line + 1; I < F.line; I++) V.unshift(() => z(I, a));
					R(F.line, 0, F.character, a);
				}
			}
			V.forEach((a) => a());
		}
	};
}
function verifyIntersections(P) {
	for (let F = 0; F < P.length; F++) {
		let I = P[F];
		if (I.start.offset > I.end.offset) throw new ShikiError(`Invalid decoration range: ${JSON.stringify(I.start)} - ${JSON.stringify(I.end)}`);
		for (let L = F + 1; L < P.length; L++) {
			let F = P[L], R = I.start.offset <= F.start.offset && F.start.offset < I.end.offset, z = I.start.offset < F.end.offset && F.end.offset <= I.end.offset, B = F.start.offset <= I.start.offset && I.start.offset < F.end.offset, V = F.start.offset < I.end.offset && I.end.offset <= F.end.offset;
			if (R || z || B || V) {
				if (R && z || B && V || B && I.start.offset === I.end.offset || z && F.start.offset === F.end.offset) continue;
				throw new ShikiError(`Decorations ${JSON.stringify(I.start)} and ${JSON.stringify(F.start)} intersect.`);
			}
		}
	}
}
function stringify(a) {
	return a.type === "text" ? a.value : a.type === "element" ? a.children.map(stringify).join("") : "";
}
var builtInTransformers = [/* @__PURE__ */ transformerDecorations()];
function getTransformers(a) {
	let P = sortTransformersByEnforcement(a.transformers || []);
	return [
		...P.pre,
		...P.normal,
		...P.post,
		...builtInTransformers
	];
}
function sortTransformersByEnforcement(a) {
	let P = [], F = [], I = [];
	for (let L of a) switch (L.enforce) {
		case "pre":
			P.push(L);
			break;
		case "post":
			F.push(L);
			break;
		default: I.push(L);
	}
	return {
		pre: P,
		post: F,
		normal: I
	};
}
var namedColors = [
	"black",
	"red",
	"green",
	"yellow",
	"blue",
	"magenta",
	"cyan",
	"white",
	"brightBlack",
	"brightRed",
	"brightGreen",
	"brightYellow",
	"brightBlue",
	"brightMagenta",
	"brightCyan",
	"brightWhite"
], decorations = {
	1: "bold",
	2: "dim",
	3: "italic",
	4: "underline",
	7: "reverse",
	8: "hidden",
	9: "strikethrough"
};
function findSequence(a, P) {
	let F = a.indexOf("\x1B", P);
	if (F !== -1 && a[F + 1] === "[") {
		let P = a.indexOf("m", F);
		if (P !== -1) return {
			sequence: a.substring(F + 2, P).split(";"),
			startPosition: F,
			position: P + 1
		};
	}
	return { position: a.length };
}
function parseColor(a) {
	let P = a.shift();
	if (P === "2") {
		let P = a.splice(0, 3).map((a) => Number.parseInt(a));
		return P.length !== 3 || P.some((a) => Number.isNaN(a)) ? void 0 : {
			type: "rgb",
			rgb: P
		};
	} else if (P === "5") {
		let P = a.shift();
		if (P) return {
			type: "table",
			index: Number(P)
		};
	}
}
function parseSequence(a) {
	let P = [];
	for (; a.length > 0;) {
		let F = a.shift();
		if (!F) continue;
		let I = Number.parseInt(F);
		if (!Number.isNaN(I)) if (I === 0) P.push({ type: "resetAll" });
		else if (I <= 9) decorations[I] && P.push({
			type: "setDecoration",
			value: decorations[I]
		});
		else if (I <= 29) {
			let a = decorations[I - 20];
			a && (P.push({
				type: "resetDecoration",
				value: a
			}), a === "dim" && P.push({
				type: "resetDecoration",
				value: "bold"
			}));
		} else if (I <= 37) P.push({
			type: "setForegroundColor",
			value: {
				type: "named",
				name: namedColors[I - 30]
			}
		});
		else if (I === 38) {
			let F = parseColor(a);
			F && P.push({
				type: "setForegroundColor",
				value: F
			});
		} else if (I === 39) P.push({ type: "resetForegroundColor" });
		else if (I <= 47) P.push({
			type: "setBackgroundColor",
			value: {
				type: "named",
				name: namedColors[I - 40]
			}
		});
		else if (I === 48) {
			let F = parseColor(a);
			F && P.push({
				type: "setBackgroundColor",
				value: F
			});
		} else I === 49 ? P.push({ type: "resetBackgroundColor" }) : I === 53 ? P.push({
			type: "setDecoration",
			value: "overline"
		}) : I === 55 ? P.push({
			type: "resetDecoration",
			value: "overline"
		}) : I >= 90 && I <= 97 ? P.push({
			type: "setForegroundColor",
			value: {
				type: "named",
				name: namedColors[I - 90 + 8]
			}
		}) : I >= 100 && I <= 107 && P.push({
			type: "setBackgroundColor",
			value: {
				type: "named",
				name: namedColors[I - 100 + 8]
			}
		});
	}
	return P;
}
function createAnsiSequenceParser() {
	let a = null, P = null, F = /* @__PURE__ */ new Set();
	return { parse(I) {
		let L = [], R = 0;
		do {
			let z = findSequence(I, R), B = z.sequence ? I.substring(R, z.startPosition) : I.substring(R);
			if (B.length > 0 && L.push({
				value: B,
				foreground: a,
				background: P,
				decorations: new Set(F)
			}), z.sequence) {
				let I = parseSequence(z.sequence);
				for (let L of I) L.type === "resetAll" ? (a = null, P = null, F.clear()) : L.type === "resetForegroundColor" ? a = null : L.type === "resetBackgroundColor" ? P = null : L.type === "resetDecoration" && F.delete(L.value);
				for (let L of I) L.type === "setForegroundColor" ? a = L.value : L.type === "setBackgroundColor" ? P = L.value : L.type === "setDecoration" && F.add(L.value);
			}
			R = z.position;
		} while (R < I.length);
		return L;
	} };
}
var defaultNamedColorsMap = {
	black: "#000000",
	red: "#bb0000",
	green: "#00bb00",
	yellow: "#bbbb00",
	blue: "#0000bb",
	magenta: "#ff00ff",
	cyan: "#00bbbb",
	white: "#eeeeee",
	brightBlack: "#555555",
	brightRed: "#ff5555",
	brightGreen: "#00ff00",
	brightYellow: "#ffff55",
	brightBlue: "#5555ff",
	brightMagenta: "#ff55ff",
	brightCyan: "#55ffff",
	brightWhite: "#ffffff"
};
function createColorPalette(a = defaultNamedColorsMap) {
	function P(P) {
		return a[P];
	}
	function F(a) {
		return `#${a.map((a) => Math.max(0, Math.min(a, 255)).toString(16).padStart(2, "0")).join("")}`;
	}
	let I;
	function L() {
		if (I) return I;
		I = [];
		for (let a = 0; a < namedColors.length; a++) I.push(P(namedColors[a]));
		let a = [
			0,
			95,
			135,
			175,
			215,
			255
		];
		for (let P = 0; P < 6; P++) for (let L = 0; L < 6; L++) for (let R = 0; R < 6; R++) I.push(F([
			a[P],
			a[L],
			a[R]
		]));
		let L = 8;
		for (let a = 0; a < 24; a++, L += 10) I.push(F([
			L,
			L,
			L
		]));
		return I;
	}
	function R(a) {
		return L()[a];
	}
	function z(a) {
		switch (a.type) {
			case "named": return P(a.name);
			case "rgb": return F(a.rgb);
			case "table": return R(a.index);
		}
	}
	return { value: z };
}
var defaultAnsiColors = {
	black: "#000000",
	red: "#cd3131",
	green: "#0DBC79",
	yellow: "#E5E510",
	blue: "#2472C8",
	magenta: "#BC3FBC",
	cyan: "#11A8CD",
	white: "#E5E5E5",
	brightBlack: "#666666",
	brightRed: "#F14C4C",
	brightGreen: "#23D18B",
	brightYellow: "#F5F543",
	brightBlue: "#3B8EEA",
	brightMagenta: "#D670D6",
	brightCyan: "#29B8DB",
	brightWhite: "#FFFFFF"
};
function tokenizeAnsiWithTheme(a, P, I) {
	let L = resolveColorReplacements(a, I), R = splitLines(P), z = createColorPalette(Object.fromEntries(namedColors.map((P) => {
		let F = `terminal.ansi${P[0].toUpperCase()}${P.substring(1)}`;
		return [P, a.colors?.[F] || defaultAnsiColors[P]];
	}))), H = createAnsiSequenceParser();
	return R.map((P) => H.parse(P[0]).map((I) => {
		let R, B;
		I.decorations.has("reverse") ? (R = I.background ? z.value(I.background) : a.bg, B = I.foreground ? z.value(I.foreground) : a.fg) : (R = I.foreground ? z.value(I.foreground) : a.fg, B = I.background ? z.value(I.background) : void 0), R = applyColorReplacements(R, L), B = applyColorReplacements(B, L), I.decorations.has("dim") && (R = dimColor(R));
		let H = FontStyle.None;
		return I.decorations.has("bold") && (H |= FontStyle.Bold), I.decorations.has("italic") && (H |= FontStyle.Italic), I.decorations.has("underline") && (H |= FontStyle.Underline), I.decorations.has("strikethrough") && (H |= FontStyle.Strikethrough), {
			content: I.value,
			offset: P[1],
			color: R,
			bgColor: B,
			fontStyle: H
		};
	}));
}
function dimColor(a) {
	let P = a.match(/#([0-9a-f]{3,8})/i);
	if (P) {
		let a = P[1];
		if (a.length === 8) {
			let P = Math.round(Number.parseInt(a.slice(6, 8), 16) / 2).toString(16).padStart(2, "0");
			return `#${a.slice(0, 6)}${P}`;
		} else if (a.length === 6) return `#${a}80`;
		else if (a.length === 4) {
			let P = a[0], F = a[1], I = a[2], L = a[3];
			return `#${P}${P}${F}${F}${I}${I}${Math.round(Number.parseInt(`${L}${L}`, 16) / 2).toString(16).padStart(2, "0")}`;
		} else if (a.length === 3) {
			let P = a[0], F = a[1], I = a[2];
			return `#${P}${P}${F}${F}${I}${I}80`;
		}
	}
	let F = a.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);
	return F ? `var(${F[1]}-dim)` : a;
}
function codeToTokensBase(P, F, I = {}) {
	let { theme: L = P.getLoadedThemes()[0] } = I, R = P.resolveLangAlias(I.lang || "text");
	if (isPlainLang(R) || isNoneTheme(L)) return splitLines(F).map((a) => [{
		content: a[0],
		offset: a[1]
	}]);
	let { theme: z, colorMap: B } = P.setTheme(L);
	if (R === "ansi") return tokenizeAnsiWithTheme(z, F, I);
	let V = P.getLanguage(I.lang || "text");
	if (I.grammarState) {
		if (I.grammarState.lang !== V.name) throw new ShikiError(`Grammar state language "${I.grammarState.lang}" does not match highlight language "${V.name}"`);
		if (!I.grammarState.themes.includes(z.name)) throw new ShikiError(`Grammar state themes "${I.grammarState.themes}" do not contain highlight theme "${z.name}"`);
	}
	return tokenizeWithTheme(F, V, z, B, I);
}
function getLastGrammarState(...P) {
	if (P.length === 2) return getLastGrammarStateFromMap(P[1]);
	let [F, I, L = {}] = P, { lang: R = "text", theme: z = F.getLoadedThemes()[0] } = L;
	if (isPlainLang(R) || isNoneTheme(z)) throw new ShikiError("Plain language does not have grammar state");
	if (R === "ansi") throw new ShikiError("ANSI language does not have grammar state");
	let { theme: B, colorMap: V } = F.setTheme(z), H = F.getLanguage(R);
	return new GrammarState(_tokenizeWithTheme(I, H, B, V, L).stateStack, H.name, B.name);
}
function tokenizeWithTheme(a, P, F, I, L) {
	let R = _tokenizeWithTheme(a, P, F, I, L), z = new GrammarState(R.stateStack, P.name, F.name);
	return setLastGrammarStateToMap(R.tokens, z), R.tokens;
}
function _tokenizeWithTheme(a, F, L, R, z) {
	let H = resolveColorReplacements(L, z), { tokenizeMaxLineLength: U = 0, tokenizeTimeLimit: W = 500 } = z, G = splitLines(a), K = z.grammarState ? getGrammarStack(z.grammarState, L.name) ?? INITIAL : z.grammarContextCode == null ? INITIAL : _tokenizeWithTheme(z.grammarContextCode, F, L, R, {
		...z,
		grammarState: void 0,
		grammarContextCode: void 0
	}).stateStack, q = [], J = [];
	for (let a = 0, I = G.length; a < I; a++) {
		let [I, B] = G[a];
		if (I === "") {
			q = [], J.push([]);
			continue;
		}
		if (U > 0 && I.length >= U) {
			q = [], J.push([{
				content: I,
				offset: B,
				color: "",
				fontStyle: 0
			}]);
			continue;
		}
		let Y, X, Z;
		z.includeExplanation && (Y = F.tokenizeLine(I, K, W), X = Y.tokens, Z = 0);
		let Q = F.tokenizeLine2(I, K, W), $ = Q.tokens.length / 2;
		for (let a = 0; a < $; a++) {
			let F = Q.tokens[2 * a], U = a + 1 < $ ? Q.tokens[2 * a + 2] : I.length;
			if (F === U) continue;
			let W = Q.tokens[2 * a + 1], G = applyColorReplacements(R[EncodedTokenMetadata.getForeground(W)], H), K = EncodedTokenMetadata.getFontStyle(W), J = {
				content: I.substring(F, U),
				offset: B + F,
				color: G,
				fontStyle: K
			};
			if (z.includeExplanation) {
				let a = [];
				if (z.includeExplanation !== "scopeName") for (let P of L.settings) {
					let F;
					switch (typeof P.scope) {
						case "string":
							F = P.scope.split(/,/).map((a) => a.trim());
							break;
						case "object":
							F = P.scope;
							break;
						default: continue;
					}
					a.push({
						settings: P,
						selectors: F.map((a) => a.split(/ /))
					});
				}
				J.explanation = [];
				let P = 0;
				for (; F + P < U;) {
					let F = X[Z], L = I.substring(F.startIndex, F.endIndex);
					P += L.length, J.explanation.push({
						content: L,
						scopes: z.includeExplanation === "scopeName" ? explainThemeScopesNameOnly(F.scopes) : explainThemeScopesFull(a, F.scopes)
					}), Z += 1;
				}
			}
			q.push(J);
		}
		J.push(q), q = [], K = Q.ruleStack;
	}
	return {
		tokens: J,
		stateStack: K
	};
}
function explainThemeScopesNameOnly(a) {
	return a.map((a) => ({ scopeName: a }));
}
function explainThemeScopesFull(a, P) {
	let F = [];
	for (let I = 0, L = P.length; I < L; I++) {
		let L = P[I];
		F[I] = {
			scopeName: L,
			themeMatches: explainThemeScope(a, L, P.slice(0, I))
		};
	}
	return F;
}
function matchesOne(a, P) {
	return a === P || P.substring(0, a.length) === a && P[a.length] === ".";
}
function matches(a, P, F) {
	if (!matchesOne(a[a.length - 1], P)) return !1;
	let I = a.length - 2, L = F.length - 1;
	for (; I >= 0 && L >= 0;) matchesOne(a[I], F[L]) && --I, --L;
	return I === -1;
}
function explainThemeScope(a, P, F) {
	let I = [];
	for (let { selectors: L, settings: R } of a) for (let a of L) if (matches(a, P, F)) {
		I.push(R);
		break;
	}
	return I;
}
function codeToTokensWithThemes(a, P, F) {
	let I = Object.entries(F.themes).filter((a) => a[1]).map((a) => ({
		color: a[0],
		theme: a[1]
	})), L = I.map((I) => {
		let L = codeToTokensBase(a, P, {
			...F,
			theme: I.theme
		});
		return {
			tokens: L,
			state: getLastGrammarStateFromMap(L),
			theme: typeof I.theme == "string" ? I.theme : I.theme.name
		};
	}), R = syncThemesTokenization(...L.map((a) => a.tokens)), z = R[0].map((a, P) => a.map((a, L) => {
		let z = {
			content: a.content,
			variants: {},
			offset: a.offset
		};
		return "includeExplanation" in F && F.includeExplanation && (z.explanation = a.explanation), R.forEach((a, F) => {
			let { content: R, explanation: B, offset: V, ...H } = a[P][L];
			z.variants[I[F].color] = H;
		}), z;
	})), B = L[0].state ? new GrammarState(Object.fromEntries(L.map((a) => [a.theme, a.state?.getInternalStack(a.theme)])), L[0].state.lang) : void 0;
	return B && setLastGrammarStateToMap(z, B), z;
}
function syncThemesTokenization(...a) {
	let P = a.map(() => []), F = a.length;
	for (let I = 0; I < a[0].length; I++) {
		let L = a.map((a) => a[I]), R = P.map(() => []);
		P.forEach((a, P) => a.push(R[P]));
		let z = L.map(() => 0), B = L.map((a) => a[0]);
		for (; B.every((a) => a);) {
			let a = Math.min(...B.map((a) => a.content.length));
			for (let P = 0; P < F; P++) {
				let F = B[P];
				F.content.length === a ? (R[P].push(F), z[P] += 1, B[P] = L[P][z[P]]) : (R[P].push({
					...F,
					content: F.content.slice(0, a)
				}), B[P] = {
					...F,
					content: F.content.slice(a),
					offset: F.offset + a
				});
			}
		}
	}
	return P;
}
function codeToTokens(P, F, I) {
	let L, R, z, H, U, W;
	if ("themes" in I) {
		let { defaultColor: V = "light", cssVariablePrefix: G = "--shiki-", colorsRendering: K = "css-vars" } = I, q = Object.entries(I.themes).filter((a) => a[1]).map((a) => ({
			color: a[0],
			theme: a[1]
		})).sort((a, P) => a.color === V ? -1 : P.color === V ? 1 : 0);
		if (q.length === 0) throw new ShikiError("`themes` option must not be empty");
		let J = codeToTokensWithThemes(P, F, I);
		if (W = getLastGrammarStateFromMap(J), V && DEFAULT_COLOR_LIGHT_DARK !== V && !q.find((a) => a.color === V)) throw new ShikiError(`\`themes\` option must contain the defaultColor key \`${V}\``);
		let Y = q.map((a) => P.getTheme(a.theme)), X = q.map((a) => a.color);
		z = J.map((a) => a.map((a) => flatTokenVariants(a, X, G, V, K))), W && setLastGrammarStateToMap(z, W);
		let Z = q.map((a) => resolveColorReplacements(a.theme, I));
		R = mapThemeColors(q, Y, Z, G, V, "fg", K), L = mapThemeColors(q, Y, Z, G, V, "bg", K), H = `shiki-themes ${Y.map((a) => a.name).join(" ")}`, U = V ? void 0 : [R, L].join(";");
	} else if ("theme" in I) {
		let a = resolveColorReplacements(I.theme, I);
		z = codeToTokensBase(P, F, I);
		let U = P.getTheme(I.theme);
		L = applyColorReplacements(U.bg, a), R = applyColorReplacements(U.fg, a), H = U.name, W = getLastGrammarStateFromMap(z);
	} else throw new ShikiError("Invalid options, either `theme` or `themes` must be provided");
	return {
		tokens: z,
		fg: R,
		bg: L,
		themeName: H,
		rootStyle: U,
		grammarState: W
	};
}
function mapThemeColors(P, F, I, L, R, z, B) {
	return P.map((H, U) => {
		let W = applyColorReplacements(F[U][z], I[U]) || "inherit", G = `${L + H.color}${z === "bg" ? "-bg" : ""}:${W}`;
		if (U === 0 && R) {
			if (R === DEFAULT_COLOR_LIGHT_DARK && P.length > 1) {
				let L = P.findIndex((a) => a.color === "light"), R = P.findIndex((a) => a.color === "dark");
				if (L === -1 || R === -1) throw new ShikiError("When using `defaultColor: \"light-dark()\"`, you must provide both `light` and `dark` themes");
				return `light-dark(${applyColorReplacements(F[L][z], I[L]) || "inherit"}, ${applyColorReplacements(F[R][z], I[R]) || "inherit"});${G}`;
			}
			return W;
		}
		return B === "css-vars" ? G : null;
	}).filter((a) => !!a).join(";");
}
function codeToHast(a, P, F, I = {
	meta: {},
	options: F,
	codeToHast: (P, F) => codeToHast(a, P, F),
	codeToTokens: (P, F) => codeToTokens(a, P, F)
}) {
	let L = P;
	for (let a of getTransformers(F)) L = a.preprocess?.call(I, L, F) || L;
	let { tokens: R, fg: z, bg: B, themeName: V, rootStyle: H, grammarState: U } = codeToTokens(a, L, F), { mergeWhitespaces: W = !0, mergeSameStyleTokens: G = !1 } = F;
	W === !0 ? R = mergeWhitespaceTokens(R) : W === "never" && (R = splitWhitespaceTokens(R)), G && (R = mergeAdjacentStyledTokens(R));
	let K = {
		...I,
		get source() {
			return L;
		}
	};
	for (let a of getTransformers(F)) R = a.tokens?.call(K, R) || R;
	return tokensToHast(R, {
		...F,
		fg: z,
		bg: B,
		themeName: V,
		rootStyle: F.rootStyle === !1 ? !1 : F.rootStyle ?? H
	}, K, U);
}
function tokensToHast(a, P, F, I = getLastGrammarStateFromMap(a)) {
	let L = getTransformers(P), R = [], z = {
		type: "root",
		children: []
	}, { structure: B = "classic", tabindex: V = "0" } = P, H = { class: `shiki ${P.themeName || ""}` };
	P.rootStyle !== !1 && (P.rootStyle == null ? H.style = `background-color:${P.bg};color:${P.fg}` : H.style = P.rootStyle), V !== !1 && V != null && (H.tabindex = V.toString());
	for (let [a, F] of Object.entries(P.meta || {})) a.startsWith("_") || (H[a] = F);
	let U = {
		type: "element",
		tagName: "pre",
		properties: H,
		children: [],
		data: P.data
	}, W = {
		type: "element",
		tagName: "code",
		properties: {},
		children: R
	}, G = [], K = {
		...F,
		structure: B,
		addClassToHast,
		get source() {
			return F.source;
		},
		get tokens() {
			return a;
		},
		get options() {
			return P;
		},
		get root() {
			return z;
		},
		get pre() {
			return U;
		},
		get code() {
			return W;
		},
		get lines() {
			return G;
		}
	};
	if (a.forEach((a, P) => {
		P && (B === "inline" ? z.children.push({
			type: "element",
			tagName: "br",
			properties: {},
			children: []
		}) : B === "classic" && R.push({
			type: "text",
			value: "\n"
		}));
		let F = {
			type: "element",
			tagName: "span",
			properties: { class: "line" },
			children: []
		}, I = 0;
		for (let R of a) {
			let a = {
				type: "element",
				tagName: "span",
				properties: { ...R.htmlAttrs },
				children: [{
					type: "text",
					value: R.content
				}]
			}, V = stringifyTokenStyle(R.htmlStyle || getTokenStyleObject(R));
			V && (a.properties.style = V);
			for (let z of L) a = z?.span?.call(K, a, P + 1, I, F, R) || a;
			B === "inline" ? z.children.push(a) : B === "classic" && F.children.push(a), I += R.content.length;
		}
		if (B === "classic") {
			for (let a of L) F = a?.line?.call(K, F, P + 1) || F;
			G.push(F), R.push(F);
		} else B === "inline" && G.push(F);
	}), B === "classic") {
		for (let a of L) W = a?.code?.call(K, W) || W;
		U.children.push(W);
		for (let a of L) U = a?.pre?.call(K, U) || U;
		z.children.push(U);
	} else if (B === "inline") {
		let a = [], P = {
			type: "element",
			tagName: "span",
			properties: { class: "line" },
			children: []
		};
		for (let F of z.children) F.type === "element" && F.tagName === "br" ? (a.push(P), P = {
			type: "element",
			tagName: "span",
			properties: { class: "line" },
			children: []
		}) : (F.type === "element" || F.type === "text") && P.children.push(F);
		a.push(P);
		let F = {
			type: "element",
			tagName: "code",
			properties: {},
			children: a
		};
		for (let a of L) F = a?.code?.call(K, F) || F;
		z.children = [];
		for (let a = 0; a < F.children.length; a++) {
			a > 0 && z.children.push({
				type: "element",
				tagName: "br",
				properties: {},
				children: []
			});
			let P = F.children[a];
			P.type === "element" && z.children.push(...P.children);
		}
	}
	let q = z;
	for (let a of L) q = a?.root?.call(K, q) || q;
	return I && setLastGrammarStateToMap(q, I), q;
}
function mergeWhitespaceTokens(a) {
	return a.map((a) => {
		let P = [], I = "", L;
		return a.forEach((R, z) => {
			let B = !(R.fontStyle && (R.fontStyle & FontStyle.Underline || R.fontStyle & FontStyle.Strikethrough));
			B && R.content.match(/^\s+$/) && a[z + 1] ? (L === void 0 && (L = R.offset), I += R.content) : I ? (B ? P.push({
				...R,
				offset: L,
				content: I + R.content
			}) : P.push({
				content: I,
				offset: L
			}, R), L = void 0, I = "") : P.push(R);
		}), P;
	});
}
function splitWhitespaceTokens(a) {
	return a.map((a) => a.flatMap((a) => {
		if (a.content.match(/^\s+$/)) return a;
		let P = a.content.match(/^(\s*)(.*?)(\s*)$/);
		if (!P) return a;
		let [, F, I, L] = P;
		if (!F && !L) return a;
		let R = [{
			...a,
			offset: a.offset + F.length,
			content: I
		}];
		return F && R.unshift({
			content: F,
			offset: a.offset
		}), L && R.push({
			content: L,
			offset: a.offset + F.length + I.length
		}), R;
	}));
}
function mergeAdjacentStyledTokens(a) {
	return a.map((a) => {
		let P = [];
		for (let I of a) {
			if (P.length === 0) {
				P.push({ ...I });
				continue;
			}
			let a = P[P.length - 1], L = stringifyTokenStyle(a.htmlStyle || getTokenStyleObject(a)), R = stringifyTokenStyle(I.htmlStyle || getTokenStyleObject(I)), z = a.fontStyle && (a.fontStyle & FontStyle.Underline || a.fontStyle & FontStyle.Strikethrough), B = I.fontStyle && (I.fontStyle & FontStyle.Underline || I.fontStyle & FontStyle.Strikethrough);
			!z && !B && L === R ? a.content += I.content : P.push({ ...I });
		}
		return P;
	});
}
var hastToHtml = toHtml;
function codeToHtml(a, P, F) {
	let I = {
		meta: {},
		options: F,
		codeToHast: (P, F) => codeToHast(a, P, F),
		codeToTokens: (P, F) => codeToTokens(a, P, F)
	}, L = hastToHtml(codeToHast(a, P, F, I));
	for (let a of getTransformers(F)) L = a.postprocess?.call(I, L, F) || L;
	return L;
}
var VSCODE_FALLBACK_EDITOR_FG = {
	light: "#333333",
	dark: "#bbbbbb"
}, VSCODE_FALLBACK_EDITOR_BG = {
	light: "#fffffe",
	dark: "#1e1e1e"
}, RESOLVED_KEY = "__shiki_resolved";
function normalizeTheme(a) {
	if (a?.[RESOLVED_KEY]) return a;
	let P = { ...a };
	P.tokenColors && !P.settings && (P.settings = P.tokenColors, delete P.tokenColors), P.type ||= "dark", P.colorReplacements = { ...P.colorReplacements }, P.settings ||= [];
	let { bg: F, fg: I } = P;
	if (!F || !I) {
		let a = P.settings ? P.settings.find((a) => !a.name && !a.scope) : void 0;
		a?.settings?.foreground && (I = a.settings.foreground), a?.settings?.background && (F = a.settings.background), !I && P?.colors?.["editor.foreground"] && (I = P.colors["editor.foreground"]), !F && P?.colors?.["editor.background"] && (F = P.colors["editor.background"]), I ||= P.type === "light" ? VSCODE_FALLBACK_EDITOR_FG.light : VSCODE_FALLBACK_EDITOR_FG.dark, F ||= P.type === "light" ? VSCODE_FALLBACK_EDITOR_BG.light : VSCODE_FALLBACK_EDITOR_BG.dark, P.fg = I, P.bg = F;
	}
	P.settings[0] && P.settings[0].settings && !P.settings[0].scope || P.settings.unshift({ settings: {
		foreground: P.fg,
		background: P.bg
	} });
	let L = 0, R = /* @__PURE__ */ new Map();
	function z(a) {
		if (R.has(a)) return R.get(a);
		L += 1;
		let F = `#${L.toString(16).padStart(8, "0").toLowerCase()}`;
		return P.colorReplacements?.[`#${F}`] ? z(a) : (R.set(a, F), F);
	}
	P.settings = P.settings.map((a) => {
		let F = a.settings?.foreground && !a.settings.foreground.startsWith("#"), I = a.settings?.background && !a.settings.background.startsWith("#");
		if (!F && !I) return a;
		let L = {
			...a,
			settings: { ...a.settings }
		};
		if (F) {
			let F = z(a.settings.foreground);
			P.colorReplacements[F] = a.settings.foreground, L.settings.foreground = F;
		}
		if (I) {
			let F = z(a.settings.background);
			P.colorReplacements[F] = a.settings.background, L.settings.background = F;
		}
		return L;
	});
	for (let a of Object.keys(P.colors || {})) if ((a === "editor.foreground" || a === "editor.background" || a.startsWith("terminal.ansi")) && !P.colors[a]?.startsWith("#")) {
		let F = z(P.colors[a]);
		P.colorReplacements[F] = P.colors[a], P.colors[a] = F;
	}
	return Object.defineProperty(P, RESOLVED_KEY, {
		enumerable: !1,
		writable: !1,
		value: !0
	}), P;
}
async function resolveLangs(a) {
	return Array.from(new Set((await Promise.all(a.filter((a) => !isSpecialLang(a)).map(async (a) => await normalizeGetter(a).then((a) => Array.isArray(a) ? a : [a])))).flat()));
}
async function resolveThemes(a) {
	return (await Promise.all(a.map(async (a) => isSpecialTheme(a) ? null : normalizeTheme(await normalizeGetter(a))))).filter((a) => !!a);
}
var _emitDeprecation = 3, _emitError = !1;
function warnDeprecated(a, P = 3) {
	if (_emitDeprecation && !(typeof _emitDeprecation == "number" && P > _emitDeprecation)) {
		if (_emitError) throw Error(`[SHIKI DEPRECATE]: ${a}`);
		console.trace(`[SHIKI DEPRECATE]: ${a}`);
	}
}
var ShikiError$1 = class extends Error {
	constructor(a) {
		super(a), this.name = "ShikiError";
	}
};
function resolveLangAlias(a, P) {
	if (!P) return a;
	if (P[a]) {
		let F = /* @__PURE__ */ new Set([a]);
		for (; P[a];) {
			if (a = P[a], F.has(a)) throw new ShikiError$1(`Circular alias \`${Array.from(F).join(" -> ")} -> ${a}\``);
			F.add(a);
		}
	}
	return a;
}
var Registry$1 = class extends Registry {
	constructor(a, P, F, I = {}) {
		super(a), this._resolver = a, this._themes = P, this._langs = F, this._alias = I, this._themes.map((a) => this.loadTheme(a)), this.loadLanguages(this._langs);
	}
	_resolvedThemes = /* @__PURE__ */ new Map();
	_resolvedGrammars = /* @__PURE__ */ new Map();
	_langMap = /* @__PURE__ */ new Map();
	_langGraph = /* @__PURE__ */ new Map();
	_textmateThemeCache = /* @__PURE__ */ new WeakMap();
	_loadedThemesCache = null;
	_loadedLanguagesCache = null;
	getTheme(a) {
		return typeof a == "string" ? this._resolvedThemes.get(a) : this.loadTheme(a);
	}
	loadTheme(a) {
		let P = normalizeTheme(a);
		return P.name && (this._resolvedThemes.set(P.name, P), this._loadedThemesCache = null), P;
	}
	getLoadedThemes() {
		return this._loadedThemesCache ||= [...this._resolvedThemes.keys()], this._loadedThemesCache;
	}
	setTheme(a) {
		let P = this._textmateThemeCache.get(a);
		P || (P = Theme.createFromRawTheme(a), this._textmateThemeCache.set(a, P)), this._syncRegistry.setTheme(P);
	}
	getGrammar(a) {
		return a = resolveLangAlias(a, this._alias), this._resolvedGrammars.get(a);
	}
	loadLanguage(a) {
		if (this.getGrammar(a.name)) return;
		let P = new Set([...this._langMap.values()].filter((P) => P.embeddedLangsLazy?.includes(a.name)));
		this._resolver.addLanguage(a);
		let F = {
			balancedBracketSelectors: a.balancedBracketSelectors || ["*"],
			unbalancedBracketSelectors: a.unbalancedBracketSelectors || []
		};
		this._syncRegistry._rawGrammars.set(a.scopeName, a);
		let I = this.loadGrammarWithConfiguration(a.scopeName, 1, F);
		if (I.name = a.name, this._resolvedGrammars.set(a.name, I), a.aliases && a.aliases.forEach((P) => {
			this._alias[P] = a.name;
		}), this._loadedLanguagesCache = null, P.size) for (let a of P) this._resolvedGrammars.delete(a.name), this._loadedLanguagesCache = null, this._syncRegistry?._injectionGrammars?.delete(a.scopeName), this._syncRegistry?._grammars?.delete(a.scopeName), this.loadLanguage(this._langMap.get(a.name));
	}
	dispose() {
		super.dispose(), this._resolvedThemes.clear(), this._resolvedGrammars.clear(), this._langMap.clear(), this._langGraph.clear(), this._loadedThemesCache = null;
	}
	loadLanguages(a) {
		for (let P of a) this.resolveEmbeddedLanguages(P);
		let P = Array.from(this._langGraph.entries()), F = P.filter(([a, P]) => !P);
		if (F.length) {
			let a = P.filter(([a, P]) => P ? (P.embeddedLanguages || P.embeddedLangs)?.some((a) => F.map(([a]) => a).includes(a)) : !1).filter((a) => !F.includes(a));
			throw new ShikiError$1(`Missing languages ${F.map(([a]) => `\`${a}\``).join(", ")}, required by ${a.map(([a]) => `\`${a}\``).join(", ")}`);
		}
		for (let [a, F] of P) this._resolver.addLanguage(F);
		for (let [a, F] of P) this.loadLanguage(F);
	}
	getLoadedLanguages() {
		return this._loadedLanguagesCache ||= [.../* @__PURE__ */ new Set([...this._resolvedGrammars.keys(), ...Object.keys(this._alias)])], this._loadedLanguagesCache;
	}
	resolveEmbeddedLanguages(a) {
		this._langMap.set(a.name, a), this._langGraph.set(a.name, a);
		let P = a.embeddedLanguages ?? a.embeddedLangs;
		if (P) for (let a of P) this._langGraph.set(a, this._langMap.get(a));
	}
}, Resolver = class {
	_langs = /* @__PURE__ */ new Map();
	_scopeToLang = /* @__PURE__ */ new Map();
	_injections = /* @__PURE__ */ new Map();
	_onigLib;
	constructor(a, P) {
		this._onigLib = {
			createOnigScanner: (P) => a.createScanner(P),
			createOnigString: (P) => a.createString(P)
		}, P.forEach((a) => this.addLanguage(a));
	}
	get onigLib() {
		return this._onigLib;
	}
	getLangRegistration(a) {
		return this._langs.get(a);
	}
	loadGrammar(a) {
		return this._scopeToLang.get(a);
	}
	addLanguage(a) {
		this._langs.set(a.name, a), a.aliases && a.aliases.forEach((P) => {
			this._langs.set(P, a);
		}), this._scopeToLang.set(a.scopeName, a), a.injectTo && a.injectTo.forEach((P) => {
			this._injections.get(P) || this._injections.set(P, []), this._injections.get(P).push(a.scopeName);
		});
	}
	getInjections(a) {
		let P = a.split("."), F = [];
		for (let a = 1; a <= P.length; a++) {
			let I = P.slice(0, a).join(".");
			F = [...F, ...this._injections.get(I) || []];
		}
		return F;
	}
}, instancesCount = 0;
function createShikiInternalSync(a) {
	instancesCount += 1, a.warnings !== !1 && instancesCount >= 10 && instancesCount % 10 == 0 && console.warn(`[Shiki] ${instancesCount} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);
	let P = !1;
	if (!a.engine) throw new ShikiError$1("`engine` option is required for synchronous mode");
	let F = (a.langs || []).flat(1), I = (a.themes || []).flat(1).map(normalizeTheme), L = new Registry$1(new Resolver(a.engine, F), I, F, a.langAlias), R;
	function z(P) {
		return resolveLangAlias(P, a.langAlias);
	}
	function B(a) {
		Y();
		let P = L.getGrammar(typeof a == "string" ? a : a.name);
		if (!P) throw new ShikiError$1(`Language \`${a}\` not found, you may need to load it first`);
		return P;
	}
	function V(a) {
		if (a === "none") return {
			bg: "",
			fg: "",
			name: "none",
			settings: [],
			type: "dark"
		};
		Y();
		let P = L.getTheme(a);
		if (!P) throw new ShikiError$1(`Theme \`${a}\` not found, you may need to load it first`);
		return P;
	}
	function H(a) {
		Y();
		let P = V(a);
		return R !== a && (L.setTheme(P), R = a), {
			theme: P,
			colorMap: L.getColorMap()
		};
	}
	function U() {
		return Y(), L.getLoadedThemes();
	}
	function W() {
		return Y(), L.getLoadedLanguages();
	}
	function G(...a) {
		Y(), L.loadLanguages(a.flat(1));
	}
	async function K(...a) {
		return G(await resolveLangs(a));
	}
	function q(...a) {
		Y();
		for (let P of a.flat(1)) L.loadTheme(P);
	}
	async function J(...a) {
		return Y(), q(await resolveThemes(a));
	}
	function Y() {
		if (P) throw new ShikiError$1("Shiki instance has been disposed");
	}
	function X() {
		P || (P = !0, L.dispose(), --instancesCount);
	}
	return {
		setTheme: H,
		getTheme: V,
		getLanguage: B,
		getLoadedThemes: U,
		getLoadedLanguages: W,
		resolveLangAlias: z,
		loadLanguage: K,
		loadLanguageSync: G,
		loadTheme: J,
		loadThemeSync: q,
		dispose: X,
		[Symbol.dispose]: X
	};
}
async function createShikiInternal(a) {
	a.engine || warnDeprecated("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");
	let [P, F, I] = await Promise.all([
		resolveThemes(a.themes || []),
		resolveLangs(a.langs || []),
		a.engine
	]);
	return createShikiInternalSync({
		...a,
		themes: P,
		langs: F,
		engine: I
	});
}
async function createHighlighterCore(a) {
	let P = await createShikiInternal(a);
	return {
		getLastGrammarState: (...a) => getLastGrammarState(P, ...a),
		codeToTokensBase: (a, F) => codeToTokensBase(P, a, F),
		codeToTokensWithThemes: (a, F) => codeToTokensWithThemes(P, a, F),
		codeToTokens: (a, F) => codeToTokens(P, a, F),
		codeToHast: (a, F) => codeToHast(P, a, F),
		codeToHtml: (a, F) => codeToHtml(P, a, F),
		getBundledLanguages: () => ({}),
		getBundledThemes: () => ({}),
		...P,
		getInternalContext: () => P
	};
}
function createBundledHighlighter(P) {
	let F = P.langs, I = P.themes, L = P.engine;
	async function R(P) {
		function R(I) {
			if (typeof I == "string") {
				if (I = P.langAlias?.[I] || I, isSpecialLang(I)) return [];
				let L = F[I];
				if (!L) throw new ShikiError(`Language \`${I}\` is not included in this bundle. You may want to load it from external source.`);
				return L;
			}
			return I;
		}
		function z(P) {
			if (isSpecialTheme(P)) return "none";
			if (typeof P == "string") {
				let F = I[P];
				if (!F) throw new ShikiError(`Theme \`${P}\` is not included in this bundle. You may want to load it from external source.`);
				return F;
			}
			return P;
		}
		let B = (P.themes ?? []).map((a) => z(a)), V = (P.langs ?? []).map((a) => R(a)), H = await createHighlighterCore({
			engine: P.engine ?? L(),
			...P,
			themes: B,
			langs: V
		});
		return {
			...H,
			loadLanguage(...a) {
				return H.loadLanguage(...a.map(R));
			},
			loadTheme(...a) {
				return H.loadTheme(...a.map(z));
			},
			getBundledLanguages() {
				return F;
			},
			getBundledThemes() {
				return I;
			}
		};
	}
	return R;
}
function makeSingletonHighlighter(a) {
	let P;
	async function F(F = {}) {
		if (P) {
			let a = await P;
			return await Promise.all([a.loadTheme(...F.themes || []), a.loadLanguage(...F.langs || [])]), a;
		} else {
			P = a({
				...F,
				themes: [],
				langs: []
			});
			let I = await P;
			return await Promise.all([I.loadTheme(...F.themes || []), I.loadLanguage(...F.langs || [])]), I;
		}
	}
	return F;
}
function createSingletonShorthands(a, P) {
	let F = makeSingletonHighlighter(a);
	async function I(a, I) {
		let L = await F({
			langs: [I.lang],
			themes: "theme" in I ? [I.theme] : Object.values(I.themes)
		}), R = await P?.guessEmbeddedLanguages?.(a, I.lang, L);
		return R && await L.loadLanguage(...R), L;
	}
	return {
		getSingletonHighlighter(a) {
			return F(a);
		},
		async codeToHtml(a, P) {
			return (await I(a, P)).codeToHtml(a, P);
		},
		async codeToHast(a, P) {
			return (await I(a, P)).codeToHast(a, P);
		},
		async codeToTokens(a, P) {
			return (await I(a, P)).codeToTokens(a, P);
		},
		async codeToTokensBase(a, P) {
			return (await I(a, P)).codeToTokensBase(a, P);
		},
		async codeToTokensWithThemes(a, P) {
			return (await I(a, P)).codeToTokensWithThemes(a, P);
		},
		async getLastGrammarState(a, P) {
			return (await F({
				langs: [P.lang],
				themes: [P.theme]
			})).getLastGrammarState(a, P);
		}
	};
}
export { addClassToHast, applyColorReplacements, createBundledHighlighter, createHighlighterCore, createPositionConverter, createShikiInternal, createShikiInternalSync, createSingletonShorthands, flatTokenVariants, getTokenStyleObject, guessEmbeddedLanguages, hastToHtml, isNoneTheme, isPlainLang, isSpecialLang, isSpecialTheme, makeSingletonHighlighter, normalizeGetter, normalizeTheme, resolveColorReplacements, splitLines, splitToken, splitTokens, stringifyTokenStyle, toArray, tokenizeAnsiWithTheme, tokenizeWithTheme, tokensToHast, transformerDecorations, warnDeprecated };
