import { splitTokens } from '@shikijs/core';

class ShikiTwoslashError extends Error {
  constructor(message) {
    super(message);
    this.name = "ShikiTwoslashError";
  }
}

class TwoslashIncludesManager {
  constructor(map = /* @__PURE__ */ new Map()) {
    this.map = map;
  }
  add(name, code) {
    const lines = [];
    code.split("\n").forEach((l, _i) => {
      const trimmed = l.trim();
      if (trimmed.startsWith("// - ")) {
        const key = trimmed.split("// - ")[1].split(" ")[0];
        this.map.set(`${name}-${key}`, lines.join("\n"));
      } else {
        lines.push(l);
      }
    });
    this.map.set(name, lines.join("\n"));
  }
  applyInclude(code) {
    const reMarker = /\/\/ @include: (.*)$/gm;
    const toReplace = [];
    for (const match of code.matchAll(reMarker)) {
      const key = match[1];
      const replaceWith = this.map.get(key);
      if (!replaceWith) {
        const msg = `Could not find an include with the key: '${key}'.
There is: ${Array.from(this.map.keys())}.`;
        throw new Error(msg);
      } else {
        toReplace.push([match.index, match[0].length, replaceWith]);
      }
    }
    let newCode = code.toString();
    toReplace.reverse().forEach(([index, length, replacementCode]) => {
      newCode = newCode.slice(0, index) + replacementCode + newCode.slice(index + length);
    });
    return newCode;
  }
}
const INCLUDE_META_REGEX = /include\s+([\w-]+)\b.*/;
function parseIncludeMeta(meta) {
  if (!meta)
    return null;
  const match = meta.match(INCLUDE_META_REGEX);
  return match?.[1] ?? null;
}

