import { bundledLanguages, bundledThemes, createHighlighter, createJavaScriptRegexEngine } from "shiki";
import { normalizeTheme } from "shiki/core";
import { diffChars, diffWordsWithSpace } from "diff";
import { transformerStyleToClass } from "@shikijs/transformers";

//#region src/constants.ts
const DEFAULT_THEMES = {
	dark: "pierre-dark",
	light: "pierre-light"
};

//#endregion
//#region src/utils/isWorkerContext.ts
function isWorkerContext() {
	return typeof WorkerGlobalScope !== "undefined" && typeof self !== "undefined" && self instanceof WorkerGlobalScope;
}

//#endregion
//#region src/highlighter/languages.ts
const ResolvedLanguages = /* @__PURE__ */ new Map();
const ResolvingLanguages = /* @__PURE__ */ new Map();
const attachedLanguages = /* @__PURE__ */ new Set();
function getResolvedOrResolveLanguage(language) {
	return ResolvedLanguages.get(language) ?? resolveLanguage(language);
}
async function resolveLanguage(lang) {
	if (isWorkerContext()) throw new Error(`resolveLanguage("${lang}") cannot be called from a worker context. Languages must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);
	const resolver = ResolvingLanguages.get(lang);
	if (resolver != null) return resolver;
	try {
		const loader = bundledLanguages[lang];
		if (loader == null) throw new Error("resolveLanguage: \"${lang}\" not found in bundled languages");
		const resolver$1 = loader().then(({ default: data }) => {
			const resolvedLang = {
				name: lang,
				data
			};
			if (!ResolvedLanguages.has(lang)) ResolvedLanguages.set(lang, resolvedLang);
			return resolvedLang;
		});
		ResolvingLanguages.set(lang, resolver$1);
		return await resolver$1;
	} finally {
		ResolvingLanguages.delete(lang);
	}
}
function attachResolvedLanguages(resolvedLanguages, highlighter$1) {
	resolvedLanguages = Array.isArray(resolvedLanguages) ? resolvedLanguages : [resolvedLanguages];
	for (const resolvedLang of resolvedLanguages) {
		if (attachedLanguages.has(resolvedLang.name)) continue;
		let lang = ResolvedLanguages.get(resolvedLang.name);
		if (lang == null) {
			lang = resolvedLang;
			ResolvedLanguages.set(resolvedLang.name, lang);
		}
		attachedLanguages.add(lang.name);
		highlighter$1.loadLanguageSync(lang.data);
	}
}

//#endregion
//#region src/highlighter/themes.ts
const ResolvedThemes = /* @__PURE__ */ new Map();
const ResolvingThemes = /* @__PURE__ */ new Map();
const RegisteredCustomThemes = /* @__PURE__ */ new Map();
const attachedThemes = /* @__PURE__ */ new Set();
function getResolvedOrResolveTheme(themeName) {
	return ResolvedThemes.get(themeName) ?? resolveTheme(themeName);
}
async function resolveTheme(themeName) {
	if (isWorkerContext()) throw new Error(`resolveTheme("${themeName}") cannot be called from a worker context. Themes must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);
	const resolver = ResolvingThemes.get(themeName);
	if (resolver != null) return resolver;
	try {
		const loader = RegisteredCustomThemes.get(themeName) ?? bundledThemes[themeName];
		if (loader == null) throw new Error(`resolveTheme: No valid loader for ${themeName}`);
		const resolver$1 = loader().then((result) => {
			return normalizeAndCacheResolvedTheme(themeName, "default" in result ? result.default : result);
		});
		ResolvingThemes.set(themeName, resolver$1);
		const theme = await resolver$1;
		if (theme.name !== themeName) throw new Error(`resolvedTheme: themeName: ${themeName} does not match theme.name: ${theme.name}`);
		ResolvedThemes.set(theme.name, theme);
		return theme;
	} finally {
		ResolvingThemes.delete(themeName);
	}
}
function attachResolvedThemes(themes, highlighter$1) {
	themes = Array.isArray(themes) ? themes : [themes];
	for (let themeRef of themes) {
		let resolvedTheme;
		if (typeof themeRef === "string") {
			resolvedTheme = ResolvedThemes.get(themeRef);
			if (resolvedTheme == null) throw new Error(`loadResolvedThemes: ${themeRef} is not resolved, you must resolve it before calling loadResolvedThemes`);
		} else {
			resolvedTheme = themeRef;
			themeRef = themeRef.name;
			if (!ResolvedThemes.has(themeRef)) ResolvedThemes.set(themeRef, resolvedTheme);
		}
		if (attachedThemes.has(themeRef)) continue;
		attachedThemes.add(themeRef);
		highlighter$1.loadThemeSync(resolvedTheme);
	}
}
function registerCustomTheme(themeName, loader) {
	if (RegisteredCustomThemes.has(themeName)) {
		console.error("SharedHighlight.registerCustomTheme: theme name already registered", themeName);
		return;
	}
	RegisteredCustomThemes.set(themeName, loader);
}
function normalizeAndCacheResolvedTheme(themeName, themeData) {
	const resolvedTheme = ResolvedThemes.get(themeName);
	if (resolvedTheme != null) return resolvedTheme;
	themeData = normalizeTheme(themeData);
	ResolvedThemes.set(themeName, themeData);
	return themeData;
}
registerCustomTheme("pierre-dark", () => {
	return import("./pierre-dark-Bl6-D6U7.js");
});
registerCustomTheme("pierre-light", () => {
	return import("./pierre-light-DGEssevQ.js");
});

