import { ShikiError as e } from "../../types/dist/index.js";
import { EncodedTokenMetadata as t, INITIAL as n, Registry as r, Theme as i } from "../../vscode-textmate/dist/index.js";
//#region ../../node_modules/@shikijs/primitive/dist/index.mjs
function a(e, t) {
	let n = typeof e == "string" ? {} : { ...e.colorReplacements }, r = typeof e == "string" ? e : e.name;
	for (let [e, i] of Object.entries(t?.colorReplacements || {})) typeof i == "string" ? n[e] = i : e === r && Object.assign(n, i);
	return n;
}
function o(e, t) {
	return e && (t?.[e?.toLowerCase()] || e);
}
function s(e) {
	return Array.isArray(e) ? e : [e];
}
async function c(e) {
	return Promise.resolve(typeof e == "function" ? e() : e).then((e) => e.default || e);
}
function l(e) {
	return !e || [
		"plaintext",
		"txt",
		"text",
		"plain"
	].includes(e);
}
function u(e) {
	return e === "ansi" || l(e);
}
function d(e) {
	return e === "none";
}
function f(e) {
	return d(e);
}
function p(e, t = !1) {
	if (e.length === 0) return [["", 0]];
	let n = e.split(/(\r?\n)/g), r = 0, i = [];
	for (let e = 0; e < n.length; e += 2) {
		let a = t ? n[e] + (n[e + 1] || "") : n[e];
		i.push([a, r]), r += n[e].length, r += n[e + 1]?.length || 0;
	}
	return i;
}
var m = {
	light: "#333333",
	dark: "#bbbbbb"
}, h = {
	light: "#fffffe",
	dark: "#1e1e1e"
}, g = "__shiki_resolved";
function _(e) {
	if (e?.[g]) return e;
	let t = { ...e };
	t.tokenColors && !t.settings && (t.settings = t.tokenColors, delete t.tokenColors), t.type ||= "dark", t.colorReplacements = { ...t.colorReplacements }, t.settings ||= [];
	let { bg: n, fg: r } = t;
	if (!n || !r) {
		let e = t.settings ? t.settings.find((e) => !e.name && !e.scope) : void 0;
		e?.settings?.foreground && (r = e.settings.foreground), e?.settings?.background && (n = e.settings.background), !r && t?.colors?.["editor.foreground"] && (r = t.colors["editor.foreground"]), !n && t?.colors?.["editor.background"] && (n = t.colors["editor.background"]), r ||= t.type === "light" ? m.light : m.dark, n ||= t.type === "light" ? h.light : h.dark, t.fg = r, t.bg = n;
	}
	t.settings[0] && t.settings[0].settings && !t.settings[0].scope || t.settings.unshift({ settings: {
		foreground: t.fg,
		background: t.bg
	} });
	let i = 0, a = /* @__PURE__ */ new Map();
	function o(e) {
		if (a.has(e)) return a.get(e);
		i += 1;
		let n = `#${i.toString(16).padStart(8, "0").toLowerCase()}`;
		return t.colorReplacements?.[`#${n}`] ? o(e) : (a.set(e, n), n);
	}
	t.settings = t.settings.map((e) => {
		let n = e.settings?.foreground && !e.settings.foreground.startsWith("#"), r = e.settings?.background && !e.settings.background.startsWith("#");
		if (!n && !r) return e;
		let i = {
			...e,
			settings: { ...e.settings }
		};
		if (n) {
			let n = o(e.settings.foreground);
			t.colorReplacements[n] = e.settings.foreground, i.settings.foreground = n;
		}
		if (r) {
			let n = o(e.settings.background);
			t.colorReplacements[n] = e.settings.background, i.settings.background = n;
		}
		return i;
	});
	for (let e of Object.keys(t.colors || {})) if ((e === "editor.foreground" || e === "editor.background" || e.startsWith("terminal.ansi")) && !t.colors[e]?.startsWith("#")) {
		let n = o(t.colors[e]);
		t.colorReplacements[n] = t.colors[e], t.colors[e] = n;
	}
	return Object.defineProperty(t, g, {
		enumerable: !1,
		writable: !1,
		value: !0
	}), t;
}
async function v(e) {
	return Array.from(new Set((await Promise.all(e.filter((e) => !u(e)).map(async (e) => await c(e).then((e) => Array.isArray(e) ? e : [e])))).flat()));
}
async function y(e) {
	return (await Promise.all(e.map(async (e) => f(e) ? null : _(await c(e))))).filter((e) => !!e);
}
function b(t, n) {
	if (!n) return t;
	if (n[t]) {
		let r = new Set([t]);
		for (; n[t];) {
			if (t = n[t], r.has(t)) throw new e(`Circular alias \`${Array.from(r).join(" -> ")} -> ${t}\``);
			r.add(t);
		}
	}
	return t;
}
var x = class extends r {
	_resolvedThemes = /* @__PURE__ */ new Map();
	_resolvedGrammars = /* @__PURE__ */ new Map();
	_langMap = /* @__PURE__ */ new Map();
	_langGraph = /* @__PURE__ */ new Map();
	_textmateThemeCache = /* @__PURE__ */ new WeakMap();
	_loadedThemesCache = null;
	_loadedLanguagesCache = null;
	constructor(e, t, n, r = {}) {
		super(e), this._resolver = e, this._themes = t, this._langs = n, this._alias = r, this._themes.map((e) => this.loadTheme(e)), this.loadLanguages(this._langs);
	}
	getTheme(e) {
		return typeof e == "string" ? this._resolvedThemes.get(e) : this.loadTheme(e);
	}
	loadTheme(e) {
		let t = _(e);
		return t.name && (this._resolvedThemes.set(t.name, t), this._loadedThemesCache = null), t;
	}
	getLoadedThemes() {
		return this._loadedThemesCache ||= [...this._resolvedThemes.keys()], this._loadedThemesCache;
	}
	setTheme(e) {
		let t = this._textmateThemeCache.get(e);
		t || (t = i.createFromRawTheme(e), this._textmateThemeCache.set(e, t)), this._syncRegistry.setTheme(t);
	}
	getGrammar(e) {
		return e = b(e, this._alias), this._resolvedGrammars.get(e);
	}
	loadLanguage(e) {
		if (this.getGrammar(e.name)) return;
		let t = new Set([...this._langMap.values()].filter((t) => t.embeddedLangsLazy?.includes(e.name)));
		this._resolver.addLanguage(e);
		let n = {
			balancedBracketSelectors: e.balancedBracketSelectors || ["*"],
			unbalancedBracketSelectors: e.unbalancedBracketSelectors || []
		};
		this._syncRegistry._rawGrammars.set(e.scopeName, e);
		let r = this.loadGrammarWithConfiguration(e.scopeName, 1, n);
		if (r.name = e.name, this._resolvedGrammars.set(e.name, r), e.aliases && e.aliases.forEach((t) => {
			this._alias[t] = e.name;
		}), this._loadedLanguagesCache = null, t.size) for (let e of t) this._resolvedGrammars.delete(e.name), this._loadedLanguagesCache = null, this._syncRegistry?._injectionGrammars?.delete(e.scopeName), this._syncRegistry?._grammars?.delete(e.scopeName), this.loadLanguage(this._langMap.get(e.name));
	}
	dispose() {
		super.dispose(), this._resolvedThemes.clear(), this._resolvedGrammars.clear(), this._langMap.clear(), this._langGraph.clear(), this._loadedThemesCache = null;
	}
	loadLanguages(t) {
		for (let e of t) this.resolveEmbeddedLanguages(e);
		let n = Array.from(this._langGraph.entries()), r = n.filter(([e, t]) => !t);
		if (r.length) {
			let t = n.filter(([e, t]) => t ? (t.embeddedLanguages || t.embeddedLangs)?.some((e) => r.map(([e]) => e).includes(e)) : !1).filter((e) => !r.includes(e));
			throw new e(`Missing languages ${r.map(([e]) => `\`${e}\``).join(", ")}, required by ${t.map(([e]) => `\`${e}\``).join(", ")}`);
		}
		for (let [e, t] of n) this._resolver.addLanguage(t);
		for (let [e, t] of n) this.loadLanguage(t);
	}
	getLoadedLanguages() {
		return this._loadedLanguagesCache ||= [...new Set([...this._resolvedGrammars.keys(), ...Object.keys(this._alias)])], this._loadedLanguagesCache;
	}
	resolveEmbeddedLanguages(e) {
		this._langMap.set(e.name, e), this._langGraph.set(e.name, e);
		let t = e.embeddedLanguages ?? e.embeddedLangs;
		if (t) for (let e of t) this._langGraph.set(e, this._langMap.get(e));
	}
}, S = class {
	_langs = /* @__PURE__ */ new Map();
	_scopeToLang = /* @__PURE__ */ new Map();
	_injections = /* @__PURE__ */ new Map();
	_onigLib;
	constructor(e, t) {
		this._onigLib = {
			createOnigScanner: (t) => e.createScanner(t),
			createOnigString: (t) => e.createString(t)
		}, t.forEach((e) => this.addLanguage(e));
	}
	get onigLib() {
		return this._onigLib;
	}
	getLangRegistration(e) {
		return this._langs.get(e);
	}
	loadGrammar(e) {
		return this._scopeToLang.get(e);
	}
	addLanguage(e) {
		this._langs.set(e.name, e), e.aliases && e.aliases.forEach((t) => {
			this._langs.set(t, e);
		}), this._scopeToLang.set(e.scopeName, e), e.injectTo && e.injectTo.forEach((t) => {
			this._injections.get(t) || this._injections.set(t, []), this._injections.get(t).push(e.scopeName);
		});
	}
	getInjections(e) {
		let t = e.split("."), n = [];
		for (let e = 1; e <= t.length; e++) {
			let r = t.slice(0, e).join(".");
			n = [...n, ...this._injections.get(r) || []];
		}
		return n;
	}
}, C = 0;
function w(t) {
	C += 1, t.warnings !== !1 && C >= 10 && C % 10 == 0 && console.warn(`[Shiki] ${C} 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 n = !1;
	if (!t.engine) throw new e("`engine` option is required for synchronous mode");
	let r = (t.langs || []).flat(1), i = (t.themes || []).flat(1).map(_), a = new x(new S(t.engine, r), i, r, t.langAlias), o;
	function s(e) {
		return b(e, t.langAlias);
	}
	function c(t) {
		w();
		let n = a.getGrammar(typeof t == "string" ? t : t.name);
		if (!n) throw new e(`Language \`${t}\` not found, you may need to load it first`);
		return n;
	}
	function l(t) {
		if (t === "none") return {
			bg: "",
			fg: "",
			name: "none",
			settings: [],
			type: "dark"
		};
		w();
		let n = a.getTheme(t);
		if (!n) throw new e(`Theme \`${t}\` not found, you may need to load it first`);
		return n;
	}
	function u(e) {
		w();
		let t = l(e);
		return o !== e && (a.setTheme(t), o = e), {
			theme: t,
			colorMap: a.getColorMap()
		};
	}
	function d() {
		return w(), a.getLoadedThemes();
	}
	function f() {
		return w(), a.getLoadedLanguages();
	}
	function p(...e) {
		w(), a.loadLanguages(e.flat(1));
	}
	async function m(...e) {
		return p(await v(e));
	}
	function h(...e) {
		w();
		for (let t of e.flat(1)) a.loadTheme(t);
	}
	async function g(...e) {
		return w(), h(await y(e));
	}
	function w() {
		if (n) throw new e("Shiki instance has been disposed");
	}
	function T() {
		n || (n = !0, a.dispose(), --C);
	}
	return {
		setTheme: u,
		getTheme: l,
		getLanguage: c,
		getLoadedThemes: d,
		getLoadedLanguages: f,
		resolveLangAlias: s,
		loadLanguage: m,
		loadLanguageSync: p,
		loadTheme: g,
		loadThemeSync: h,
		dispose: T,
		[Symbol.dispose]: T
	};
}
async function T(e) {
	e.engine || console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");
	let [t, n, r] = await Promise.all([
		y(e.themes || []),
		v(e.langs || []),
		e.engine
	]);
	return w({
		...e,
		themes: t,
		langs: n,
		engine: r
	});
}
var E = /* @__PURE__ */ new WeakMap();
function D(e, t) {
	E.set(e, t);
}
function O(e) {
	return E.get(e);
}
var k = class e {
	_stacks = {};
	lang;
	get themes() {
		return Object.keys(this._stacks);
	}
	get theme() {
		return this.themes[0];
	}
	get _stack() {
		return this._stacks[this.theme];
	}
	static initial(t, r) {
		return new e(Object.fromEntries(s(r).map((e) => [e, n])), t);
	}
	constructor(...e) {
		if (e.length === 2) {
			let [t, n] = e;
			this.lang = n, this._stacks = t;
		} else {
			let [t, n, r] = e;
			this.lang = n, this._stacks = { [r]: t };
		}
	}
	getInternalStack(e = this.theme) {
		return this._stacks[e];
	}
	getScopes(e = this.theme) {
		return A(this._stacks[e]);
	}
	toJSON() {
		return {
			lang: this.lang,
			theme: this.theme,
			themes: this.themes,
			scopes: this.getScopes()
		};
	}
};
function A(e) {
	let t = [], n = /* @__PURE__ */ new Set();
	function r(e) {
		if (n.has(e)) return;
		n.add(e);
		let i = e?.nameScopesList?.scopeName;
		i && t.push(i), e.parent && r(e.parent);
	}
	return r(e), t;
}
function j(t, n) {
	if (!(t instanceof k)) throw new e("Invalid grammar state");
	return t.getInternalStack(n);
}
function M(t, n, r = {}) {
	let { theme: i = t.getLoadedThemes()[0] } = r;
	if (l(t.resolveLangAlias(r.lang || "text")) || d(i)) return p(n).map((e) => [{
		content: e[0],
		offset: e[1]
	}]);
	let { theme: a, colorMap: o } = t.setTheme(i), s = t.getLanguage(r.lang || "text");
	if (r.grammarState) {
		if (r.grammarState.lang !== s.name) throw new e(`Grammar state language "${r.grammarState.lang}" does not match highlight language "${s.name}"`);
		if (!r.grammarState.themes.includes(a.name)) throw new e(`Grammar state themes "${r.grammarState.themes}" do not contain highlight theme "${a.name}"`);
	}
	return P(n, s, a, o, r);
}
function N(...t) {
	if (t.length === 2) return O(t[1]);
	let [n, r, i = {}] = t, { lang: a = "text", theme: o = n.getLoadedThemes()[0] } = i;
	if (l(a) || d(o)) throw new e("Plain language does not have grammar state");
	if (a === "ansi") throw new e("ANSI language does not have grammar state");
	let { theme: s, colorMap: c } = n.setTheme(o), u = n.getLanguage(a);
	return new k(F(r, u, s, c, i).stateStack, u.name, s.name);
}
function P(e, t, n, r, i) {
	let a = F(e, t, n, r, i), o = new k(a.stateStack, t.name, n.name);
	return D(a.tokens, o), a.tokens;
}
function F(e, r, i, s, c) {
	let l = a(i, c), { tokenizeMaxLineLength: u = 0, tokenizeTimeLimit: d = 500 } = c, f = p(e), m = c.grammarState ? j(c.grammarState, i.name) ?? n : c.grammarContextCode == null ? n : F(c.grammarContextCode, r, i, s, {
		...c,
		grammarState: void 0,
		grammarContextCode: void 0
	}).stateStack, h = [], g = [];
	for (let e = 0, n = f.length; e < n; e++) {
		let [n, a] = f[e];
		if (n === "") {
			h = [], g.push([]);
			continue;
		}
		if (u > 0 && n.length >= u) {
			h = [], g.push([{
				content: n,
				offset: a,
				color: "",
				fontStyle: 0
			}]);
			continue;
		}
		let p, _, v;
		c.includeExplanation && (p = r.tokenizeLine(n, m, d), _ = p.tokens, v = 0);
		let y = r.tokenizeLine2(n, m, d), b = y.tokens.length / 2;
		for (let e = 0; e < b; e++) {
			let r = y.tokens[2 * e], u = e + 1 < b ? y.tokens[2 * e + 2] : n.length;
			if (r === u) continue;
			let d = y.tokens[2 * e + 1], f = o(s[t.getForeground(d)], l), p = t.getFontStyle(d), m = {
				content: n.substring(r, u),
				offset: a + r,
				color: f,
				fontStyle: p
			};
			if (c.includeExplanation) {
				let e = [];
				if (c.includeExplanation !== "scopeName") for (let t of i.settings) {
					let n;
					switch (typeof t.scope) {
						case "string":
							n = t.scope.split(/,/).map((e) => e.trim());
							break;
						case "object":
							n = t.scope;
							break;
						default: continue;
					}
					e.push({
						settings: t,
						selectors: n.map((e) => e.split(/ /))
					});
				}
				m.explanation = [];
				let t = 0;
				for (; r + t < u;) {
					let r = _[v], i = n.substring(r.startIndex, r.endIndex);
					t += i.length, m.explanation.push({
						content: i,
						scopes: c.includeExplanation === "scopeName" ? I(r.scopes) : L(e, r.scopes)
					}), v += 1;
				}
			}
			h.push(m);
		}
		g.push(h), h = [], m = y.ruleStack;
	}
	return {
		tokens: g,
		stateStack: m
	};
}
function I(e) {
	return e.map((e) => ({ scopeName: e }));
}
function L(e, t) {
	let n = [];
	for (let r = 0, i = t.length; r < i; r++) {
		let i = t[r];
		n[r] = {
			scopeName: i,
			themeMatches: B(e, i, t.slice(0, r))
		};
	}
	return n;
}
function R(e, t) {
	return e === t || t.substring(0, e.length) === e && t[e.length] === ".";
}
function z(e, t, n) {
	if (!R(e[e.length - 1], t)) return !1;
	let r = e.length - 2, i = n.length - 1;
	for (; r >= 0 && i >= 0;) R(e[r], n[i]) && --r, --i;
	return r === -1;
}
function B(e, t, n) {
	let r = [];
	for (let { selectors: i, settings: a } of e) for (let e of i) if (z(e, t, n)) {
		r.push(a);
		break;
	}
	return r;
}
function V(e, t, n, r = M) {
	let i = Object.entries(n.themes).filter((e) => e[1]).map((e) => ({
		color: e[0],
		theme: e[1]
	})), a = i.map((i) => {
		let a = r(e, t, {
			...n,
			theme: i.theme
		});
		return {
			tokens: a,
			state: O(a),
			theme: typeof i.theme == "string" ? i.theme : i.theme.name
		};
	}), o = H(...a.map((e) => e.tokens)), s = o[0].map((e, t) => e.map((e, r) => {
		let a = {
			content: e.content,
			variants: {},
			offset: e.offset
		};
		return "includeExplanation" in n && n.includeExplanation && (a.explanation = e.explanation), o.forEach((e, n) => {
			let { content: o, explanation: s, offset: c, ...l } = e[t][r];
			a.variants[i[n].color] = l;
		}), a;
	})), c = a[0].state ? new k(Object.fromEntries(a.map((e) => [e.theme, e.state?.getInternalStack(e.theme)])), a[0].state.lang) : void 0;
	return c && D(s, c), s;
}
function H(...e) {
	let t = e.map(() => []), n = e.length;
	for (let r = 0; r < e[0].length; r++) {
		let i = e.map((e) => e[r]), a = t.map(() => []);
		t.forEach((e, t) => e.push(a[t]));
		let o = i.map(() => 0), s = i.map((e) => e[0]);
		for (; s.every((e) => e);) {
			let e = Math.min(...s.map((e) => e.content.length));
			for (let t = 0; t < n; t++) {
				let n = s[t];
				n.content.length === e ? (a[t].push(n), o[t] += 1, s[t] = i[t][o[t]]) : (a[t].push({
					...n,
					content: n.content.slice(0, e)
				}), s[t] = {
					...n,
					content: n.content.slice(e),
					offset: n.offset + e
				});
			}
		}
	}
	return t;
}
//#endregion
export { o as applyColorReplacements, M as codeToTokensBase, V as codeToTokensWithThemes, w as createShikiPrimitive, T as createShikiPrimitiveAsync, N as getLastGrammarState, O as getLastGrammarStateFromMap, d as isNoneTheme, l as isPlainLang, u as isSpecialLang, f as isSpecialTheme, c as normalizeGetter, _ as normalizeTheme, a as resolveColorReplacements, D as setLastGrammarStateToMap, p as splitLines, s as toArray, P as tokenizeWithTheme };