const module = {
	type: "element",
	tagName: "svg",
	properties: {
		viewBox: "0 0 32 32"
	},
	children: [
		{
			type: "element",
			tagName: "path",
			properties: {
				d: "M11 2H2v9h2V4h7V2z",
				fill: "currentColor"
			},
			children: [
			]
		},
		{
			type: "element",
			tagName: "path",
			properties: {
				d: "M2 21v9h9v-2H4v-7H2z",
				fill: "currentColor"
			},
			children: [
			]
		},
		{
			type: "element",
			tagName: "path",
			properties: {
				d: "M30 11V2h-9v2h7v7h2z",
				fill: "currentColor"
			},
			children: [
			]
		},
		{
			type: "element",
			tagName: "path",
			properties: {
				d: "M21 30h9v-9h-2v7h-7v2z",
				fill: "currentColor"
			},
			children: [
			]
		},
		{
			type: "element",
			tagName: "path",
			properties: {
				d: "M25.49 10.13l-9-5a1 1 0 0 0-1 0l-9 5A1 1 0 0 0 6 11v10a1 1 0 0 0 .51.87l9 5a1 1 0 0 0 1 0l9-5A1 1 0 0 0 26 21V11a1 1 0 0 0-.51-.87zM16 7.14L22.94 11L16 14.86L9.06 11zM8 12.7l7 3.89v7.71l-7-3.89zm9 11.6v-7.71l7-3.89v7.71z",
				fill: "currentColor"
			},
			children: [
			]
		}
	]
};
const method = {
	type: "element",
	tagName: "svg",
	properties: {
		viewBox: "0 0 32 32"
	},
	children: [
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "m19.626 29.526l-.516-1.933a12.004 12.004 0 0 0 6.121-19.26l1.538-1.28a14.003 14.003 0 0 1-7.143 22.473"
			},
			children: [
			]
		},
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M10 29H8v-3.82l.804-.16C10.262 24.727 12 23.62 12 20v-1.382l-4-2v-2.236l4-2V12c0-5.467 3.925-9 10-9h2v3.82l-.804.16C21.738 7.273 20 8.38 20 12v.382l4 2v2.236l-4 2V20c0 5.467-3.925 9-10 9m0-2c4.935 0 8-2.682 8-7v-2.618l3.764-1.882L18 13.618V12c0-4.578 2.385-6.192 4-6.76V5c-4.935 0-8 2.682-8 7v1.618L10.236 15.5L14 17.382V20c0 4.578-2.385 6.192-4 6.76Z"
			},
			children: [
			]
		},
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M5.231 24.947a14.003 14.003 0 0 1 7.147-22.474l.516 1.932a12.004 12.004 0 0 0-6.125 19.263Z"
			},
			children: [
			]
		}
	]
};
const property = {
	type: "element",
	tagName: "svg",
	properties: {
		viewBox: "0 0 32 32"
	},
	children: [
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M12.1 2a9.8 9.8 0 0 0-5.4 1.6l6.4 6.4a2.1 2.1 0 0 1 .2 3a2.1 2.1 0 0 1-3-.2L3.7 6.4A9.84 9.84 0 0 0 2 12.1a10.14 10.14 0 0 0 10.1 10.1a10.9 10.9 0 0 0 2.6-.3l6.7 6.7a5 5 0 0 0 7.1-7.1l-6.7-6.7a10.9 10.9 0 0 0 .3-2.6A10 10 0 0 0 12.1 2m8 10.1a7.61 7.61 0 0 1-.3 2.1l-.3 1.1l.8.8l6.7 6.7a2.88 2.88 0 0 1 .9 2.1A2.72 2.72 0 0 1 27 27a2.9 2.9 0 0 1-4.2 0l-6.7-6.7l-.8-.8l-1.1.3a7.61 7.61 0 0 1-2.1.3a8.27 8.27 0 0 1-5.7-2.3A7.63 7.63 0 0 1 4 12.1a8.33 8.33 0 0 1 .3-2.2l4.4 4.4a4.14 4.14 0 0 0 5.9.2a4.14 4.14 0 0 0-.2-5.9L10 4.2a6.45 6.45 0 0 1 2-.3a8.27 8.27 0 0 1 5.7 2.3a8.49 8.49 0 0 1 2.4 5.9"
			},
			children: [
			]
		}
	]
};
const constructor = {
	type: "element",
	tagName: "svg",
	properties: {
		viewBox: "0 0 32 32"
	},
	children: [
		{
			type: "element",
			tagName: "path",
			properties: {
				d: "M21.49 13.115l-9-5a1 1 0 0 0-1 0l-9 5A1.008 1.008 0 0 0 2 14v9.995a1 1 0 0 0 .52.87l9 5A1.004 1.004 0 0 0 12 30a1.056 1.056 0 0 0 .49-.135l9-5A.992.992 0 0 0 22 24V14a1.008 1.008 0 0 0-.51-.885zM11 27.295l-7-3.89v-7.72l7 3.89zm1-9.45L5.06 14L12 10.135l6.94 3.86zm8 5.56l-7 3.89v-7.72l7-3.89z",
				fill: "currentColor"
			},
			children: [
			]
		},
		{
			type: "element",
			tagName: "path",
			properties: {
				d: "M30 6h-4V2h-2v4h-4v2h4v4h2V8h4V6z",
				fill: "currentColor"
			},
			children: [
			]
		}
	]
};
const string = {
	type: "element",
	tagName: "svg",
	properties: {
		viewBox: "0 0 32 32"
	},
	children: [
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M29 22h-5a2.003 2.003 0 0 1-2-2v-6a2.002 2.002 0 0 1 2-2h5v2h-5v6h5zM18 12h-4V8h-2v14h6a2.003 2.003 0 0 0 2-2v-6a2.002 2.002 0 0 0-2-2m-4 8v-6h4v6zm-6-8H3v2h5v2H4a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h6v-8a2.002 2.002 0 0 0-2-2m0 8H4v-2h4z"
			},
			children: [
			]
		}
	]
};
const completionIcons = {
	module: module,
	"class": {
	type: "element",
	tagName: "svg",
	properties: {
		viewBox: "0 0 32 32"
	},
	children: [
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M26 16a3.961 3.961 0 0 0-2.02.566l-2.859-2.859l2.293-2.293a2 2 0 0 0 0-2.828l-6-6a2 2 0 0 0-2.828 0l-6 6a2 2 0 0 0 0 2.828l2.293 2.293l-2.859 2.859a4.043 4.043 0 1 0 1.414 1.414l2.859-2.859l2.293 2.293a1.977 1.977 0 0 0 .414.31V22h-3v8h8v-8h-3v-4.277a1.977 1.977 0 0 0 .414-.309l2.293-2.293l2.859 2.859A3.989 3.989 0 1 0 26 16M8 20a2 2 0 1 1-2-2a2.002 2.002 0 0 1 2 2m10 4v4h-4v-4zm-2-8l-6-6l6-6l6 6Zm10 6a2 2 0 1 1 2-2a2.002 2.002 0 0 1-2 2"
			},
			children: [
			]
		}
	]
},
	method: method,
	property: property,
	constructor: constructor,
	"interface": {
	type: "element",
	tagName: "svg",
	properties: {
		viewBox: "0 0 32 32"
	},
	children: [
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M23 16.01a7 7 0 0 0-4.18 1.39l-4.22-4.22A6.86 6.86 0 0 0 16 9.01a7 7 0 1 0-2.81 5.59l4.21 4.22a7 7 0 1 0 5.6-2.81m-19-7a5 5 0 1 1 5 5a5 5 0 0 1-5-5"
			},
			children: [
			]
		}
	]
},
	"function": {
	type: "element",
	tagName: "svg",
	properties: {
		viewBox: "0 0 32 32"
	},
	children: [
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "m19.626 29.526l-.516-1.933a12.004 12.004 0 0 0 6.121-19.26l1.538-1.28a14.003 14.003 0 0 1-7.143 22.473"
			},
			children: [
			]
		},
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M10 29H8v-3.82l.804-.16C10.262 24.727 12 23.62 12 20v-1.382l-4-2v-2.236l4-2V12c0-5.467 3.925-9 10-9h2v3.82l-.804.16C21.738 7.273 20 8.38 20 12v.382l4 2v2.236l-4 2V20c0 5.467-3.925 9-10 9m0-2c4.935 0 8-2.682 8-7v-2.618l3.764-1.882L18 13.618V12c0-4.578 2.385-6.192 4-6.76V5c-4.935 0-8 2.682-8 7v1.618L10.236 15.5L14 17.382V20c0 4.578-2.385 6.192-4 6.76Z"
			},
			children: [
			]
		},
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M5.231 24.947a14.003 14.003 0 0 1 7.147-22.474l.516 1.932a12.004 12.004 0 0 0-6.125 19.263Z"
			},
			children: [
			]
		}
	]
},
	string: string
};