//#endregion
//#region src/highlighter/shared_highlighter.ts
let highlighter;
async function getSharedHighlighter({ themes, langs }) {
	highlighter ??= createHighlighter({
		themes: [],
		langs: ["text"],
		engine: createJavaScriptRegexEngine()
	});
	const instance = isHighlighterLoading(highlighter) ? await highlighter : highlighter;
	highlighter = instance;
	const languageLoaders = [];
	for (const language of langs) {
		if (language === "text") continue;
		const maybeResolvedLanguage = getResolvedOrResolveLanguage(language);
		if ("then" in maybeResolvedLanguage) languageLoaders.push(maybeResolvedLanguage);
		else attachResolvedLanguages(maybeResolvedLanguage, instance);
	}
	const themeLoaders = [];
	for (const themeName of themes) {
		const maybeResolvedTheme = getResolvedOrResolveTheme(themeName);
		if ("then" in maybeResolvedTheme) themeLoaders.push(maybeResolvedTheme);
		else attachResolvedThemes(maybeResolvedTheme, highlighter);
	}
	if (languageLoaders.length > 0 || themeLoaders.length > 0) await Promise.all([Promise.all(languageLoaders).then((languages) => {
		attachResolvedLanguages(languages, instance);
	}), Promise.all(themeLoaders).then((themes$1) => {
		attachResolvedThemes(themes$1, instance);
	})]);
	return instance;
}
function getHighlighterIfLoaded() {
	if (highlighter != null && !("then" in highlighter)) return highlighter;
}
function isHighlighterLoading(h = highlighter) {
	return h != null && "then" in h;
}

//#endregion
//#region src/utils/cleanLastNewline.ts
function cleanLastNewline(contents) {
	return contents.replace(/\n$|\r\n$/, "");
}

//#endregion
//#region src/utils/hast_utils.ts
function createTextNodeElement(value) {
	return {
		type: "text",
		value
	};
}
function createHastElement({ tagName, children = [], properties = {} }) {
	return {
		type: "element",
		tagName,
		properties,
		children
	};
}
function findCodeElement(nodes) {
	let firstChild = nodes.children[0];
	while (firstChild != null) {
		if (firstChild.type === "element" && firstChild.tagName === "code") return firstChild;
		if ("children" in firstChild) firstChild = firstChild.children[0];
		else firstChild = null;
	}
}

//#endregion
//#region src/utils/processLine.ts
function processLine(node, line, state) {
	const lineInfo = typeof state.lineInfo === "function" ? state.lineInfo(line) : state.lineInfo[line];
	if (lineInfo == null) {
		console.error({
			node,
			line,
			state
		});
		throw new Error(`processLine: line ${line}, contains no state.lineInfo`);
	}
	node.tagName = "span";
	node.properties["data-column-content"] = "";
	if (node.children.length === 0) node.children.push(createTextNodeElement("\n"));
	return createHastElement({
		tagName: "div",
		children: [createHastElement({
			tagName: "span",
			children: [createHastElement({
				tagName: "span",
				children: [{
					type: "text",
					value: `${lineInfo.lineNumber}`
				}],
				properties: { "data-line-number-content": "" }
			})],
			properties: { "data-column-number": "" }
		}), node],
		properties: {
			"data-line": lineInfo.lineNumber,
			"data-alt-line": lineInfo.altLineNumber,
			"data-line-type": lineInfo.type,
			"data-line-index": lineInfo.lineIndex >= 0 ? lineInfo.lineIndex : void 0
		}
	});
}

