/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as $e } from "../../chunks/runtime.js";
import { ref as ne } from "lit/directives/ref.js";
import { u as Te } from "../../chunks/useT9n.js";
import { LitElement as Re, createEvent as Ae, nothing as ie, safeClassMap as re } from "@arcgis/lumina";
import { css as Ie, html as m } from "lit";
import { render as I } from "lit-html";
import { unsafeHTML as ae } from "lit/directives/unsafe-html.js";
import { useContextConsumer as Ce } from "@arcgis/lumina/context";
import { A as ze, W as Le, T as Pe, J as Z } from "../../chunks/interfaces.js";
const qe = Ie`:host{display:block;height:100%}.display-flex-row{display:flex;flex-direction:row}.padding-left-10{padding-left:10px}.chat-container{display:flex;flex-direction:column;gap:0px;max-width:600px;height:75%;background-color:var(--calcite-color-foreground-3);padding:1px}.chat-container_expanded{display:flex;flex-direction:column;gap:0px;max-width:100%;height:95%;background-color:var(--calcite-color-background);border-radius:10px;padding:10px}.chat-panel{--calcite-dialog-header-background-color: var(--calcite-color-brand);--calcite-dialog-header-action-background-color: var(--calcite-color-brand);--calcite-dialog-heading-text-color: var(--calcite-color-background);--calcite-dialog-header-action-text-color: var(--calcite-color-background);--calcite-dialog-header-action-text-color-press: var(--calcite-color-background);--calcite-color-focus: var(--calcite-color-background);--calcite-dialog-min-size-y: 90vh;--calcite-dialog-max-size-y: 90vh}.chat-panel calcite-card,.chat-panel calcite-text-area,.chat-panel calcite-button:not(.icon-color-background),.chat-panel .chat-messages,.chat-panel .chat-input{--calcite-color-focus: var(--calcite-color-brand)}.assistant-followup-chip:focus{outline:2px solid var(--calcite-color-brand)}.chat-panel-heading{font-size:var(--calcite-font-size-0);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-background, var(--calcite-color-text-1))}.chat-messages{display:flex;flex-direction:column;gap:20px;padding:4px;height:100%;overflow-y:auto}.user-message{align-self:flex-end;background:var(--calcite-color-brand);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-brand);--calcite-card-border-color: var(--calcite-color-brand);color:var(--calcite-color-text-inverse);text-align:left}.system-message{align-self:flex-start;background:var(--calcite-color-foreground-2);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-foreground-3);--calcite-card-border-color: var(--calcite-color-foreground-3);color:var(--calcite-color-inverse);text-align:left}.loader-message{align-self:flex-start;background:var(--calcite-color-foreground-3);border-radius:8px;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-foreground-3);--calcite-card-border-color: var(--calcite-color-foreground-3)}.message-content{padding:0;font-size:14px}.response-message.message-content>p:first-of-type{margin-top:0}.message-content img{max-width:100%;height:auto;display:block;object-fit:contain}.message-content-pad{padding-bottom:10px;font-size:14px}.message-content-summary{padding-bottom:14px}.message-content-alignment{display:flex;align-items:center;gap:var(--calcite-spacing-md);font-size:var(--calcite-font-size--1);color:var(--calcite-color-text-1)}.padding-top-10{padding-top:10px}.padding-right-8{padding-right:8px}.padding-left-right-5{padding-right:5px;padding-left:5px}.chip-content{padding:5px 5px 5px 0}.chat-input{display:flex;flex-direction:row;flex-grow:1}.table-cell{--calcite-table-cell-background: var(--calcite-color-foreground-3)}.cursor-pointer{cursor:pointer}.notice-border-color{--temp-initial-brand: var(--calcite-color-brand)}.notice-border-color calcite-notice{--calcite-color-brand: #ddd;--calcite-icon-color: var(--temp-initial-brand)}.notice-border-color calcite-notice *{--calcite-color-brand: var(--temp-initial-brand)}.solution-card{padding:5px 0;text-decoration:none;display:block;width:100%;cursor:pointer}.solution-card calcite-card{display:flex;flex-direction:column;max-width:520px;overflow:hidden;--calcite-card-corner-radius: var(--calcite-corner-radius-round) !important;--calcite-card-shadow: var(--calcite-shadow-sm);--calcite-card-background-color: var(--calcite-card-background-color) }.solution-card div[slot=thumbnail]{max-height:100%;width:100%;position:relative;&:after{content:"";position:absolute;top:0;left:0;width:100%;height:100%;transition:all .15s ease-in-out}}.solution-card div[slot=thumbnail] img{max-height:100%;width:100%;object-fit:cover}.solution-card span[slot=description]{padding-top:10px}.solution-card calcite-chip{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);visibility:hidden;pointer-events:none;opacity:0;transition:all .15s ease-in-out;z-index:9999}.solution-card:hover calcite-chip{visibility:visible;opacity:1}.solution-card:hover div[slot=thumbnail]:after{background-color:#00000080}.solution-card:hover h3{text-decoration:underline}.solution-card:focus{outline:2px solid var(--calcite-color-brand)}.references-container{padding-top:10px;display:block}.references-container.collapsed{display:none}.width-100{width:100%}.disclaimer-div{display:flex;gap:var(--calcite-spacing-sm);font-size:var(--calcite-font-size--0);color:var(--calcite-color-text-1)}.display-none{display:none}.chat-messages calcite-fab{position:absolute;bottom:16px;left:50%;transform:translate(-50%);z-index:999}.icon-color-background{--calcite-button-icon-color: var(--calcite-color-background)}.icon-color-background:focus{--calcite-color-focus: var(--calcite-color-background)}@media(max-width:430px){.solution-card .solution-snippet{display:none}}.height-32-flex-auto{height:32px;flex:0 0 auto}.margin-top-0.message-content>p:first-of-type{margin-top:0}a:not(.solution-card){color:var(--calcite-link-text-color, var(--calcite-color-text-link));cursor:pointer;text-decoration:none;line-height:inherit;background-image:linear-gradient(currentColor,currentColor),linear-gradient(var(--calcite-color-brand-underline),var(--calcite-color-brand-underline));background-position-x:0%,100%;background-position-y:min(1.5em,100%);background-repeat:no-repeat,no-repeat;background-size:0% 1px,100% 1px;transition-property:background-size,color;transition-duration:var(--calcite-animation-timing, .15s);transition-timing-function:ease-in-out;outline-color:transparent;position:relative}a:not(.solution-card):hover{background-size:100% 1px,100% 1px}a:not(.solution-card):focus{outline:2px solid var(--calcite-color-brand);outline-offset:2px;outline-color:var(--calcite-color-brand)}a:not(.solution-card):active{color:var(--calcite-color-brand-press)}`;
function W() {
  return { async: !1, breaks: !1, extensions: null, gfm: !0, hooks: null, pedantic: !1, renderer: null, silent: !1, tokenizer: null, walkTokens: null };
}
var A = W();
function de(i) {
  A = i;
}
var T = { exec: () => null };
function d(i, e = "") {
  let t = typeof i == "string" ? i : i.source, n = { replace: (s, a) => {
    let r = typeof a == "string" ? a : a.source;
    return r = r.replace(b.caret, "$1"), t = t.replace(s, r), n;
  }, getRegex: () => new RegExp(t, e) };
  return n;
}
var Be = (() => {
  try {
    return !!new RegExp("(?<=1)(?<!1)");
  } catch {
    return !1;
  }
})(), b = { codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm, outputLinkReplace: /\\([\[\]])/g, indentCodeCompensation: /^(\s+)(?:```)/, beginningSpace: /^\s+/, endingHash: /#$/, startingSpaceChar: /^ /, endingSpaceChar: / $/, nonSpaceChar: /[^ ]/, newLineCharGlobal: /\n/g, tabCharGlobal: /\t/g, multipleSpaceGlobal: /\s+/g, blankLine: /^[ \t]*$/, doubleBlankLine: /\n[ \t]*\n[ \t]*$/, blockquoteStart: /^ {0,3}>/, blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, listIsTask: /^\[[ xX]\] +\S/, listReplaceTask: /^\[[ xX]\] +/, listTaskCheckbox: /\[[ xX]\]/, anyLine: /\n.*\n/, hrefBrackets: /^<(.*)>$/, tableDelimiter: /[:|]/, tableAlignChars: /^\||\| *$/g, tableRowBlankLine: /\n[ \t]*$/, tableAlignRight: /^ *-+: *$/, tableAlignCenter: /^ *:-+: *$/, tableAlignLeft: /^ *:-+ *$/, startATag: /^<a /i, endATag: /^<\/a>/i, startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, startAngleBracket: /^</, endAngleBracket: />$/, pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, unicodeAlphaNumeric: /[\p{L}\p{N}]/u, escapeTest: /[&<>"']/, escapeReplace: /[&<>"']/g, escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, caret: /(^|[^\[])\^/g, percentDecode: /%25/g, findPipe: /\|/g, splitPipe: / \|/, slashPipe: /\\\|/g, carriageReturn: /\r\n|\r/g, spaceLine: /^ +$/gm, notSpaceStart: /^\S*/, endingNewline: /\n$/, listItemRegex: (i) => new RegExp(`^( {0,3}${i})((?:[	 ][^\\n]*)?(?:\\n|$))`), nextBulletRegex: (i) => new RegExp(`^ {0,${Math.min(3, i - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`), hrRegex: (i) => new RegExp(`^ {0,${Math.min(3, i - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), fencesBeginRegex: (i) => new RegExp(`^ {0,${Math.min(3, i - 1)}}(?:\`\`\`|~~~)`), headingBeginRegex: (i) => new RegExp(`^ {0,${Math.min(3, i - 1)}}#`), htmlBeginRegex: (i) => new RegExp(`^ {0,${Math.min(3, i - 1)}}<(?:[a-z].*>|!--)`, "i"), blockquoteBeginRegex: (i) => new RegExp(`^ {0,${Math.min(3, i - 1)}}>`) }, Ee = /^(?:[ \t]*(?:\n|$))+/, Me = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/, Ne = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/, B = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/, Qe = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/, X = / {0,3}(?:[*+-]|\d{1,9}[.)])/, ge = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/, fe = d(ge).replace(/bull/g, X).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex(), De = d(ge).replace(/bull/g, X).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(), K = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/, Fe = /^[^\n]+/, J = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/, Ue = d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", J).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(), Oe = d(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, X).getRegex(), U = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul", Y = /<!--(?:-?>|[\s\S]*?(?:-->|$))/, Ze = d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$))", "i").replace("comment", Y).replace("tag", U).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(), ke = d(K).replace("hr", B).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", U).getRegex(), je = d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", ke).getRegex(), V = { blockquote: je, code: Me, def: Ue, fences: Ne, heading: Qe, hr: B, html: Ze, lheading: fe, list: Oe, newline: Ee, paragraph: ke, table: T, text: Fe }, oe = d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", B).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3}	)[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", U).getRegex(), He = { ...V, lheading: De, table: oe, paragraph: d(K).replace("hr", B).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", oe).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", U).getRegex() }, Ge = { ...V, html: d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", Y).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^(#{1,6})(.*)(?:\n+|$)/, fences: T, lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, paragraph: d(K).replace("hr", B).replace("heading", ` *#{1,6} *[^
]`).replace("lheading", fe).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex() }, We = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, Xe = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, me = /^( {2,}|\\)\n(?!\s*$)/, Ke = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/, O = /[\p{P}\p{S}]/u, ee = /[\s\p{P}\p{S}]/u, xe = /[^\s\p{P}\p{S}]/u, Je = d(/^((?![*_])punctSpace)/, "u").replace(/punctSpace/g, ee).getRegex(), be = /(?!~)[\p{P}\p{S}]/u, Ye = /(?!~)[\s\p{P}\p{S}]/u, Ve = /(?:[^\s\p{P}\p{S}]|~)/u, we = /(?![*_])[\p{P}\p{S}]/u, et = /(?![*_])[\s\p{P}\p{S}]/u, tt = /(?:[^\s\p{P}\p{S}]|[*_])/u, st = d(/link|precode-code|html/, "g").replace("link", /\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-", Be ? "(?<!`)()" : "(^^|[^`])").replace("code", /(?<b>`+)[^`]+\k<b>(?!`)/).replace("html", /<(?! )[^<>]*?>/).getRegex(), _e = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/, nt = d(_e, "u").replace(/punct/g, O).getRegex(), it = d(_e, "u").replace(/punct/g, be).getRegex(), ve = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)", rt = d(ve, "gu").replace(/notPunctSpace/g, xe).replace(/punctSpace/g, ee).replace(/punct/g, O).getRegex(), at = d(ve, "gu").replace(/notPunctSpace/g, Ve).replace(/punctSpace/g, Ye).replace(/punct/g, be).getRegex(), ot = d("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, xe).replace(/punctSpace/g, ee).replace(/punct/g, O).getRegex(), lt = d(/^~~?(?:((?!~)punct)|[^\s~])/, "u").replace(/punct/g, we).getRegex(), ct = "^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)", ht = d(ct, "gu").replace(/notPunctSpace/g, tt).replace(/punctSpace/g, et).replace(/punct/g, we).getRegex(), pt = d(/\\(punct)/, "gu").replace(/punct/g, O).getRegex(), ut = d(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(), dt = d(Y).replace("(?:-->|$)", "-->").getRegex(), gt = d("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", dt).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(), Q = /(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/, ft = d(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label", Q).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(), ye = d(/^!?\[(label)\]\[(ref)\]/).replace("label", Q).replace("ref", J).getRegex(), Se = d(/^!?\[(ref)\](?:\[\])?/).replace("ref", J).getRegex(), kt = d("reflink|nolink(?!\\()", "g").replace("reflink", ye).replace("nolink", Se).getRegex(), le = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/, te = { _backpedal: T, anyPunctuation: pt, autolink: ut, blockSkip: st, br: me, code: Xe, del: T, delLDelim: T, delRDelim: T, emStrongLDelim: nt, emStrongRDelimAst: rt, emStrongRDelimUnd: ot, escape: We, link: ft, nolink: Se, punctuation: Je, reflink: ye, reflinkSearch: kt, tag: gt, text: Ke, url: T }, mt = { ...te, link: d(/^!?\[(label)\]\((.*?)\)/).replace("label", Q).getRegex(), reflink: d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", Q).getRegex() }, j = { ...te, emStrongRDelimAst: at, emStrongLDelim: it, delLDelim: lt, delRDelim: ht, url: d(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol", le).replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(), _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, del: /^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/, text: d(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol", le).getRegex() }, xt = { ...j, br: d(me).replace("{2,}", "*").getRegex(), text: d(j.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex() }, N = { normal: V, gfm: He, pedantic: Ge }, L = { normal: te, gfm: j, breaks: xt, pedantic: mt }, bt = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }, ce = (i) => bt[i];
function S(i, e) {
  if (e) {
    if (b.escapeTest.test(i)) return i.replace(b.escapeReplace, ce);
  } else if (b.escapeTestNoEncode.test(i)) return i.replace(b.escapeReplaceNoEncode, ce);
  return i;
}
function he(i) {
  try {
    i = encodeURI(i).replace(b.percentDecode, "%");
  } catch {
    return null;
  }
  return i;
}
function pe(i, e) {
  let t = i.replace(b.findPipe, (a, r, l) => {
    let o = !1, h = r;
    for (; --h >= 0 && l[h] === "\\"; ) o = !o;
    return o ? "|" : " |";
  }), n = t.split(b.splitPipe), s = 0;
  if (n[0].trim() || n.shift(), n.length > 0 && !n.at(-1)?.trim() && n.pop(), e) if (n.length > e) n.splice(e);
  else for (; n.length < e; ) n.push("");
  for (; s < n.length; s++) n[s] = n[s].trim().replace(b.slashPipe, "|");
  return n;
}
function P(i, e, t) {
  let n = i.length;
  if (n === 0) return "";
  let s = 0;
  for (; s < n && i.charAt(n - s - 1) === e; )
    s++;
  return i.slice(0, n - s);
}
function wt(i, e) {
  if (i.indexOf(e[1]) === -1) return -1;
  let t = 0;
  for (let n = 0; n < i.length; n++) if (i[n] === "\\") n++;
  else if (i[n] === e[0]) t++;
  else if (i[n] === e[1] && (t--, t < 0)) return n;
  return t > 0 ? -2 : -1;
}
function _t(i, e = 0) {
  let t = e, n = "";
  for (let s of i) if (s === "	") {
    let a = 4 - t % 4;
    n += " ".repeat(a), t += a;
  } else n += s, t++;
  return n;
}
function ue(i, e, t, n, s) {
  let a = e.href, r = e.title || null, l = i[1].replace(s.other.outputLinkReplace, "$1");
  n.state.inLink = !0;
  let o = { type: i[0].charAt(0) === "!" ? "image" : "link", raw: t, href: a, title: r, text: l, tokens: n.inlineTokens(l) };
  return n.state.inLink = !1, o;
}
function vt(i, e, t) {
  let n = i.match(t.other.indentCodeCompensation);
  if (n === null) return e;
  let s = n[1];
  return e.split(`
`).map((a) => {
    let r = a.match(t.other.beginningSpace);
    if (r === null) return a;
    let [l] = r;
    return l.length >= s.length ? a.slice(s.length) : a;
  }).join(`
`);
}
var D = class {
  options;
  rules;
  lexer;
  constructor(i) {
    this.options = i || A;
  }
  space(i) {
    let e = this.rules.block.newline.exec(i);
    if (e && e[0].length > 0) return { type: "space", raw: e[0] };
  }
  code(i) {
    let e = this.rules.block.code.exec(i);
    if (e) {
      let t = e[0].replace(this.rules.other.codeRemoveIndent, "");
      return { type: "code", raw: e[0], codeBlockStyle: "indented", text: this.options.pedantic ? t : P(t, `
`) };
    }
  }
  fences(i) {
    let e = this.rules.block.fences.exec(i);
    if (e) {
      let t = e[0], n = vt(t, e[3] || "", this.rules);
      return { type: "code", raw: t, lang: e[2] ? e[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : e[2], text: n };
    }
  }
  heading(i) {
    let e = this.rules.block.heading.exec(i);
    if (e) {
      let t = e[2].trim();
      if (this.rules.other.endingHash.test(t)) {
        let n = P(t, "#");
        (this.options.pedantic || !n || this.rules.other.endingSpaceChar.test(n)) && (t = n.trim());
      }
      return { type: "heading", raw: e[0], depth: e[1].length, text: t, tokens: this.lexer.inline(t) };
    }
  }
  hr(i) {
    let e = this.rules.block.hr.exec(i);
    if (e) return { type: "hr", raw: P(e[0], `
`) };
  }
  blockquote(i) {
    let e = this.rules.block.blockquote.exec(i);
    if (e) {
      let t = P(e[0], `
`).split(`
`), n = "", s = "", a = [];
      for (; t.length > 0; ) {
        let r = !1, l = [], o;
        for (o = 0; o < t.length; o++) if (this.rules.other.blockquoteStart.test(t[o])) l.push(t[o]), r = !0;
        else if (!r) l.push(t[o]);
        else break;
        t = t.slice(o);
        let h = l.join(`
`), c = h.replace(this.rules.other.blockquoteSetextReplace, `
    $1`).replace(this.rules.other.blockquoteSetextReplace2, "");
        n = n ? `${n}
${h}` : h, s = s ? `${s}
${c}` : c;
        let p = this.lexer.state.top;
        if (this.lexer.state.top = !0, this.lexer.blockTokens(c, a, !0), this.lexer.state.top = p, t.length === 0) break;
        let u = a.at(-1);
        if (u?.type === "code") break;
        if (u?.type === "blockquote") {
          let g = u, k = g.raw + `
` + t.join(`
`), w = this.blockquote(k);
          a[a.length - 1] = w, n = n.substring(0, n.length - g.raw.length) + w.raw, s = s.substring(0, s.length - g.text.length) + w.text;
          break;
        } else if (u?.type === "list") {
          let g = u, k = g.raw + `
` + t.join(`
`), w = this.list(k);
          a[a.length - 1] = w, n = n.substring(0, n.length - u.raw.length) + w.raw, s = s.substring(0, s.length - g.raw.length) + w.raw, t = k.substring(a.at(-1).raw.length).split(`
`);
          continue;
        }
      }
      return { type: "blockquote", raw: n, tokens: a, text: s };
    }
  }
  list(i) {
    let e = this.rules.block.list.exec(i);
    if (e) {
      let t = e[1].trim(), n = t.length > 1, s = { type: "list", raw: "", ordered: n, start: n ? +t.slice(0, -1) : "", loose: !1, items: [] };
      t = n ? `\\d{1,9}\\${t.slice(-1)}` : `\\${t}`, this.options.pedantic && (t = n ? t : "[*+-]");
      let a = this.rules.other.listItemRegex(t), r = !1;
      for (; i; ) {
        let o = !1, h = "", c = "";
        if (!(e = a.exec(i)) || this.rules.block.hr.test(i)) break;
        h = e[0], i = i.substring(h.length);
        let p = _t(e[2].split(`
`, 1)[0], e[1].length), u = i.split(`
`, 1)[0], g = !p.trim(), k = 0;
        if (this.options.pedantic ? (k = 2, c = p.trimStart()) : g ? k = e[1].length + 1 : (k = p.search(this.rules.other.nonSpaceChar), k = k > 4 ? 1 : k, c = p.slice(k), k += e[1].length), g && this.rules.other.blankLine.test(u) && (h += u + `
`, i = i.substring(u.length + 1), o = !0), !o) {
          let w = this.rules.other.nextBulletRegex(k), E = this.rules.other.hrRegex(k), M = this.rules.other.fencesBeginRegex(k), x = this.rules.other.headingBeginRegex(k), _ = this.rules.other.htmlBeginRegex(k), C = this.rules.other.blockquoteBeginRegex(k);
          for (; i; ) {
            let z = i.split(`
`, 1)[0], $;
            if (u = z, this.options.pedantic ? (u = u.replace(this.rules.other.listReplaceNesting, "  "), $ = u) : $ = u.replace(this.rules.other.tabCharGlobal, "    "), M.test(u) || x.test(u) || _.test(u) || C.test(u) || w.test(u) || E.test(u)) break;
            if ($.search(this.rules.other.nonSpaceChar) >= k || !u.trim()) c += `
` + $.slice(k);
            else {
              if (g || p.replace(this.rules.other.tabCharGlobal, "    ").search(this.rules.other.nonSpaceChar) >= 4 || M.test(p) || x.test(p) || E.test(p)) break;
              c += `
` + u;
            }
            g = !u.trim(), h += z + `
`, i = i.substring(z.length + 1), p = $.slice(k);
          }
        }
        s.loose || (r ? s.loose = !0 : this.rules.other.doubleBlankLine.test(h) && (r = !0)), s.items.push({ type: "list_item", raw: h, task: !!this.options.gfm && this.rules.other.listIsTask.test(c), loose: !1, text: c, tokens: [] }), s.raw += h;
      }
      let l = s.items.at(-1);
      if (l) l.raw = l.raw.trimEnd(), l.text = l.text.trimEnd();
      else return;
      s.raw = s.raw.trimEnd();
      for (let o of s.items) {
        if (this.lexer.state.top = !1, o.tokens = this.lexer.blockTokens(o.text, []), o.task) {
          if (o.text = o.text.replace(this.rules.other.listReplaceTask, ""), o.tokens[0]?.type === "text" || o.tokens[0]?.type === "paragraph") {
            o.tokens[0].raw = o.tokens[0].raw.replace(this.rules.other.listReplaceTask, ""), o.tokens[0].text = o.tokens[0].text.replace(this.rules.other.listReplaceTask, "");
            for (let c = this.lexer.inlineQueue.length - 1; c >= 0; c--) if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[c].src)) {
              this.lexer.inlineQueue[c].src = this.lexer.inlineQueue[c].src.replace(this.rules.other.listReplaceTask, "");
              break;
            }
          }
          let h = this.rules.other.listTaskCheckbox.exec(o.raw);
          if (h) {
            let c = { type: "checkbox", raw: h[0] + " ", checked: h[0] !== "[ ]" };
            o.checked = c.checked, s.loose ? o.tokens[0] && ["paragraph", "text"].includes(o.tokens[0].type) && "tokens" in o.tokens[0] && o.tokens[0].tokens ? (o.tokens[0].raw = c.raw + o.tokens[0].raw, o.tokens[0].text = c.raw + o.tokens[0].text, o.tokens[0].tokens.unshift(c)) : o.tokens.unshift({ type: "paragraph", raw: c.raw, text: c.raw, tokens: [c] }) : o.tokens.unshift(c);
          }
        }
        if (!s.loose) {
          let h = o.tokens.filter((p) => p.type === "space"), c = h.length > 0 && h.some((p) => this.rules.other.anyLine.test(p.raw));
          s.loose = c;
        }
      }
      if (s.loose) for (let o of s.items) {
        o.loose = !0;
        for (let h of o.tokens) h.type === "text" && (h.type = "paragraph");
      }
      return s;
    }
  }
  html(i) {
    let e = this.rules.block.html.exec(i);
    if (e) return { type: "html", block: !0, raw: e[0], pre: e[1] === "pre" || e[1] === "script" || e[1] === "style", text: e[0] };
  }
  def(i) {
    let e = this.rules.block.def.exec(i);
    if (e) {
      let t = e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " "), n = e[2] ? e[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "", s = e[3] ? e[3].substring(1, e[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : e[3];
      return { type: "def", tag: t, raw: e[0], href: n, title: s };
    }
  }
  table(i) {
    let e = this.rules.block.table.exec(i);
    if (!e || !this.rules.other.tableDelimiter.test(e[2])) return;
    let t = pe(e[1]), n = e[2].replace(this.rules.other.tableAlignChars, "").split("|"), s = e[3]?.trim() ? e[3].replace(this.rules.other.tableRowBlankLine, "").split(`
`) : [], a = { type: "table", raw: e[0], header: [], align: [], rows: [] };
    if (t.length === n.length) {
      for (let r of n) this.rules.other.tableAlignRight.test(r) ? a.align.push("right") : this.rules.other.tableAlignCenter.test(r) ? a.align.push("center") : this.rules.other.tableAlignLeft.test(r) ? a.align.push("left") : a.align.push(null);
      for (let r = 0; r < t.length; r++) a.header.push({ text: t[r], tokens: this.lexer.inline(t[r]), header: !0, align: a.align[r] });
      for (let r of s) a.rows.push(pe(r, a.header.length).map((l, o) => ({ text: l, tokens: this.lexer.inline(l), header: !1, align: a.align[o] })));
      return a;
    }
  }
  lheading(i) {
    let e = this.rules.block.lheading.exec(i);
    if (e) return { type: "heading", raw: e[0], depth: e[2].charAt(0) === "=" ? 1 : 2, text: e[1], tokens: this.lexer.inline(e[1]) };
  }
  paragraph(i) {
    let e = this.rules.block.paragraph.exec(i);
    if (e) {
      let t = e[1].charAt(e[1].length - 1) === `
` ? e[1].slice(0, -1) : e[1];
      return { type: "paragraph", raw: e[0], text: t, tokens: this.lexer.inline(t) };
    }
  }
  text(i) {
    let e = this.rules.block.text.exec(i);
    if (e) return { type: "text", raw: e[0], text: e[0], tokens: this.lexer.inline(e[0]) };
  }
  escape(i) {
    let e = this.rules.inline.escape.exec(i);
    if (e) return { type: "escape", raw: e[0], text: e[1] };
  }
  tag(i) {
    let e = this.rules.inline.tag.exec(i);
    if (e) return !this.lexer.state.inLink && this.rules.other.startATag.test(e[0]) ? this.lexer.state.inLink = !0 : this.lexer.state.inLink && this.rules.other.endATag.test(e[0]) && (this.lexer.state.inLink = !1), !this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(e[0]) ? this.lexer.state.inRawBlock = !0 : this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(e[0]) && (this.lexer.state.inRawBlock = !1), { type: "html", raw: e[0], inLink: this.lexer.state.inLink, inRawBlock: this.lexer.state.inRawBlock, block: !1, text: e[0] };
  }
  link(i) {
    let e = this.rules.inline.link.exec(i);
    if (e) {
      let t = e[2].trim();
      if (!this.options.pedantic && this.rules.other.startAngleBracket.test(t)) {
        if (!this.rules.other.endAngleBracket.test(t)) return;
        let a = P(t.slice(0, -1), "\\");
        if ((t.length - a.length) % 2 === 0) return;
      } else {
        let a = wt(e[2], "()");
        if (a === -2) return;
        if (a > -1) {
          let r = (e[0].indexOf("!") === 0 ? 5 : 4) + e[1].length + a;
          e[2] = e[2].substring(0, a), e[0] = e[0].substring(0, r).trim(), e[3] = "";
        }
      }
      let n = e[2], s = "";
      if (this.options.pedantic) {
        let a = this.rules.other.pedanticHrefTitle.exec(n);
        a && (n = a[1], s = a[3]);
      } else s = e[3] ? e[3].slice(1, -1) : "";
      return n = n.trim(), this.rules.other.startAngleBracket.test(n) && (this.options.pedantic && !this.rules.other.endAngleBracket.test(t) ? n = n.slice(1) : n = n.slice(1, -1)), ue(e, { href: n && n.replace(this.rules.inline.anyPunctuation, "$1"), title: s && s.replace(this.rules.inline.anyPunctuation, "$1") }, e[0], this.lexer, this.rules);
    }
  }
  reflink(i, e) {
    let t;
    if ((t = this.rules.inline.reflink.exec(i)) || (t = this.rules.inline.nolink.exec(i))) {
      let n = (t[2] || t[1]).replace(this.rules.other.multipleSpaceGlobal, " "), s = e[n.toLowerCase()];
      if (!s) {
        let a = t[0].charAt(0);
        return { type: "text", raw: a, text: a };
      }
      return ue(t, s, t[0], this.lexer, this.rules);
    }
  }
  emStrong(i, e, t = "") {
    let n = this.rules.inline.emStrongLDelim.exec(i);
    if (!(!n || n[3] && t.match(this.rules.other.unicodeAlphaNumeric)) && (!(n[1] || n[2]) || !t || this.rules.inline.punctuation.exec(t))) {
      let s = [...n[0]].length - 1, a, r, l = s, o = 0, h = n[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
      for (h.lastIndex = 0, e = e.slice(-1 * i.length + s); (n = h.exec(e)) != null; ) {
        if (a = n[1] || n[2] || n[3] || n[4] || n[5] || n[6], !a) continue;
        if (r = [...a].length, n[3] || n[4]) {
          l += r;
          continue;
        } else if ((n[5] || n[6]) && s % 3 && !((s + r) % 3)) {
          o += r;
          continue;
        }
        if (l -= r, l > 0) continue;
        r = Math.min(r, r + l + o);
        let c = [...n[0]][0].length, p = i.slice(0, s + n.index + c + r);
        if (Math.min(s, r) % 2) {
          let g = p.slice(1, -1);
          return { type: "em", raw: p, text: g, tokens: this.lexer.inlineTokens(g) };
        }
        let u = p.slice(2, -2);
        return { type: "strong", raw: p, text: u, tokens: this.lexer.inlineTokens(u) };
      }
    }
  }
  codespan(i) {
    let e = this.rules.inline.code.exec(i);
    if (e) {
      let t = e[2].replace(this.rules.other.newLineCharGlobal, " "), n = this.rules.other.nonSpaceChar.test(t), s = this.rules.other.startingSpaceChar.test(t) && this.rules.other.endingSpaceChar.test(t);
      return n && s && (t = t.substring(1, t.length - 1)), { type: "codespan", raw: e[0], text: t };
    }
  }
  br(i) {
    let e = this.rules.inline.br.exec(i);
    if (e) return { type: "br", raw: e[0] };
  }
  del(i, e, t = "") {
    let n = this.rules.inline.delLDelim.exec(i);
    if (n && (!n[1] || !t || this.rules.inline.punctuation.exec(t))) {
      let s = [...n[0]].length - 1, a, r, l = s, o = this.rules.inline.delRDelim;
      for (o.lastIndex = 0, e = e.slice(-1 * i.length + s); (n = o.exec(e)) != null; ) {
        if (a = n[1] || n[2] || n[3] || n[4] || n[5] || n[6], !a || (r = [...a].length, r !== s)) continue;
        if (n[3] || n[4]) {
          l += r;
          continue;
        }
        if (l -= r, l > 0) continue;
        r = Math.min(r, r + l);
        let h = [...n[0]][0].length, c = i.slice(0, s + n.index + h + r), p = c.slice(s, -s);
        return { type: "del", raw: c, text: p, tokens: this.lexer.inlineTokens(p) };
      }
    }
  }
  autolink(i) {
    let e = this.rules.inline.autolink.exec(i);
    if (e) {
      let t, n;
      return e[2] === "@" ? (t = e[1], n = "mailto:" + t) : (t = e[1], n = t), { type: "link", raw: e[0], text: t, href: n, tokens: [{ type: "text", raw: t, text: t }] };
    }
  }
  url(i) {
    let e;
    if (e = this.rules.inline.url.exec(i)) {
      let t, n;
      if (e[2] === "@") t = e[0], n = "mailto:" + t;
      else {
        let s;
        do
          s = e[0], e[0] = this.rules.inline._backpedal.exec(e[0])?.[0] ?? "";
        while (s !== e[0]);
        t = e[0], e[1] === "www." ? n = "http://" + e[0] : n = e[0];
      }
      return { type: "link", raw: e[0], text: t, href: n, tokens: [{ type: "text", raw: t, text: t }] };
    }
  }
  inlineText(i) {
    let e = this.rules.inline.text.exec(i);
    if (e) {
      let t = this.lexer.state.inRawBlock;
      return { type: "text", raw: e[0], text: e[0], escaped: t };
    }
  }
}, v = class H {
  tokens;
  options;
  state;
  inlineQueue;
  tokenizer;
  constructor(e) {
    this.tokens = [], this.tokens.links = /* @__PURE__ */ Object.create(null), this.options = e || A, this.options.tokenizer = this.options.tokenizer || new D(), this.tokenizer = this.options.tokenizer, this.tokenizer.options = this.options, this.tokenizer.lexer = this, this.inlineQueue = [], this.state = { inLink: !1, inRawBlock: !1, top: !0 };
    let t = { other: b, block: N.normal, inline: L.normal };
    this.options.pedantic ? (t.block = N.pedantic, t.inline = L.pedantic) : this.options.gfm && (t.block = N.gfm, this.options.breaks ? t.inline = L.breaks : t.inline = L.gfm), this.tokenizer.rules = t;
  }
  static get rules() {
    return { block: N, inline: L };
  }
  static lex(e, t) {
    return new H(t).lex(e);
  }
  static lexInline(e, t) {
    return new H(t).inlineTokens(e);
  }
  lex(e) {
    e = e.replace(b.carriageReturn, `
`), this.blockTokens(e, this.tokens);
    for (let t = 0; t < this.inlineQueue.length; t++) {
      let n = this.inlineQueue[t];
      this.inlineTokens(n.src, n.tokens);
    }
    return this.inlineQueue = [], this.tokens;
  }
  blockTokens(e, t = [], n = !1) {
    for (this.options.pedantic && (e = e.replace(b.tabCharGlobal, "    ").replace(b.spaceLine, "")); e; ) {
      let s;
      if (this.options.extensions?.block?.some((r) => (s = r.call({ lexer: this }, e, t)) ? (e = e.substring(s.raw.length), t.push(s), !0) : !1)) continue;
      if (s = this.tokenizer.space(e)) {
        e = e.substring(s.raw.length);
        let r = t.at(-1);
        s.raw.length === 1 && r !== void 0 ? r.raw += `
` : t.push(s);
        continue;
      }
      if (s = this.tokenizer.code(e)) {
        e = e.substring(s.raw.length);
        let r = t.at(-1);
        r?.type === "paragraph" || r?.type === "text" ? (r.raw += (r.raw.endsWith(`
`) ? "" : `
`) + s.raw, r.text += `
` + s.text, this.inlineQueue.at(-1).src = r.text) : t.push(s);
        continue;
      }
      if (s = this.tokenizer.fences(e)) {
        e = e.substring(s.raw.length), t.push(s);
        continue;
      }
      if (s = this.tokenizer.heading(e)) {
        e = e.substring(s.raw.length), t.push(s);
        continue;
      }
      if (s = this.tokenizer.hr(e)) {
        e = e.substring(s.raw.length), t.push(s);
        continue;
      }
      if (s = this.tokenizer.blockquote(e)) {
        e = e.substring(s.raw.length), t.push(s);
        continue;
      }
      if (s = this.tokenizer.list(e)) {
        e = e.substring(s.raw.length), t.push(s);
        continue;
      }
      if (s = this.tokenizer.html(e)) {
        e = e.substring(s.raw.length), t.push(s);
        continue;
      }
      if (s = this.tokenizer.def(e)) {
        e = e.substring(s.raw.length);
        let r = t.at(-1);
        r?.type === "paragraph" || r?.type === "text" ? (r.raw += (r.raw.endsWith(`
`) ? "" : `
`) + s.raw, r.text += `
` + s.raw, this.inlineQueue.at(-1).src = r.text) : this.tokens.links[s.tag] || (this.tokens.links[s.tag] = { href: s.href, title: s.title }, t.push(s));
        continue;
      }
      if (s = this.tokenizer.table(e)) {
        e = e.substring(s.raw.length), t.push(s);
        continue;
      }
      if (s = this.tokenizer.lheading(e)) {
        e = e.substring(s.raw.length), t.push(s);
        continue;
      }
      let a = e;
      if (this.options.extensions?.startBlock) {
        let r = 1 / 0, l = e.slice(1), o;
        this.options.extensions.startBlock.forEach((h) => {
          o = h.call({ lexer: this }, l), typeof o == "number" && o >= 0 && (r = Math.min(r, o));
        }), r < 1 / 0 && r >= 0 && (a = e.substring(0, r + 1));
      }
      if (this.state.top && (s = this.tokenizer.paragraph(a))) {
        let r = t.at(-1);
        n && r?.type === "paragraph" ? (r.raw += (r.raw.endsWith(`
`) ? "" : `
`) + s.raw, r.text += `
` + s.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = r.text) : t.push(s), n = a.length !== e.length, e = e.substring(s.raw.length);
        continue;
      }
      if (s = this.tokenizer.text(e)) {
        e = e.substring(s.raw.length);
        let r = t.at(-1);
        r?.type === "text" ? (r.raw += (r.raw.endsWith(`
`) ? "" : `
`) + s.raw, r.text += `
` + s.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = r.text) : t.push(s);
        continue;
      }
      if (e) {
        let r = "Infinite loop on byte: " + e.charCodeAt(0);
        if (this.options.silent) {
          console.error(r);
          break;
        } else throw new Error(r);
      }
    }
    return this.state.top = !0, t;
  }
  inline(e, t = []) {
    return this.inlineQueue.push({ src: e, tokens: t }), t;
  }
  inlineTokens(e, t = []) {
    let n = e, s = null;
    if (this.tokens.links) {
      let o = Object.keys(this.tokens.links);
      if (o.length > 0) for (; (s = this.tokenizer.rules.inline.reflinkSearch.exec(n)) != null; ) o.includes(s[0].slice(s[0].lastIndexOf("[") + 1, -1)) && (n = n.slice(0, s.index) + "[" + "a".repeat(s[0].length - 2) + "]" + n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex));
    }
    for (; (s = this.tokenizer.rules.inline.anyPunctuation.exec(n)) != null; ) n = n.slice(0, s.index) + "++" + n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
    let a;
    for (; (s = this.tokenizer.rules.inline.blockSkip.exec(n)) != null; ) a = s[2] ? s[2].length : 0, n = n.slice(0, s.index + a) + "[" + "a".repeat(s[0].length - a - 2) + "]" + n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
    n = this.options.hooks?.emStrongMask?.call({ lexer: this }, n) ?? n;
    let r = !1, l = "";
    for (; e; ) {
      r || (l = ""), r = !1;
      let o;
      if (this.options.extensions?.inline?.some((c) => (o = c.call({ lexer: this }, e, t)) ? (e = e.substring(o.raw.length), t.push(o), !0) : !1)) continue;
      if (o = this.tokenizer.escape(e)) {
        e = e.substring(o.raw.length), t.push(o);
        continue;
      }
      if (o = this.tokenizer.tag(e)) {
        e = e.substring(o.raw.length), t.push(o);
        continue;
      }
      if (o = this.tokenizer.link(e)) {
        e = e.substring(o.raw.length), t.push(o);
        continue;
      }
      if (o = this.tokenizer.reflink(e, this.tokens.links)) {
        e = e.substring(o.raw.length);
        let c = t.at(-1);
        o.type === "text" && c?.type === "text" ? (c.raw += o.raw, c.text += o.text) : t.push(o);
        continue;
      }
      if (o = this.tokenizer.emStrong(e, n, l)) {
        e = e.substring(o.raw.length), t.push(o);
        continue;
      }
      if (o = this.tokenizer.codespan(e)) {
        e = e.substring(o.raw.length), t.push(o);
        continue;
      }
      if (o = this.tokenizer.br(e)) {
        e = e.substring(o.raw.length), t.push(o);
        continue;
      }
      if (o = this.tokenizer.del(e, n, l)) {
        e = e.substring(o.raw.length), t.push(o);
        continue;
      }
      if (o = this.tokenizer.autolink(e)) {
        e = e.substring(o.raw.length), t.push(o);
        continue;
      }
      if (!this.state.inLink && (o = this.tokenizer.url(e))) {
        e = e.substring(o.raw.length), t.push(o);
        continue;
      }
      let h = e;
      if (this.options.extensions?.startInline) {
        let c = 1 / 0, p = e.slice(1), u;
        this.options.extensions.startInline.forEach((g) => {
          u = g.call({ lexer: this }, p), typeof u == "number" && u >= 0 && (c = Math.min(c, u));
        }), c < 1 / 0 && c >= 0 && (h = e.substring(0, c + 1));
      }
      if (o = this.tokenizer.inlineText(h)) {
        e = e.substring(o.raw.length), o.raw.slice(-1) !== "_" && (l = o.raw.slice(-1)), r = !0;
        let c = t.at(-1);
        c?.type === "text" ? (c.raw += o.raw, c.text += o.text) : t.push(o);
        continue;
      }
      if (e) {
        let c = "Infinite loop on byte: " + e.charCodeAt(0);
        if (this.options.silent) {
          console.error(c);
          break;
        } else throw new Error(c);
      }
    }
    return t;
  }
}, F = class {
  options;
  parser;
  constructor(i) {
    this.options = i || A;
  }
  space(i) {
    return "";
  }
  code({ text: i, lang: e, escaped: t }) {
    let n = (e || "").match(b.notSpaceStart)?.[0], s = i.replace(b.endingNewline, "") + `
`;
    return n ? '<pre><code class="language-' + S(n) + '">' + (t ? s : S(s, !0)) + `</code></pre>
` : "<pre><code>" + (t ? s : S(s, !0)) + `</code></pre>
`;
  }
  blockquote({ tokens: i }) {
    return `<blockquote>
${this.parser.parse(i)}</blockquote>
`;
  }
  html({ text: i }) {
    return i;
  }
  def(i) {
    return "";
  }
  heading({ tokens: i, depth: e }) {
    return `<h${e}>${this.parser.parseInline(i)}</h${e}>
`;
  }
  hr(i) {
    return `<hr>
`;
  }
  list(i) {
    let e = i.ordered, t = i.start, n = "";
    for (let r = 0; r < i.items.length; r++) {
      let l = i.items[r];
      n += this.listitem(l);
    }
    let s = e ? "ol" : "ul", a = e && t !== 1 ? ' start="' + t + '"' : "";
    return "<" + s + a + `>
` + n + "</" + s + `>
`;
  }
  listitem(i) {
    return `<li>${this.parser.parse(i.tokens)}</li>
`;
  }
  checkbox({ checked: i }) {
    return "<input " + (i ? 'checked="" ' : "") + 'disabled="" type="checkbox"> ';
  }
  paragraph({ tokens: i }) {
    return `<p>${this.parser.parseInline(i)}</p>
`;
  }
  table(i) {
    let e = "", t = "";
    for (let s = 0; s < i.header.length; s++) t += this.tablecell(i.header[s]);
    e += this.tablerow({ text: t });
    let n = "";
    for (let s = 0; s < i.rows.length; s++) {
      let a = i.rows[s];
      t = "";
      for (let r = 0; r < a.length; r++) t += this.tablecell(a[r]);
      n += this.tablerow({ text: t });
    }
    return n && (n = `<tbody>${n}</tbody>`), `<table>
<thead>
` + e + `</thead>
` + n + `</table>
`;
  }
  tablerow({ text: i }) {
    return `<tr>
${i}</tr>
`;
  }
  tablecell(i) {
    let e = this.parser.parseInline(i.tokens), t = i.header ? "th" : "td";
    return (i.align ? `<${t} align="${i.align}">` : `<${t}>`) + e + `</${t}>
`;
  }
  strong({ tokens: i }) {
    return `<strong>${this.parser.parseInline(i)}</strong>`;
  }
  em({ tokens: i }) {
    return `<em>${this.parser.parseInline(i)}</em>`;
  }
  codespan({ text: i }) {
    return `<code>${S(i, !0)}</code>`;
  }
  br(i) {
    return "<br>";
  }
  del({ tokens: i }) {
    return `<del>${this.parser.parseInline(i)}</del>`;
  }
  link({ href: i, title: e, tokens: t }) {
    let n = this.parser.parseInline(t), s = he(i);
    if (s === null) return n;
    i = s;
    let a = '<a href="' + i + '"';
    return e && (a += ' title="' + S(e) + '"'), a += ">" + n + "</a>", a;
  }
  image({ href: i, title: e, text: t, tokens: n }) {
    n && (t = this.parser.parseInline(n, this.parser.textRenderer));
    let s = he(i);
    if (s === null) return S(t);
    i = s;
    let a = `<img src="${i}" alt="${S(t)}"`;
    return e && (a += ` title="${S(e)}"`), a += ">", a;
  }
  text(i) {
    return "tokens" in i && i.tokens ? this.parser.parseInline(i.tokens) : "escaped" in i && i.escaped ? i.text : S(i.text);
  }
}, se = class {
  strong({ text: i }) {
    return i;
  }
  em({ text: i }) {
    return i;
  }
  codespan({ text: i }) {
    return i;
  }
  del({ text: i }) {
    return i;
  }
  html({ text: i }) {
    return i;
  }
  text({ text: i }) {
    return i;
  }
  link({ text: i }) {
    return "" + i;
  }
  image({ text: i }) {
    return "" + i;
  }
  br() {
    return "";
  }
  checkbox({ raw: i }) {
    return i;
  }
}, y = class G {
  options;
  renderer;
  textRenderer;
  constructor(e) {
    this.options = e || A, this.options.renderer = this.options.renderer || new F(), this.renderer = this.options.renderer, this.renderer.options = this.options, this.renderer.parser = this, this.textRenderer = new se();
  }
  static parse(e, t) {
    return new G(t).parse(e);
  }
  static parseInline(e, t) {
    return new G(t).parseInline(e);
  }
  parse(e) {
    let t = "";
    for (let n = 0; n < e.length; n++) {
      let s = e[n];
      if (this.options.extensions?.renderers?.[s.type]) {
        let r = s, l = this.options.extensions.renderers[r.type].call({ parser: this }, r);
        if (l !== !1 || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "def", "paragraph", "text"].includes(r.type)) {
          t += l || "";
          continue;
        }
      }
      let a = s;
      switch (a.type) {
        case "space": {
          t += this.renderer.space(a);
          break;
        }
        case "hr": {
          t += this.renderer.hr(a);
          break;
        }
        case "heading": {
          t += this.renderer.heading(a);
          break;
        }
        case "code": {
          t += this.renderer.code(a);
          break;
        }
        case "table": {
          t += this.renderer.table(a);
          break;
        }
        case "blockquote": {
          t += this.renderer.blockquote(a);
          break;
        }
        case "list": {
          t += this.renderer.list(a);
          break;
        }
        case "checkbox": {
          t += this.renderer.checkbox(a);
          break;
        }
        case "html": {
          t += this.renderer.html(a);
          break;
        }
        case "def": {
          t += this.renderer.def(a);
          break;
        }
        case "paragraph": {
          t += this.renderer.paragraph(a);
          break;
        }
        case "text": {
          t += this.renderer.text(a);
          break;
        }
        default: {
          let r = 'Token with "' + a.type + '" type was not found.';
          if (this.options.silent) return console.error(r), "";
          throw new Error(r);
        }
      }
    }
    return t;
  }
  parseInline(e, t = this.renderer) {
    let n = "";
    for (let s = 0; s < e.length; s++) {
      let a = e[s];
      if (this.options.extensions?.renderers?.[a.type]) {
        let l = this.options.extensions.renderers[a.type].call({ parser: this }, a);
        if (l !== !1 || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(a.type)) {
          n += l || "";
          continue;
        }
      }
      let r = a;
      switch (r.type) {
        case "escape": {
          n += t.text(r);
          break;
        }
        case "html": {
          n += t.html(r);
          break;
        }
        case "link": {
          n += t.link(r);
          break;
        }
        case "image": {
          n += t.image(r);
          break;
        }
        case "checkbox": {
          n += t.checkbox(r);
          break;
        }
        case "strong": {
          n += t.strong(r);
          break;
        }
        case "em": {
          n += t.em(r);
          break;
        }
        case "codespan": {
          n += t.codespan(r);
          break;
        }
        case "br": {
          n += t.br(r);
          break;
        }
        case "del": {
          n += t.del(r);
          break;
        }
        case "text": {
          n += t.text(r);
          break;
        }
        default: {
          let l = 'Token with "' + r.type + '" type was not found.';
          if (this.options.silent) return console.error(l), "";
          throw new Error(l);
        }
      }
    }
    return n;
  }
}, q = class {
  options;
  block;
  constructor(i) {
    this.options = i || A;
  }
  static passThroughHooks = /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens", "emStrongMask"]);
  static passThroughHooksRespectAsync = /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens"]);
  preprocess(i) {
    return i;
  }
  postprocess(i) {
    return i;
  }
  processAllTokens(i) {
    return i;
  }
  emStrongMask(i) {
    return i;
  }
  provideLexer() {
    return this.block ? v.lex : v.lexInline;
  }
  provideParser() {
    return this.block ? y.parse : y.parseInline;
  }
}, yt = class {
  defaults = W();
  options = this.setOptions;
  parse = this.parseMarkdown(!0);
  parseInline = this.parseMarkdown(!1);
  Parser = y;
  Renderer = F;
  TextRenderer = se;
  Lexer = v;
  Tokenizer = D;
  Hooks = q;
  constructor(...i) {
    this.use(...i);
  }
  walkTokens(i, e) {
    let t = [];
    for (let n of i) switch (t = t.concat(e.call(this, n)), n.type) {
      case "table": {
        let s = n;
        for (let a of s.header) t = t.concat(this.walkTokens(a.tokens, e));
        for (let a of s.rows) for (let r of a) t = t.concat(this.walkTokens(r.tokens, e));
        break;
      }
      case "list": {
        let s = n;
        t = t.concat(this.walkTokens(s.items, e));
        break;
      }
      default: {
        let s = n;
        this.defaults.extensions?.childTokens?.[s.type] ? this.defaults.extensions.childTokens[s.type].forEach((a) => {
          let r = s[a].flat(1 / 0);
          t = t.concat(this.walkTokens(r, e));
        }) : s.tokens && (t = t.concat(this.walkTokens(s.tokens, e)));
      }
    }
    return t;
  }
  use(...i) {
    let e = this.defaults.extensions || { renderers: {}, childTokens: {} };
    return i.forEach((t) => {
      let n = { ...t };
      if (n.async = this.defaults.async || n.async || !1, t.extensions && (t.extensions.forEach((s) => {
        if (!s.name) throw new Error("extension name required");
        if ("renderer" in s) {
          let a = e.renderers[s.name];
          a ? e.renderers[s.name] = function(...r) {
            let l = s.renderer.apply(this, r);
            return l === !1 && (l = a.apply(this, r)), l;
          } : e.renderers[s.name] = s.renderer;
        }
        if ("tokenizer" in s) {
          if (!s.level || s.level !== "block" && s.level !== "inline") throw new Error("extension level must be 'block' or 'inline'");
          let a = e[s.level];
          a ? a.unshift(s.tokenizer) : e[s.level] = [s.tokenizer], s.start && (s.level === "block" ? e.startBlock ? e.startBlock.push(s.start) : e.startBlock = [s.start] : s.level === "inline" && (e.startInline ? e.startInline.push(s.start) : e.startInline = [s.start]));
        }
        "childTokens" in s && s.childTokens && (e.childTokens[s.name] = s.childTokens);
      }), n.extensions = e), t.renderer) {
        let s = this.defaults.renderer || new F(this.defaults);
        for (let a in t.renderer) {
          if (!(a in s)) throw new Error(`renderer '${a}' does not exist`);
          if (["options", "parser"].includes(a)) continue;
          let r = a, l = t.renderer[r], o = s[r];
          s[r] = (...h) => {
            let c = l.apply(s, h);
            return c === !1 && (c = o.apply(s, h)), c || "";
          };
        }
        n.renderer = s;
      }
      if (t.tokenizer) {
        let s = this.defaults.tokenizer || new D(this.defaults);
        for (let a in t.tokenizer) {
          if (!(a in s)) throw new Error(`tokenizer '${a}' does not exist`);
          if (["options", "rules", "lexer"].includes(a)) continue;
          let r = a, l = t.tokenizer[r], o = s[r];
          s[r] = (...h) => {
            let c = l.apply(s, h);
            return c === !1 && (c = o.apply(s, h)), c;
          };
        }
        n.tokenizer = s;
      }
      if (t.hooks) {
        let s = this.defaults.hooks || new q();
        for (let a in t.hooks) {
          if (!(a in s)) throw new Error(`hook '${a}' does not exist`);
          if (["options", "block"].includes(a)) continue;
          let r = a, l = t.hooks[r], o = s[r];
          q.passThroughHooks.has(a) ? s[r] = (h) => {
            if (this.defaults.async && q.passThroughHooksRespectAsync.has(a)) return (async () => {
              let p = await l.call(s, h);
              return o.call(s, p);
            })();
            let c = l.call(s, h);
            return o.call(s, c);
          } : s[r] = (...h) => {
            if (this.defaults.async) return (async () => {
              let p = await l.apply(s, h);
              return p === !1 && (p = await o.apply(s, h)), p;
            })();
            let c = l.apply(s, h);
            return c === !1 && (c = o.apply(s, h)), c;
          };
        }
        n.hooks = s;
      }
      if (t.walkTokens) {
        let s = this.defaults.walkTokens, a = t.walkTokens;
        n.walkTokens = function(r) {
          let l = [];
          return l.push(a.call(this, r)), s && (l = l.concat(s.call(this, r))), l;
        };
      }
      this.defaults = { ...this.defaults, ...n };
    }), this;
  }
  setOptions(i) {
    return this.defaults = { ...this.defaults, ...i }, this;
  }
  lexer(i, e) {
    return v.lex(i, e ?? this.defaults);
  }
  parser(i, e) {
    return y.parse(i, e ?? this.defaults);
  }
  parseMarkdown(i) {
    return (e, t) => {
      let n = { ...t }, s = { ...this.defaults, ...n }, a = this.onError(!!s.silent, !!s.async);
      if (this.defaults.async === !0 && n.async === !1) return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
      if (typeof e > "u" || e === null) return a(new Error("marked(): input parameter is undefined or null"));
      if (typeof e != "string") return a(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(e) + ", string expected"));
      if (s.hooks && (s.hooks.options = s, s.hooks.block = i), s.async) return (async () => {
        let r = s.hooks ? await s.hooks.preprocess(e) : e, l = await (s.hooks ? await s.hooks.provideLexer() : i ? v.lex : v.lexInline)(r, s), o = s.hooks ? await s.hooks.processAllTokens(l) : l;
        s.walkTokens && await Promise.all(this.walkTokens(o, s.walkTokens));
        let h = await (s.hooks ? await s.hooks.provideParser() : i ? y.parse : y.parseInline)(o, s);
        return s.hooks ? await s.hooks.postprocess(h) : h;
      })().catch(a);
      try {
        s.hooks && (e = s.hooks.preprocess(e));
        let r = (s.hooks ? s.hooks.provideLexer() : i ? v.lex : v.lexInline)(e, s);
        s.hooks && (r = s.hooks.processAllTokens(r)), s.walkTokens && this.walkTokens(r, s.walkTokens);
        let l = (s.hooks ? s.hooks.provideParser() : i ? y.parse : y.parseInline)(r, s);
        return s.hooks && (l = s.hooks.postprocess(l)), l;
      } catch (r) {
        return a(r);
      }
    };
  }
  onError(i, e) {
    return (t) => {
      if (t.message += `
Please report this to https://github.com/markedjs/marked.`, i) {
        let n = "<p>An error occurred:</p><pre>" + S(t.message + "", !0) + "</pre>";
        return e ? Promise.resolve(n) : n;
      }
      if (e) return Promise.reject(t);
      throw t;
    };
  }
}, R = new yt();
function f(i, e) {
  return R.parse(i, e);
}
f.options = f.setOptions = function(i) {
  return R.setOptions(i), f.defaults = R.defaults, de(f.defaults), f;
};
f.getDefaults = W;
f.defaults = A;
f.use = function(...i) {
  return R.use(...i), f.defaults = R.defaults, de(f.defaults), f;
};
f.walkTokens = function(i, e) {
  return R.walkTokens(i, e);
};
f.parseInline = R.parseInline;
f.Parser = y;
f.parser = y.parse;
f.Renderer = F;
f.TextRenderer = se;
f.Lexer = v;
f.lexer = v.lex;
f.Tokenizer = D;
f.Hooks = q;
f.parse = f;
f.options;
f.setOptions;
f.use;
f.walkTokens;
f.parseInline;
y.parse;
v.lex;
class St {
  constructor(e = "") {
    this._text = "", this._displayedText = "", this._pendingText = "", this._text = e, this._pendingText = e;
  }
  /** Set or update the text that will be type written
   * @param text the new or updated string to type write
   */
  setText(e) {
    this._text = e, this._displayedText && e.includes(this._displayedText) ? this._pendingText = e.substring(this._displayedText.length) : (this._pendingText = this._text, this._displayedText = "");
  }
  /** Gets the current text that is written out */
  getText() {
    return this._displayedText;
  }
  /** Clear all the text and state */
  clearText() {
    this._displayedText = "", this._text = "", this._pendingText = "";
  }
  /**
   * Updates the display text on what will be shown to the users.
   */
  updateDisplayText() {
    if (this._pendingText.length > 0) {
      const e = this._pendingText[0];
      if (e === "[" || e === "<" || e === "!") {
        const t = this._matchMarkdownPattern(
          this._displayedText + this._pendingText,
          this._displayedText.length
        );
        if (t) {
          const n = t.end - t.start, s = this._pendingText.substring(0, n);
          this._displayedText += s, this._pendingText = this._pendingText.substring(n);
        } else
          this._displayedText += e, this._pendingText = this._pendingText.substring(1);
      } else
        this._displayedText += e, this._pendingText = this._pendingText.substring(1);
    }
  }
  /**
   * Check the string for any markdown pattern and the length of that pattern.
   * @param text the string to check markdown
   * @param position The current position in the text to check
   * @returns the start and end positions.
   */
  _matchMarkdownPattern(e, t) {
    const n = [
      /<sup>\[\[[^\]]+\]\]\([^)]+\)<\/sup>/,
      // <sup>[[1]](url)</sup>
      /\[\[[^\]]+\]\]\([^)]+\)/,
      // [[1]](url)
      /\[[^\]]+\]\([^)]+\)/,
      // [text](url)
      /!\[[^\]]*\]\([^)]+\)/
      // ![alt](url)
    ], s = e.substring(t);
    for (const a of n) {
      const r = s.match(a);
      if (r && r.index === 0)
        return {
          start: t,
          end: t + r[0].length
        };
    }
    return null;
  }
}
const $t = "https://links.esri.com/solutions/agol-organizational-account", Tt = "https://links.esri.com/solutions/configure-assistants";
class Rt extends Re {
  constructor() {
    super(), this.serverRoot = "https://aiservices-beta.arcgis.com", this.open = !1, this.userFirstName = "", this.conversationStore = {
      conversationId: null,
      inquiryId: null,
      ackSequenceNumber: null
    }, this._currentResponse = "", this._isAutoScroll = !1, this._isLoading = !1, this._isLoadingText = "", this.messages = [], this._orgSettings = {
      aiAssistantsEnabled: !1,
      blockBetaApps: !0,
      colocateCompute: !1
    }, this._translations = Te({ name: "arcgis-solutions-assistant", blocking: !0 }), this._isTyping = !1, this._configContextConsumer = Ce({
      context: ze,
      subscribe: !0,
      callback: (e) => {
        e?.userSession && !this.userFirstName && this._loadUserFirstName(), e?.authentication?.PortalSubset?.orgSettings && (this._orgSettings = e?.authentication?.PortalSubset?.orgSettings, this._getAIServiceUrl());
      }
    }), this.closeAssistant = Ae(), this._resetConversation = () => {
      this.conversationStore.conversationId = null, this.conversationStore.inquiryId = null, this.conversationStore.ackSequenceNumber = null;
    }, this._setMessageContainerRef = (e) => {
      this._chatContainer = e;
    }, this._setInputRef = (e) => {
      this._inputRef = e, this._inputRef.addEventListener("keydown", (t) => {
        t.key === "Enter" && !t.shiftKey && !this._isLoading && !this._isTyping && (t.preventDefault(), this._inputRef && (this.handleSendMessage(this._inputRef.value.trim()), this._inputRef.value = ""));
      }), setTimeout(() => {
        this._inputRef?.focus();
      }, 100);
    }, this._submitQuestion = (e) => {
      this.handleSendMessage(e);
    }, this._handleSignIn = () => {
      this._configContextConsumer.value?.authentication?.signIn("aiOpen");
    }, this._checkURLOpenParameter = () => {
      this.open = this._configContextConsumer.value?.authentication?.SignInParam === "aiOpen" || this.open;
    }, this.listenOn(window, "submitQuestion", (e) => {
      this._submitQuestion(e.detail);
    });
  }
  static {
    this.properties = { serverRoot: 1, open: 5, userFirstName: 1, conversationStore: 16, _currentResponse: 16, _isAutoScroll: 16, _isLoading: 16, _isLoadingText: 16, messages: 16, _orgSettings: 16, _translations: 16, _isTyping: 16 };
  }
  static {
    this.styles = qe;
  }
  get _telemetry() {
    return this._configContextConsumer.value?.telemetrySession;
  }
  get solutionAIurl() {
    return `${this.serverRoot}/skills/solution_deployment/chat`;
  }
  get docAIurl() {
    return `${this.serverRoot}/skills/doc_ai_assistant/chat`;
  }
  async handleSendMessage(e) {
    this._isLoading = !0;
    let t = {
      message: e,
      context: {
        debug: !1,
        kind: "SolutionRequest"
      }
    };
    if (this.conversationStore.conversationId !== null) {
      t.conversationId = this.conversationStore.conversationId;
      const n = {
        author: "human",
        conversationId: this.conversationStore.conversationId ? this.conversationStore.conversationId : "",
        message: e,
        render: this._renderSimpleTextMessage(e, "human", "", "Other")
      };
      this.messages = [...this.messages, n];
      const s = await this.requestAIServer(t, this.solutionAIurl);
      this.loopRequest(s, this.solutionAIurl);
    } else {
      const n = {
        author: "human",
        message: e,
        render: this._renderSimpleTextMessage(e, "human", "", "Other")
      };
      this.messages = [...this.messages, n];
      const s = await this.requestAIServer(t, this.solutionAIurl);
      this.conversationStore.conversationId = s.conversationId, this.conversationStore.inquiryId = s.inquiryId, this.conversationStore.ackSequenceNumber = s.sequenceNumber, this.loopRequest(s, this.solutionAIurl);
    }
  }
  async loopRequest(e, t) {
    const n = Date.now();
    let s, a = t;
    this._isLoading = !0;
    const r = document.createElement("div");
    r.classList.add("response-message", "message-content");
    let l = document.createElement("div");
    l.classList.add("display-none");
    const o = document.createElement("div");
    o.classList.add("display-none");
    const h = e.conversationId + Date.now(), c = this._renderResponseBlock(r, l, o, h), p = new St(this._currentResponse), u = {
      author: "ai",
      conversationId: e.conversationId,
      message: e.message ?? "",
      render: c
    };
    for (this.messages.push(u), this.requestUpdate(), this._isAutoScroll = !0; e.hasMore; ) {
      await new Promise((_) => setTimeout(_, 500));
      let x = {
        conversationId: e.conversationId,
        ackSequenceNumber: e.sequenceNumber,
        inquiryId: e.inquiryId
      };
      if (e.context)
        if (this.conversationStore.context = e.context, e.context.results && !e.context.intent)
          for (const _ of e.context.results)
            this._currentResponse = _.reply, this._currentResponse !== "" && (this._isLoading = !1, this._isTyping = !0, this._showCardById(h), this._startTypeWriter(p, this._currentResponse, r, l, o)), e = await this.requestAIServer(x, a);
        else if (e.context.intent === "Solution question") {
          s = e.context.intent;
          const _ = {
            message: e.message,
            conversationId: x.conversationId,
            context: {
              kind: "DocAIAssistantRequest",
              filters: {
                products: "ArcGIS Solutions"
              }
            }
          };
          a = this.docAIurl, e = await this.requestAIServer(_, a);
        } else
          this._currentResponse = e.message ?? "", e.context.kind && e.context.kind.toLowerCase() === "ArcGISErrorAsContext".toLowerCase() && (this._currentResponse = this._translations.genericErrorMessage), this._currentResponse !== "" && (this._isLoading = !1, this._isTyping = !0, this._showCardById(h), this._startTypeWriter(p, this._currentResponse, r, l, o)), e = await this.requestAIServer(x, a);
      else
        e = await this.requestAIServer(x, a);
    }
    this._isLoading = !1;
    const { context: g } = this.conversationStore, k = this.messages.length >= 2 ? this._getMostRecentQuestion() : "", w = typeof k == "string" ? "" : k?.message ?? "", E = Le(n), M = s || g?.intent || "Unknown";
    if (this._telemetry?.logEvent({
      category: Pe.ASSISTANT,
      action: "Chat",
      dimensions: [M],
      metrics: [E]
    }), g && g.intent)
      switch (g.intent) {
        case "Recommend solution": {
          if (g.results) {
            const x = g.results, _ = x.map(($) => `- ${$.title}`).join(`
`), C = this._renderSuggestedSolutions(x), z = this._renderFeedback(this._currentResponse + `
` + _, w, this.conversationStore.conversationId, g.intent);
            I(C, l), I(z, o);
          } else
            l.innerHTML = "";
          this._scrollToBottom();
          break;
        }
        default: {
          const x = this._renderFeedback(this._currentResponse, w, this.conversationStore.conversationId, g.intent);
          I(x, o), this._scrollToBottom();
          break;
        }
      }
    else {
      if (g && g.results && !g.intent)
        for (const x of g.results) {
          const _ = this._renderSolutionsQuestionTable(x.ref, x.followupQuestions), C = this._renderFeedback(this._currentResponse, w, this.conversationStore.conversationId, "Solution question");
          I(_, l), I(C, o);
        }
      else if (g && g.kind && g.kind.toLowerCase() === "ArcGISErrorAsContext".toLowerCase()) {
        const x = this._renderFeedback(this._currentResponse, w, this.conversationStore.conversationId, "Error");
        I(x, o);
      }
      this._scrollToBottom();
    }
  }
  async requestAIServer(e, t) {
    try {
      const n = this._configContextConsumer.value?.userSession?.token ?? "", a = await (await fetch(t, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          token: n
        },
        body: JSON.stringify(e)
      })).json();
      if (a)
        return a;
      throw new Error("No data returned");
    } catch (n) {
      throw new Error(`Request failed: ${n}`);
    }
  }
  resetChat() {
    const e = this.messages[this.messages.length - 1];
    if (e.author !== "system" && e.conversationId !== "-1") {
      this._resetConversation();
      const t = {
        author: "system",
        conversationId: "-1",
        message: this._translations.newConversationStarted,
        render: this._renderSimpleTextMessage(this._translations.newConversationStarted, "system", "", "Other", "speech-bubble-plus")
      };
      this.messages = [...this.messages, t], this._inputRef && (this._inputRef.value = "");
    }
  }
  loaded() {
    this._checkURLOpenParameter();
    const e = this._chatContainer;
    e && e.addEventListener("scroll", () => {
      this._isAutoScroll = this._isAtBottom(e);
    });
  }
  firstUpdated(e) {
    this._loadUserFirstName();
  }
  willUpdate(e) {
    if (this._configContextConsumer.value?.userSession?.token && this._configContextConsumer.value?.authentication?.CanUseAI && this.messages.length === 0 && this._translations.defaultStartUpMessage) {
      const t = this._translations.defaultStartUpMessage.replace("{{name}}", this.userFirstName), n = Object.values(this._translations.defaultFollowUpQuestions), s = this._renderSolutionQuestionFollowup(n);
      this.messages = [
        {
          author: "ai",
          conversationId: "",
          message: t,
          render: this._renderSimpleTextMessage(t, "ai", "", "Other", void 0, s, "margin-top-0")
        }
      ];
    }
    (e.has("_isLoading") || e.has("_isTyping")) && this.renderRoot.querySelectorAll(".assistant-followup-chip").forEach((n) => {
      const s = this._isLoading || this._isTyping;
      n.disabled = s, n.tabIndex = s ? -1 : 0;
    });
  }
  updated(e) {
    (e.size || this._isLoading) && this._scrollToBottom();
  }
  _renderFeedback(e, t, n, s) {
    const a = Date.now();
    return m`
      <div>
        <calcite-button
          appearance='transparent'
          class='height-32-flex-auto'
          id='good-${a}'
          icon-start='thumbs-up'
          label='position feedback'
          kind='neutral'
          @click=${() => {
      this._sendFeedback(e, t, "Good", n, s);
    }}
        >
        </calcite-button>
        <calcite-tooltip placement='bottom' reference-element='good-${a}'>
          <span>${this._translations.tooltips.likeButton}</span>
        </calcite-tooltip>

        <calcite-button
          appearance='transparent'
          class='height-32-flex-auto'
          id='bad-${a}'
          icon-start='thumbs-down'
          label='position feedback'
          kind='neutral'
          @click=${() => {
      this._sendFeedback(e, t, "Bad", n, s);
    }}
        >
        </calcite-button>
        <calcite-tooltip placement='bottom' reference-element='bad-${a}'>
          <span>${this._translations.tooltips.dislikeButton}</span>
        </calcite-tooltip>

        <calcite-button
          appearance='transparent'
          class='height-32-flex-auto'
          id='copy-${a}'
          icon-start='copy'
          label='position feedback'
          kind='neutral'
          @click=${(r) => {
      this._copyResponseToClipboard(e, r);
    }}
        >
        </calcite-button>
        <calcite-tooltip placement='bottom' reference-element='copy-${a}'>
          <span>${this._translations.tooltips.copyButton}</span>
        </calcite-tooltip>
      </div>
    `;
  }
  _renderSolutionQuestionReferences(e) {
    return m`
      ${e.map((t) => m`
          <div class='message-content-pad'>
            <a href=${t.url} target='_blank'>
              ${t.title}
            </a>
          </div>
        `)}
    `;
  }
  _renderSolutionQuestionFollowup(e) {
    return m`
      ${e.map((t) => m`
          <calcite-chip
            class='chip-content cursor-pointer assistant-followup-chip'
            kind='brand'
            label=${t}
            tabindex='0'
            @click=${(n) => {
      n.currentTarget.disabled || this._submitFollowupQuestion(t);
    }}
            @keydown=${(n) => {
      n.currentTarget.disabled || Z(n, () => this._submitFollowupQuestion(t));
    }}
          >
            ${t}
          </calcite-chip>
        `)}
    `;
  }
  _renderSolutionsQuestionTable(e, t) {
    const n = this._renderSolutionQuestionReferences(e), s = this._renderSolutionQuestionFollowup(t);
    return m`
      <div slot='description' class='message-content'>
        <div style='display: flex; justify-content: flex-start;'>
          <calcite-button
            appearance='outline'
            icon-end='chevron-down'
            icon-start='link'
            @click=${(a) => {
      const r = a.currentTarget, l = r.parentElement.nextElementSibling;
      l.classList.toggle("collapsed"), r.setAttribute("icon-end", l.classList.contains("collapsed") ? "chevron-down" : "chevron-up");
    }}
          >
            ${e.length}
            ${e.length === 1 ? this._translations.solutionsDocReference : this._translations.solutionsDocReferences}
          </calcite-button>
        </div>

        <div class='references-container collapsed'>
          ${n}
        </div>
      </div>

      <div class='padding-top-10'>
        ${s}
      </div>
    `;
  }
  _renderSolutionCard(e) {
    return m`
      <a
        class='solution-card'
        id='${e.id}'
        tabindex='0'
        @click=${() => this._emitItemIdFromAI(e.id)}
        @keydown=${(t) => {
      Z(t, () => this._emitItemIdFromAI(e.id));
    }}
      >
        <calcite-card thumbnail-position='inline-start'>
          <div slot='thumbnail'>
            <img src='${e.thumbnail}' alt='Thumbnail' />
            <calcite-chip icon='launch' label='View solution'>
              ${this._translations.viewSolutionInApp}
            </calcite-chip>
          </div>

          <h3 slot='heading'><b>${e.title}</b></h3>

          <span slot='description' class='solution-snippet'>${e.snippet}</span>
        </calcite-card>
      </a>
    `;
  }
  _renderResponseBlock(e, t, n, s) {
    return m`<calcite-card id=${s ?? ie} class="system-message display-none">${e}${t}${n}</calcite-card>`;
  }
  _renderSimpleTextMessage(e, t, n, s, a, r, l) {
    const o = this.messages.length >= 2 ? this._getMostRecentQuestion() : "", h = typeof o == "string" ? "" : o?.message ?? "";
    return t === "system" ? m`<div class="message-content message-content-alignment">${a && m`<calcite-icon .icon=${a}></calcite-icon>` || ""}${e}</div>` : m`<calcite-card class=${re(t === "human" ? "user-message" : "system-message")}><div class=${re(l ? `${l} message-content` : "message-content")}>${ae(e)}${r}${t === "ai" && n !== "" && this._renderFeedback(e, h, n, s) || ""}</div></calcite-card>`;
  }
  _renderSuggestedSolutions(e) {
    const t = e.map((n) => this._renderSolutionCard(n));
    return m`
      <div class='message-content'>
        ${t}
      </div>
    `;
  }
  _renderNoSign() {
    return m`<calcite-notice open scale=m icon=effects kind=info><div slot=message>${this._translations.signInMessage}</div><calcite-link @click=${this._handleSignIn} slot=link title=${this._translations.signInMessage ?? ie} class="padding-top-10">${this._translations.signIn}</calcite-link></calcite-notice>`;
  }
  _renderNoPermission() {
    return m`<calcite-notice open scale=m icon=effects kind=info><div slot=title>${this._translations.noPermissionTitle}</div><div slot=message class="padding-top-10">${ae(this._translations.noPermissionMessage.replace("{{orgUrl}}", $t).replace("{{configAI}}", Tt))}</div></calcite-notice>`;
  }
  render() {
    return m`<calcite-dialog class="chat-panel" .open=${this.open} .heading=${this._translations.solutionAssistantTitle} placement=bottom-start @calciteDialogClose=${() => {
      this.closeAssistant.emit(!0), this.open = !1;
    }}><span class="chat-panel-heading" slot=header-content><span class="padding-right-8">${this._translations.solutionAssistantTitle}</span><calcite-chip .label=${this._translations.betaTag} .value=${this._translations.betaTag}>${this._translations.betaTag}</calcite-chip></span>${this.messages.length > 1 ? m`<calcite-button appearance=transparent class="icon-color-background" .disabled=${!!this._isLoading || this._isTyping} id=newChatButton icon-end=speech-bubble-plus kind=neutral label="New conversation" @click=${this.resetChat} scale=l slot=header-actions-end></calcite-button><calcite-tooltip placement=bottom reference-element=newChatButton><span>${this._translations.tooltips.newConversation}</span></calcite-tooltip>` : ""}<div class="chat-messages" ${ne(this._setMessageContainerRef)}>${this.messages.map((e) => e.render)}${this._isLoading && m`<calcite-card class="loader-message"><div class="message-content display-flex-row"><calcite-loader .label=${this._isLoadingText} inline scale=s></calcite-loader>${this._isLoadingText != "" && m`<div class="padding-left-10">${this._isLoadingText}</div>` || ""}</div></calcite-card>` || ""}${this._chatContainer && !this._isAtBottom(this._chatContainer) && !this._isAutoScroll && m`<calcite-fab icon=arrow-down @click=${() => {
      this._isAutoScroll = !0, this._scrollToBottom(), setTimeout(() => {
        this.requestUpdate();
      }, 100);
    }} scale=m></calcite-fab>` || ""}${this._configContextConsumer.value?.userSession?.token ? this._configContextConsumer.value?.authentication?.CanUseAI ? "" : this._renderNoPermission() : this._renderNoSign()}</div><div slot=footer class="width-100"><div class="chat-input"><calcite-text-area .disabled=${!this._configContextConsumer.value?.userSession?.token || !this._configContextConsumer.value?.authentication?.CanUseAI} resize=none rows=3 .placeholder=${this._translations.sendMessage} value ${ne(this._setInputRef)}></calcite-text-area><calcite-button appearance=outline .disabled=${!!this._isLoading || this._isTyping || !this._configContextConsumer.value?.userSession?.token || !this._configContextConsumer.value?.authentication?.CanUseAI} icon-start=send id=sendQuestion kind=neutral icon-flip-rtl=start @click=${() => {
      this._inputRef && (this.handleSendMessage(this._inputRef.value.trim()), this._inputRef.value = "");
    }} @keydown=${(e) => Z(e, () => {
      this._inputRef && (this.handleSendMessage(this._inputRef.value.trim()), this._inputRef.value = "");
    })}></calcite-button><calcite-tooltip placement=bottom reference-element=sendQuestion><span>${this._translations.tooltips.sendQuestion}</span></calcite-tooltip></div><div class="disclaimer-div padding-top-10" slot=footer><calcite-icon icon=information scale=s></calcite-icon>${this._translations.disclaimerMessage}<a href=https://links.esri.com/solutions/security-concern target=_blank>${this._translations.reportConcern}</a></div></div></calcite-dialog>`;
  }
  _scrollToBottom() {
    this._chatContainer && this._isAutoScroll && setTimeout(() => {
      this._chatContainer && (this._chatContainer.scrollTop = this._chatContainer.scrollHeight);
    }, 100);
  }
  _emitItemIdFromAI(e) {
    const t = new CustomEvent("solutionIDFromAssistant", {
      detail: e,
      bubbles: !0,
      composed: !0
    });
    window.dispatchEvent(t);
  }
  _submitFollowupQuestion(e) {
    const t = new CustomEvent("submitQuestion", {
      detail: e,
      bubbles: !0,
      composed: !0
    });
    window.dispatchEvent(t);
  }
  _getMostRecentQuestion() {
    return [...this.messages].reverse().find((e) => e.author === "human") || null;
  }
  _sendFeedback(e, t, n, s, a) {
    const r = `https://survey123.arcgis.com/share/6e349a50b4504ca6b6107216d568db5f?field:_source=${encodeURIComponent("Solutions Assistant")}&field:user_evaluation=${encodeURIComponent(n)}&field:question=${encodeURIComponent(t)}&field:answer=${encodeURIComponent(e)}&field:context=${encodeURIComponent(JSON.stringify({ intent: a }))}&field:conversation_id=${encodeURIComponent(s)}&field:version=${encodeURIComponent("v1")}`;
    window.open(r, "_blank");
  }
  _copyResponseToClipboard(e, t) {
    navigator.clipboard.writeText(e);
    const n = t.currentTarget;
    n.iconStart = "check", setTimeout(() => {
      n.iconStart = "copy";
    }, 3e3);
  }
  _startTypeWriter(e, t, n, s, a) {
    if (t.length > 0) {
      e.setText(t);
      const r = async () => {
        e.updateDisplayText();
        const l = e.getText(), o = await f.parse(l);
        n.innerHTML = o.replace(/<a\s+/g, '<a target="_blank" '), l.length < this._currentResponse.length ? (this._scrollToBottom(), setTimeout(r, 5)) : (this._isTyping = !1, this._isAutoScroll = !1, s.classList.remove("display-none"), a.classList.remove("display-none"));
      };
      r();
    }
  }
  _showCardById(e) {
    const t = this.renderRoot.querySelector(`#${e}`);
    t && t.classList.remove("display-none");
  }
  _isAtBottom(e) {
    return e.scrollTop + e.clientHeight >= e.scrollHeight - 5;
  }
  async _loadUserFirstName() {
    try {
      const e = await this._configContextConsumer.value?.userSession?.getUser();
      if (e?.fullName) {
        const t = e.fullName.split(" ")[0];
        this.userFirstName = t;
      }
    } catch {
    }
  }
  _getAIServiceUrl() {
    if (this._configContextConsumer.value) {
      const e = this._configContextConsumer.value;
      e.authentication && e.authentication?.Portal && e.authentication?.Portal.helperServices.aiAssistantServices && (this.serverRoot = e.authentication?.Portal.helperServices.aiAssistantServices.url);
    }
  }
}
$e("arcgis-solutions-assistant", Rt);
export {
  Rt as ArcgisSolutionsAssistant
};