const log = {
	type: "element",
	tagName: "svg",
	properties: {
		viewBox: "0 0 32 32"
	},
	children: [
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M17 22v-8h-4v2h2v6h-3v2h8v-2zM16 8a1.5 1.5 0 1 0 1.5 1.5A1.5 1.5 0 0 0 16 8"
			},
			children: [
			]
		},
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M26 28H6a2.002 2.002 0 0 1-2-2V6a2.002 2.002 0 0 1 2-2h20a2.002 2.002 0 0 1 2 2v20a2.002 2.002 0 0 1-2 2M6 6v20h20V6Z"
			},
			children: [
			]
		}
	]
};
const error = {
	type: "element",
	tagName: "svg",
	properties: {
		viewBox: "0 0 32 32"
	},
	children: [
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M16 2a14 14 0 1 0 14 14A14 14 0 0 0 16 2m0 26a12 12 0 1 1 12-12a12 12 0 0 1-12 12"
			},
			children: [
			]
		},
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M15 8h2v11h-2zm1 14a1.5 1.5 0 1 0 1.5 1.5A1.5 1.5 0 0 0 16 22"
			},
			children: [
			]
		}
	]
};
const warn = {
	type: "element",
	tagName: "svg",
	properties: {
		viewBox: "0 0 32 32"
	},
	children: [
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M16 23a1.5 1.5 0 1 0 1.5 1.5A1.5 1.5 0 0 0 16 23m-1-11h2v9h-2z"
			},
			children: [
			]
		},
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M29 30H3a1 1 0 0 1-.887-1.461l13-25a1 1 0 0 1 1.774 0l13 25A1 1 0 0 1 29 30M4.65 28h22.7l.001-.003L16.002 6.17h-.004L4.648 27.997Z"
			},
			children: [
			]
		}
	]
};
const annotate = {
	type: "element",
	tagName: "svg",
	properties: {
		viewBox: "0 0 32 32"
	},
	children: [
		{
			type: "element",
			tagName: "path",
			properties: {
				fill: "currentColor",
				d: "M11 24h10v2H11zm2 4h6v2h-6zm3-26A10 10 0 0 0 6 12a9.19 9.19 0 0 0 3.46 7.62c1 .93 1.54 1.46 1.54 2.38h2c0-1.84-1.11-2.87-2.19-3.86A7.2 7.2 0 0 1 8 12a8 8 0 0 1 16 0a7.2 7.2 0 0 1-2.82 6.14c-1.07 1-2.18 2-2.18 3.86h2c0-.92.53-1.45 1.54-2.39A9.18 9.18 0 0 0 26 12A10 10 0 0 0 16 2"
			},
			children: [
			]
		}
	]
};
const tagIcons = {
	log: log,
	error: error,
	warn: warn,
	annotate: annotate
};

const defaultCompletionIcons = completionIcons;
const defaultCustomTagIcons = tagIcons;