//#endregion
//#region src/utils/createTransformerWithState.ts
function createTransformerWithState(useCSSClasses = false) {
	const state = { lineInfo: {} };
	const transformers = [{
		line(node) {
			delete node.properties.class;
			return node;
		},
		pre(pre) {
			const code = findCodeElement(pre);
			const children = [];
			if (code != null) {
				let index = 1;
				for (const node of code.children) {
					if (node.type !== "element") continue;
					children.push(processLine(node, index, state));
					index++;
				}
				code.children = children;
			}
			return pre;
		}
	}];
	if (useCSSClasses) transformers.push(tokenStyleNormalizer, toClass);
	return {
		state,
		transformers,
		toClass
	};
}
const toClass = transformerStyleToClass({ classPrefix: "hl-" });
const tokenStyleNormalizer = {
	name: "token-style-normalizer",
	tokens(lines) {
		for (const line of lines) for (const token of line) {
			if (token.htmlStyle != null) continue;
			const style = {};
			if (token.color != null) style.color = token.color;
			if (token.bgColor != null) style["background-color"] = token.bgColor;
			if (token.fontStyle != null && token.fontStyle !== 0) {
				if ((token.fontStyle & 1) !== 0) style["font-style"] = "italic";
				if ((token.fontStyle & 2) !== 0) style["font-weight"] = "bold";
				if ((token.fontStyle & 4) !== 0) style["text-decoration"] = "underline";
			}
			if (Object.keys(style).length > 0) token.htmlStyle = style;
		}
	}
};

//#endregion
//#region src/utils/formatCSSVariablePrefix.ts
function formatCSSVariablePrefix(prefix = "pjs") {
	return `--${prefix}-`;
}

//#endregion
//#region src/utils/getFiletypeFromFileName.ts
const EXTENSION_TO_FILE_FORMAT = {
	"1c": "1c",
	abap: "abap",
	as: "actionscript-3",
	ada: "ada",
	adb: "ada",
	ads: "ada",
	adoc: "asciidoc",
	asciidoc: "asciidoc",
	"component.html": "angular-html",
	"component.ts": "angular-ts",
	conf: "nginx",
	htaccess: "apache",
	cls: "tex",
	trigger: "apex",
	apl: "apl",
	applescript: "applescript",
	scpt: "applescript",
	ara: "ara",
	asm: "asm",
	s: "riscv",
	astro: "astro",
	awk: "awk",
	bal: "ballerina",
	sh: "zsh",
	bash: "zsh",
	bat: "cmd",
	cmd: "cmd",
	be: "berry",
	beancount: "beancount",
	bib: "bibtex",
	bicep: "bicep",
	"blade.php": "blade",
	bsl: "bsl",
	c: "c",
	h: "objective-cpp",
	cs: "csharp",
	cpp: "cpp",
	hpp: "cpp",
	cc: "cpp",
	cxx: "cpp",
	hh: "cpp",
	cdc: "cdc",
	cairo: "cairo",
	clar: "clarity",
	clj: "clojure",
	cljs: "clojure",
	cljc: "clojure",
	soy: "soy",
	cmake: "cmake",
	"CMakeLists.txt": "cmake",
	cob: "cobol",
	cbl: "cobol",
	cobol: "cobol",
	CODEOWNERS: "codeowners",
	ql: "ql",
	coffee: "coffeescript",
	lisp: "lisp",
	cl: "lisp",
	lsp: "lisp",
	log: "log",
	v: "verilog",
	cql: "cql",
	cr: "crystal",
	css: "css",
	csv: "csv",
	cue: "cue",
	cypher: "cypher",
	cyp: "cypher",
	d: "d",
	dart: "dart",
	dax: "dax",
	desktop: "desktop",
	diff: "diff",
	patch: "diff",
	Dockerfile: "dockerfile",
	dockerfile: "dockerfile",
	env: "dotenv",
	dm: "dream-maker",
	edge: "edge",
	el: "emacs-lisp",
	ex: "elixir",
	exs: "elixir",
	elm: "elm",
	erb: "erb",
	erl: "erlang",
	hrl: "erlang",
	f: "fortran-fixed-form",
	for: "fortran-fixed-form",
	fs: "fsharp",
	fsi: "fsharp",
	fsx: "fsharp",
	f03: "f03",
	f08: "f08",
	f18: "f18",
	f77: "f77",
	f90: "fortran-free-form",
	f95: "fortran-free-form",
	fnl: "fennel",
	fish: "fish",
	ftl: "ftl",
	tres: "gdresource",
	res: "gdresource",
	gd: "gdscript",
	gdshader: "gdshader",
	gs: "genie",
	feature: "gherkin",
	COMMIT_EDITMSG: "git-commit",
	"git-rebase-todo": "git-rebase",
	gjs: "glimmer-js",
	gleam: "gleam",
	gts: "glimmer-ts",
	glsl: "glsl",
	vert: "glsl",
	frag: "glsl",
	shader: "shaderlab",
	gp: "gnuplot",
	plt: "gnuplot",
	gnuplot: "gnuplot",
	go: "go",
	graphql: "graphql",
	gql: "graphql",
	groovy: "groovy",
	gvy: "groovy",
	hack: "hack",
	haml: "haml",
	hbs: "handlebars",
	handlebars: "handlebars",
	hs: "haskell",
	lhs: "haskell",
	hx: "haxe",
	hcl: "hcl",
	hjson: "hjson",
	hlsl: "hlsl",
	fx: "hlsl",
	html: "html",
	htm: "html",
	http: "http",
	rest: "http",
	hxml: "hxml",
	hy: "hy",
	imba: "imba",
	ini: "ini",
	cfg: "ini",
	jade: "pug",
	pug: "pug",
	java: "java",
	js: "javascript",
	mjs: "javascript",
	cjs: "javascript",
	jinja: "jinja",
	jinja2: "jinja",
	j2: "jinja",
	jison: "jison",
	jl: "julia",
	json: "json",
	json5: "json5",
	jsonc: "jsonc",
	jsonl: "jsonl",
	jsonnet: "jsonnet",
	libsonnet: "jsonnet",
	jssm: "jssm",
	jsx: "jsx",
	kt: "kotlin",
	kts: "kts",
	kql: "kusto",
	tex: "tex",
	ltx: "tex",
	lean: "lean4",
	less: "less",
	liquid: "liquid",
	lit: "lit",
	ll: "llvm",
	logo: "logo",
	lua: "lua",
	luau: "luau",
	Makefile: "makefile",
	mk: "makefile",
	makefile: "makefile",
	md: "markdown",
	markdown: "markdown",
	marko: "marko",
	m: "wolfram",
	mat: "matlab",
	mdc: "mdc",
	mdx: "mdx",
	wiki: "wikitext",
	mediawiki: "wikitext",
	mmd: "mermaid",
	mermaid: "mermaid",
	mips: "mipsasm",
	mojo: "mojo",
	"🔥": "mojo",
	move: "move",
	nar: "narrat",
	nf: "nextflow",
	nim: "nim",
	nims: "nim",
	nimble: "nim",
	nix: "nix",
	nu: "nushell",
	mm: "objective-cpp",
	ml: "ocaml",
	mli: "ocaml",
	mll: "ocaml",
	mly: "ocaml",
	pas: "pascal",
	p: "pascal",
	pl: "prolog",
	pm: "perl",
	t: "perl",
	raku: "raku",
	p6: "raku",
	pl6: "raku",
	php: "php",
	phtml: "php",
	pls: "plsql",
	sql: "sql",
	po: "po",
	polar: "polar",
	pcss: "postcss",
	pot: "pot",
	potx: "potx",
	pq: "powerquery",
	pqm: "powerquery",
	ps1: "powershell",
	psm1: "powershell",
	psd1: "powershell",
	prisma: "prisma",
	pro: "prolog",
	P: "prolog",
	properties: "properties",
	proto: "protobuf",
	pp: "puppet",
	purs: "purescript",
	py: "python",
	pyw: "python",
	pyi: "python",
	qml: "qml",
	qmldir: "qmldir",
	qss: "qss",
	r: "r",
	R: "r",
	rkt: "racket",
	rktl: "racket",
	razor: "razor",
	cshtml: "razor",
	rb: "ruby",
	rbw: "ruby",
	reg: "reg",
	regex: "regexp",
	rel: "rel",
	rs: "rust",
	rst: "rst",
	rake: "ruby",
	gemspec: "ruby",
	sas: "sas",
	sass: "sass",
	scala: "scala",
	sc: "scala",
	scm: "scheme",
	ss: "scheme",
	sld: "scheme",
	scss: "scss",
	sdbl: "sdbl",
	shadergraph: "shader",
	st: "smalltalk",
	sol: "solidity",
	sparql: "sparql",
	rq: "sparql",
	spl: "splunk",
	config: "ssh-config",
	do: "stata",
	ado: "stata",
	dta: "stata",
	styl: "stylus",
	stylus: "stylus",
	svelte: "svelte",
	swift: "swift",
	sv: "system-verilog",
	svh: "system-verilog",
	service: "systemd",
	socket: "systemd",
	device: "systemd",
	timer: "systemd",
	talon: "talonscript",
	tasl: "tasl",
	tcl: "tcl",
	templ: "templ",
	tf: "tf",
	tfvars: "tfvars",
	toml: "toml",
	ts: "typescript",
	tsp: "typespec",
	tsv: "tsv",
	tsx: "tsx",
	ttl: "turtle",
	twig: "twig",
	typ: "typst",
	vv: "v",
	vala: "vala",
	vapi: "vala",
	vb: "vb",
	vbs: "vb",
	bas: "vb",
	vh: "verilog",
	vhd: "vhdl",
	vhdl: "vhdl",
	vim: "vimscript",
	vue: "vue",
	"vine.ts": "vue-vine",
	vy: "vyper",
	wasm: "wasm",
	wat: "wasm",
	wy: "文言",
	wgsl: "wgsl",
	wit: "wit",
	wl: "wolfram",
	nb: "wolfram",
	xml: "xml",
	xsl: "xsl",
	xslt: "xsl",
	yaml: "yaml",
	yml: "yml",
	zs: "zenscript",
	zig: "zig",
	zsh: "zsh",
	sty: "tex"
};
function getFiletypeFromFileName(fileName) {
	if (EXTENSION_TO_FILE_FORMAT[fileName] != null) return EXTENSION_TO_FILE_FORMAT[fileName];
	const compoundMatch = fileName.match(/\.([^/\\]+\.[^/\\]+)$/);
	if (compoundMatch != null && EXTENSION_TO_FILE_FORMAT[compoundMatch[1]] != null) return EXTENSION_TO_FILE_FORMAT[compoundMatch[1]] ?? "text";
	return EXTENSION_TO_FILE_FORMAT[fileName.match(/\.([^.]+)$/)?.[1] ?? ""] ?? "text";
}