function rendererClassic() {
  return {
    nodeStaticInfo(info, node) {
      return {
        type: "element",
        tagName: "data-lsp",
        properties: {
          lsp: info.text
        },
        children: [node]
      };
    },
    nodeError(_, node) {
      return {
        type: "element",
        tagName: "data-err",
        properties: {},
        children: [node]
      };
    },
    lineError(error) {
      return [
        {
          type: "element",
          tagName: "div",
          properties: {
            class: "error"
          },
          children: [
            {
              type: "element",
              tagName: "span",
              properties: {},
              children: [
                {
                  type: "text",
                  value: error.text
                }
              ]
            },
            {
              type: "element",
              tagName: "span",
              properties: {
                class: "code"
              },
              children: [
                {
                  type: "text",
                  value: String(error.code)
                }
              ]
            }
          ]
        },
        {
          type: "element",
          tagName: "span",
          properties: {
            class: "error-behind"
          },
          children: [
            {
              type: "text",
              value: error.text
            }
          ]
        }
      ];
    },
    lineCompletion(query) {
      return [
        {
          type: "element",
          tagName: "div",
          properties: { class: "meta-line" },
          children: [
            { type: "text", value: " ".repeat(query.character) },
            {
              type: "element",
              tagName: "span",
              properties: { class: "inline-completions" },
              children: [{
                type: "element",
                tagName: "ul",
                properties: { class: "dropdown" },
                children: query.completions.filter((i) => i.name.startsWith(query.completionsPrefix || "____")).map((i) => ({
                  type: "element",
                  tagName: "li",
                  properties: {
                    class: "kindModifiers" in i && typeof i.kindModifiers === "string" && i.kindModifiers?.split(",").includes("deprecated") ? "deprecated" : undefined
                  },
                  children: [{
                    type: "element",
                    tagName: "span",
                    properties: {},
                    children: [
                      {
                        type: "element",
                        tagName: "span",
                        properties: { class: "result-found" },
                        children: [
                          {
                            type: "text",
                            value: query.completionsPrefix || ""
                          }
                        ]
                      },
                      {
                        type: "text",
                        value: i.name.slice(query.completionsPrefix?.length || 0)
                      }
                    ]
                  }]
                }))
              }]
            }
          ]
        }
      ];
    },
    lineQuery(query, targetNode) {
      const targetText = targetNode?.type === "text" ? targetNode.value : "";
      const offset = Math.max(0, (query.character || 0) + Math.floor(targetText.length / 2) - 1);
      return [
        {
          type: "element",
          tagName: "div",
          properties: { class: "meta-line" },
          children: [
            { type: "text", value: " ".repeat(offset) },
            {
              type: "element",
              tagName: "span",
              properties: { class: "popover" },
              children: [
                {
                  type: "element",
                  tagName: "div",
                  properties: { class: "arrow" },
                  children: []
                },
                {
                  type: "text",
                  value: query.text || ""
                }
              ]
            }
          ]
        }
      ];
    },
    lineCustomTag(tag) {
      return [
        {
          type: "element",
          tagName: "div",
          properties: { class: `meta-line logger ${tag.name}-log` },
          children: [
            {
              type: "element",
              tagName: "span",
              properties: { class: "message" },
              children: [
                {
                  type: "text",
                  value: tag.text || ""
                }
              ]
            }
          ]
        }
      ];
    }
  };
}