//#endregion
//#region src/utils/getHighlighterThemeStyles.ts
function getHighlighterThemeStyles({ theme = DEFAULT_THEMES, highlighter: highlighter$1, prefix }) {
	let styles = "";
	if (typeof theme === "string") {
		const themeData = highlighter$1.getTheme(theme);
		styles += `color:${themeData.fg};`;
		styles += `background-color:${themeData.bg};`;
		styles += `${formatCSSVariablePrefix(prefix)}fg:${themeData.fg};`;
		styles += `${formatCSSVariablePrefix(prefix)}bg:${themeData.bg};`;
		styles += getThemeVariables(themeData, prefix);
	} else {
		let themeData = highlighter$1.getTheme(theme.dark);
		styles += `${formatCSSVariablePrefix(prefix)}dark:${themeData.fg};`;
		styles += `${formatCSSVariablePrefix(prefix)}dark-bg:${themeData.bg};`;
		styles += getThemeVariables(themeData, prefix, "dark");
		themeData = highlighter$1.getTheme(theme.light);
		styles += `${formatCSSVariablePrefix(prefix)}light:${themeData.fg};`;
		styles += `${formatCSSVariablePrefix(prefix)}light-bg:${themeData.bg};`;
		styles += getThemeVariables(themeData, prefix, "light");
	}
	return styles;
}
function getThemeVariables(themeData, prefix, modePrefix) {
	modePrefix = modePrefix != null ? `${modePrefix}-` : "";
	let styles = "";
	const additionGreen = themeData.colors?.["gitDecoration.addedResourceForeground"] ?? themeData.colors?.["terminal.ansiGreen"];
	if (additionGreen != null) styles += `${formatCSSVariablePrefix(prefix)}${modePrefix}addition-color:${additionGreen};`;
	const deletionRed = themeData.colors?.["gitDecoration.deletedResourceForeground"] ?? themeData.colors?.["terminal.ansiRed"];
	if (deletionRed != null) styles += `${formatCSSVariablePrefix(prefix)}${modePrefix}deletion-color:${deletionRed};`;
	const modifiedBlue = themeData.colors?.["gitDecoration.modifiedResourceForeground"] ?? themeData.colors?.["terminal.ansiBlue"];
	if (modifiedBlue != null) styles += `${formatCSSVariablePrefix(prefix)}${modePrefix}modified-color:${modifiedBlue};`;
	return styles;
}

//#endregion
//#region src/utils/getLineNodes.ts
function getLineNodes(nodes) {
	let firstChild = nodes.children[0];
	while (firstChild != null) {
		if (firstChild.type === "element" && firstChild.tagName === "code") return firstChild.children;
		if ("children" in firstChild) firstChild = firstChild.children[0];
		else firstChild = null;
	}
	console.error(nodes);
	throw new Error("getLineNodes: Unable to find children");
}

//#endregion
//#region src/utils/parseDiffDecorations.ts
function createDiffSpanDecoration({ line, spanStart, spanLength }) {
	return {
		start: {
			line,
			character: spanStart
		},
		end: {
			line,
			character: spanStart + spanLength
		},
		properties: { "data-diff-span": "" },
		alwaysWrap: true
	};
}
function pushOrJoinSpan({ item, arr, enableJoin, isNeutral = false, isLastItem = false }) {
	const lastItem = arr[arr.length - 1];
	if (lastItem == null || isLastItem || !enableJoin) {
		arr.push([isNeutral ? 0 : 1, item.value]);
		return;
	}
	const isLastItemNeutral = lastItem[0] === 0;
	if (isNeutral === isLastItemNeutral || isNeutral && item.value.length === 1 && !isLastItemNeutral) {
		lastItem[1] += item.value;
		return;
	}
	arr.push([isNeutral ? 0 : 1, item.value]);
}

//#endregion
//#region src/utils/renderDiffWithHighlighter.ts
function renderDiffWithHighlighter(diff, highlighter$1, options, forcePlainText = false) {
	const baseThemeType = (() => {
		const theme = options.theme ?? DEFAULT_THEMES;
		if (typeof theme === "string") return highlighter$1.getTheme(theme).type;
	})();
	const themeStyles = getHighlighterThemeStyles({
		theme: options.theme,
		highlighter: highlighter$1
	});
	if (diff.newLines != null && diff.oldLines != null) {
		const { oldContent, newContent, oldInfo, newInfo, oldDecorations, newDecorations } = processLines({
			hunks: diff.hunks,
			oldLines: diff.oldLines,
			newLines: diff.newLines,
			lineDiffType: options.lineDiffType
		});
		return {
			code: renderTwoFiles({
				oldFile: {
					name: diff.prevName ?? diff.name,
					contents: oldContent
				},
				oldInfo,
				oldDecorations,
				newFile: {
					name: diff.name,
					contents: newContent
				},
				newInfo,
				newDecorations,
				highlighter: highlighter$1,
				options,
				languageOverride: forcePlainText ? "text" : diff.lang
			}),
			themeStyles,
			baseThemeType
		};
	}
	const hunks = [];
	let lineIndex = 0;
	for (const hunk of diff.hunks) {
		const { oldContent, newContent, oldInfo, newInfo, oldDecorations, newDecorations, lineIndex: newLineIndex } = processLines({
			hunks: [hunk],
			lineIndex,
			lineDiffType: options.lineDiffType
		});
		const oldFile = {
			name: diff.prevName ?? diff.name,
			contents: oldContent
		};
		const newFile = {
			name: diff.name,
			contents: newContent
		};
		hunks.push(renderTwoFiles({
			oldFile,
			oldInfo,
			oldDecorations,
			newFile,
			newInfo,
			newDecorations,
			highlighter: highlighter$1,
			options,
			languageOverride: forcePlainText ? "text" : diff.lang
		}));
		lineIndex = newLineIndex;
	}
	return {
		code: (() => {
			if (hunks.length <= 1) {
				const hunk = hunks[0] ?? {
					oldLines: [],
					newLines: []
				};
				if (hunk.newLines.length === 0 || hunk.oldLines.length === 0) return hunk;
			}
			return { hunks };
		})(),
		themeStyles,
		baseThemeType
	};
}
function computeLineDiffDecorations({ oldLine, newLine, oldLineIndex, newLineIndex, oldDecorations, newDecorations, lineDiffType }) {
	if (oldLine == null || newLine == null || lineDiffType === "none") return;
	oldLine = cleanLastNewline(oldLine);
	newLine = cleanLastNewline(newLine);
	const lineDiff = lineDiffType === "char" ? diffChars(oldLine, newLine) : diffWordsWithSpace(oldLine, newLine);
	const deletionSpans = [];
	const additionSpans = [];
	const enableJoin = lineDiffType === "word-alt";
	for (const item of lineDiff) {
		const isLastItem = item === lineDiff[lineDiff.length - 1];
		if (!item.added && !item.removed) {
			pushOrJoinSpan({
				item,
				arr: deletionSpans,
				enableJoin,
				isNeutral: true,
				isLastItem
			});
			pushOrJoinSpan({
				item,
				arr: additionSpans,
				enableJoin,
				isNeutral: true,
				isLastItem
			});
		} else if (item.removed) pushOrJoinSpan({
			item,
			arr: deletionSpans,
			enableJoin,
			isLastItem
		});
		else pushOrJoinSpan({
			item,
			arr: additionSpans,
			enableJoin,
			isLastItem
		});
	}
	let spanIndex = 0;
	for (const span of deletionSpans) {
		if (span[0] === 1) oldDecorations.push(createDiffSpanDecoration({
			line: oldLineIndex - 1,
			spanStart: spanIndex,
			spanLength: span[1].length
		}));
		spanIndex += span[1].length;
	}
	spanIndex = 0;
	for (const span of additionSpans) {
		if (span[0] === 1) newDecorations.push(createDiffSpanDecoration({
			line: newLineIndex - 1,
			spanStart: spanIndex,
			spanLength: span[1].length
		}));
		spanIndex += span[1].length;
	}
}
function processLines({ hunks, oldLines, newLines, lineIndex = 0, lineDiffType }) {
	const oldInfo = {};
	const newInfo = {};
	const oldDecorations = [];
	const newDecorations = [];
	let newLineIndex = 1;
	let oldLineIndex = 1;
	let newLineNumber = 1;
	let oldLineNumber = 1;
	let oldContent = "";
	let newContent = "";
	for (const hunk of hunks) {
		while (oldLines != null && newLines != null && newLineIndex < hunk.additionStart && oldLineIndex < hunk.deletionStart) {
			oldInfo[oldLineIndex] = {
				type: "context-expanded",
				lineNumber: oldLineNumber,
				lineIndex
			};
			newInfo[newLineIndex] = {
				type: "context-expanded",
				lineNumber: newLineNumber,
				lineIndex
			};
			oldContent += oldLines[oldLineIndex - 1];
			newContent += newLines[newLineIndex - 1];
			oldLineIndex++;
			newLineIndex++;
			oldLineNumber++;
			newLineNumber++;
			lineIndex++;
		}
		oldLineNumber = hunk.deletionStart;
		newLineNumber = hunk.additionStart;
		for (const hunkContent of hunk.hunkContent) if (hunkContent.type === "context") for (const line of hunkContent.lines) {
			oldInfo[oldLineIndex] = {
				type: "context",
				lineNumber: oldLineNumber,
				lineIndex
			};
			newInfo[newLineIndex] = {
				type: "context",
				lineNumber: newLineNumber,
				lineIndex
			};
			oldContent += line;
			newContent += line;
			oldLineIndex++;
			newLineIndex++;
			newLineNumber++;
			oldLineNumber++;
			lineIndex++;
		}
		else {
			const len = Math.max(hunkContent.additions.length, hunkContent.deletions.length);
			let i = 0;
			while (i < len) {
				const oldLine = hunkContent.deletions[i];
				const newLine = hunkContent.additions[i];
				computeLineDiffDecorations({
					newLine,
					oldLine,
					oldLineIndex,
					newLineIndex,
					oldDecorations,
					newDecorations,
					lineDiffType
				});
				if (oldLine != null) {
					oldInfo[oldLineIndex] = {
						type: "change-deletion",
						lineNumber: oldLineNumber,
						lineIndex
					};
					oldContent += oldLine;
					oldLineIndex++;
					oldLineNumber++;
				}
				if (newLine != null) {
					newInfo[newLineIndex] = {
						type: "change-addition",
						lineNumber: newLineNumber,
						lineIndex
					};
					newContent += newLine;
					newLineIndex++;
					newLineNumber++;
				}
				lineIndex++;
				i++;
			}
		}
		if (oldLines == null || newLines == null || hunk !== hunks[hunks.length - 1]) continue;
		while (oldLineIndex <= oldLines.length || newLineIndex <= oldLines.length) {
			const oldLine = oldLines[oldLineIndex - 1];
			const newLine = newLines[newLineIndex - 1];
			if (oldLine == null && newLine == null) break;
			if (oldLine != null) {
				oldInfo[oldLineIndex] = {
					type: "context-expanded",
					lineNumber: oldLineNumber,
					lineIndex
				};
				oldContent += oldLine;
				oldLineIndex++;
				oldLineNumber++;
			}
			if (newLine != null) {
				newInfo[newLineIndex] = {
					type: "context-expanded",
					lineNumber: newLineNumber,
					lineIndex
				};
				newContent += newLine;
				newLineIndex++;
				newLineNumber++;
			}
			lineIndex++;
		}
	}
	return {
		oldContent: cleanLastNewline(oldContent),
		newContent: cleanLastNewline(newContent),
		oldInfo,
		newInfo,
		oldDecorations,
		newDecorations,
		lineIndex
	};
}
function renderTwoFiles({ oldFile, newFile, oldInfo, newInfo, highlighter: highlighter$1, oldDecorations, newDecorations, languageOverride, options: { theme: themeOrThemes = DEFAULT_THEMES,...options } }) {
	const oldLang = languageOverride ?? getFiletypeFromFileName(oldFile.name);
	const newLang = languageOverride ?? getFiletypeFromFileName(newFile.name);
	const { state, transformers } = createTransformerWithState();
	const hastConfig = (() => {
		return typeof themeOrThemes === "string" ? {
			...options,
			lang: "text",
			theme: themeOrThemes,
			transformers,
			decorations: void 0,
			defaultColor: false,
			cssVariablePrefix: formatCSSVariablePrefix()
		} : {
			...options,
			lang: "text",
			themes: themeOrThemes,
			transformers,
			decorations: void 0,
			defaultColor: false,
			cssVariablePrefix: formatCSSVariablePrefix()
		};
	})();
	return {
		oldLines: (() => {
			if (oldFile.contents === "") return [];
			hastConfig.lang = oldLang;
			state.lineInfo = oldInfo;
			hastConfig.decorations = oldDecorations;
			return getLineNodes(highlighter$1.codeToHast(oldFile.contents, hastConfig));
		})(),
		newLines: (() => {
			if (newFile.contents === "") return [];
			hastConfig.lang = newLang;
			hastConfig.decorations = newDecorations;
			state.lineInfo = newInfo;
			return getLineNodes(highlighter$1.codeToHast(newFile.contents, hastConfig));
		})()
	};
}