function extend(extension, node) {
  if (!extension)
    return node;
  return {
    ...node,
    tagName: extension.tagName ?? node.tagName,
    properties: {
      ...node.properties,
      class: extension.class || node.properties?.class,
      ...extension.properties
    },
    children: extension.children?.(node.children) ?? node.children
  };
}
function renderMarkdownPassThrough(markdown) {
  return [
    {
      type: "text",
      value: markdown
    }
  ];
}
function rendererRich(options = {}) {
  const {
    completionIcons = defaultCompletionIcons,
    customTagIcons = defaultCustomTagIcons,
    processHoverInfo = defaultHoverInfoProcessor,
    processHoverDocs = (docs) => docs,
    classExtra = "",
    jsdoc = true,
    errorRendering = "line",
    queryRendering = "popup",
    renderMarkdown = renderMarkdownPassThrough,
    renderMarkdownInline = renderMarkdownPassThrough,
    hast
  } = options;
  function highlightPopupContent(info) {
    if (!info.text)
      return [];
    const content = processHoverInfo(info.text);
    if (!content || content === "any")
      return [];
    const popupContents = [];
    const typeCode = {
      type: "element",
      tagName: "code",
      properties: {},
      children: this.codeToHast(
        content,
        {
          ...this.options,
          meta: {},
          transformers: [],
          lang: this.options.lang === "tsx" || this.options.lang === "jsx" ? "tsx" : "ts",
          structure: content.trim().includes("\n") ? "classic" : "inline"
        }
      ).children
    };
    typeCode.properties.class = "twoslash-popup-code";
    popupContents.push(
      extend(
        hast?.popupTypes,
        typeCode
      )
    );
    if (jsdoc && info.docs) {
      const docs = processHoverDocs(info.docs) ?? info.docs;
      if (docs) {
        const children = renderMarkdown.call(this, docs);
        popupContents.push(extend(
          hast?.popupDocs,
          {
            type: "element",
            tagName: "div",
            properties: { class: "twoslash-popup-docs" },
            children
          }
        ));
      }
    }
    if (jsdoc && info.tags?.length) {
      popupContents.push(extend(
        hast?.popupDocsTags,
        {
          type: "element",
          tagName: "div",
          properties: {
            class: "twoslash-popup-docs twoslash-popup-docs-tags"
          },
          children: info.tags.map((tag) => ({
            type: "element",
            tagName: "span",
            properties: {
              class: `twoslash-popup-docs-tag`
            },
            children: [
              {
                type: "element",
                tagName: "span",
                properties: {
                  class: "twoslash-popup-docs-tag-name"
                },
                children: [
                  {
                    type: "text",
                    value: `@${tag[0]}`
                  }
                ]
              },
              ...tag[1] ? [
                {
                  type: "element",
                  tagName: "span",
                  properties: {
                    class: "twoslash-popup-docs-tag-value"
                  },
                  children: renderMarkdownInline.call(this, tag[1], `tag:${tag[0]}`)
                }
              ] : []
            ]
          }))
        }
      ));
    }
    return popupContents;
  }
  return {
    nodeStaticInfo(info, node) {
      const themedContent = highlightPopupContent.call(this, info);
      if (!themedContent.length)
        return node;
      const popup = extend(
        hast?.hoverPopup,
        {
          type: "element",
          tagName: "span",
          properties: {
            class: ["twoslash-popup-container", classExtra].filter(Boolean).join(" ")
          },
          children: themedContent
        }
      );
      return extend(
        hast?.hoverToken,
        {
          type: "element",
          tagName: "span",
          properties: {
            class: "twoslash-hover"
          },
          children: hast?.hoverCompose ? hast?.hoverCompose({ popup, token: node }) : [popup, node]
        }
      );
    },
    nodeQuery(query, node) {
      if (!query.text)
        return {};
      const themedContent = highlightPopupContent.call(this, query);
      if (queryRendering !== "popup") {
        return extend(
          hast?.queryToken,
          {
            type: "element",
            tagName: "span",
            properties: {
              class: "twoslash-hover"
            },
            children: [
              node
            ]
          }
        );
      }
      const popup = extend(
        hast?.queryPopup,
        {
          type: "element",
          tagName: "span",
          properties: {
            class: ["twoslash-popup-container", classExtra].filter(Boolean).join(" ")
          },
          children: [
            {
              type: "element",
              tagName: "div",
              properties: { class: "twoslash-popup-arrow" },
              children: []
            },
            ...themedContent
          ]
        }
      );
      return extend(
        hast?.queryToken,
        {
          type: "element",
          tagName: "span",
          properties: {
            class: "twoslash-hover twoslash-query-presisted"
          },
          children: hast?.queryCompose ? hast?.queryCompose({ popup, token: node }) : [popup, node]
        }
      );
    },
    nodeCompletion(query, node) {
      if (node.type !== "text")
        throw new ShikiTwoslashError(`Renderer hook nodeCompletion only works on text nodes, got ${node.type}`);
      const items = query.completions.map((i) => {
        const kind = i.kind || "default";
        const isDeprecated = "kindModifiers" in i && typeof i.kindModifiers === "string" && i.kindModifiers?.split(",").includes("deprecated");
        return {
          type: "element",
          tagName: "li",
          properties: {},
          children: [
            ...completionIcons ? [{
              type: "element",
              tagName: "span",
              properties: { class: `twoslash-completions-icon completions-${kind.replace(/\s/g, "-")}` },
              children: [
                completionIcons[kind] || completionIcons.property
              ].filter(Boolean)
            }] : [],
            {
              type: "element",
              tagName: "span",
              properties: {
                class: isDeprecated ? "deprecated" : undefined
              },
              children: [
                {
                  type: "element",
                  tagName: "span",
                  properties: { class: "twoslash-completions-matched" },
                  children: [
                    {
                      type: "text",
                      value: i.name.startsWith(query.completionsPrefix) ? query.completionsPrefix : ""
                    }
                  ]
                },
                {
                  type: "element",
                  tagName: "span",
                  properties: { class: "twoslash-completions-unmatched" },
                  children: [
                    {
                      type: "text",
                      value: i.name.startsWith(query.completionsPrefix) ? i.name.slice(query.completionsPrefix.length || 0) : i.name
                    }
                  ]
                }
              ]
            }
          ]
        };
      });
      const cursor = extend(
        hast?.completionCursor,
        {
          type: "element",
          tagName: "span",
          properties: {
            class: ["twoslash-completion-cursor", classExtra].filter(Boolean).join(" ")
          },
          children: []
        }
      );
      const popup = extend(
        hast?.completionPopup,
        {
          type: "element",
          tagName: "ul",
          properties: {
            class: ["twoslash-completion-list", classExtra].filter(Boolean).join(" ")
          },
          children: items
        }
      );
      const children = [];
      if (node.value)
        children.push({ type: "text", value: node.value });
      if (hast?.completionCompose) {
        children.push(...hast.completionCompose({ popup, cursor }));
      } else {
        children.push({
          ...cursor,
          children: [popup]
        });
      }
      return extend(
        hast?.completionToken,
        {
          type: "element",
          tagName: "span",
          properties: {},
          children
        }
      );
    },
    nodesError(error, children) {
      if (errorRendering !== "hover") {
        return [
          extend(
            hast?.errorToken,
            {
              type: "element",
              tagName: "span",
              properties: {
                class: [`twoslash-error`, getErrorLevelClass(error)].filter(Boolean).join(" ")
              },
              children
            }
          )
        ];
      }
      const popup = extend(
        hast?.errorPopup,
        {
          type: "element",
          tagName: "span",
          properties: {
            class: ["twoslash-popup-container", classExtra].filter(Boolean).join(" ")
          },
          children: [
            extend(
              hast?.popupError,
              {
                type: "element",
                tagName: "div",
                properties: {
                  class: "twoslash-popup-error"
                },
                children: renderMarkdown.call(this, error.text)
              }
            )
          ]
        }
      );
      const token = {
        type: "element",
        tagName: "span",
        children,
        properties: {}
      };
      return [
        extend(
          hast?.errorToken,
          {
            type: "element",
            tagName: "span",
            properties: {
              class: `twoslash-error twoslash-error-hover ${getErrorLevelClass(error)}`
            },
            children: hast?.errorCompose ? hast?.errorCompose({ popup, token }) : [popup, token]
          }
        )
      ];
    },
    lineQuery(query, node) {
      if (queryRendering !== "line")
        return [];
      const themedContent = highlightPopupContent.call(this, query);
      const targetNode = node?.type === "element" ? node.children[0] : undefined;
      const targetText = targetNode?.type === "text" ? targetNode.value : "";
      const offset = Math.max(0, (query.character || 0) + Math.floor(targetText.length / 2) - 2);
      return [
        {
          type: "element",
          tagName: "div",
          properties: {
            class: ["twoslash-meta-line twoslash-query-line", classExtra].filter(Boolean).join(" ")
          },
          children: [
            { type: "text", value: " ".repeat(offset) },
            {
              type: "element",
              tagName: "span",
              properties: {
                class: ["twoslash-popup-container", classExtra].filter(Boolean).join(" ")
              },
              children: [
                {
                  type: "element",
                  tagName: "div",
                  properties: { class: "twoslash-popup-arrow" },
                  children: []
                },
                ...themedContent
              ]
            }
          ]
        }
      ];
    },
    lineError(error) {
      if (errorRendering !== "line")
        return [];
      return [
        {
          type: "element",
          tagName: "div",
          properties: {
            class: ["twoslash-meta-line twoslash-error-line", getErrorLevelClass(error), classExtra].filter(Boolean).join(" ")
          },
          children: [
            {
              type: "text",
              value: error.text
            }
          ]
        }
      ];
    },
    lineCustomTag(tag) {
      return [
        {
          type: "element",
          tagName: "div",
          properties: {
            class: [`twoslash-tag-line twoslash-tag-${tag.name}-line`, classExtra].filter(Boolean).join(" ")
          },
          children: [
            ...customTagIcons ? [{
              type: "element",
              tagName: "span",
              properties: { class: `twoslash-tag-icon tag-${tag.name}-icon` },
              children: [
                customTagIcons[tag.name]
              ].filter(Boolean)
            }] : [],
            {
              type: "text",
              value: tag.text || ""
            }
          ]
        }
      ];
    },
    nodesHighlight(highlight, nodes) {
      return [
        extend(
          hast?.nodesHighlight,
          {
            type: "element",
            tagName: "span",
            properties: {
              class: "twoslash-highlighted"
            },
            children: nodes
          }
        )
      ];
    }
  };
}
const regexType = /^[A-Z]\w*(<[^>]*>)?:/;
const regexFunction = /^\w*\(/;
function defaultHoverInfoProcessor(type) {
  let content = type.replace(/^\(([\w-]+)\)\s+/gm, "").replace(/\nimport .*$/, "").replace(/^(interface|namespace) \w+$/gm, "").trim();
  if (content.match(regexType))
    content = `type ${content}`;
  else if (content.match(regexFunction))
    content = `function ${content}`;
  return content;
}
function getErrorLevelClass(error) {
  switch (error.level) {
    case "warning":
      return "twoslash-error-level-warning";
    case "suggestion":
      return "twoslash-error-level-suggestion";
    case "message":
      return "twoslash-error-level-message";
    default:
      return "";
  }
}

function defaultTwoslashOptions() {
  return {
    customTags: ["annotate", "log", "warn", "error"]
  };
}
function createTransformerFactory(defaultTwoslasher, defaultRenderer) {
  return function transformerTwoslash(options = {}) {
    const {
      langs = ["ts", "tsx"],
      twoslashOptions = defaultTwoslashOptions(),
      langAlias = {
        typescript: "ts",
        json5: "json",
        yml: "yaml"
      },
      twoslasher = defaultTwoslasher,
      explicitTrigger = false,
      disableTriggers = ["notwoslash", "no-twoslash"],
      renderer = defaultRenderer,
      throws = true,
      includesMap = /* @__PURE__ */ new Map()
    } = options;
    const onTwoslashError = options.onTwoslashError || (throws ? (error) => {
      throw error;
    } : () => false);
    const onShikiError = options.onShikiError || (throws ? (error) => {
      throw error;
    } : () => false);
    const trigger = explicitTrigger instanceof RegExp ? explicitTrigger : /\btwoslash\b/;
    if (!renderer)
      throw new ShikiTwoslashError("Missing renderer");
    const map = /* @__PURE__ */ new WeakMap();
    const {
      filter = (lang, _, options2) => {
        return langs.includes(lang) && (!explicitTrigger || trigger.test(options2.meta?.__raw || "")) && !disableTriggers.some((i) => typeof i === "string" ? options2.meta?.__raw?.includes(i) : i.test(options2.meta?.__raw || ""));
      }
    } = options;
    const includes = new TwoslashIncludesManager(includesMap);
    return {
      preprocess(code) {
        let lang = this.options.lang;
        if (lang in langAlias)
          lang = langAlias[this.options.lang];
        if (filter(lang, code, this.options)) {
          try {
            const codeWithIncludes = includes.applyInclude(code);
            const include = parseIncludeMeta(this.options.meta?.__raw);
            if (include)
              includes.add(include, codeWithIncludes);
            const twoslash = twoslasher(codeWithIncludes, lang, twoslashOptions);
            map.set(this.meta, twoslash);
            this.meta.twoslash = twoslash;
            this.options.lang = twoslash.meta?.extension || lang;
            return twoslash.code;
          } catch (error) {
            const result = onTwoslashError(error, code, lang, this.options);
            if (typeof result === "string")
              return code;
          }
        }
      },
      tokens(tokens) {
        const twoslash = map.get(this.meta);
        if (!twoslash)
          return;
        return splitTokens(
          tokens,
          twoslash.nodes.flatMap(
            (i) => ["hover", "error", "query", "highlight", "completion"].includes(i.type) ? [i.start, i.start + i.length] : []
          )
        );
      },
      pre(pre) {
        const twoslash = map.get(this.meta);
        if (!twoslash)
          return;
        this.addClassToHast(pre, "twoslash lsp");
      },
      code(codeEl) {
        const twoslash = map.get(this.meta);
        if (!twoslash)
          return;
        const insertAfterLine = (line, nodes) => {
          if (!nodes.length)
            return;
          let index;
          if (line >= this.lines.length) {
            index = codeEl.children.length;
          } else {
            const lineEl = this.lines[line];
            index = codeEl.children.indexOf(lineEl);
            if (index === -1) {
              onShikiError(new ShikiTwoslashError(`Cannot find line ${line} in code element`), this.source, this.options.lang);
              return;
            }
          }
          const nodeAfter = codeEl.children[index + 1];
          if (nodeAfter && nodeAfter.type === "text" && nodeAfter.value === "\n")
            codeEl.children.splice(index + 1, 1);
          codeEl.children.splice(index + 1, 0, ...nodes);
        };
        const tokensMap = [];
        this.lines.forEach((lineEl, line) => {
          let index = 0;
          for (const token of lineEl.children.flatMap((i) => i.type === "element" ? i.children || [] : [])) {
            if ("value" in token && typeof token.value === "string") {
              tokensMap.push([line, index, index + token.value.length, token]);
              index += token.value.length;
            }
          }
        });
        const locateTextTokens = (line, character, length) => {
          const start = character;
          const end = character + length;
          if (length === 0) {
            return tokensMap.filter(([l, s, e]) => l === line && s < start && start <= e).map((i) => i[3]);
          }
          return tokensMap.filter(([l, s, e]) => l === line && (start <= s && s < end) && (start < e && e <= end)).map((i) => i[3]);
        };
        const tokensSkipHover = /* @__PURE__ */ new Set();
        const actionsHovers = [];
        const actionsHighlights = [];
        for (const node of twoslash.nodes) {
          if (node.type === "tag") {
            if (renderer.lineCustomTag)
              insertAfterLine(node.line, renderer.lineCustomTag.call(this, node));
            continue;
          }
          const tokens = locateTextTokens(node.line, node.character, node.length);
          if (!tokens.length && !(node.type === "error" && renderer.nodesError)) {
            onShikiError(new ShikiTwoslashError(`Cannot find tokens for node: ${JSON.stringify(node)}`), this.source, this.options.lang);
            continue;
          }
          const wrapTokens = (fn) => {
            const line = this.lines[node.line];
            let charIndex = 0;
            let itemStart = line.children.length;
            let itemEnd = 0;
            line.children.forEach((token, index) => {
              if (charIndex >= node.character && index < itemStart)
                itemStart = index;
              if (charIndex <= node.character + node.length && index > itemEnd)
                itemEnd = index;
              charIndex += getTokenString(token).length;
            });
            if (charIndex <= node.character + node.length)
              itemEnd = line.children.length;
            const targets = line.children.slice(itemStart, itemEnd);
            const length = targets.length;
            line.children.splice(itemStart, length, ...fn(targets));
          };
          switch (node.type) {
            case "error": {
              if (renderer.nodeError) {
                tokens.forEach((token) => {
                  tokensSkipHover.add(token);
                  const clone = { ...token };
                  Object.assign(token, renderer.nodeError.call(this, node, clone));
                });
              }
              if (renderer.nodesError) {
                tokens.forEach((token) => {
                  tokensSkipHover.add(token);
                });
                actionsHighlights.push(() => {
                  wrapTokens((targets) => renderer.nodesError?.call(this, node, targets) || targets);
                });
              }
              if (renderer.lineError)
                insertAfterLine(node.line, renderer.lineError.call(this, node));
              break;
            }
            case "query": {
              const token = tokens[0];
              if (token && renderer.nodeQuery) {
                tokensSkipHover.add(token);
                const clone = { ...token };
                Object.assign(token, renderer.nodeQuery.call(this, node, clone));
              }
              if (renderer.lineQuery)
                insertAfterLine(node.line, renderer.lineQuery.call(this, node, token));
              break;
            }
            case "completion": {
              if (renderer.nodeCompletion) {
                tokens.forEach((token) => {
                  tokensSkipHover.add(token);
                  const clone = { ...token };
                  Object.assign(token, renderer.nodeCompletion.call(this, node, clone));
                });
              }
              if (renderer.lineCompletion)
                insertAfterLine(node.line, renderer.lineCompletion.call(this, node));
              break;
            }
            case "highlight": {
              if (renderer.nodesHighlight) {
                actionsHighlights.push(() => {
                  wrapTokens((targets) => renderer.nodesHighlight?.call(this, node, targets) || targets);
                });
              }
              break;
            }
            case "hover": {
              if (renderer.nodeStaticInfo) {
                actionsHovers.push(() => {
                  tokens.forEach((token) => {
                    if (tokensSkipHover.has(token))
                      return;
                    tokensSkipHover.add(token);
                    const clone = { ...token };
                    Object.assign(token, renderer.nodeStaticInfo.call(this, node, clone));
                  });
                });
              }
              break;
            }
            default: {
              onShikiError(new ShikiTwoslashError(`Unknown node type: ${node?.type}`), this.source, this.options.lang);
            }
          }
        }
        actionsHovers.forEach((i) => i());
        actionsHighlights.forEach((i) => i());
      }
    };
  };
}
function getTokenString(token) {
  if ("value" in token)
    return token.value;
  return token.children?.map(getTokenString).join("") || "";
}

export { ShikiTwoslashError, createTransformerFactory, defaultCompletionIcons, defaultCustomTagIcons, defaultHoverInfoProcessor, defaultTwoslashOptions, rendererClassic, rendererRich };