//#endregion
//#region src/utils/renderFileWithHighlighter.ts
function renderFileWithHighlighter(file, highlighter$1, { theme = DEFAULT_THEMES, tokenizeMaxLineLength }, forcePlainText = false) {
	const { state, transformers } = createTransformerWithState();
	const lang = forcePlainText ? "text" : file.lang ?? getFiletypeFromFileName(file.name);
	const baseThemeType = (() => {
		if (typeof theme === "string") return highlighter$1.getTheme(theme).type;
	})();
	const themeStyles = getHighlighterThemeStyles({
		theme,
		highlighter: highlighter$1
	});
	state.lineInfo = (shikiLineNumber) => ({
		type: "context",
		lineIndex: shikiLineNumber - 1,
		lineNumber: shikiLineNumber
	});
	const hastConfig = (() => {
		if (typeof theme === "string") return {
			lang,
			theme,
			transformers,
			defaultColor: false,
			cssVariablePrefix: formatCSSVariablePrefix(),
			tokenizeMaxLineLength
		};
		return {
			lang,
			themes: theme,
			transformers,
			defaultColor: false,
			cssVariablePrefix: formatCSSVariablePrefix(),
			tokenizeMaxLineLength
		};
	})();
	return {
		code: getLineNodes(highlighter$1.codeToHast(cleanLastNewline(file.contents), hastConfig)),
		themeStyles,
		baseThemeType
	};
}

//#endregion
//#region src/worker/worker.ts
let renderOptions = {
	theme: DEFAULT_THEMES,
	tokenizeMaxLineLength: 1e3,
	lineDiffType: "word-alt"
};
self.addEventListener("error", (event) => {
	console.error("[Shiki Worker] Unhandled error:", event.error);
});
self.addEventListener("message", async (event) => {
	const request = event.data;
	try {
		switch (request.type) {
			case "initialize":
				await handleInitialize(request);
				break;
			case "register-theme":
				await handleRegisterTheme(request);
				break;
			case "file":
				await handleRenderFile(request);
				break;
			case "diff":
				await handleRenderDiffMetadata(request);
				break;
			default: throw new Error(`Unknown request type: ${request.type}`);
		}
	} catch (error) {
		console.error("Worker error:", error);
		sendError(request.id, error);
	}
});
async function handleInitialize({ id, renderOptions: options, resolvedThemes, resolvedLanguages }) {
	const highlighter$1 = await getHighlighter();
	attachResolvedThemes(resolvedThemes, highlighter$1);
	if (resolvedLanguages != null) attachResolvedLanguages(resolvedLanguages, highlighter$1);
	renderOptions = options;
	postMessage({
		type: "success",
		id,
		requestType: "initialize",
		sentAt: Date.now()
	});
}
async function handleRegisterTheme({ id, theme, resolvedThemes }) {
	attachResolvedThemes(resolvedThemes, getHighlighterIfLoaded() ?? await getHighlighter());
	renderOptions.theme = theme;
	postMessage({
		type: "success",
		id,
		requestType: "register-theme",
		sentAt: Date.now()
	});
}
async function handleRenderFile({ id, file, resolvedLanguages }) {
	const highlighter$1 = getHighlighterIfLoaded() ?? await getHighlighter();
	if (resolvedLanguages != null) attachResolvedLanguages(resolvedLanguages, highlighter$1);
	sendFileSuccess(id, renderFileWithHighlighter(file, highlighter$1, renderOptions), renderOptions);
}
async function handleRenderDiffMetadata({ id, diff, resolvedLanguages }) {
	const highlighter$1 = getHighlighterIfLoaded() ?? await getHighlighter();
	if (resolvedLanguages != null) attachResolvedLanguages(resolvedLanguages, highlighter$1);
	sendDiffMetadataSuccess(id, renderDiffWithHighlighter(diff, highlighter$1, renderOptions), renderOptions);
}
async function getHighlighter() {
	return await getSharedHighlighter({
		themes: [],
		langs: ["text"]
	});
}
function sendFileSuccess(id, result, options) {
	postMessage({
		type: "success",
		requestType: "file",
		id,
		result,
		options,
		sentAt: Date.now()
	});
}
function sendDiffMetadataSuccess(id, result, options) {
	postMessage({
		type: "success",
		requestType: "diff",
		id,
		result,
		options,
		sentAt: Date.now()
	});
}
function sendError(id, error) {
	const response = {
		type: "error",
		id,
		error: error instanceof Error ? error.message : String(error),
		stack: error instanceof Error ? error.stack : void 0
	};
	postMessage(response);
}

//#endregion
//# sourceMappingURL=worker.js.map