index.cjs.map 297 KB

1
  1. {"version":3,"file":"index.cjs","sources":["../node_modules/tabbable/dist/index.esm.js","../node_modules/focus-trap/dist/focus-trap.esm.js","../node_modules/marked/lib/marked.esm.js","../node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs","../node_modules/@floating-ui/core/dist/floating-ui.core.mjs","../node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs","../node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs","../src/widgetHtmlString.ts","../src/index.ts"],"sourcesContent":["/*!\n* tabbable 6.2.0\n* @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE\n*/\n// NOTE: separate `:not()` selectors has broader browser support than the newer\n// `:not([inert], [inert] *)` (Feb 2023)\n// CAREFUL: JSDom does not support `:not([inert] *)` as a selector; using it causes\n// the entire query to fail, resulting in no nodes found, which will break a lot\n// of things... so we have to rely on JS to identify nodes inside an inert container\nvar candidateSelectors = ['input:not([inert])', 'select:not([inert])', 'textarea:not([inert])', 'a[href]:not([inert])', 'button:not([inert])', '[tabindex]:not(slot):not([inert])', 'audio[controls]:not([inert])', 'video[controls]:not([inert])', '[contenteditable]:not([contenteditable=\"false\"]):not([inert])', 'details>summary:first-of-type:not([inert])', 'details:not([inert])'];\nvar candidateSelector = /* #__PURE__ */candidateSelectors.join(',');\nvar NoElement = typeof Element === 'undefined';\nvar matches = NoElement ? function () {} : Element.prototype.matches || Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;\nvar getRootNode = !NoElement && Element.prototype.getRootNode ? function (element) {\n var _element$getRootNode;\n return element === null || element === void 0 ? void 0 : (_element$getRootNode = element.getRootNode) === null || _element$getRootNode === void 0 ? void 0 : _element$getRootNode.call(element);\n} : function (element) {\n return element === null || element === void 0 ? void 0 : element.ownerDocument;\n};\n\n/**\n * Determines if a node is inert or in an inert ancestor.\n * @param {Element} [node]\n * @param {boolean} [lookUp] If true and `node` is not inert, looks up at ancestors to\n * see if any of them are inert. If false, only `node` itself is considered.\n * @returns {boolean} True if inert itself or by way of being in an inert ancestor.\n * False if `node` is falsy.\n */\nvar isInert = function isInert(node, lookUp) {\n var _node$getAttribute;\n if (lookUp === void 0) {\n lookUp = true;\n }\n // CAREFUL: JSDom does not support inert at all, so we can't use the `HTMLElement.inert`\n // JS API property; we have to check the attribute, which can either be empty or 'true';\n // if it's `null` (not specified) or 'false', it's an active element\n var inertAtt = node === null || node === void 0 ? void 0 : (_node$getAttribute = node.getAttribute) === null || _node$getAttribute === void 0 ? void 0 : _node$getAttribute.call(node, 'inert');\n var inert = inertAtt === '' || inertAtt === 'true';\n\n // NOTE: this could also be handled with `node.matches('[inert], :is([inert] *)')`\n // if it weren't for `matches()` not being a function on shadow roots; the following\n // code works for any kind of node\n // CAREFUL: JSDom does not appear to support certain selectors like `:not([inert] *)`\n // so it likely would not support `:is([inert] *)` either...\n var result = inert || lookUp && node && isInert(node.parentNode); // recursive\n\n return result;\n};\n\n/**\n * Determines if a node's content is editable.\n * @param {Element} [node]\n * @returns True if it's content-editable; false if it's not or `node` is falsy.\n */\nvar isContentEditable = function isContentEditable(node) {\n var _node$getAttribute2;\n // CAREFUL: JSDom does not support the `HTMLElement.isContentEditable` API so we have\n // to use the attribute directly to check for this, which can either be empty or 'true';\n // if it's `null` (not specified) or 'false', it's a non-editable element\n var attValue = node === null || node === void 0 ? void 0 : (_node$getAttribute2 = node.getAttribute) === null || _node$getAttribute2 === void 0 ? void 0 : _node$getAttribute2.call(node, 'contenteditable');\n return attValue === '' || attValue === 'true';\n};\n\n/**\n * @param {Element} el container to check in\n * @param {boolean} includeContainer add container to check\n * @param {(node: Element) => boolean} filter filter candidates\n * @returns {Element[]}\n */\nvar getCandidates = function getCandidates(el, includeContainer, filter) {\n // even if `includeContainer=false`, we still have to check it for inertness because\n // if it's inert, all its children are inert\n if (isInert(el)) {\n return [];\n }\n var candidates = Array.prototype.slice.apply(el.querySelectorAll(candidateSelector));\n if (includeContainer && matches.call(el, candidateSelector)) {\n candidates.unshift(el);\n }\n candidates = candidates.filter(filter);\n return candidates;\n};\n\n/**\n * @callback GetShadowRoot\n * @param {Element} element to check for shadow root\n * @returns {ShadowRoot|boolean} ShadowRoot if available or boolean indicating if a shadowRoot is attached but not available.\n */\n\n/**\n * @callback ShadowRootFilter\n * @param {Element} shadowHostNode the element which contains shadow content\n * @returns {boolean} true if a shadow root could potentially contain valid candidates.\n */\n\n/**\n * @typedef {Object} CandidateScope\n * @property {Element} scopeParent contains inner candidates\n * @property {Element[]} candidates list of candidates found in the scope parent\n */\n\n/**\n * @typedef {Object} IterativeOptions\n * @property {GetShadowRoot|boolean} getShadowRoot true if shadow support is enabled; falsy if not;\n * if a function, implies shadow support is enabled and either returns the shadow root of an element\n * or a boolean stating if it has an undisclosed shadow root\n * @property {(node: Element) => boolean} filter filter candidates\n * @property {boolean} flatten if true then result will flatten any CandidateScope into the returned list\n * @property {ShadowRootFilter} shadowRootFilter filter shadow roots;\n */\n\n/**\n * @param {Element[]} elements list of element containers to match candidates from\n * @param {boolean} includeContainer add container list to check\n * @param {IterativeOptions} options\n * @returns {Array.<Element|CandidateScope>}\n */\nvar getCandidatesIteratively = function getCandidatesIteratively(elements, includeContainer, options) {\n var candidates = [];\n var elementsToCheck = Array.from(elements);\n while (elementsToCheck.length) {\n var element = elementsToCheck.shift();\n if (isInert(element, false)) {\n // no need to look up since we're drilling down\n // anything inside this container will also be inert\n continue;\n }\n if (element.tagName === 'SLOT') {\n // add shadow dom slot scope (slot itself cannot be focusable)\n var assigned = element.assignedElements();\n var content = assigned.length ? assigned : element.children;\n var nestedCandidates = getCandidatesIteratively(content, true, options);\n if (options.flatten) {\n candidates.push.apply(candidates, nestedCandidates);\n } else {\n candidates.push({\n scopeParent: element,\n candidates: nestedCandidates\n });\n }\n } else {\n // check candidate element\n var validCandidate = matches.call(element, candidateSelector);\n if (validCandidate && options.filter(element) && (includeContainer || !elements.includes(element))) {\n candidates.push(element);\n }\n\n // iterate over shadow content if possible\n var shadowRoot = element.shadowRoot ||\n // check for an undisclosed shadow\n typeof options.getShadowRoot === 'function' && options.getShadowRoot(element);\n\n // no inert look up because we're already drilling down and checking for inertness\n // on the way down, so all containers to this root node should have already been\n // vetted as non-inert\n var validShadowRoot = !isInert(shadowRoot, false) && (!options.shadowRootFilter || options.shadowRootFilter(element));\n if (shadowRoot && validShadowRoot) {\n // add shadow dom scope IIF a shadow root node was given; otherwise, an undisclosed\n // shadow exists, so look at light dom children as fallback BUT create a scope for any\n // child candidates found because they're likely slotted elements (elements that are\n // children of the web component element (which has the shadow), in the light dom, but\n // slotted somewhere _inside_ the undisclosed shadow) -- the scope is created below,\n // _after_ we return from this recursive call\n var _nestedCandidates = getCandidatesIteratively(shadowRoot === true ? element.children : shadowRoot.children, true, options);\n if (options.flatten) {\n candidates.push.apply(candidates, _nestedCandidates);\n } else {\n candidates.push({\n scopeParent: element,\n candidates: _nestedCandidates\n });\n }\n } else {\n // there's not shadow so just dig into the element's (light dom) children\n // __without__ giving the element special scope treatment\n elementsToCheck.unshift.apply(elementsToCheck, element.children);\n }\n }\n }\n return candidates;\n};\n\n/**\n * @private\n * Determines if the node has an explicitly specified `tabindex` attribute.\n * @param {HTMLElement} node\n * @returns {boolean} True if so; false if not.\n */\nvar hasTabIndex = function hasTabIndex(node) {\n return !isNaN(parseInt(node.getAttribute('tabindex'), 10));\n};\n\n/**\n * Determine the tab index of a given node.\n * @param {HTMLElement} node\n * @returns {number} Tab order (negative, 0, or positive number).\n * @throws {Error} If `node` is falsy.\n */\nvar getTabIndex = function getTabIndex(node) {\n if (!node) {\n throw new Error('No node provided');\n }\n if (node.tabIndex < 0) {\n // in Chrome, <details/>, <audio controls/> and <video controls/> elements get a default\n // `tabIndex` of -1 when the 'tabindex' attribute isn't specified in the DOM,\n // yet they are still part of the regular tab order; in FF, they get a default\n // `tabIndex` of 0; since Chrome still puts those elements in the regular tab\n // order, consider their tab index to be 0.\n // Also browsers do not return `tabIndex` correctly for contentEditable nodes;\n // so if they don't have a tabindex attribute specifically set, assume it's 0.\n if ((/^(AUDIO|VIDEO|DETAILS)$/.test(node.tagName) || isContentEditable(node)) && !hasTabIndex(node)) {\n return 0;\n }\n }\n return node.tabIndex;\n};\n\n/**\n * Determine the tab index of a given node __for sort order purposes__.\n * @param {HTMLElement} node\n * @param {boolean} [isScope] True for a custom element with shadow root or slot that, by default,\n * has tabIndex -1, but needs to be sorted by document order in order for its content to be\n * inserted into the correct sort position.\n * @returns {number} Tab order (negative, 0, or positive number).\n */\nvar getSortOrderTabIndex = function getSortOrderTabIndex(node, isScope) {\n var tabIndex = getTabIndex(node);\n if (tabIndex < 0 && isScope && !hasTabIndex(node)) {\n return 0;\n }\n return tabIndex;\n};\nvar sortOrderedTabbables = function sortOrderedTabbables(a, b) {\n return a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex;\n};\nvar isInput = function isInput(node) {\n return node.tagName === 'INPUT';\n};\nvar isHiddenInput = function isHiddenInput(node) {\n return isInput(node) && node.type === 'hidden';\n};\nvar isDetailsWithSummary = function isDetailsWithSummary(node) {\n var r = node.tagName === 'DETAILS' && Array.prototype.slice.apply(node.children).some(function (child) {\n return child.tagName === 'SUMMARY';\n });\n return r;\n};\nvar getCheckedRadio = function getCheckedRadio(nodes, form) {\n for (var i = 0; i < nodes.length; i++) {\n if (nodes[i].checked && nodes[i].form === form) {\n return nodes[i];\n }\n }\n};\nvar isTabbableRadio = function isTabbableRadio(node) {\n if (!node.name) {\n return true;\n }\n var radioScope = node.form || getRootNode(node);\n var queryRadios = function queryRadios(name) {\n return radioScope.querySelectorAll('input[type=\"radio\"][name=\"' + name + '\"]');\n };\n var radioSet;\n if (typeof window !== 'undefined' && typeof window.CSS !== 'undefined' && typeof window.CSS.escape === 'function') {\n radioSet = queryRadios(window.CSS.escape(node.name));\n } else {\n try {\n radioSet = queryRadios(node.name);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s', err.message);\n return false;\n }\n }\n var checked = getCheckedRadio(radioSet, node.form);\n return !checked || checked === node;\n};\nvar isRadio = function isRadio(node) {\n return isInput(node) && node.type === 'radio';\n};\nvar isNonTabbableRadio = function isNonTabbableRadio(node) {\n return isRadio(node) && !isTabbableRadio(node);\n};\n\n// determines if a node is ultimately attached to the window's document\nvar isNodeAttached = function isNodeAttached(node) {\n var _nodeRoot;\n // The root node is the shadow root if the node is in a shadow DOM; some document otherwise\n // (but NOT _the_ document; see second 'If' comment below for more).\n // If rootNode is shadow root, it'll have a host, which is the element to which the shadow\n // is attached, and the one we need to check if it's in the document or not (because the\n // shadow, and all nodes it contains, is never considered in the document since shadows\n // behave like self-contained DOMs; but if the shadow's HOST, which is part of the document,\n // is hidden, or is not in the document itself but is detached, it will affect the shadow's\n // visibility, including all the nodes it contains). The host could be any normal node,\n // or a custom element (i.e. web component). Either way, that's the one that is considered\n // part of the document, not the shadow root, nor any of its children (i.e. the node being\n // tested).\n // To further complicate things, we have to look all the way up until we find a shadow HOST\n // that is attached (or find none) because the node might be in nested shadows...\n // If rootNode is not a shadow root, it won't have a host, and so rootNode should be the\n // document (per the docs) and while it's a Document-type object, that document does not\n // appear to be the same as the node's `ownerDocument` for some reason, so it's safer\n // to ignore the rootNode at this point, and use `node.ownerDocument`. Otherwise,\n // using `rootNode.contains(node)` will _always_ be true we'll get false-positives when\n // node is actually detached.\n // NOTE: If `nodeRootHost` or `node` happens to be the `document` itself (which is possible\n // if a tabbable/focusable node was quickly added to the DOM, focused, and then removed\n // from the DOM as in https://github.com/focus-trap/focus-trap-react/issues/905), then\n // `ownerDocument` will be `null`, hence the optional chaining on it.\n var nodeRoot = node && getRootNode(node);\n var nodeRootHost = (_nodeRoot = nodeRoot) === null || _nodeRoot === void 0 ? void 0 : _nodeRoot.host;\n\n // in some cases, a detached node will return itself as the root instead of a document or\n // shadow root object, in which case, we shouldn't try to look further up the host chain\n var attached = false;\n if (nodeRoot && nodeRoot !== node) {\n var _nodeRootHost, _nodeRootHost$ownerDo, _node$ownerDocument;\n attached = !!((_nodeRootHost = nodeRootHost) !== null && _nodeRootHost !== void 0 && (_nodeRootHost$ownerDo = _nodeRootHost.ownerDocument) !== null && _nodeRootHost$ownerDo !== void 0 && _nodeRootHost$ownerDo.contains(nodeRootHost) || node !== null && node !== void 0 && (_node$ownerDocument = node.ownerDocument) !== null && _node$ownerDocument !== void 0 && _node$ownerDocument.contains(node));\n while (!attached && nodeRootHost) {\n var _nodeRoot2, _nodeRootHost2, _nodeRootHost2$ownerD;\n // since it's not attached and we have a root host, the node MUST be in a nested shadow DOM,\n // which means we need to get the host's host and check if that parent host is contained\n // in (i.e. attached to) the document\n nodeRoot = getRootNode(nodeRootHost);\n nodeRootHost = (_nodeRoot2 = nodeRoot) === null || _nodeRoot2 === void 0 ? void 0 : _nodeRoot2.host;\n attached = !!((_nodeRootHost2 = nodeRootHost) !== null && _nodeRootHost2 !== void 0 && (_nodeRootHost2$ownerD = _nodeRootHost2.ownerDocument) !== null && _nodeRootHost2$ownerD !== void 0 && _nodeRootHost2$ownerD.contains(nodeRootHost));\n }\n }\n return attached;\n};\nvar isZeroArea = function isZeroArea(node) {\n var _node$getBoundingClie = node.getBoundingClientRect(),\n width = _node$getBoundingClie.width,\n height = _node$getBoundingClie.height;\n return width === 0 && height === 0;\n};\nvar isHidden = function isHidden(node, _ref) {\n var displayCheck = _ref.displayCheck,\n getShadowRoot = _ref.getShadowRoot;\n // NOTE: visibility will be `undefined` if node is detached from the document\n // (see notes about this further down), which means we will consider it visible\n // (this is legacy behavior from a very long way back)\n // NOTE: we check this regardless of `displayCheck=\"none\"` because this is a\n // _visibility_ check, not a _display_ check\n if (getComputedStyle(node).visibility === 'hidden') {\n return true;\n }\n var isDirectSummary = matches.call(node, 'details>summary:first-of-type');\n var nodeUnderDetails = isDirectSummary ? node.parentElement : node;\n if (matches.call(nodeUnderDetails, 'details:not([open]) *')) {\n return true;\n }\n if (!displayCheck || displayCheck === 'full' || displayCheck === 'legacy-full') {\n if (typeof getShadowRoot === 'function') {\n // figure out if we should consider the node to be in an undisclosed shadow and use the\n // 'non-zero-area' fallback\n var originalNode = node;\n while (node) {\n var parentElement = node.parentElement;\n var rootNode = getRootNode(node);\n if (parentElement && !parentElement.shadowRoot && getShadowRoot(parentElement) === true // check if there's an undisclosed shadow\n ) {\n // node has an undisclosed shadow which means we can only treat it as a black box, so we\n // fall back to a non-zero-area test\n return isZeroArea(node);\n } else if (node.assignedSlot) {\n // iterate up slot\n node = node.assignedSlot;\n } else if (!parentElement && rootNode !== node.ownerDocument) {\n // cross shadow boundary\n node = rootNode.host;\n } else {\n // iterate up normal dom\n node = parentElement;\n }\n }\n node = originalNode;\n }\n // else, `getShadowRoot` might be true, but all that does is enable shadow DOM support\n // (i.e. it does not also presume that all nodes might have undisclosed shadows); or\n // it might be a falsy value, which means shadow DOM support is disabled\n\n // Since we didn't find it sitting in an undisclosed shadow (or shadows are disabled)\n // now we can just test to see if it would normally be visible or not, provided it's\n // attached to the main document.\n // NOTE: We must consider case where node is inside a shadow DOM and given directly to\n // `isTabbable()` or `isFocusable()` -- regardless of `getShadowRoot` option setting.\n\n if (isNodeAttached(node)) {\n // this works wherever the node is: if there's at least one client rect, it's\n // somehow displayed; it also covers the CSS 'display: contents' case where the\n // node itself is hidden in place of its contents; and there's no need to search\n // up the hierarchy either\n return !node.getClientRects().length;\n }\n\n // Else, the node isn't attached to the document, which means the `getClientRects()`\n // API will __always__ return zero rects (this can happen, for example, if React\n // is used to render nodes onto a detached tree, as confirmed in this thread:\n // https://github.com/facebook/react/issues/9117#issuecomment-284228870)\n //\n // It also means that even window.getComputedStyle(node).display will return `undefined`\n // because styles are only computed for nodes that are in the document.\n //\n // NOTE: THIS HAS BEEN THE CASE FOR YEARS. It is not new, nor is it caused by tabbable\n // somehow. Though it was never stated officially, anyone who has ever used tabbable\n // APIs on nodes in detached containers has actually implicitly used tabbable in what\n // was later (as of v5.2.0 on Apr 9, 2021) called `displayCheck=\"none\"` mode -- essentially\n // considering __everything__ to be visible because of the innability to determine styles.\n //\n // v6.0.0: As of this major release, the default 'full' option __no longer treats detached\n // nodes as visible with the 'none' fallback.__\n if (displayCheck !== 'legacy-full') {\n return true; // hidden\n }\n // else, fallback to 'none' mode and consider the node visible\n } else if (displayCheck === 'non-zero-area') {\n // NOTE: Even though this tests that the node's client rect is non-zero to determine\n // whether it's displayed, and that a detached node will __always__ have a zero-area\n // client rect, we don't special-case for whether the node is attached or not. In\n // this mode, we do want to consider nodes that have a zero area to be hidden at all\n // times, and that includes attached or not.\n return isZeroArea(node);\n }\n\n // visible, as far as we can tell, or per current `displayCheck=none` mode, we assume\n // it's visible\n return false;\n};\n\n// form fields (nested) inside a disabled fieldset are not focusable/tabbable\n// unless they are in the _first_ <legend> element of the top-most disabled\n// fieldset\nvar isDisabledFromFieldset = function isDisabledFromFieldset(node) {\n if (/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(node.tagName)) {\n var parentNode = node.parentElement;\n // check if `node` is contained in a disabled <fieldset>\n while (parentNode) {\n if (parentNode.tagName === 'FIELDSET' && parentNode.disabled) {\n // look for the first <legend> among the children of the disabled <fieldset>\n for (var i = 0; i < parentNode.children.length; i++) {\n var child = parentNode.children.item(i);\n // when the first <legend> (in document order) is found\n if (child.tagName === 'LEGEND') {\n // if its parent <fieldset> is not nested in another disabled <fieldset>,\n // return whether `node` is a descendant of its first <legend>\n return matches.call(parentNode, 'fieldset[disabled] *') ? true : !child.contains(node);\n }\n }\n // the disabled <fieldset> containing `node` has no <legend>\n return true;\n }\n parentNode = parentNode.parentElement;\n }\n }\n\n // else, node's tabbable/focusable state should not be affected by a fieldset's\n // enabled/disabled state\n return false;\n};\nvar isNodeMatchingSelectorFocusable = function isNodeMatchingSelectorFocusable(options, node) {\n if (node.disabled ||\n // we must do an inert look up to filter out any elements inside an inert ancestor\n // because we're limited in the type of selectors we can use in JSDom (see related\n // note related to `candidateSelectors`)\n isInert(node) || isHiddenInput(node) || isHidden(node, options) ||\n // For a details element with a summary, the summary element gets the focus\n isDetailsWithSummary(node) || isDisabledFromFieldset(node)) {\n return false;\n }\n return true;\n};\nvar isNodeMatchingSelectorTabbable = function isNodeMatchingSelectorTabbable(options, node) {\n if (isNonTabbableRadio(node) || getTabIndex(node) < 0 || !isNodeMatchingSelectorFocusable(options, node)) {\n return false;\n }\n return true;\n};\nvar isValidShadowRootTabbable = function isValidShadowRootTabbable(shadowHostNode) {\n var tabIndex = parseInt(shadowHostNode.getAttribute('tabindex'), 10);\n if (isNaN(tabIndex) || tabIndex >= 0) {\n return true;\n }\n // If a custom element has an explicit negative tabindex,\n // browsers will not allow tab targeting said element's children.\n return false;\n};\n\n/**\n * @param {Array.<Element|CandidateScope>} candidates\n * @returns Element[]\n */\nvar sortByOrder = function sortByOrder(candidates) {\n var regularTabbables = [];\n var orderedTabbables = [];\n candidates.forEach(function (item, i) {\n var isScope = !!item.scopeParent;\n var element = isScope ? item.scopeParent : item;\n var candidateTabindex = getSortOrderTabIndex(element, isScope);\n var elements = isScope ? sortByOrder(item.candidates) : element;\n if (candidateTabindex === 0) {\n isScope ? regularTabbables.push.apply(regularTabbables, elements) : regularTabbables.push(element);\n } else {\n orderedTabbables.push({\n documentOrder: i,\n tabIndex: candidateTabindex,\n item: item,\n isScope: isScope,\n content: elements\n });\n }\n });\n return orderedTabbables.sort(sortOrderedTabbables).reduce(function (acc, sortable) {\n sortable.isScope ? acc.push.apply(acc, sortable.content) : acc.push(sortable.content);\n return acc;\n }, []).concat(regularTabbables);\n};\nvar tabbable = function tabbable(container, options) {\n options = options || {};\n var candidates;\n if (options.getShadowRoot) {\n candidates = getCandidatesIteratively([container], options.includeContainer, {\n filter: isNodeMatchingSelectorTabbable.bind(null, options),\n flatten: false,\n getShadowRoot: options.getShadowRoot,\n shadowRootFilter: isValidShadowRootTabbable\n });\n } else {\n candidates = getCandidates(container, options.includeContainer, isNodeMatchingSelectorTabbable.bind(null, options));\n }\n return sortByOrder(candidates);\n};\nvar focusable = function focusable(container, options) {\n options = options || {};\n var candidates;\n if (options.getShadowRoot) {\n candidates = getCandidatesIteratively([container], options.includeContainer, {\n filter: isNodeMatchingSelectorFocusable.bind(null, options),\n flatten: true,\n getShadowRoot: options.getShadowRoot\n });\n } else {\n candidates = getCandidates(container, options.includeContainer, isNodeMatchingSelectorFocusable.bind(null, options));\n }\n return candidates;\n};\nvar isTabbable = function isTabbable(node, options) {\n options = options || {};\n if (!node) {\n throw new Error('No node provided');\n }\n if (matches.call(node, candidateSelector) === false) {\n return false;\n }\n return isNodeMatchingSelectorTabbable(options, node);\n};\nvar focusableCandidateSelector = /* #__PURE__ */candidateSelectors.concat('iframe').join(',');\nvar isFocusable = function isFocusable(node, options) {\n options = options || {};\n if (!node) {\n throw new Error('No node provided');\n }\n if (matches.call(node, focusableCandidateSelector) === false) {\n return false;\n }\n return isNodeMatchingSelectorFocusable(options, node);\n};\n\nexport { focusable, getTabIndex, isFocusable, isTabbable, tabbable };\n//# sourceMappingURL=index.esm.js.map\n","/*!\n* focus-trap 7.5.4\n* @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE\n*/\nimport { isFocusable, tabbable, focusable, isTabbable, getTabIndex } from 'tabbable';\n\nfunction ownKeys(e, r) {\n var t = Object.keys(e);\n if (Object.getOwnPropertySymbols) {\n var o = Object.getOwnPropertySymbols(e);\n r && (o = o.filter(function (r) {\n return Object.getOwnPropertyDescriptor(e, r).enumerable;\n })), t.push.apply(t, o);\n }\n return t;\n}\nfunction _objectSpread2(e) {\n for (var r = 1; r < arguments.length; r++) {\n var t = null != arguments[r] ? arguments[r] : {};\n r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {\n _defineProperty(e, r, t[r]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {\n Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n });\n }\n return e;\n}\nfunction _defineProperty(obj, key, value) {\n key = _toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nfunction _toPrimitive(input, hint) {\n if (typeof input !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (typeof res !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}\nfunction _toPropertyKey(arg) {\n var key = _toPrimitive(arg, \"string\");\n return typeof key === \"symbol\" ? key : String(key);\n}\n\nvar activeFocusTraps = {\n activateTrap: function activateTrap(trapStack, trap) {\n if (trapStack.length > 0) {\n var activeTrap = trapStack[trapStack.length - 1];\n if (activeTrap !== trap) {\n activeTrap.pause();\n }\n }\n var trapIndex = trapStack.indexOf(trap);\n if (trapIndex === -1) {\n trapStack.push(trap);\n } else {\n // move this existing trap to the front of the queue\n trapStack.splice(trapIndex, 1);\n trapStack.push(trap);\n }\n },\n deactivateTrap: function deactivateTrap(trapStack, trap) {\n var trapIndex = trapStack.indexOf(trap);\n if (trapIndex !== -1) {\n trapStack.splice(trapIndex, 1);\n }\n if (trapStack.length > 0) {\n trapStack[trapStack.length - 1].unpause();\n }\n }\n};\nvar isSelectableInput = function isSelectableInput(node) {\n return node.tagName && node.tagName.toLowerCase() === 'input' && typeof node.select === 'function';\n};\nvar isEscapeEvent = function isEscapeEvent(e) {\n return (e === null || e === void 0 ? void 0 : e.key) === 'Escape' || (e === null || e === void 0 ? void 0 : e.key) === 'Esc' || (e === null || e === void 0 ? void 0 : e.keyCode) === 27;\n};\nvar isTabEvent = function isTabEvent(e) {\n return (e === null || e === void 0 ? void 0 : e.key) === 'Tab' || (e === null || e === void 0 ? void 0 : e.keyCode) === 9;\n};\n\n// checks for TAB by default\nvar isKeyForward = function isKeyForward(e) {\n return isTabEvent(e) && !e.shiftKey;\n};\n\n// checks for SHIFT+TAB by default\nvar isKeyBackward = function isKeyBackward(e) {\n return isTabEvent(e) && e.shiftKey;\n};\nvar delay = function delay(fn) {\n return setTimeout(fn, 0);\n};\n\n// Array.find/findIndex() are not supported on IE; this replicates enough\n// of Array.findIndex() for our needs\nvar findIndex = function findIndex(arr, fn) {\n var idx = -1;\n arr.every(function (value, i) {\n if (fn(value)) {\n idx = i;\n return false; // break\n }\n\n return true; // next\n });\n\n return idx;\n};\n\n/**\n * Get an option's value when it could be a plain value, or a handler that provides\n * the value.\n * @param {*} value Option's value to check.\n * @param {...*} [params] Any parameters to pass to the handler, if `value` is a function.\n * @returns {*} The `value`, or the handler's returned value.\n */\nvar valueOrHandler = function valueOrHandler(value) {\n for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n params[_key - 1] = arguments[_key];\n }\n return typeof value === 'function' ? value.apply(void 0, params) : value;\n};\nvar getActualTarget = function getActualTarget(event) {\n // NOTE: If the trap is _inside_ a shadow DOM, event.target will always be the\n // shadow host. However, event.target.composedPath() will be an array of\n // nodes \"clicked\" from inner-most (the actual element inside the shadow) to\n // outer-most (the host HTML document). If we have access to composedPath(),\n // then use its first element; otherwise, fall back to event.target (and\n // this only works for an _open_ shadow DOM; otherwise,\n // composedPath()[0] === event.target always).\n return event.target.shadowRoot && typeof event.composedPath === 'function' ? event.composedPath()[0] : event.target;\n};\n\n// NOTE: this must be _outside_ `createFocusTrap()` to make sure all traps in this\n// current instance use the same stack if `userOptions.trapStack` isn't specified\nvar internalTrapStack = [];\nvar createFocusTrap = function createFocusTrap(elements, userOptions) {\n // SSR: a live trap shouldn't be created in this type of environment so this\n // should be safe code to execute if the `document` option isn't specified\n var doc = (userOptions === null || userOptions === void 0 ? void 0 : userOptions.document) || document;\n var trapStack = (userOptions === null || userOptions === void 0 ? void 0 : userOptions.trapStack) || internalTrapStack;\n var config = _objectSpread2({\n returnFocusOnDeactivate: true,\n escapeDeactivates: true,\n delayInitialFocus: true,\n isKeyForward: isKeyForward,\n isKeyBackward: isKeyBackward\n }, userOptions);\n var state = {\n // containers given to createFocusTrap()\n // @type {Array<HTMLElement>}\n containers: [],\n // list of objects identifying tabbable nodes in `containers` in the trap\n // NOTE: it's possible that a group has no tabbable nodes if nodes get removed while the trap\n // is active, but the trap should never get to a state where there isn't at least one group\n // with at least one tabbable node in it (that would lead to an error condition that would\n // result in an error being thrown)\n // @type {Array<{\n // container: HTMLElement,\n // tabbableNodes: Array<HTMLElement>, // empty if none\n // focusableNodes: Array<HTMLElement>, // empty if none\n // posTabIndexesFound: boolean,\n // firstTabbableNode: HTMLElement|undefined,\n // lastTabbableNode: HTMLElement|undefined,\n // firstDomTabbableNode: HTMLElement|undefined,\n // lastDomTabbableNode: HTMLElement|undefined,\n // nextTabbableNode: (node: HTMLElement, forward: boolean) => HTMLElement|undefined\n // }>}\n containerGroups: [],\n // same order/length as `containers` list\n\n // references to objects in `containerGroups`, but only those that actually have\n // tabbable nodes in them\n // NOTE: same order as `containers` and `containerGroups`, but __not necessarily__\n // the same length\n tabbableGroups: [],\n nodeFocusedBeforeActivation: null,\n mostRecentlyFocusedNode: null,\n active: false,\n paused: false,\n // timer ID for when delayInitialFocus is true and initial focus in this trap\n // has been delayed during activation\n delayInitialFocusTimer: undefined,\n // the most recent KeyboardEvent for the configured nav key (typically [SHIFT+]TAB), if any\n recentNavEvent: undefined\n };\n var trap; // eslint-disable-line prefer-const -- some private functions reference it, and its methods reference private functions, so we must declare here and define later\n\n /**\n * Gets a configuration option value.\n * @param {Object|undefined} configOverrideOptions If true, and option is defined in this set,\n * value will be taken from this object. Otherwise, value will be taken from base configuration.\n * @param {string} optionName Name of the option whose value is sought.\n * @param {string|undefined} [configOptionName] Name of option to use __instead of__ `optionName`\n * IIF `configOverrideOptions` is not defined. Otherwise, `optionName` is used.\n */\n var getOption = function getOption(configOverrideOptions, optionName, configOptionName) {\n return configOverrideOptions && configOverrideOptions[optionName] !== undefined ? configOverrideOptions[optionName] : config[configOptionName || optionName];\n };\n\n /**\n * Finds the index of the container that contains the element.\n * @param {HTMLElement} element\n * @param {Event} [event] If available, and `element` isn't directly found in any container,\n * the event's composed path is used to see if includes any known trap containers in the\n * case where the element is inside a Shadow DOM.\n * @returns {number} Index of the container in either `state.containers` or\n * `state.containerGroups` (the order/length of these lists are the same); -1\n * if the element isn't found.\n */\n var findContainerIndex = function findContainerIndex(element, event) {\n var composedPath = typeof (event === null || event === void 0 ? void 0 : event.composedPath) === 'function' ? event.composedPath() : undefined;\n // NOTE: search `containerGroups` because it's possible a group contains no tabbable\n // nodes, but still contains focusable nodes (e.g. if they all have `tabindex=-1`)\n // and we still need to find the element in there\n return state.containerGroups.findIndex(function (_ref) {\n var container = _ref.container,\n tabbableNodes = _ref.tabbableNodes;\n return container.contains(element) || ( // fall back to explicit tabbable search which will take into consideration any\n // web components if the `tabbableOptions.getShadowRoot` option was used for\n // the trap, enabling shadow DOM support in tabbable (`Node.contains()` doesn't\n // look inside web components even if open)\n composedPath === null || composedPath === void 0 ? void 0 : composedPath.includes(container)) || tabbableNodes.find(function (node) {\n return node === element;\n });\n });\n };\n\n /**\n * Gets the node for the given option, which is expected to be an option that\n * can be either a DOM node, a string that is a selector to get a node, `false`\n * (if a node is explicitly NOT given), or a function that returns any of these\n * values.\n * @param {string} optionName\n * @returns {undefined | false | HTMLElement | SVGElement} Returns\n * `undefined` if the option is not specified; `false` if the option\n * resolved to `false` (node explicitly not given); otherwise, the resolved\n * DOM node.\n * @throws {Error} If the option is set, not `false`, and is not, or does not\n * resolve to a node.\n */\n var getNodeForOption = function getNodeForOption(optionName) {\n var optionValue = config[optionName];\n if (typeof optionValue === 'function') {\n for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n params[_key2 - 1] = arguments[_key2];\n }\n optionValue = optionValue.apply(void 0, params);\n }\n if (optionValue === true) {\n optionValue = undefined; // use default value\n }\n\n if (!optionValue) {\n if (optionValue === undefined || optionValue === false) {\n return optionValue;\n }\n // else, empty string (invalid), null (invalid), 0 (invalid)\n\n throw new Error(\"`\".concat(optionName, \"` was specified but was not a node, or did not return a node\"));\n }\n var node = optionValue; // could be HTMLElement, SVGElement, or non-empty string at this point\n\n if (typeof optionValue === 'string') {\n node = doc.querySelector(optionValue); // resolve to node, or null if fails\n if (!node) {\n throw new Error(\"`\".concat(optionName, \"` as selector refers to no known node\"));\n }\n }\n return node;\n };\n var getInitialFocusNode = function getInitialFocusNode() {\n var node = getNodeForOption('initialFocus');\n\n // false explicitly indicates we want no initialFocus at all\n if (node === false) {\n return false;\n }\n if (node === undefined || !isFocusable(node, config.tabbableOptions)) {\n // option not specified nor focusable: use fallback options\n if (findContainerIndex(doc.activeElement) >= 0) {\n node = doc.activeElement;\n } else {\n var firstTabbableGroup = state.tabbableGroups[0];\n var firstTabbableNode = firstTabbableGroup && firstTabbableGroup.firstTabbableNode;\n\n // NOTE: `fallbackFocus` option function cannot return `false` (not supported)\n node = firstTabbableNode || getNodeForOption('fallbackFocus');\n }\n }\n if (!node) {\n throw new Error('Your focus-trap needs to have at least one focusable element');\n }\n return node;\n };\n var updateTabbableNodes = function updateTabbableNodes() {\n state.containerGroups = state.containers.map(function (container) {\n var tabbableNodes = tabbable(container, config.tabbableOptions);\n\n // NOTE: if we have tabbable nodes, we must have focusable nodes; focusable nodes\n // are a superset of tabbable nodes since nodes with negative `tabindex` attributes\n // are focusable but not tabbable\n var focusableNodes = focusable(container, config.tabbableOptions);\n var firstTabbableNode = tabbableNodes.length > 0 ? tabbableNodes[0] : undefined;\n var lastTabbableNode = tabbableNodes.length > 0 ? tabbableNodes[tabbableNodes.length - 1] : undefined;\n var firstDomTabbableNode = focusableNodes.find(function (node) {\n return isTabbable(node);\n });\n var lastDomTabbableNode = focusableNodes.slice().reverse().find(function (node) {\n return isTabbable(node);\n });\n var posTabIndexesFound = !!tabbableNodes.find(function (node) {\n return getTabIndex(node) > 0;\n });\n return {\n container: container,\n tabbableNodes: tabbableNodes,\n focusableNodes: focusableNodes,\n /** True if at least one node with positive `tabindex` was found in this container. */\n posTabIndexesFound: posTabIndexesFound,\n /** First tabbable node in container, __tabindex__ order; `undefined` if none. */\n firstTabbableNode: firstTabbableNode,\n /** Last tabbable node in container, __tabindex__ order; `undefined` if none. */\n lastTabbableNode: lastTabbableNode,\n // NOTE: DOM order is NOT NECESSARILY \"document position\" order, but figuring that out\n // would require more than just https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition\n // because that API doesn't work with Shadow DOM as well as it should (@see\n // https://github.com/whatwg/dom/issues/320) and since this first/last is only needed, so far,\n // to address an edge case related to positive tabindex support, this seems like a much easier,\n // \"close enough most of the time\" alternative for positive tabindexes which should generally\n // be avoided anyway...\n /** First tabbable node in container, __DOM__ order; `undefined` if none. */\n firstDomTabbableNode: firstDomTabbableNode,\n /** Last tabbable node in container, __DOM__ order; `undefined` if none. */\n lastDomTabbableNode: lastDomTabbableNode,\n /**\n * Finds the __tabbable__ node that follows the given node in the specified direction,\n * in this container, if any.\n * @param {HTMLElement} node\n * @param {boolean} [forward] True if going in forward tab order; false if going\n * in reverse.\n * @returns {HTMLElement|undefined} The next tabbable node, if any.\n */\n nextTabbableNode: function nextTabbableNode(node) {\n var forward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n var nodeIdx = tabbableNodes.indexOf(node);\n if (nodeIdx < 0) {\n // either not tabbable nor focusable, or was focused but not tabbable (negative tabindex):\n // since `node` should at least have been focusable, we assume that's the case and mimic\n // what browsers do, which is set focus to the next node in __document position order__,\n // regardless of positive tabindexes, if any -- and for reasons explained in the NOTE\n // above related to `firstDomTabbable` and `lastDomTabbable` properties, we fall back to\n // basic DOM order\n if (forward) {\n return focusableNodes.slice(focusableNodes.indexOf(node) + 1).find(function (el) {\n return isTabbable(el);\n });\n }\n return focusableNodes.slice(0, focusableNodes.indexOf(node)).reverse().find(function (el) {\n return isTabbable(el);\n });\n }\n return tabbableNodes[nodeIdx + (forward ? 1 : -1)];\n }\n };\n });\n state.tabbableGroups = state.containerGroups.filter(function (group) {\n return group.tabbableNodes.length > 0;\n });\n\n // throw if no groups have tabbable nodes and we don't have a fallback focus node either\n if (state.tabbableGroups.length <= 0 && !getNodeForOption('fallbackFocus') // returning false not supported for this option\n ) {\n throw new Error('Your focus-trap must have at least one container with at least one tabbable node in it at all times');\n }\n\n // NOTE: Positive tabindexes are only properly supported in single-container traps because\n // doing it across multiple containers where tabindexes could be all over the place\n // would require Tabbable to support multiple containers, would require additional\n // specialized Shadow DOM support, and would require Tabbable's multi-container support\n // to look at those containers in document position order rather than user-provided\n // order (as they are treated in Focus-trap, for legacy reasons). See discussion on\n // https://github.com/focus-trap/focus-trap/issues/375 for more details.\n if (state.containerGroups.find(function (g) {\n return g.posTabIndexesFound;\n }) && state.containerGroups.length > 1) {\n throw new Error(\"At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps.\");\n }\n };\n\n /**\n * Gets the current activeElement. If it's a web-component and has open shadow-root\n * it will recursively search inside shadow roots for the \"true\" activeElement.\n *\n * @param {Document | ShadowRoot} el\n *\n * @returns {HTMLElement} The element that currently has the focus\n **/\n var getActiveElement = function getActiveElement(el) {\n var activeElement = el.activeElement;\n if (!activeElement) {\n return;\n }\n if (activeElement.shadowRoot && activeElement.shadowRoot.activeElement !== null) {\n return getActiveElement(activeElement.shadowRoot);\n }\n return activeElement;\n };\n var tryFocus = function tryFocus(node) {\n if (node === false) {\n return;\n }\n if (node === getActiveElement(document)) {\n return;\n }\n if (!node || !node.focus) {\n tryFocus(getInitialFocusNode());\n return;\n }\n node.focus({\n preventScroll: !!config.preventScroll\n });\n // NOTE: focus() API does not trigger focusIn event so set MRU node manually\n state.mostRecentlyFocusedNode = node;\n if (isSelectableInput(node)) {\n node.select();\n }\n };\n var getReturnFocusNode = function getReturnFocusNode(previousActiveElement) {\n var node = getNodeForOption('setReturnFocus', previousActiveElement);\n return node ? node : node === false ? false : previousActiveElement;\n };\n\n /**\n * Finds the next node (in either direction) where focus should move according to a\n * keyboard focus-in event.\n * @param {Object} params\n * @param {Node} [params.target] Known target __from which__ to navigate, if any.\n * @param {KeyboardEvent|FocusEvent} [params.event] Event to use if `target` isn't known (event\n * will be used to determine the `target`). Ignored if `target` is specified.\n * @param {boolean} [params.isBackward] True if focus should move backward.\n * @returns {Node|undefined} The next node, or `undefined` if a next node couldn't be\n * determined given the current state of the trap.\n */\n var findNextNavNode = function findNextNavNode(_ref2) {\n var target = _ref2.target,\n event = _ref2.event,\n _ref2$isBackward = _ref2.isBackward,\n isBackward = _ref2$isBackward === void 0 ? false : _ref2$isBackward;\n target = target || getActualTarget(event);\n updateTabbableNodes();\n var destinationNode = null;\n if (state.tabbableGroups.length > 0) {\n // make sure the target is actually contained in a group\n // NOTE: the target may also be the container itself if it's focusable\n // with tabIndex='-1' and was given initial focus\n var containerIndex = findContainerIndex(target, event);\n var containerGroup = containerIndex >= 0 ? state.containerGroups[containerIndex] : undefined;\n if (containerIndex < 0) {\n // target not found in any group: quite possible focus has escaped the trap,\n // so bring it back into...\n if (isBackward) {\n // ...the last node in the last group\n destinationNode = state.tabbableGroups[state.tabbableGroups.length - 1].lastTabbableNode;\n } else {\n // ...the first node in the first group\n destinationNode = state.tabbableGroups[0].firstTabbableNode;\n }\n } else if (isBackward) {\n // REVERSE\n\n // is the target the first tabbable node in a group?\n var startOfGroupIndex = findIndex(state.tabbableGroups, function (_ref3) {\n var firstTabbableNode = _ref3.firstTabbableNode;\n return target === firstTabbableNode;\n });\n if (startOfGroupIndex < 0 && (containerGroup.container === target || isFocusable(target, config.tabbableOptions) && !isTabbable(target, config.tabbableOptions) && !containerGroup.nextTabbableNode(target, false))) {\n // an exception case where the target is either the container itself, or\n // a non-tabbable node that was given focus (i.e. tabindex is negative\n // and user clicked on it or node was programmatically given focus)\n // and is not followed by any other tabbable node, in which\n // case, we should handle shift+tab as if focus were on the container's\n // first tabbable node, and go to the last tabbable node of the LAST group\n startOfGroupIndex = containerIndex;\n }\n if (startOfGroupIndex >= 0) {\n // YES: then shift+tab should go to the last tabbable node in the\n // previous group (and wrap around to the last tabbable node of\n // the LAST group if it's the first tabbable node of the FIRST group)\n var destinationGroupIndex = startOfGroupIndex === 0 ? state.tabbableGroups.length - 1 : startOfGroupIndex - 1;\n var destinationGroup = state.tabbableGroups[destinationGroupIndex];\n destinationNode = getTabIndex(target) >= 0 ? destinationGroup.lastTabbableNode : destinationGroup.lastDomTabbableNode;\n } else if (!isTabEvent(event)) {\n // user must have customized the nav keys so we have to move focus manually _within_\n // the active group: do this based on the order determined by tabbable()\n destinationNode = containerGroup.nextTabbableNode(target, false);\n }\n } else {\n // FORWARD\n\n // is the target the last tabbable node in a group?\n var lastOfGroupIndex = findIndex(state.tabbableGroups, function (_ref4) {\n var lastTabbableNode = _ref4.lastTabbableNode;\n return target === lastTabbableNode;\n });\n if (lastOfGroupIndex < 0 && (containerGroup.container === target || isFocusable(target, config.tabbableOptions) && !isTabbable(target, config.tabbableOptions) && !containerGroup.nextTabbableNode(target))) {\n // an exception case where the target is the container itself, or\n // a non-tabbable node that was given focus (i.e. tabindex is negative\n // and user clicked on it or node was programmatically given focus)\n // and is not followed by any other tabbable node, in which\n // case, we should handle tab as if focus were on the container's\n // last tabbable node, and go to the first tabbable node of the FIRST group\n lastOfGroupIndex = containerIndex;\n }\n if (lastOfGroupIndex >= 0) {\n // YES: then tab should go to the first tabbable node in the next\n // group (and wrap around to the first tabbable node of the FIRST\n // group if it's the last tabbable node of the LAST group)\n var _destinationGroupIndex = lastOfGroupIndex === state.tabbableGroups.length - 1 ? 0 : lastOfGroupIndex + 1;\n var _destinationGroup = state.tabbableGroups[_destinationGroupIndex];\n destinationNode = getTabIndex(target) >= 0 ? _destinationGroup.firstTabbableNode : _destinationGroup.firstDomTabbableNode;\n } else if (!isTabEvent(event)) {\n // user must have customized the nav keys so we have to move focus manually _within_\n // the active group: do this based on the order determined by tabbable()\n destinationNode = containerGroup.nextTabbableNode(target);\n }\n }\n } else {\n // no groups available\n // NOTE: the fallbackFocus option does not support returning false to opt-out\n destinationNode = getNodeForOption('fallbackFocus');\n }\n return destinationNode;\n };\n\n // This needs to be done on mousedown and touchstart instead of click\n // so that it precedes the focus event.\n var checkPointerDown = function checkPointerDown(e) {\n var target = getActualTarget(e);\n if (findContainerIndex(target, e) >= 0) {\n // allow the click since it ocurred inside the trap\n return;\n }\n if (valueOrHandler(config.clickOutsideDeactivates, e)) {\n // immediately deactivate the trap\n trap.deactivate({\n // NOTE: by setting `returnFocus: false`, deactivate() will do nothing,\n // which will result in the outside click setting focus to the node\n // that was clicked (and if not focusable, to \"nothing\"); by setting\n // `returnFocus: true`, we'll attempt to re-focus the node originally-focused\n // on activation (or the configured `setReturnFocus` node), whether the\n // outside click was on a focusable node or not\n returnFocus: config.returnFocusOnDeactivate\n });\n return;\n }\n\n // This is needed for mobile devices.\n // (If we'll only let `click` events through,\n // then on mobile they will be blocked anyways if `touchstart` is blocked.)\n if (valueOrHandler(config.allowOutsideClick, e)) {\n // allow the click outside the trap to take place\n return;\n }\n\n // otherwise, prevent the click\n e.preventDefault();\n };\n\n // In case focus escapes the trap for some strange reason, pull it back in.\n // NOTE: the focusIn event is NOT cancelable, so if focus escapes, it may cause unexpected\n // scrolling if the node that got focused was out of view; there's nothing we can do to\n // prevent that from happening by the time we discover that focus escaped\n var checkFocusIn = function checkFocusIn(event) {\n var target = getActualTarget(event);\n var targetContained = findContainerIndex(target, event) >= 0;\n\n // In Firefox when you Tab out of an iframe the Document is briefly focused.\n if (targetContained || target instanceof Document) {\n if (targetContained) {\n state.mostRecentlyFocusedNode = target;\n }\n } else {\n // escaped! pull it back in to where it just left\n event.stopImmediatePropagation();\n\n // focus will escape if the MRU node had a positive tab index and user tried to nav forward;\n // it will also escape if the MRU node had a 0 tab index and user tried to nav backward\n // toward a node with a positive tab index\n var nextNode; // next node to focus, if we find one\n var navAcrossContainers = true;\n if (state.mostRecentlyFocusedNode) {\n if (getTabIndex(state.mostRecentlyFocusedNode) > 0) {\n // MRU container index must be >=0 otherwise we wouldn't have it as an MRU node...\n var mruContainerIdx = findContainerIndex(state.mostRecentlyFocusedNode);\n // there MAY not be any tabbable nodes in the container if there are at least 2 containers\n // and the MRU node is focusable but not tabbable (focus-trap requires at least 1 container\n // with at least one tabbable node in order to function, so this could be the other container\n // with nothing tabbable in it)\n var tabbableNodes = state.containerGroups[mruContainerIdx].tabbableNodes;\n if (tabbableNodes.length > 0) {\n // MRU tab index MAY not be found if the MRU node is focusable but not tabbable\n var mruTabIdx = tabbableNodes.findIndex(function (node) {\n return node === state.mostRecentlyFocusedNode;\n });\n if (mruTabIdx >= 0) {\n if (config.isKeyForward(state.recentNavEvent)) {\n if (mruTabIdx + 1 < tabbableNodes.length) {\n nextNode = tabbableNodes[mruTabIdx + 1];\n navAcrossContainers = false;\n }\n // else, don't wrap within the container as focus should move to next/previous\n // container\n } else {\n if (mruTabIdx - 1 >= 0) {\n nextNode = tabbableNodes[mruTabIdx - 1];\n navAcrossContainers = false;\n }\n // else, don't wrap within the container as focus should move to next/previous\n // container\n }\n // else, don't find in container order without considering direction too\n }\n }\n // else, no tabbable nodes in that container (which means we must have at least one other\n // container with at least one tabbable node in it, otherwise focus-trap would've thrown\n // an error the last time updateTabbableNodes() was run): find next node among all known\n // containers\n } else {\n // check to see if there's at least one tabbable node with a positive tab index inside\n // the trap because focus seems to escape when navigating backward from a tabbable node\n // with tabindex=0 when this is the case (instead of wrapping to the tabbable node with\n // the greatest positive tab index like it should)\n if (!state.containerGroups.some(function (g) {\n return g.tabbableNodes.some(function (n) {\n return getTabIndex(n) > 0;\n });\n })) {\n // no containers with tabbable nodes with positive tab indexes which means the focus\n // escaped for some other reason and we should just execute the fallback to the\n // MRU node or initial focus node, if any\n navAcrossContainers = false;\n }\n }\n } else {\n // no MRU node means we're likely in some initial condition when the trap has just\n // been activated and initial focus hasn't been given yet, in which case we should\n // fall through to trying to focus the initial focus node, which is what should\n // happen below at this point in the logic\n navAcrossContainers = false;\n }\n if (navAcrossContainers) {\n nextNode = findNextNavNode({\n // move FROM the MRU node, not event-related node (which will be the node that is\n // outside the trap causing the focus escape we're trying to fix)\n target: state.mostRecentlyFocusedNode,\n isBackward: config.isKeyBackward(state.recentNavEvent)\n });\n }\n if (nextNode) {\n tryFocus(nextNode);\n } else {\n tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());\n }\n }\n state.recentNavEvent = undefined; // clear\n };\n\n // Hijack key nav events on the first and last focusable nodes of the trap,\n // in order to prevent focus from escaping. If it escapes for even a\n // moment it can end up scrolling the page and causing confusion so we\n // kind of need to capture the action at the keydown phase.\n var checkKeyNav = function checkKeyNav(event) {\n var isBackward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n state.recentNavEvent = event;\n var destinationNode = findNextNavNode({\n event: event,\n isBackward: isBackward\n });\n if (destinationNode) {\n if (isTabEvent(event)) {\n // since tab natively moves focus, we wouldn't have a destination node unless we\n // were on the edge of a container and had to move to the next/previous edge, in\n // which case we want to prevent default to keep the browser from moving focus\n // to where it normally would\n event.preventDefault();\n }\n tryFocus(destinationNode);\n }\n // else, let the browser take care of [shift+]tab and move the focus\n };\n\n var checkKey = function checkKey(event) {\n if (isEscapeEvent(event) && valueOrHandler(config.escapeDeactivates, event) !== false) {\n event.preventDefault();\n trap.deactivate();\n return;\n }\n if (config.isKeyForward(event) || config.isKeyBackward(event)) {\n checkKeyNav(event, config.isKeyBackward(event));\n }\n };\n var checkClick = function checkClick(e) {\n var target = getActualTarget(e);\n if (findContainerIndex(target, e) >= 0) {\n return;\n }\n if (valueOrHandler(config.clickOutsideDeactivates, e)) {\n return;\n }\n if (valueOrHandler(config.allowOutsideClick, e)) {\n return;\n }\n e.preventDefault();\n e.stopImmediatePropagation();\n };\n\n //\n // EVENT LISTENERS\n //\n\n var addListeners = function addListeners() {\n if (!state.active) {\n return;\n }\n\n // There can be only one listening focus trap at a time\n activeFocusTraps.activateTrap(trapStack, trap);\n\n // Delay ensures that the focused element doesn't capture the event\n // that caused the focus trap activation.\n state.delayInitialFocusTimer = config.delayInitialFocus ? delay(function () {\n tryFocus(getInitialFocusNode());\n }) : tryFocus(getInitialFocusNode());\n doc.addEventListener('focusin', checkFocusIn, true);\n doc.addEventListener('mousedown', checkPointerDown, {\n capture: true,\n passive: false\n });\n doc.addEventListener('touchstart', checkPointerDown, {\n capture: true,\n passive: false\n });\n doc.addEventListener('click', checkClick, {\n capture: true,\n passive: false\n });\n doc.addEventListener('keydown', checkKey, {\n capture: true,\n passive: false\n });\n return trap;\n };\n var removeListeners = function removeListeners() {\n if (!state.active) {\n return;\n }\n doc.removeEventListener('focusin', checkFocusIn, true);\n doc.removeEventListener('mousedown', checkPointerDown, true);\n doc.removeEventListener('touchstart', checkPointerDown, true);\n doc.removeEventListener('click', checkClick, true);\n doc.removeEventListener('keydown', checkKey, true);\n return trap;\n };\n\n //\n // MUTATION OBSERVER\n //\n\n var checkDomRemoval = function checkDomRemoval(mutations) {\n var isFocusedNodeRemoved = mutations.some(function (mutation) {\n var removedNodes = Array.from(mutation.removedNodes);\n return removedNodes.some(function (node) {\n return node === state.mostRecentlyFocusedNode;\n });\n });\n\n // If the currently focused is removed then browsers will move focus to the\n // <body> element. If this happens, try to move focus back into the trap.\n if (isFocusedNodeRemoved) {\n tryFocus(getInitialFocusNode());\n }\n };\n\n // Use MutationObserver - if supported - to detect if focused node is removed\n // from the DOM.\n var mutationObserver = typeof window !== 'undefined' && 'MutationObserver' in window ? new MutationObserver(checkDomRemoval) : undefined;\n var updateObservedNodes = function updateObservedNodes() {\n if (!mutationObserver) {\n return;\n }\n mutationObserver.disconnect();\n if (state.active && !state.paused) {\n state.containers.map(function (container) {\n mutationObserver.observe(container, {\n subtree: true,\n childList: true\n });\n });\n }\n };\n\n //\n // TRAP DEFINITION\n //\n\n trap = {\n get active() {\n return state.active;\n },\n get paused() {\n return state.paused;\n },\n activate: function activate(activateOptions) {\n if (state.active) {\n return this;\n }\n var onActivate = getOption(activateOptions, 'onActivate');\n var onPostActivate = getOption(activateOptions, 'onPostActivate');\n var checkCanFocusTrap = getOption(activateOptions, 'checkCanFocusTrap');\n if (!checkCanFocusTrap) {\n updateTabbableNodes();\n }\n state.active = true;\n state.paused = false;\n state.nodeFocusedBeforeActivation = doc.activeElement;\n onActivate === null || onActivate === void 0 || onActivate();\n var finishActivation = function finishActivation() {\n if (checkCanFocusTrap) {\n updateTabbableNodes();\n }\n addListeners();\n updateObservedNodes();\n onPostActivate === null || onPostActivate === void 0 || onPostActivate();\n };\n if (checkCanFocusTrap) {\n checkCanFocusTrap(state.containers.concat()).then(finishActivation, finishActivation);\n return this;\n }\n finishActivation();\n return this;\n },\n deactivate: function deactivate(deactivateOptions) {\n if (!state.active) {\n return this;\n }\n var options = _objectSpread2({\n onDeactivate: config.onDeactivate,\n onPostDeactivate: config.onPostDeactivate,\n checkCanReturnFocus: config.checkCanReturnFocus\n }, deactivateOptions);\n clearTimeout(state.delayInitialFocusTimer); // noop if undefined\n state.delayInitialFocusTimer = undefined;\n removeListeners();\n state.active = false;\n state.paused = false;\n updateObservedNodes();\n activeFocusTraps.deactivateTrap(trapStack, trap);\n var onDeactivate = getOption(options, 'onDeactivate');\n var onPostDeactivate = getOption(options, 'onPostDeactivate');\n var checkCanReturnFocus = getOption(options, 'checkCanReturnFocus');\n var returnFocus = getOption(options, 'returnFocus', 'returnFocusOnDeactivate');\n onDeactivate === null || onDeactivate === void 0 || onDeactivate();\n var finishDeactivation = function finishDeactivation() {\n delay(function () {\n if (returnFocus) {\n tryFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation));\n }\n onPostDeactivate === null || onPostDeactivate === void 0 || onPostDeactivate();\n });\n };\n if (returnFocus && checkCanReturnFocus) {\n checkCanReturnFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation)).then(finishDeactivation, finishDeactivation);\n return this;\n }\n finishDeactivation();\n return this;\n },\n pause: function pause(pauseOptions) {\n if (state.paused || !state.active) {\n return this;\n }\n var onPause = getOption(pauseOptions, 'onPause');\n var onPostPause = getOption(pauseOptions, 'onPostPause');\n state.paused = true;\n onPause === null || onPause === void 0 || onPause();\n removeListeners();\n updateObservedNodes();\n onPostPause === null || onPostPause === void 0 || onPostPause();\n return this;\n },\n unpause: function unpause(unpauseOptions) {\n if (!state.paused || !state.active) {\n return this;\n }\n var onUnpause = getOption(unpauseOptions, 'onUnpause');\n var onPostUnpause = getOption(unpauseOptions, 'onPostUnpause');\n state.paused = false;\n onUnpause === null || onUnpause === void 0 || onUnpause();\n updateTabbableNodes();\n addListeners();\n updateObservedNodes();\n onPostUnpause === null || onPostUnpause === void 0 || onPostUnpause();\n return this;\n },\n updateContainerElements: function updateContainerElements(containerElements) {\n var elementsAsArray = [].concat(containerElements).filter(Boolean);\n state.containers = elementsAsArray.map(function (element) {\n return typeof element === 'string' ? doc.querySelector(element) : element;\n });\n if (state.active) {\n updateTabbableNodes();\n }\n updateObservedNodes();\n return this;\n }\n };\n\n // initialize container elements\n trap.updateContainerElements(elements);\n return trap;\n};\n\nexport { createFocusTrap };\n//# sourceMappingURL=focus-trap.esm.js.map\n","/**\n * marked v12.0.0 - a markdown parser\n * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed)\n * https://github.com/markedjs/marked\n */\n\n/**\n * DO NOT EDIT THIS FILE\n * The code in this file is generated from files in ./src/\n */\n\n/**\n * Gets the original marked default options.\n */\nfunction _getDefaults() {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null\n };\n}\nlet _defaults = _getDefaults();\nfunction changeDefaults(newDefaults) {\n _defaults = newDefaults;\n}\n\n/**\n * Helpers\n */\nconst escapeTest = /[&<>\"']/;\nconst escapeReplace = new RegExp(escapeTest.source, 'g');\nconst escapeTestNoEncode = /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/;\nconst escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g');\nconst escapeReplacements = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;'\n};\nconst getEscapeReplacement = (ch) => escapeReplacements[ch];\nfunction escape$1(html, encode) {\n if (encode) {\n if (escapeTest.test(html)) {\n return html.replace(escapeReplace, getEscapeReplacement);\n }\n }\n else {\n if (escapeTestNoEncode.test(html)) {\n return html.replace(escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n return html;\n}\nconst unescapeTest = /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig;\nfunction unescape(html) {\n // explicitly match decimal, hex, and named HTML entities\n return html.replace(unescapeTest, (_, n) => {\n n = n.toLowerCase();\n if (n === 'colon')\n return ':';\n if (n.charAt(0) === '#') {\n return n.charAt(1) === 'x'\n ? String.fromCharCode(parseInt(n.substring(2), 16))\n : String.fromCharCode(+n.substring(1));\n }\n return '';\n });\n}\nconst caret = /(^|[^\\[])\\^/g;\nfunction edit(regex, opt) {\n let source = typeof regex === 'string' ? regex : regex.source;\n opt = opt || '';\n const obj = {\n replace: (name, val) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(caret, '$1');\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n }\n };\n return obj;\n}\nfunction cleanUrl(href) {\n try {\n href = encodeURI(href).replace(/%25/g, '%');\n }\n catch (e) {\n return null;\n }\n return href;\n}\nconst noopTest = { exec: () => null };\nfunction splitCells(tableRow, count) {\n // ensure that every cell-delimiting pipe has a space\n // before it to distinguish it from an escaped pipe\n const row = tableRow.replace(/\\|/g, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\')\n escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n }\n else {\n // add space before unescaped |\n return ' |';\n }\n }), cells = row.split(/ \\|/);\n let i = 0;\n // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells[cells.length - 1].trim()) {\n cells.pop();\n }\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n }\n else {\n while (cells.length < count)\n cells.push('');\n }\n }\n for (; i < cells.length; i++) {\n // leading or trailing whitespace is ignored per the gfm spec\n cells[i] = cells[i].trim().replace(/\\\\\\|/g, '|');\n }\n return cells;\n}\n/**\n * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n * /c*$/ is vulnerable to REDOS.\n *\n * @param str\n * @param c\n * @param invert Remove suffix of non-c chars instead. Default falsey.\n */\nfunction rtrim(str, c, invert) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n // Step left until we fail to match the invert condition.\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n }\n else if (currChar !== c && invert) {\n suffLen++;\n }\n else {\n break;\n }\n }\n return str.slice(0, l - suffLen);\n}\nfunction findClosingBracket(str, b) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n }\n else if (str[i] === b[0]) {\n level++;\n }\n else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n return -1;\n}\n\nfunction outputLink(cap, link, raw, lexer) {\n const href = link.href;\n const title = link.title ? escape$1(link.title) : null;\n const text = cap[1].replace(/\\\\([\\[\\]])/g, '$1');\n if (cap[0].charAt(0) !== '!') {\n lexer.state.inLink = true;\n const token = {\n type: 'link',\n raw,\n href,\n title,\n text,\n tokens: lexer.inlineTokens(text)\n };\n lexer.state.inLink = false;\n return token;\n }\n return {\n type: 'image',\n raw,\n href,\n title,\n text: escape$1(text)\n };\n}\nfunction indentCodeCompensation(raw, text) {\n const matchIndentToCode = raw.match(/^(\\s+)(?:```)/);\n if (matchIndentToCode === null) {\n return text;\n }\n const indentToCode = matchIndentToCode[1];\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(/^\\s+/);\n if (matchIndentInNode === null) {\n return node;\n }\n const [indentInNode] = matchIndentInNode;\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n return node;\n })\n .join('\\n');\n}\n/**\n * Tokenizer\n */\nclass _Tokenizer {\n options;\n rules; // set by the lexer\n lexer; // set by the lexer\n constructor(options) {\n this.options = options || _defaults;\n }\n space(src) {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: 'space',\n raw: cap[0]\n };\n }\n }\n code(src) {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const text = cap[0].replace(/^ {1,4}/gm, '');\n return {\n type: 'code',\n raw: cap[0],\n codeBlockStyle: 'indented',\n text: !this.options.pedantic\n ? rtrim(text, '\\n')\n : text\n };\n }\n }\n fences(src) {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '');\n return {\n type: 'code',\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],\n text\n };\n }\n }\n heading(src) {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n // remove trailing #s\n if (/#$/.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n }\n else if (!trimmed || / $/.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text)\n };\n }\n }\n hr(src) {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: 'hr',\n raw: cap[0]\n };\n }\n }\n blockquote(src) {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n const text = rtrim(cap[0].replace(/^ *>[ \\t]?/gm, ''), '\\n');\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n const tokens = this.lexer.blockTokens(text);\n this.lexer.state.top = top;\n return {\n type: 'blockquote',\n raw: cap[0],\n tokens,\n text\n };\n }\n }\n list(src) {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n const list = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: []\n };\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n // Get next list item\n const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`);\n let raw = '';\n let itemContents = '';\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n raw = cap[0];\n src = src.substring(raw.length);\n let line = cap[2].split('\\n', 1)[0].replace(/^\\t+/, (t) => ' '.repeat(3 * t.length));\n let nextLine = src.split('\\n', 1)[0];\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n }\n else {\n indent = cap[2].search(/[^ ]/); // Find first non-space char\n indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent\n itemContents = line.slice(indent);\n indent += cap[1].length;\n }\n let blankLine = false;\n if (!line && /^ *$/.test(nextLine)) { // Items begin with at most one blank line\n raw += nextLine + '\\n';\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n if (!endEarly) {\n const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`);\n const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`);\n const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`);\n const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n nextLine = rawLine;\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' ');\n }\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n // Horizontal rule found\n if (hrRegex.test(src)) {\n break;\n }\n if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLine.slice(indent);\n }\n else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n // paragraph continuation unless last line was a different block level element\n if (line.search(/[^ ]/) >= 4) { // indented code block\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n itemContents += '\\n' + nextLine;\n }\n if (!blankLine && !nextLine.trim()) { // Check if current line is blank\n blankLine = true;\n }\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLine.slice(indent);\n }\n }\n if (!list.loose) {\n // If the previous item ended with a blank line, the list is loose\n if (endsWithBlankLine) {\n list.loose = true;\n }\n else if (/\\n *\\n *$/.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n let istask = null;\n let ischecked;\n // Check for task list items\n if (this.options.gfm) {\n istask = /^\\[[ xX]\\] /.exec(itemContents);\n if (istask) {\n ischecked = istask[0] !== '[ ] ';\n itemContents = itemContents.replace(/^\\[[ xX]\\] +/, '');\n }\n }\n list.items.push({\n type: 'list_item',\n raw,\n task: !!istask,\n checked: ischecked,\n loose: false,\n text: itemContents,\n tokens: []\n });\n list.raw += raw;\n }\n // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n list.items[list.items.length - 1].raw = raw.trimEnd();\n (list.items[list.items.length - 1]).text = itemContents.trimEnd();\n list.raw = list.raw.trimEnd();\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (let i = 0; i < list.items.length; i++) {\n this.lexer.state.top = false;\n list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);\n if (!list.loose) {\n // Check if list should be loose\n const spacers = list.items[i].tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\\n.*\\n/.test(t.raw));\n list.loose = hasMultipleLineBreaks;\n }\n }\n // Set all items to loose if list is loose\n if (list.loose) {\n for (let i = 0; i < list.items.length; i++) {\n list.items[i].loose = true;\n }\n }\n return list;\n }\n }\n html(src) {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const token = {\n type: 'html',\n block: true,\n raw: cap[0],\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: cap[0]\n };\n return token;\n }\n }\n def(src) {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(/\\s+/g, ' ');\n const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];\n return {\n type: 'def',\n tag,\n raw: cap[0],\n href,\n title\n };\n }\n }\n table(src) {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n if (!/[:|]/.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(/^\\||\\| *$/g, '').split('|');\n const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\\n[ \\t]*$/, '').split('\\n') : [];\n const item = {\n type: 'table',\n raw: cap[0],\n header: [],\n align: [],\n rows: []\n };\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n for (const align of aligns) {\n if (/^ *-+: *$/.test(align)) {\n item.align.push('right');\n }\n else if (/^ *:-+: *$/.test(align)) {\n item.align.push('center');\n }\n else if (/^ *:-+ *$/.test(align)) {\n item.align.push('left');\n }\n else {\n item.align.push(null);\n }\n }\n for (const header of headers) {\n item.header.push({\n text: header,\n tokens: this.lexer.inline(header)\n });\n }\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map(cell => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell)\n };\n }));\n }\n return item;\n }\n lheading(src) {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text: cap[1],\n tokens: this.lexer.inline(cap[1])\n };\n }\n }\n paragraph(src) {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === '\\n'\n ? cap[1].slice(0, -1)\n : cap[1];\n return {\n type: 'paragraph',\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text)\n };\n }\n }\n text(src) {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0])\n };\n }\n }\n escape(src) {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: escape$1(cap[1])\n };\n }\n }\n tag(src) {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {\n this.lexer.state.inLink = true;\n }\n else if (this.lexer.state.inLink && /^<\\/a>/i.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\\s|>)/i.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n }\n else if (this.lexer.state.inRawBlock && /^<\\/(pre|code|kbd|script)(\\s|>)/i.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n return {\n type: 'html',\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0]\n };\n }\n }\n link(src) {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && /^</.test(trimmedUrl)) {\n // commonmark requires matching angle brackets\n if (!(/>$/.test(trimmedUrl))) {\n return;\n }\n // ending angle bracket cannot be escaped\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n }\n else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf('!') === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = '';\n }\n }\n let href = cap[2];\n let title = '';\n if (this.options.pedantic) {\n // split pedantic href and title\n const link = /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/.exec(href);\n if (link) {\n href = link[1];\n title = link[3];\n }\n }\n else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n href = href.trim();\n if (/^</.test(href)) {\n if (this.options.pedantic && !(/>$/.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\n }\n else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title\n }, cap[0], this.lexer);\n }\n }\n reflink(src, links) {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src))\n || (cap = this.rules.inline.nolink.exec(src))) {\n const linkString = (cap[2] || cap[1]).replace(/\\s+/g, ' ');\n const link = links[linkString.toLowerCase()];\n if (!link) {\n const text = cap[0].charAt(0);\n return {\n type: 'text',\n raw: text,\n text\n };\n }\n return outputLink(cap, link, cap[0], this.lexer);\n }\n }\n emStrong(src, maskedSrc, prevChar = '') {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match)\n return;\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[3] && prevChar.match(/[\\p{L}\\p{N}]/u))\n return;\n const nextChar = match[1] || match[2] || '';\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n while ((match = endReg.exec(maskedSrc)) != null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n if (!rDelim)\n continue; // skip single * in __abc*abc__\n rLength = [...rDelim].length;\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n }\n else if (match[5] || match[6]) { // either Left or Right Delim\n if (lLength % 3 && !((lLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue; // CommonMark Emphasis Rules 9-10\n }\n }\n delimTotal -= rLength;\n if (delimTotal > 0)\n continue; // Haven't found enough closing delimiters\n // Remove extra characters. *a*** -> *a*\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n // char length can be >1 for unicode characters;\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n // Create `em` if smallest delimiter has odd char count. *a***\n if (Math.min(lLength, rLength) % 2) {\n const text = raw.slice(1, -1);\n return {\n type: 'em',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text)\n };\n }\n // Create 'strong' if smallest delimiter has even char count. **a***\n const text = raw.slice(2, -2);\n return {\n type: 'strong',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text)\n };\n }\n }\n }\n codespan(src) {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(/\\n/g, ' ');\n const hasNonSpaceChars = /[^ ]/.test(text);\n const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n text = escape$1(text, true);\n return {\n type: 'codespan',\n raw: cap[0],\n text\n };\n }\n }\n br(src) {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: 'br',\n raw: cap[0]\n };\n }\n }\n del(src) {\n const cap = this.rules.inline.del.exec(src);\n if (cap) {\n return {\n type: 'del',\n raw: cap[0],\n text: cap[2],\n tokens: this.lexer.inlineTokens(cap[2])\n };\n }\n }\n autolink(src) {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = escape$1(cap[1]);\n href = 'mailto:' + text;\n }\n else {\n text = escape$1(cap[1]);\n href = text;\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text\n }\n ]\n };\n }\n }\n url(src) {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = escape$1(cap[0]);\n href = 'mailto:' + text;\n }\n else {\n // do extended autolink path validation\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';\n } while (prevCapZero !== cap[0]);\n text = escape$1(cap[0]);\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\n }\n else {\n href = cap[0];\n }\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text\n }\n ]\n };\n }\n }\n inlineText(src) {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n let text;\n if (this.lexer.state.inRawBlock) {\n text = cap[0];\n }\n else {\n text = escape$1(cap[0]);\n }\n return {\n type: 'text',\n raw: cap[0],\n text\n };\n }\n }\n}\n\n/**\n * Block-Level Grammar\n */\nconst newline = /^(?: *(?:\\n|$))+/;\nconst blockCode = /^( {4}[^\\n]+(?:\\n(?: *(?:\\n|$))*)?)+/;\nconst fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/;\nconst hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nconst heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nconst bullet = /(?:[*+-]|\\d{1,9}[.)])/;\nconst lheading = edit(/^(?!bull )((?:.|\\n(?!\\s*?\\n|bull ))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/)\n .replace(/bull/g, bullet) // lists can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\.|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n *)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n *)?| *\\n *)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\nconst list = edit(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\nconst _tag = 'address|article|aside|base|basefont|blockquote|body|caption'\n + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'\n + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'\n + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'\n + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'\n + '|tr|track|ul';\nconst _comment = /<!--(?:-?>|[\\s\\S]*?(?:-->|$))/;\nconst html = edit('^ {0,3}(?:' // optional indentation\n + '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:</\\\\1>[^\\\\n]*\\\\n+|$)' // (1)\n + '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n + '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)' // (3)\n + '|<![A-Z][\\\\s\\\\S]*?(?:>\\\\n*|$)' // (4)\n + '|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?(?:\\\\]\\\\]>\\\\n*|$)' // (5)\n + '|</?(tag)(?: +|\\\\n|/?>)[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (6)\n + '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (7) open tag\n + '|</(?!script|pre|style|textarea)[a-z][\\\\w-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (7) closing tag\n + ')', 'i')\n .replace('comment', _comment)\n .replace('tag', _tag)\n .replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/)\n .getRegex();\nconst paragraph = edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex();\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n/**\n * Normal Block Grammar\n */\nconst blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText\n};\n/**\n * GFM Block Grammar\n */\nconst gfmTable = edit('^ *([^\\\\n ].*)\\\\n' // Header\n + ' {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)' // Align\n + '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)') // Cells\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('blockquote', ' {0,3}>')\n .replace('code', ' {4}[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // tables can be interrupted by type (6) html blocks\n .getRegex();\nconst blockGfm = {\n ...blockNormal,\n table: gfmTable,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs\n .replace('table', gfmTable) // interrupt paragraphs with table\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex()\n};\n/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\nconst blockPedantic = {\n ...blockNormal,\n html: edit('^ *(?:comment *(?:\\\\n|\\\\s*$)'\n + '|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)' // closed tag\n + '|<tag(?:\"[^\"]*\"|\\'[^\\']*\\'|\\\\s[^\\'\"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))')\n .replace('comment', _comment)\n .replace(/tag/g, '(?!(?:'\n + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'\n + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'\n + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b')\n .getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest, // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' *#{1,6} *[^\\n]')\n .replace('lheading', lheading)\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('|fences', '')\n .replace('|list', '')\n .replace('|html', '')\n .replace('|tag', '')\n .getRegex()\n};\n/**\n * Inline-Level Grammar\n */\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/;\n// list of unicode punctuation marks, plus any missing characters from CommonMark spec\nconst _punctuation = '\\\\p{P}\\\\p{S}';\nconst punctuation = edit(/^((?![*_])[\\spunctuation])/, 'u')\n .replace(/punctuation/g, _punctuation).getRegex();\n// sequences em should skip over [title](link), `code`, <html>\nconst blockSkip = /\\[[^[\\]]*?\\]\\([^\\(\\)]*?\\)|`[^`]*?`|<[^<>]*?>/g;\nconst emStrongLDelim = edit(/^(?:\\*+(?:((?!\\*)[punct])|[^\\s*]))|^_+(?:((?!_)[punct])|([^\\s_]))/, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst emStrongRDelimAst = edit('^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n + '|[^*]+(?=[^*])' // Consume to delim\n + '|(?!\\\\*)[punct](\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n + '|[^punct\\\\s](\\\\*+)(?!\\\\*)(?=[punct\\\\s]|$)' // (2) a***#, a*** can only be a Right Delimiter\n + '|(?!\\\\*)[punct\\\\s](\\\\*+)(?=[^punct\\\\s])' // (3) #***a, ***a can only be Left Delimiter\n + '|[\\\\s](\\\\*+)(?!\\\\*)(?=[punct])' // (4) ***# can only be Left Delimiter\n + '|(?!\\\\*)[punct](\\\\*+)(?!\\\\*)(?=[punct])' // (5) #***# can be either Left or Right Delimiter\n + '|[^punct\\\\s](\\\\*+)(?=[^punct\\\\s])', 'gu') // (6) a***a can be either Left or Right Delimiter\n .replace(/punct/g, _punctuation)\n .getRegex();\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit('^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n + '|[^_]+(?=[^_])' // Consume to delim\n + '|(?!_)[punct](_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n + '|[^punct\\\\s](_+)(?!_)(?=[punct\\\\s]|$)' // (2) a___#, a___ can only be a Right Delimiter\n + '|(?!_)[punct\\\\s](_+)(?=[^punct\\\\s])' // (3) #___a, ___a can only be Left Delimiter\n + '|[\\\\s](_+)(?!_)(?=[punct])' // (4) ___# can only be Left Delimiter\n + '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu') // (5) #___# can be either Left or Right Delimiter\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst anyPunctuation = edit(/\\\\([punct])/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/)\n .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)\n .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])?)+(?![-_])/)\n .getRegex();\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit('^comment'\n + '|^</[a-zA-Z][\\\\w:-]*\\\\s*>' // self-closing tag\n + '|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>' // open tag\n + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. <?php ?>\n + '|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>' // declaration, e.g. <!DOCTYPE html>\n + '|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>') // CDATA section\n .replace('comment', _inlineComment)\n .replace('attribute', /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/)\n .getRegex();\nconst _inlineLabel = /(?:\\[(?:\\\\.|[^\\[\\]\\\\])*\\]|\\\\.|`[^`]*`|[^\\[\\]\\\\`])*?/;\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:\\s+(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^\\s\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n/**\n * Normal Inline Grammar\n */\nconst inlineNormal = {\n _backpedal: noopTest, // only used for GFM url\n anyPunctuation,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest\n};\n/**\n * Pedantic Inline Grammar\n */\nconst inlinePedantic = {\n ...inlineNormal,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/)\n .replace('label', _inlineLabel)\n .getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/)\n .replace('label', _inlineLabel)\n .getRegex()\n};\n/**\n * GFM Inline Grammar\n */\nconst inlineGfm = {\n ...inlineNormal,\n escape: edit(escape).replace('])', '~|])').getRegex(),\n url: edit(/^((?:ftp|https?):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/, 'i')\n .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)\n .getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])([\\s\\S]*?[^\\s~])\\1(?=[^~]|$)/,\n text: /^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|https?:\\/\\/|ftp:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)))/\n};\n/**\n * GFM + Line Breaks Inline Grammar\n */\nconst inlineBreaks = {\n ...inlineGfm,\n br: edit(br).replace('{2,}', '*').getRegex(),\n text: edit(inlineGfm.text)\n .replace('\\\\b_', '\\\\b_| {2,}\\\\n')\n .replace(/\\{2,\\}/g, '*')\n .getRegex()\n};\n/**\n * exports\n */\nconst block = {\n normal: blockNormal,\n gfm: blockGfm,\n pedantic: blockPedantic\n};\nconst inline = {\n normal: inlineNormal,\n gfm: inlineGfm,\n breaks: inlineBreaks,\n pedantic: inlinePedantic\n};\n\n/**\n * Block Lexer\n */\nclass _Lexer {\n tokens;\n options;\n state;\n tokenizer;\n inlineQueue;\n constructor(options) {\n // TokenList cannot be created in one go\n this.tokens = [];\n this.tokens.links = Object.create(null);\n this.options = options || _defaults;\n this.options.tokenizer = this.options.tokenizer || new _Tokenizer();\n this.tokenizer = this.options.tokenizer;\n this.tokenizer.options = this.options;\n this.tokenizer.lexer = this;\n this.inlineQueue = [];\n this.state = {\n inLink: false,\n inRawBlock: false,\n top: true\n };\n const rules = {\n block: block.normal,\n inline: inline.normal\n };\n if (this.options.pedantic) {\n rules.block = block.pedantic;\n rules.inline = inline.pedantic;\n }\n else if (this.options.gfm) {\n rules.block = block.gfm;\n if (this.options.breaks) {\n rules.inline = inline.breaks;\n }\n else {\n rules.inline = inline.gfm;\n }\n }\n this.tokenizer.rules = rules;\n }\n /**\n * Expose Rules\n */\n static get rules() {\n return {\n block,\n inline\n };\n }\n /**\n * Static Lex Method\n */\n static lex(src, options) {\n const lexer = new _Lexer(options);\n return lexer.lex(src);\n }\n /**\n * Static Lex Inline Method\n */\n static lexInline(src, options) {\n const lexer = new _Lexer(options);\n return lexer.inlineTokens(src);\n }\n /**\n * Preprocessing\n */\n lex(src) {\n src = src\n .replace(/\\r\\n|\\r/g, '\\n');\n this.blockTokens(src, this.tokens);\n for (let i = 0; i < this.inlineQueue.length; i++) {\n const next = this.inlineQueue[i];\n this.inlineTokens(next.src, next.tokens);\n }\n this.inlineQueue = [];\n return this.tokens;\n }\n blockTokens(src, tokens = []) {\n if (this.options.pedantic) {\n src = src.replace(/\\t/g, ' ').replace(/^ +$/gm, '');\n }\n else {\n src = src.replace(/^( *)(\\t+)/gm, (_, leading, tabs) => {\n return leading + ' '.repeat(tabs.length);\n });\n }\n let token;\n let lastToken;\n let cutSrc;\n let lastParagraphClipped;\n while (src) {\n if (this.options.extensions\n && this.options.extensions.block\n && this.options.extensions.block.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n if (token.raw.length === 1 && tokens.length > 0) {\n // if there's a single \\n as a spacer, it's terminating the last line,\n // so move it there so that we don't get unnecessary paragraph tags\n tokens[tokens.length - 1].raw += '\\n';\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n // An indented code block cannot interrupt a paragraph.\n if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // fences\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // hr\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // list\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title\n };\n }\n continue;\n }\n // table (gfm)\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n cutSrc = src;\n if (this.options.extensions && this.options.extensions.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n lastToken = tokens[tokens.length - 1];\n if (lastParagraphClipped && lastToken.type === 'paragraph') {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n lastParagraphClipped = (cutSrc.length !== src.length);\n src = src.substring(token.raw.length);\n continue;\n }\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && lastToken.type === 'text') {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n }\n else {\n throw new Error(errMsg);\n }\n }\n }\n this.state.top = true;\n return tokens;\n }\n inline(src, tokens = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n /**\n * Lexing/Compiling\n */\n inlineTokens(src, tokens = []) {\n let token, lastToken, cutSrc;\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match;\n let keepPrevChar, prevChar;\n // Mask out reflinks\n if (this.tokens.links) {\n const links = Object.keys(this.tokens.links);\n if (links.length > 0) {\n while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {\n maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\n // Mask out other blocks\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n // Mask out escaped characters\n while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);\n }\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n // extensions\n if (this.options.extensions\n && this.options.extensions.inline\n && this.options.extensions.inline.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && token.type === 'text' && lastToken.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // link\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n lastToken = tokens[tokens.length - 1];\n if (lastToken && token.type === 'text' && lastToken.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // em & strong\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // br\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // del (gfm)\n if (token = this.tokenizer.del(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // autolink\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // url (gfm)\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n cutSrc = src;\n if (this.options.extensions && this.options.extensions.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n lastToken = tokens[tokens.length - 1];\n if (lastToken && lastToken.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n }\n else {\n throw new Error(errMsg);\n }\n }\n }\n return tokens;\n }\n}\n\n/**\n * Renderer\n */\nclass _Renderer {\n options;\n constructor(options) {\n this.options = options || _defaults;\n }\n code(code, infostring, escaped) {\n const lang = (infostring || '').match(/^\\S*/)?.[0];\n code = code.replace(/\\n$/, '') + '\\n';\n if (!lang) {\n return '<pre><code>'\n + (escaped ? code : escape$1(code, true))\n + '</code></pre>\\n';\n }\n return '<pre><code class=\"language-'\n + escape$1(lang)\n + '\">'\n + (escaped ? code : escape$1(code, true))\n + '</code></pre>\\n';\n }\n blockquote(quote) {\n return `<blockquote>\\n${quote}</blockquote>\\n`;\n }\n html(html, block) {\n return html;\n }\n heading(text, level, raw) {\n // ignore IDs\n return `<h${level}>${text}</h${level}>\\n`;\n }\n hr() {\n return '<hr>\\n';\n }\n list(body, ordered, start) {\n const type = ordered ? 'ol' : 'ul';\n const startatt = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startatt + '>\\n' + body + '</' + type + '>\\n';\n }\n listitem(text, task, checked) {\n return `<li>${text}</li>\\n`;\n }\n checkbox(checked) {\n return '<input '\n + (checked ? 'checked=\"\" ' : '')\n + 'disabled=\"\" type=\"checkbox\">';\n }\n paragraph(text) {\n return `<p>${text}</p>\\n`;\n }\n table(header, body) {\n if (body)\n body = `<tbody>${body}</tbody>`;\n return '<table>\\n'\n + '<thead>\\n'\n + header\n + '</thead>\\n'\n + body\n + '</table>\\n';\n }\n tablerow(content) {\n return `<tr>\\n${content}</tr>\\n`;\n }\n tablecell(content, flags) {\n const type = flags.header ? 'th' : 'td';\n const tag = flags.align\n ? `<${type} align=\"${flags.align}\">`\n : `<${type}>`;\n return tag + content + `</${type}>\\n`;\n }\n /**\n * span level renderer\n */\n strong(text) {\n return `<strong>${text}</strong>`;\n }\n em(text) {\n return `<em>${text}</em>`;\n }\n codespan(text) {\n return `<code>${text}</code>`;\n }\n br() {\n return '<br>';\n }\n del(text) {\n return `<del>${text}</del>`;\n }\n link(href, title, text) {\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text;\n }\n href = cleanHref;\n let out = '<a href=\"' + href + '\"';\n if (title) {\n out += ' title=\"' + title + '\"';\n }\n out += '>' + text + '</a>';\n return out;\n }\n image(href, title, text) {\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text;\n }\n href = cleanHref;\n let out = `<img src=\"${href}\" alt=\"${text}\"`;\n if (title) {\n out += ` title=\"${title}\"`;\n }\n out += '>';\n return out;\n }\n text(text) {\n return text;\n }\n}\n\n/**\n * TextRenderer\n * returns only the textual part of the token\n */\nclass _TextRenderer {\n // no need for block level renderers\n strong(text) {\n return text;\n }\n em(text) {\n return text;\n }\n codespan(text) {\n return text;\n }\n del(text) {\n return text;\n }\n html(text) {\n return text;\n }\n text(text) {\n return text;\n }\n link(href, title, text) {\n return '' + text;\n }\n image(href, title, text) {\n return '' + text;\n }\n br() {\n return '';\n }\n}\n\n/**\n * Parsing & Compiling\n */\nclass _Parser {\n options;\n renderer;\n textRenderer;\n constructor(options) {\n this.options = options || _defaults;\n this.options.renderer = this.options.renderer || new _Renderer();\n this.renderer = this.options.renderer;\n this.renderer.options = this.options;\n this.textRenderer = new _TextRenderer();\n }\n /**\n * Static Parse Method\n */\n static parse(tokens, options) {\n const parser = new _Parser(options);\n return parser.parse(tokens);\n }\n /**\n * Static Parse Inline Method\n */\n static parseInline(tokens, options) {\n const parser = new _Parser(options);\n return parser.parseInline(tokens);\n }\n /**\n * Parse Loop\n */\n parse(tokens, top = true) {\n let out = '';\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n // Run any renderer extensions\n if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {\n const genericToken = token;\n const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);\n if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(genericToken.type)) {\n out += ret || '';\n continue;\n }\n }\n switch (token.type) {\n case 'space': {\n continue;\n }\n case 'hr': {\n out += this.renderer.hr();\n continue;\n }\n case 'heading': {\n const headingToken = token;\n out += this.renderer.heading(this.parseInline(headingToken.tokens), headingToken.depth, unescape(this.parseInline(headingToken.tokens, this.textRenderer)));\n continue;\n }\n case 'code': {\n const codeToken = token;\n out += this.renderer.code(codeToken.text, codeToken.lang, !!codeToken.escaped);\n continue;\n }\n case 'table': {\n const tableToken = token;\n let header = '';\n // header\n let cell = '';\n for (let j = 0; j < tableToken.header.length; j++) {\n cell += this.renderer.tablecell(this.parseInline(tableToken.header[j].tokens), { header: true, align: tableToken.align[j] });\n }\n header += this.renderer.tablerow(cell);\n let body = '';\n for (let j = 0; j < tableToken.rows.length; j++) {\n const row = tableToken.rows[j];\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.renderer.tablecell(this.parseInline(row[k].tokens), { header: false, align: tableToken.align[k] });\n }\n body += this.renderer.tablerow(cell);\n }\n out += this.renderer.table(header, body);\n continue;\n }\n case 'blockquote': {\n const blockquoteToken = token;\n const body = this.parse(blockquoteToken.tokens);\n out += this.renderer.blockquote(body);\n continue;\n }\n case 'list': {\n const listToken = token;\n const ordered = listToken.ordered;\n const start = listToken.start;\n const loose = listToken.loose;\n let body = '';\n for (let j = 0; j < listToken.items.length; j++) {\n const item = listToken.items[j];\n const checked = item.checked;\n const task = item.task;\n let itemBody = '';\n if (item.task) {\n const checkbox = this.renderer.checkbox(!!checked);\n if (loose) {\n if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {\n item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;\n }\n }\n else {\n item.tokens.unshift({\n type: 'text',\n text: checkbox + ' '\n });\n }\n }\n else {\n itemBody += checkbox + ' ';\n }\n }\n itemBody += this.parse(item.tokens, loose);\n body += this.renderer.listitem(itemBody, task, !!checked);\n }\n out += this.renderer.list(body, ordered, start);\n continue;\n }\n case 'html': {\n const htmlToken = token;\n out += this.renderer.html(htmlToken.text, htmlToken.block);\n continue;\n }\n case 'paragraph': {\n const paragraphToken = token;\n out += this.renderer.paragraph(this.parseInline(paragraphToken.tokens));\n continue;\n }\n case 'text': {\n let textToken = token;\n let body = textToken.tokens ? this.parseInline(textToken.tokens) : textToken.text;\n while (i + 1 < tokens.length && tokens[i + 1].type === 'text') {\n textToken = tokens[++i];\n body += '\\n' + (textToken.tokens ? this.parseInline(textToken.tokens) : textToken.text);\n }\n out += top ? this.renderer.paragraph(body) : body;\n continue;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '';\n }\n else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out;\n }\n /**\n * Parse Inline Tokens\n */\n parseInline(tokens, renderer) {\n renderer = renderer || this.renderer;\n let out = '';\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n // Run any renderer extensions\n if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {\n const ret = this.options.extensions.renderers[token.type].call({ parser: this }, token);\n if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(token.type)) {\n out += ret || '';\n continue;\n }\n }\n switch (token.type) {\n case 'escape': {\n const escapeToken = token;\n out += renderer.text(escapeToken.text);\n break;\n }\n case 'html': {\n const tagToken = token;\n out += renderer.html(tagToken.text);\n break;\n }\n case 'link': {\n const linkToken = token;\n out += renderer.link(linkToken.href, linkToken.title, this.parseInline(linkToken.tokens, renderer));\n break;\n }\n case 'image': {\n const imageToken = token;\n out += renderer.image(imageToken.href, imageToken.title, imageToken.text);\n break;\n }\n case 'strong': {\n const strongToken = token;\n out += renderer.strong(this.parseInline(strongToken.tokens, renderer));\n break;\n }\n case 'em': {\n const emToken = token;\n out += renderer.em(this.parseInline(emToken.tokens, renderer));\n break;\n }\n case 'codespan': {\n const codespanToken = token;\n out += renderer.codespan(codespanToken.text);\n break;\n }\n case 'br': {\n out += renderer.br();\n break;\n }\n case 'del': {\n const delToken = token;\n out += renderer.del(this.parseInline(delToken.tokens, renderer));\n break;\n }\n case 'text': {\n const textToken = token;\n out += renderer.text(textToken.text);\n break;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '';\n }\n else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out;\n }\n}\n\nclass _Hooks {\n options;\n constructor(options) {\n this.options = options || _defaults;\n }\n static passThroughHooks = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens'\n ]);\n /**\n * Process markdown before marked\n */\n preprocess(markdown) {\n return markdown;\n }\n /**\n * Process HTML after marked is finished\n */\n postprocess(html) {\n return html;\n }\n /**\n * Process all tokens before walk tokens\n */\n processAllTokens(tokens) {\n return tokens;\n }\n}\n\nclass Marked {\n defaults = _getDefaults();\n options = this.setOptions;\n parse = this.#parseMarkdown(_Lexer.lex, _Parser.parse);\n parseInline = this.#parseMarkdown(_Lexer.lexInline, _Parser.parseInline);\n Parser = _Parser;\n Renderer = _Renderer;\n TextRenderer = _TextRenderer;\n Lexer = _Lexer;\n Tokenizer = _Tokenizer;\n Hooks = _Hooks;\n constructor(...args) {\n this.use(...args);\n }\n /**\n * Run callback for every token\n */\n walkTokens(tokens, callback) {\n let values = [];\n for (const token of tokens) {\n values = values.concat(callback.call(this, token));\n switch (token.type) {\n case 'table': {\n const tableToken = token;\n for (const cell of tableToken.header) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n for (const row of tableToken.rows) {\n for (const cell of row) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n }\n break;\n }\n case 'list': {\n const listToken = token;\n values = values.concat(this.walkTokens(listToken.items, callback));\n break;\n }\n default: {\n const genericToken = token;\n if (this.defaults.extensions?.childTokens?.[genericToken.type]) {\n this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {\n const tokens = genericToken[childTokens].flat(Infinity);\n values = values.concat(this.walkTokens(tokens, callback));\n });\n }\n else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n use(...args) {\n const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack };\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n // ==-- Parse \"addon\" extensions --== //\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error('extension name required');\n }\n if ('renderer' in ext) { // Renderer extensions\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n // Replace extension with func to run new extension but fall back if false\n extensions.renderers[ext.name] = function (...args) {\n let ret = ext.renderer.apply(this, args);\n if (ret === false) {\n ret = prevRenderer.apply(this, args);\n }\n return ret;\n };\n }\n else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if ('tokenizer' in ext) { // Tokenizer Extensions\n if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n }\n else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) { // Function to check for start of token\n if (ext.level === 'block') {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n }\n else {\n extensions.startBlock = [ext.start];\n }\n }\n else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n }\n else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n // ==-- Parse \"overwrite\" extensions --== //\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if (prop === 'options') {\n // ignore options property\n continue;\n }\n const rendererProp = prop;\n const rendererFunc = pack.renderer[rendererProp];\n const prevRenderer = renderer[rendererProp];\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args) => {\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return ret || '';\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if (['options', 'rules', 'lexer'].includes(prop)) {\n // ignore options, rules, and lexer properties\n continue;\n }\n const tokenizerProp = prop;\n const tokenizerFunc = pack.tokenizer[tokenizerProp];\n const prevTokenizer = tokenizer[tokenizerProp];\n // Replace tokenizer with func to run extension, but fall back if false\n // @ts-expect-error cannot type tokenizer function dynamically\n tokenizer[tokenizerProp] = (...args) => {\n let ret = tokenizerFunc.apply(tokenizer, args);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n // ==-- Parse Hooks extensions --== //\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if (prop === 'options') {\n // ignore options property\n continue;\n }\n const hooksProp = prop;\n const hooksFunc = pack.hooks[hooksProp];\n const prevHook = hooks[hooksProp];\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg) => {\n if (this.defaults.async) {\n return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {\n return prevHook.call(hooks, ret);\n });\n }\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n }\n else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args) => {\n let ret = hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = prevHook.apply(hooks, args);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n // ==-- Parse WalkTokens extensions --== //\n if (pack.walkTokens) {\n const walkTokens = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function (token) {\n let values = [];\n values.push(packWalktokens.call(this, token));\n if (walkTokens) {\n values = values.concat(walkTokens.call(this, token));\n }\n return values;\n };\n }\n this.defaults = { ...this.defaults, ...opts };\n });\n return this;\n }\n setOptions(opt) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n lexer(src, options) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n parser(tokens, options) {\n return _Parser.parse(tokens, options ?? this.defaults);\n }\n #parseMarkdown(lexer, parser) {\n return (src, options) => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n // Show warning if an extension set async to true but the parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n if (!opt.silent) {\n console.warn('marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored.');\n }\n opt.async = true;\n }\n const throwError = this.#onError(!!opt.silent, !!opt.async);\n // throw error in case of non string input\n if (typeof src === 'undefined' || src === null) {\n return throwError(new Error('marked(): input parameter is undefined or null'));\n }\n if (typeof src !== 'string') {\n return throwError(new Error('marked(): input parameter is of type '\n + Object.prototype.toString.call(src) + ', string expected'));\n }\n if (opt.hooks) {\n opt.hooks.options = opt;\n }\n if (opt.async) {\n return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src)\n .then(src => lexer(src, opt))\n .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens)\n .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens)\n .then(tokens => parser(tokens, opt))\n .then(html => opt.hooks ? opt.hooks.postprocess(html) : html)\n .catch(throwError);\n }\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src);\n }\n let tokens = lexer(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n }\n catch (e) {\n return throwError(e);\n }\n };\n }\n #onError(silent, async) {\n return (e) => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n if (silent) {\n const msg = '<p>An error occurred:</p><pre>'\n + escape$1(e.message + '', true)\n + '</pre>';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n\nconst markedInstance = new Marked();\nfunction marked(src, opt) {\n return markedInstance.parse(src, opt);\n}\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\n marked.setOptions = function (options) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n };\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\nmarked.defaults = _defaults;\n/**\n * Use Extension\n */\nmarked.use = function (...args) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n/**\n * Run callback for every token\n */\nmarked.walkTokens = function (tokens, callback) {\n return markedInstance.walkTokens(tokens, callback);\n};\n/**\n * Compiles markdown to HTML without enclosing `p` tag.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options\n * @return String of compiled HTML\n */\nmarked.parseInline = markedInstance.parseInline;\n/**\n * Expose\n */\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\nconst options = marked.options;\nconst setOptions = marked.setOptions;\nconst use = marked.use;\nconst walkTokens = marked.walkTokens;\nconst parseInline = marked.parseInline;\nconst parse = marked;\nconst parser = _Parser.parse;\nconst lexer = _Lexer.lex;\n\nexport { _Hooks as Hooks, _Lexer as Lexer, Marked, _Parser as Parser, _Renderer as Renderer, _TextRenderer as TextRenderer, _Tokenizer as Tokenizer, _defaults as defaults, _getDefaults as getDefaults, lexer, marked, options, parse, parseInline, parser, setOptions, use, walkTokens };\n//# sourceMappingURL=marked.esm.js.map\n","/**\n * Custom positioning reference element.\n * @see https://floating-ui.com/docs/virtual-elements\n */\n\nconst sides = ['top', 'right', 'bottom', 'left'];\nconst alignments = ['start', 'end'];\nconst placements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + \"-\" + alignments[0], side + \"-\" + alignments[1]), []);\nconst min = Math.min;\nconst max = Math.max;\nconst round = Math.round;\nconst floor = Math.floor;\nconst createCoords = v => ({\n x: v,\n y: v\n});\nconst oppositeSideMap = {\n left: 'right',\n right: 'left',\n bottom: 'top',\n top: 'bottom'\n};\nconst oppositeAlignmentMap = {\n start: 'end',\n end: 'start'\n};\nfunction clamp(start, value, end) {\n return max(start, min(value, end));\n}\nfunction evaluate(value, param) {\n return typeof value === 'function' ? value(param) : value;\n}\nfunction getSide(placement) {\n return placement.split('-')[0];\n}\nfunction getAlignment(placement) {\n return placement.split('-')[1];\n}\nfunction getOppositeAxis(axis) {\n return axis === 'x' ? 'y' : 'x';\n}\nfunction getAxisLength(axis) {\n return axis === 'y' ? 'height' : 'width';\n}\nfunction getSideAxis(placement) {\n return ['top', 'bottom'].includes(getSide(placement)) ? 'y' : 'x';\n}\nfunction getAlignmentAxis(placement) {\n return getOppositeAxis(getSideAxis(placement));\n}\nfunction getAlignmentSides(placement, rects, rtl) {\n if (rtl === void 0) {\n rtl = false;\n }\n const alignment = getAlignment(placement);\n const alignmentAxis = getAlignmentAxis(placement);\n const length = getAxisLength(alignmentAxis);\n let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top';\n if (rects.reference[length] > rects.floating[length]) {\n mainAlignmentSide = getOppositePlacement(mainAlignmentSide);\n }\n return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];\n}\nfunction getExpandedPlacements(placement) {\n const oppositePlacement = getOppositePlacement(placement);\n return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];\n}\nfunction getOppositeAlignmentPlacement(placement) {\n return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]);\n}\nfunction getSideList(side, isStart, rtl) {\n const lr = ['left', 'right'];\n const rl = ['right', 'left'];\n const tb = ['top', 'bottom'];\n const bt = ['bottom', 'top'];\n switch (side) {\n case 'top':\n case 'bottom':\n if (rtl) return isStart ? rl : lr;\n return isStart ? lr : rl;\n case 'left':\n case 'right':\n return isStart ? tb : bt;\n default:\n return [];\n }\n}\nfunction getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {\n const alignment = getAlignment(placement);\n let list = getSideList(getSide(placement), direction === 'start', rtl);\n if (alignment) {\n list = list.map(side => side + \"-\" + alignment);\n if (flipAlignment) {\n list = list.concat(list.map(getOppositeAlignmentPlacement));\n }\n }\n return list;\n}\nfunction getOppositePlacement(placement) {\n return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]);\n}\nfunction expandPaddingObject(padding) {\n return {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n ...padding\n };\n}\nfunction getPaddingObject(padding) {\n return typeof padding !== 'number' ? expandPaddingObject(padding) : {\n top: padding,\n right: padding,\n bottom: padding,\n left: padding\n };\n}\nfunction rectToClientRect(rect) {\n return {\n ...rect,\n top: rect.y,\n left: rect.x,\n right: rect.x + rect.width,\n bottom: rect.y + rect.height\n };\n}\n\nexport { alignments, clamp, createCoords, evaluate, expandPaddingObject, floor, getAlignment, getAlignmentAxis, getAlignmentSides, getAxisLength, getExpandedPlacements, getOppositeAlignmentPlacement, getOppositeAxis, getOppositeAxisPlacements, getOppositePlacement, getPaddingObject, getSide, getSideAxis, max, min, placements, rectToClientRect, round, sides };\n","import { getSideAxis, getAlignmentAxis, getAxisLength, getSide, getAlignment, evaluate, getPaddingObject, rectToClientRect, min, clamp, placements, getAlignmentSides, getOppositeAlignmentPlacement, getOppositePlacement, getExpandedPlacements, getOppositeAxisPlacements, sides, max, getOppositeAxis } from '@floating-ui/utils';\nexport { rectToClientRect } from '@floating-ui/utils';\n\nfunction computeCoordsFromPlacement(_ref, placement, rtl) {\n let {\n reference,\n floating\n } = _ref;\n const sideAxis = getSideAxis(placement);\n const alignmentAxis = getAlignmentAxis(placement);\n const alignLength = getAxisLength(alignmentAxis);\n const side = getSide(placement);\n const isVertical = sideAxis === 'y';\n const commonX = reference.x + reference.width / 2 - floating.width / 2;\n const commonY = reference.y + reference.height / 2 - floating.height / 2;\n const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;\n let coords;\n switch (side) {\n case 'top':\n coords = {\n x: commonX,\n y: reference.y - floating.height\n };\n break;\n case 'bottom':\n coords = {\n x: commonX,\n y: reference.y + reference.height\n };\n break;\n case 'right':\n coords = {\n x: reference.x + reference.width,\n y: commonY\n };\n break;\n case 'left':\n coords = {\n x: reference.x - floating.width,\n y: commonY\n };\n break;\n default:\n coords = {\n x: reference.x,\n y: reference.y\n };\n }\n switch (getAlignment(placement)) {\n case 'start':\n coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);\n break;\n case 'end':\n coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);\n break;\n }\n return coords;\n}\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a given reference element.\n *\n * This export does not have any `platform` interface logic. You will need to\n * write one for the platform you are using Floating UI with.\n */\nconst computePosition = async (reference, floating, config) => {\n const {\n placement = 'bottom',\n strategy = 'absolute',\n middleware = [],\n platform\n } = config;\n const validMiddleware = middleware.filter(Boolean);\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));\n let rects = await platform.getElementRects({\n reference,\n floating,\n strategy\n });\n let {\n x,\n y\n } = computeCoordsFromPlacement(rects, placement, rtl);\n let statefulPlacement = placement;\n let middlewareData = {};\n let resetCount = 0;\n for (let i = 0; i < validMiddleware.length; i++) {\n const {\n name,\n fn\n } = validMiddleware[i];\n const {\n x: nextX,\n y: nextY,\n data,\n reset\n } = await fn({\n x,\n y,\n initialPlacement: placement,\n placement: statefulPlacement,\n strategy,\n middlewareData,\n rects,\n platform,\n elements: {\n reference,\n floating\n }\n });\n x = nextX != null ? nextX : x;\n y = nextY != null ? nextY : y;\n middlewareData = {\n ...middlewareData,\n [name]: {\n ...middlewareData[name],\n ...data\n }\n };\n if (reset && resetCount <= 50) {\n resetCount++;\n if (typeof reset === 'object') {\n if (reset.placement) {\n statefulPlacement = reset.placement;\n }\n if (reset.rects) {\n rects = reset.rects === true ? await platform.getElementRects({\n reference,\n floating,\n strategy\n }) : reset.rects;\n }\n ({\n x,\n y\n } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));\n }\n i = -1;\n }\n }\n return {\n x,\n y,\n placement: statefulPlacement,\n strategy,\n middlewareData\n };\n};\n\n/**\n * Resolves with an object of overflow side offsets that determine how much the\n * element is overflowing a given clipping boundary on each side.\n * - positive = overflowing the boundary by that number of pixels\n * - negative = how many pixels left before it will overflow\n * - 0 = lies flush with the boundary\n * @see https://floating-ui.com/docs/detectOverflow\n */\nasync function detectOverflow(state, options) {\n var _await$platform$isEle;\n if (options === void 0) {\n options = {};\n }\n const {\n x,\n y,\n platform,\n rects,\n elements,\n strategy\n } = state;\n const {\n boundary = 'clippingAncestors',\n rootBoundary = 'viewport',\n elementContext = 'floating',\n altBoundary = false,\n padding = 0\n } = evaluate(options, state);\n const paddingObject = getPaddingObject(padding);\n const altContext = elementContext === 'floating' ? 'reference' : 'floating';\n const element = elements[altBoundary ? altContext : elementContext];\n const clippingClientRect = rectToClientRect(await platform.getClippingRect({\n element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))),\n boundary,\n rootBoundary,\n strategy\n }));\n const rect = elementContext === 'floating' ? {\n ...rects.floating,\n x,\n y\n } : rects.reference;\n const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating));\n const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || {\n x: 1,\n y: 1\n } : {\n x: 1,\n y: 1\n };\n const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({\n elements,\n rect,\n offsetParent,\n strategy\n }) : rect);\n return {\n top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,\n bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,\n left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,\n right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x\n };\n}\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = options => ({\n name: 'arrow',\n options,\n async fn(state) {\n const {\n x,\n y,\n placement,\n rects,\n platform,\n elements,\n middlewareData\n } = state;\n // Since `element` is required, we don't Partial<> the type.\n const {\n element,\n padding = 0\n } = evaluate(options, state) || {};\n if (element == null) {\n return {};\n }\n const paddingObject = getPaddingObject(padding);\n const coords = {\n x,\n y\n };\n const axis = getAlignmentAxis(placement);\n const length = getAxisLength(axis);\n const arrowDimensions = await platform.getDimensions(element);\n const isYAxis = axis === 'y';\n const minProp = isYAxis ? 'top' : 'left';\n const maxProp = isYAxis ? 'bottom' : 'right';\n const clientProp = isYAxis ? 'clientHeight' : 'clientWidth';\n const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];\n const startDiff = coords[axis] - rects.reference[axis];\n const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element));\n let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;\n\n // DOM platform can return `window` as the `offsetParent`.\n if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) {\n clientSize = elements.floating[clientProp] || rects.floating[length];\n }\n const centerToReference = endDiff / 2 - startDiff / 2;\n\n // If the padding is large enough that it causes the arrow to no longer be\n // centered, modify the padding so that it is centered.\n const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;\n const minPadding = min(paddingObject[minProp], largestPossiblePadding);\n const maxPadding = min(paddingObject[maxProp], largestPossiblePadding);\n\n // Make sure the arrow doesn't overflow the floating element if the center\n // point is outside the floating element's bounds.\n const min$1 = minPadding;\n const max = clientSize - arrowDimensions[length] - maxPadding;\n const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;\n const offset = clamp(min$1, center, max);\n\n // If the reference is small enough that the arrow's padding causes it to\n // to point to nothing for an aligned placement, adjust the offset of the\n // floating element itself. To ensure `shift()` continues to take action,\n // a single reset is performed when this is true.\n const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;\n const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0;\n return {\n [axis]: coords[axis] + alignmentOffset,\n data: {\n [axis]: offset,\n centerOffset: center - offset - alignmentOffset,\n ...(shouldAddOffset && {\n alignmentOffset\n })\n },\n reset: shouldAddOffset\n };\n }\n});\n\nfunction getPlacementList(alignment, autoAlignment, allowedPlacements) {\n const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement);\n return allowedPlacementsSortedByAlignment.filter(placement => {\n if (alignment) {\n return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false);\n }\n return true;\n });\n}\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'autoPlacement',\n options,\n async fn(state) {\n var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE;\n const {\n rects,\n middlewareData,\n placement,\n platform,\n elements\n } = state;\n const {\n crossAxis = false,\n alignment,\n allowedPlacements = placements,\n autoAlignment = true,\n ...detectOverflowOptions\n } = evaluate(options, state);\n const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements;\n const overflow = await detectOverflow(state, detectOverflowOptions);\n const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0;\n const currentPlacement = placements$1[currentIndex];\n if (currentPlacement == null) {\n return {};\n }\n const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)));\n\n // Make `computeCoords` start from the right place.\n if (placement !== currentPlacement) {\n return {\n reset: {\n placement: placements$1[0]\n }\n };\n }\n const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]];\n const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), {\n placement: currentPlacement,\n overflows: currentOverflows\n }];\n const nextPlacement = placements$1[currentIndex + 1];\n\n // There are more placements to check.\n if (nextPlacement) {\n return {\n data: {\n index: currentIndex + 1,\n overflows: allOverflows\n },\n reset: {\n placement: nextPlacement\n }\n };\n }\n const placementsSortedByMostSpace = allOverflows.map(d => {\n const alignment = getAlignment(d.placement);\n return [d.placement, alignment && crossAxis ?\n // Check along the mainAxis and main crossAxis side.\n d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) :\n // Check only the mainAxis.\n d.overflows[0], d.overflows];\n }).sort((a, b) => a[1] - b[1]);\n const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0,\n // Aligned placements should not check their opposite crossAxis\n // side.\n getAlignment(d[0]) ? 2 : 3).every(v => v <= 0));\n const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0];\n if (resetPlacement !== placement) {\n return {\n data: {\n index: currentIndex + 1,\n overflows: allOverflows\n },\n reset: {\n placement: resetPlacement\n }\n };\n }\n return {};\n }\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'flip',\n options,\n async fn(state) {\n var _middlewareData$arrow, _middlewareData$flip;\n const {\n placement,\n middlewareData,\n rects,\n initialPlacement,\n platform,\n elements\n } = state;\n const {\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = true,\n fallbackPlacements: specifiedFallbackPlacements,\n fallbackStrategy = 'bestFit',\n fallbackAxisSideDirection = 'none',\n flipAlignment = true,\n ...detectOverflowOptions\n } = evaluate(options, state);\n\n // If a reset by the arrow was caused due to an alignment offset being\n // added, we should skip any logic now since `flip()` has already done its\n // work.\n // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643\n if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n return {};\n }\n const side = getSide(placement);\n const isBasePlacement = getSide(initialPlacement) === initialPlacement;\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));\n if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== 'none') {\n fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));\n }\n const placements = [initialPlacement, ...fallbackPlacements];\n const overflow = await detectOverflow(state, detectOverflowOptions);\n const overflows = [];\n let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];\n if (checkMainAxis) {\n overflows.push(overflow[side]);\n }\n if (checkCrossAxis) {\n const sides = getAlignmentSides(placement, rects, rtl);\n overflows.push(overflow[sides[0]], overflow[sides[1]]);\n }\n overflowsData = [...overflowsData, {\n placement,\n overflows\n }];\n\n // One or more sides is overflowing.\n if (!overflows.every(side => side <= 0)) {\n var _middlewareData$flip2, _overflowsData$filter;\n const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;\n const nextPlacement = placements[nextIndex];\n if (nextPlacement) {\n // Try next placement and re-run the lifecycle.\n return {\n data: {\n index: nextIndex,\n overflows: overflowsData\n },\n reset: {\n placement: nextPlacement\n }\n };\n }\n\n // First, find the candidates that fit on the mainAxis side of overflow,\n // then find the placement that fits the best on the main crossAxis side.\n let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;\n\n // Otherwise fallback.\n if (!resetPlacement) {\n switch (fallbackStrategy) {\n case 'bestFit':\n {\n var _overflowsData$map$so;\n const placement = (_overflowsData$map$so = overflowsData.map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$map$so[0];\n if (placement) {\n resetPlacement = placement;\n }\n break;\n }\n case 'initialPlacement':\n resetPlacement = initialPlacement;\n break;\n }\n }\n if (placement !== resetPlacement) {\n return {\n reset: {\n placement: resetPlacement\n }\n };\n }\n }\n return {};\n }\n };\n};\n\nfunction getSideOffsets(overflow, rect) {\n return {\n top: overflow.top - rect.height,\n right: overflow.right - rect.width,\n bottom: overflow.bottom - rect.height,\n left: overflow.left - rect.width\n };\n}\nfunction isAnySideFullyClipped(overflow) {\n return sides.some(side => overflow[side] >= 0);\n}\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'hide',\n options,\n async fn(state) {\n const {\n rects\n } = state;\n const {\n strategy = 'referenceHidden',\n ...detectOverflowOptions\n } = evaluate(options, state);\n switch (strategy) {\n case 'referenceHidden':\n {\n const overflow = await detectOverflow(state, {\n ...detectOverflowOptions,\n elementContext: 'reference'\n });\n const offsets = getSideOffsets(overflow, rects.reference);\n return {\n data: {\n referenceHiddenOffsets: offsets,\n referenceHidden: isAnySideFullyClipped(offsets)\n }\n };\n }\n case 'escaped':\n {\n const overflow = await detectOverflow(state, {\n ...detectOverflowOptions,\n altBoundary: true\n });\n const offsets = getSideOffsets(overflow, rects.floating);\n return {\n data: {\n escapedOffsets: offsets,\n escaped: isAnySideFullyClipped(offsets)\n }\n };\n }\n default:\n {\n return {};\n }\n }\n }\n };\n};\n\nfunction getBoundingRect(rects) {\n const minX = min(...rects.map(rect => rect.left));\n const minY = min(...rects.map(rect => rect.top));\n const maxX = max(...rects.map(rect => rect.right));\n const maxY = max(...rects.map(rect => rect.bottom));\n return {\n x: minX,\n y: minY,\n width: maxX - minX,\n height: maxY - minY\n };\n}\nfunction getRectsByLine(rects) {\n const sortedRects = rects.slice().sort((a, b) => a.y - b.y);\n const groups = [];\n let prevRect = null;\n for (let i = 0; i < sortedRects.length; i++) {\n const rect = sortedRects[i];\n if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) {\n groups.push([rect]);\n } else {\n groups[groups.length - 1].push(rect);\n }\n prevRect = rect;\n }\n return groups.map(rect => rectToClientRect(getBoundingRect(rect)));\n}\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'inline',\n options,\n async fn(state) {\n const {\n placement,\n elements,\n rects,\n platform,\n strategy\n } = state;\n // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a\n // ClientRect's bounds, despite the event listener being triggered. A\n // padding of 2 seems to handle this issue.\n const {\n padding = 2,\n x,\n y\n } = evaluate(options, state);\n const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []);\n const clientRects = getRectsByLine(nativeClientRects);\n const fallback = rectToClientRect(getBoundingRect(nativeClientRects));\n const paddingObject = getPaddingObject(padding);\n function getBoundingClientRect() {\n // There are two rects and they are disjoined.\n if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) {\n // Find the first rect in which the point is fully inside.\n return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback;\n }\n\n // There are 2 or more connected rects.\n if (clientRects.length >= 2) {\n if (getSideAxis(placement) === 'y') {\n const firstRect = clientRects[0];\n const lastRect = clientRects[clientRects.length - 1];\n const isTop = getSide(placement) === 'top';\n const top = firstRect.top;\n const bottom = lastRect.bottom;\n const left = isTop ? firstRect.left : lastRect.left;\n const right = isTop ? firstRect.right : lastRect.right;\n const width = right - left;\n const height = bottom - top;\n return {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x: left,\n y: top\n };\n }\n const isLeftSide = getSide(placement) === 'left';\n const maxRight = max(...clientRects.map(rect => rect.right));\n const minLeft = min(...clientRects.map(rect => rect.left));\n const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight);\n const top = measureRects[0].top;\n const bottom = measureRects[measureRects.length - 1].bottom;\n const left = minLeft;\n const right = maxRight;\n const width = right - left;\n const height = bottom - top;\n return {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x: left,\n y: top\n };\n }\n return fallback;\n }\n const resetRects = await platform.getElementRects({\n reference: {\n getBoundingClientRect\n },\n floating: elements.floating,\n strategy\n });\n if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) {\n return {\n reset: {\n rects: resetRects\n }\n };\n }\n return {};\n }\n };\n};\n\n// For type backwards-compatibility, the `OffsetOptions` type was also\n// Derivable.\n\nasync function convertValueToCoords(state, options) {\n const {\n placement,\n platform,\n elements\n } = state;\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n const side = getSide(placement);\n const alignment = getAlignment(placement);\n const isVertical = getSideAxis(placement) === 'y';\n const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1;\n const crossAxisMulti = rtl && isVertical ? -1 : 1;\n const rawValue = evaluate(options, state);\n let {\n mainAxis,\n crossAxis,\n alignmentAxis\n } = typeof rawValue === 'number' ? {\n mainAxis: rawValue,\n crossAxis: 0,\n alignmentAxis: null\n } : {\n mainAxis: 0,\n crossAxis: 0,\n alignmentAxis: null,\n ...rawValue\n };\n if (alignment && typeof alignmentAxis === 'number') {\n crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;\n }\n return isVertical ? {\n x: crossAxis * crossAxisMulti,\n y: mainAxis * mainAxisMulti\n } : {\n x: mainAxis * mainAxisMulti,\n y: crossAxis * crossAxisMulti\n };\n}\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = function (options) {\n if (options === void 0) {\n options = 0;\n }\n return {\n name: 'offset',\n options,\n async fn(state) {\n var _middlewareData$offse, _middlewareData$arrow;\n const {\n x,\n y,\n placement,\n middlewareData\n } = state;\n const diffCoords = await convertValueToCoords(state, options);\n\n // If the placement is the same and the arrow caused an alignment offset\n // then we don't need to change the positioning coordinates.\n if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n return {};\n }\n return {\n x: x + diffCoords.x,\n y: y + diffCoords.y,\n data: {\n ...diffCoords,\n placement\n }\n };\n }\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'shift',\n options,\n async fn(state) {\n const {\n x,\n y,\n placement\n } = state;\n const {\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = false,\n limiter = {\n fn: _ref => {\n let {\n x,\n y\n } = _ref;\n return {\n x,\n y\n };\n }\n },\n ...detectOverflowOptions\n } = evaluate(options, state);\n const coords = {\n x,\n y\n };\n const overflow = await detectOverflow(state, detectOverflowOptions);\n const crossAxis = getSideAxis(getSide(placement));\n const mainAxis = getOppositeAxis(crossAxis);\n let mainAxisCoord = coords[mainAxis];\n let crossAxisCoord = coords[crossAxis];\n if (checkMainAxis) {\n const minSide = mainAxis === 'y' ? 'top' : 'left';\n const maxSide = mainAxis === 'y' ? 'bottom' : 'right';\n const min = mainAxisCoord + overflow[minSide];\n const max = mainAxisCoord - overflow[maxSide];\n mainAxisCoord = clamp(min, mainAxisCoord, max);\n }\n if (checkCrossAxis) {\n const minSide = crossAxis === 'y' ? 'top' : 'left';\n const maxSide = crossAxis === 'y' ? 'bottom' : 'right';\n const min = crossAxisCoord + overflow[minSide];\n const max = crossAxisCoord - overflow[maxSide];\n crossAxisCoord = clamp(min, crossAxisCoord, max);\n }\n const limitedCoords = limiter.fn({\n ...state,\n [mainAxis]: mainAxisCoord,\n [crossAxis]: crossAxisCoord\n });\n return {\n ...limitedCoords,\n data: {\n x: limitedCoords.x - x,\n y: limitedCoords.y - y\n }\n };\n }\n };\n};\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n options,\n fn(state) {\n const {\n x,\n y,\n placement,\n rects,\n middlewareData\n } = state;\n const {\n offset = 0,\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = true\n } = evaluate(options, state);\n const coords = {\n x,\n y\n };\n const crossAxis = getSideAxis(placement);\n const mainAxis = getOppositeAxis(crossAxis);\n let mainAxisCoord = coords[mainAxis];\n let crossAxisCoord = coords[crossAxis];\n const rawOffset = evaluate(offset, state);\n const computedOffset = typeof rawOffset === 'number' ? {\n mainAxis: rawOffset,\n crossAxis: 0\n } : {\n mainAxis: 0,\n crossAxis: 0,\n ...rawOffset\n };\n if (checkMainAxis) {\n const len = mainAxis === 'y' ? 'height' : 'width';\n const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;\n const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;\n if (mainAxisCoord < limitMin) {\n mainAxisCoord = limitMin;\n } else if (mainAxisCoord > limitMax) {\n mainAxisCoord = limitMax;\n }\n }\n if (checkCrossAxis) {\n var _middlewareData$offse, _middlewareData$offse2;\n const len = mainAxis === 'y' ? 'width' : 'height';\n const isOriginSide = ['top', 'left'].includes(getSide(placement));\n const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);\n const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);\n if (crossAxisCoord < limitMin) {\n crossAxisCoord = limitMin;\n } else if (crossAxisCoord > limitMax) {\n crossAxisCoord = limitMax;\n }\n }\n return {\n [mainAxis]: mainAxisCoord,\n [crossAxis]: crossAxisCoord\n };\n }\n };\n};\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'size',\n options,\n async fn(state) {\n const {\n placement,\n rects,\n platform,\n elements\n } = state;\n const {\n apply = () => {},\n ...detectOverflowOptions\n } = evaluate(options, state);\n const overflow = await detectOverflow(state, detectOverflowOptions);\n const side = getSide(placement);\n const alignment = getAlignment(placement);\n const isYAxis = getSideAxis(placement) === 'y';\n const {\n width,\n height\n } = rects.floating;\n let heightSide;\n let widthSide;\n if (side === 'top' || side === 'bottom') {\n heightSide = side;\n widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right';\n } else {\n widthSide = side;\n heightSide = alignment === 'end' ? 'top' : 'bottom';\n }\n const overflowAvailableHeight = height - overflow[heightSide];\n const overflowAvailableWidth = width - overflow[widthSide];\n const noShift = !state.middlewareData.shift;\n let availableHeight = overflowAvailableHeight;\n let availableWidth = overflowAvailableWidth;\n if (isYAxis) {\n const maximumClippingWidth = width - overflow.left - overflow.right;\n availableWidth = alignment || noShift ? min(overflowAvailableWidth, maximumClippingWidth) : maximumClippingWidth;\n } else {\n const maximumClippingHeight = height - overflow.top - overflow.bottom;\n availableHeight = alignment || noShift ? min(overflowAvailableHeight, maximumClippingHeight) : maximumClippingHeight;\n }\n if (noShift && !alignment) {\n const xMin = max(overflow.left, 0);\n const xMax = max(overflow.right, 0);\n const yMin = max(overflow.top, 0);\n const yMax = max(overflow.bottom, 0);\n if (isYAxis) {\n availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));\n } else {\n availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));\n }\n }\n await apply({\n ...state,\n availableWidth,\n availableHeight\n });\n const nextDimensions = await platform.getDimensions(elements.floating);\n if (width !== nextDimensions.width || height !== nextDimensions.height) {\n return {\n reset: {\n rects: true\n }\n };\n }\n return {};\n }\n };\n};\n\nexport { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, shift, size };\n","function getNodeName(node) {\n if (isNode(node)) {\n return (node.nodeName || '').toLowerCase();\n }\n // Mocked nodes in testing environments may not be instances of Node. By\n // returning `#document` an infinite loop won't occur.\n // https://github.com/floating-ui/floating-ui/issues/2317\n return '#document';\n}\nfunction getWindow(node) {\n var _node$ownerDocument;\n return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;\n}\nfunction getDocumentElement(node) {\n var _ref;\n return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;\n}\nfunction isNode(value) {\n return value instanceof Node || value instanceof getWindow(value).Node;\n}\nfunction isElement(value) {\n return value instanceof Element || value instanceof getWindow(value).Element;\n}\nfunction isHTMLElement(value) {\n return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;\n}\nfunction isShadowRoot(value) {\n // Browsers without `ShadowRoot` support.\n if (typeof ShadowRoot === 'undefined') {\n return false;\n }\n return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;\n}\nfunction isOverflowElement(element) {\n const {\n overflow,\n overflowX,\n overflowY,\n display\n } = getComputedStyle(element);\n return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !['inline', 'contents'].includes(display);\n}\nfunction isTableElement(element) {\n return ['table', 'td', 'th'].includes(getNodeName(element));\n}\nfunction isContainingBlock(element) {\n const webkit = isWebKit();\n const css = getComputedStyle(element);\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n return css.transform !== 'none' || css.perspective !== 'none' || (css.containerType ? css.containerType !== 'normal' : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !webkit && (css.filter ? css.filter !== 'none' : false) || ['transform', 'perspective', 'filter'].some(value => (css.willChange || '').includes(value)) || ['paint', 'layout', 'strict', 'content'].some(value => (css.contain || '').includes(value));\n}\nfunction getContainingBlock(element) {\n let currentNode = getParentNode(element);\n while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {\n if (isContainingBlock(currentNode)) {\n return currentNode;\n } else {\n currentNode = getParentNode(currentNode);\n }\n }\n return null;\n}\nfunction isWebKit() {\n if (typeof CSS === 'undefined' || !CSS.supports) return false;\n return CSS.supports('-webkit-backdrop-filter', 'none');\n}\nfunction isLastTraversableNode(node) {\n return ['html', 'body', '#document'].includes(getNodeName(node));\n}\nfunction getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}\nfunction getNodeScroll(element) {\n if (isElement(element)) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n }\n return {\n scrollLeft: element.pageXOffset,\n scrollTop: element.pageYOffset\n };\n}\nfunction getParentNode(node) {\n if (getNodeName(node) === 'html') {\n return node;\n }\n const result =\n // Step into the shadow DOM of the parent of a slotted node.\n node.assignedSlot ||\n // DOM Element detected.\n node.parentNode ||\n // ShadowRoot detected.\n isShadowRoot(node) && node.host ||\n // Fallback.\n getDocumentElement(node);\n return isShadowRoot(result) ? result.host : result;\n}\nfunction getNearestOverflowAncestor(node) {\n const parentNode = getParentNode(node);\n if (isLastTraversableNode(parentNode)) {\n return node.ownerDocument ? node.ownerDocument.body : node.body;\n }\n if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {\n return parentNode;\n }\n return getNearestOverflowAncestor(parentNode);\n}\nfunction getOverflowAncestors(node, list, traverseIframes) {\n var _node$ownerDocument2;\n if (list === void 0) {\n list = [];\n }\n if (traverseIframes === void 0) {\n traverseIframes = true;\n }\n const scrollableAncestor = getNearestOverflowAncestor(node);\n const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);\n const win = getWindow(scrollableAncestor);\n if (isBody) {\n return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], win.frameElement && traverseIframes ? getOverflowAncestors(win.frameElement) : []);\n }\n return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));\n}\n\nexport { getComputedStyle, getContainingBlock, getDocumentElement, getNearestOverflowAncestor, getNodeName, getNodeScroll, getOverflowAncestors, getParentNode, getWindow, isContainingBlock, isElement, isHTMLElement, isLastTraversableNode, isNode, isOverflowElement, isShadowRoot, isTableElement, isWebKit };\n","import { rectToClientRect, autoPlacement as autoPlacement$1, shift as shift$1, flip as flip$1, size as size$1, hide as hide$1, arrow as arrow$1, inline as inline$1, limitShift as limitShift$1, computePosition as computePosition$1 } from '@floating-ui/core';\nexport { detectOverflow, offset } from '@floating-ui/core';\nimport { round, createCoords, max, min, floor } from '@floating-ui/utils';\nimport { getComputedStyle, isHTMLElement, isElement, getWindow, isWebKit, getDocumentElement, getNodeName, isOverflowElement, getNodeScroll, getOverflowAncestors, getParentNode, isLastTraversableNode, isContainingBlock, isTableElement, getContainingBlock } from '@floating-ui/utils/dom';\nexport { getOverflowAncestors } from '@floating-ui/utils/dom';\n\nfunction getCssDimensions(element) {\n const css = getComputedStyle(element);\n // In testing environments, the `width` and `height` properties are empty\n // strings for SVG elements, returning NaN. Fallback to `0` in this case.\n let width = parseFloat(css.width) || 0;\n let height = parseFloat(css.height) || 0;\n const hasOffset = isHTMLElement(element);\n const offsetWidth = hasOffset ? element.offsetWidth : width;\n const offsetHeight = hasOffset ? element.offsetHeight : height;\n const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;\n if (shouldFallback) {\n width = offsetWidth;\n height = offsetHeight;\n }\n return {\n width,\n height,\n $: shouldFallback\n };\n}\n\nfunction unwrapElement(element) {\n return !isElement(element) ? element.contextElement : element;\n}\n\nfunction getScale(element) {\n const domElement = unwrapElement(element);\n if (!isHTMLElement(domElement)) {\n return createCoords(1);\n }\n const rect = domElement.getBoundingClientRect();\n const {\n width,\n height,\n $\n } = getCssDimensions(domElement);\n let x = ($ ? round(rect.width) : rect.width) / width;\n let y = ($ ? round(rect.height) : rect.height) / height;\n\n // 0, NaN, or Infinity should always fallback to 1.\n\n if (!x || !Number.isFinite(x)) {\n x = 1;\n }\n if (!y || !Number.isFinite(y)) {\n y = 1;\n }\n return {\n x,\n y\n };\n}\n\nconst noOffsets = /*#__PURE__*/createCoords(0);\nfunction getVisualOffsets(element) {\n const win = getWindow(element);\n if (!isWebKit() || !win.visualViewport) {\n return noOffsets;\n }\n return {\n x: win.visualViewport.offsetLeft,\n y: win.visualViewport.offsetTop\n };\n}\nfunction shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {\n if (isFixed === void 0) {\n isFixed = false;\n }\n if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {\n return false;\n }\n return isFixed;\n}\n\nfunction getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {\n if (includeScale === void 0) {\n includeScale = false;\n }\n if (isFixedStrategy === void 0) {\n isFixedStrategy = false;\n }\n const clientRect = element.getBoundingClientRect();\n const domElement = unwrapElement(element);\n let scale = createCoords(1);\n if (includeScale) {\n if (offsetParent) {\n if (isElement(offsetParent)) {\n scale = getScale(offsetParent);\n }\n } else {\n scale = getScale(element);\n }\n }\n const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);\n let x = (clientRect.left + visualOffsets.x) / scale.x;\n let y = (clientRect.top + visualOffsets.y) / scale.y;\n let width = clientRect.width / scale.x;\n let height = clientRect.height / scale.y;\n if (domElement) {\n const win = getWindow(domElement);\n const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;\n let currentWin = win;\n let currentIFrame = currentWin.frameElement;\n while (currentIFrame && offsetParent && offsetWin !== currentWin) {\n const iframeScale = getScale(currentIFrame);\n const iframeRect = currentIFrame.getBoundingClientRect();\n const css = getComputedStyle(currentIFrame);\n const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;\n const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;\n x *= iframeScale.x;\n y *= iframeScale.y;\n width *= iframeScale.x;\n height *= iframeScale.y;\n x += left;\n y += top;\n currentWin = getWindow(currentIFrame);\n currentIFrame = currentWin.frameElement;\n }\n }\n return rectToClientRect({\n width,\n height,\n x,\n y\n });\n}\n\nconst topLayerSelectors = [':popover-open', ':modal'];\nfunction isTopLayer(floating) {\n return topLayerSelectors.some(selector => {\n try {\n return floating.matches(selector);\n } catch (e) {\n return false;\n }\n });\n}\n\nfunction convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {\n let {\n elements,\n rect,\n offsetParent,\n strategy\n } = _ref;\n const isFixed = strategy === 'fixed';\n const documentElement = getDocumentElement(offsetParent);\n const topLayer = elements ? isTopLayer(elements.floating) : false;\n if (offsetParent === documentElement || topLayer && isFixed) {\n return rect;\n }\n let scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n let scale = createCoords(1);\n const offsets = createCoords(0);\n const isOffsetParentAnElement = isHTMLElement(offsetParent);\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n if (isHTMLElement(offsetParent)) {\n const offsetRect = getBoundingClientRect(offsetParent);\n scale = getScale(offsetParent);\n offsets.x = offsetRect.x + offsetParent.clientLeft;\n offsets.y = offsetRect.y + offsetParent.clientTop;\n }\n }\n return {\n width: rect.width * scale.x,\n height: rect.height * scale.y,\n x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x,\n y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y\n };\n}\n\nfunction getClientRects(element) {\n return Array.from(element.getClientRects());\n}\n\nfunction getWindowScrollBarX(element) {\n // If <html> has a CSS width greater than the viewport, then this will be\n // incorrect for RTL.\n return getBoundingClientRect(getDocumentElement(element)).left + getNodeScroll(element).scrollLeft;\n}\n\n// Gets the entire size of the scrollable document area, even extending outside\n// of the `<html>` and `<body>` rect bounds if horizontally scrollable.\nfunction getDocumentRect(element) {\n const html = getDocumentElement(element);\n const scroll = getNodeScroll(element);\n const body = element.ownerDocument.body;\n const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);\n const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);\n let x = -scroll.scrollLeft + getWindowScrollBarX(element);\n const y = -scroll.scrollTop;\n if (getComputedStyle(body).direction === 'rtl') {\n x += max(html.clientWidth, body.clientWidth) - width;\n }\n return {\n width,\n height,\n x,\n y\n };\n}\n\nfunction getViewportRect(element, strategy) {\n const win = getWindow(element);\n const html = getDocumentElement(element);\n const visualViewport = win.visualViewport;\n let width = html.clientWidth;\n let height = html.clientHeight;\n let x = 0;\n let y = 0;\n if (visualViewport) {\n width = visualViewport.width;\n height = visualViewport.height;\n const visualViewportBased = isWebKit();\n if (!visualViewportBased || visualViewportBased && strategy === 'fixed') {\n x = visualViewport.offsetLeft;\n y = visualViewport.offsetTop;\n }\n }\n return {\n width,\n height,\n x,\n y\n };\n}\n\n// Returns the inner client rect, subtracting scrollbars if present.\nfunction getInnerBoundingClientRect(element, strategy) {\n const clientRect = getBoundingClientRect(element, true, strategy === 'fixed');\n const top = clientRect.top + element.clientTop;\n const left = clientRect.left + element.clientLeft;\n const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);\n const width = element.clientWidth * scale.x;\n const height = element.clientHeight * scale.y;\n const x = left * scale.x;\n const y = top * scale.y;\n return {\n width,\n height,\n x,\n y\n };\n}\nfunction getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {\n let rect;\n if (clippingAncestor === 'viewport') {\n rect = getViewportRect(element, strategy);\n } else if (clippingAncestor === 'document') {\n rect = getDocumentRect(getDocumentElement(element));\n } else if (isElement(clippingAncestor)) {\n rect = getInnerBoundingClientRect(clippingAncestor, strategy);\n } else {\n const visualOffsets = getVisualOffsets(element);\n rect = {\n ...clippingAncestor,\n x: clippingAncestor.x - visualOffsets.x,\n y: clippingAncestor.y - visualOffsets.y\n };\n }\n return rectToClientRect(rect);\n}\nfunction hasFixedPositionAncestor(element, stopNode) {\n const parentNode = getParentNode(element);\n if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {\n return false;\n }\n return getComputedStyle(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode);\n}\n\n// A \"clipping ancestor\" is an `overflow` element with the characteristic of\n// clipping (or hiding) child elements. This returns all clipping ancestors\n// of the given element up the tree.\nfunction getClippingElementAncestors(element, cache) {\n const cachedResult = cache.get(element);\n if (cachedResult) {\n return cachedResult;\n }\n let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body');\n let currentContainingBlockComputedStyle = null;\n const elementIsFixed = getComputedStyle(element).position === 'fixed';\n let currentNode = elementIsFixed ? getParentNode(element) : element;\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {\n const computedStyle = getComputedStyle(currentNode);\n const currentNodeIsContaining = isContainingBlock(currentNode);\n if (!currentNodeIsContaining && computedStyle.position === 'fixed') {\n currentContainingBlockComputedStyle = null;\n }\n const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && ['absolute', 'fixed'].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);\n if (shouldDropCurrentNode) {\n // Drop non-containing blocks.\n result = result.filter(ancestor => ancestor !== currentNode);\n } else {\n // Record last containing block for next iteration.\n currentContainingBlockComputedStyle = computedStyle;\n }\n currentNode = getParentNode(currentNode);\n }\n cache.set(element, result);\n return result;\n}\n\n// Gets the maximum area that the element is visible in due to any number of\n// clipping ancestors.\nfunction getClippingRect(_ref) {\n let {\n element,\n boundary,\n rootBoundary,\n strategy\n } = _ref;\n const elementClippingAncestors = boundary === 'clippingAncestors' ? getClippingElementAncestors(element, this._c) : [].concat(boundary);\n const clippingAncestors = [...elementClippingAncestors, rootBoundary];\n const firstClippingAncestor = clippingAncestors[0];\n const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {\n const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);\n accRect.top = max(rect.top, accRect.top);\n accRect.right = min(rect.right, accRect.right);\n accRect.bottom = min(rect.bottom, accRect.bottom);\n accRect.left = max(rect.left, accRect.left);\n return accRect;\n }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));\n return {\n width: clippingRect.right - clippingRect.left,\n height: clippingRect.bottom - clippingRect.top,\n x: clippingRect.left,\n y: clippingRect.top\n };\n}\n\nfunction getDimensions(element) {\n const {\n width,\n height\n } = getCssDimensions(element);\n return {\n width,\n height\n };\n}\n\nfunction getRectRelativeToOffsetParent(element, offsetParent, strategy) {\n const isOffsetParentAnElement = isHTMLElement(offsetParent);\n const documentElement = getDocumentElement(offsetParent);\n const isFixed = strategy === 'fixed';\n const rect = getBoundingClientRect(element, true, isFixed, offsetParent);\n let scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n const offsets = createCoords(0);\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n if (isOffsetParentAnElement) {\n const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);\n offsets.x = offsetRect.x + offsetParent.clientLeft;\n offsets.y = offsetRect.y + offsetParent.clientTop;\n } else if (documentElement) {\n offsets.x = getWindowScrollBarX(documentElement);\n }\n }\n const x = rect.left + scroll.scrollLeft - offsets.x;\n const y = rect.top + scroll.scrollTop - offsets.y;\n return {\n x,\n y,\n width: rect.width,\n height: rect.height\n };\n}\n\nfunction getTrueOffsetParent(element, polyfill) {\n if (!isHTMLElement(element) || getComputedStyle(element).position === 'fixed') {\n return null;\n }\n if (polyfill) {\n return polyfill(element);\n }\n return element.offsetParent;\n}\n\n// Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\nfunction getOffsetParent(element, polyfill) {\n const window = getWindow(element);\n if (!isHTMLElement(element) || isTopLayer(element)) {\n return window;\n }\n let offsetParent = getTrueOffsetParent(element, polyfill);\n while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {\n offsetParent = getTrueOffsetParent(offsetParent, polyfill);\n }\n if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static' && !isContainingBlock(offsetParent))) {\n return window;\n }\n return offsetParent || getContainingBlock(element) || window;\n}\n\nconst getElementRects = async function (data) {\n const getOffsetParentFn = this.getOffsetParent || getOffsetParent;\n const getDimensionsFn = this.getDimensions;\n return {\n reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),\n floating: {\n x: 0,\n y: 0,\n ...(await getDimensionsFn(data.floating))\n }\n };\n};\n\nfunction isRTL(element) {\n return getComputedStyle(element).direction === 'rtl';\n}\n\nconst platform = {\n convertOffsetParentRelativeRectToViewportRelativeRect,\n getDocumentElement,\n getClippingRect,\n getOffsetParent,\n getElementRects,\n getClientRects,\n getDimensions,\n getScale,\n isElement,\n isRTL\n};\n\n// https://samthor.au/2021/observing-dom/\nfunction observeMove(element, onMove) {\n let io = null;\n let timeoutId;\n const root = getDocumentElement(element);\n function cleanup() {\n var _io;\n clearTimeout(timeoutId);\n (_io = io) == null || _io.disconnect();\n io = null;\n }\n function refresh(skip, threshold) {\n if (skip === void 0) {\n skip = false;\n }\n if (threshold === void 0) {\n threshold = 1;\n }\n cleanup();\n const {\n left,\n top,\n width,\n height\n } = element.getBoundingClientRect();\n if (!skip) {\n onMove();\n }\n if (!width || !height) {\n return;\n }\n const insetTop = floor(top);\n const insetRight = floor(root.clientWidth - (left + width));\n const insetBottom = floor(root.clientHeight - (top + height));\n const insetLeft = floor(left);\n const rootMargin = -insetTop + \"px \" + -insetRight + \"px \" + -insetBottom + \"px \" + -insetLeft + \"px\";\n const options = {\n rootMargin,\n threshold: max(0, min(1, threshold)) || 1\n };\n let isFirstUpdate = true;\n function handleObserve(entries) {\n const ratio = entries[0].intersectionRatio;\n if (ratio !== threshold) {\n if (!isFirstUpdate) {\n return refresh();\n }\n if (!ratio) {\n timeoutId = setTimeout(() => {\n refresh(false, 1e-7);\n }, 100);\n } else {\n refresh(false, ratio);\n }\n }\n isFirstUpdate = false;\n }\n\n // Older browsers don't support a `document` as the root and will throw an\n // error.\n try {\n io = new IntersectionObserver(handleObserve, {\n ...options,\n // Handle <iframe>s\n root: root.ownerDocument\n });\n } catch (e) {\n io = new IntersectionObserver(handleObserve, options);\n }\n io.observe(element);\n }\n refresh(true);\n return cleanup;\n}\n\n/**\n * Automatically updates the position of the floating element when necessary.\n * Should only be called when the floating element is mounted on the DOM or\n * visible on the screen.\n * @returns cleanup function that should be invoked when the floating element is\n * removed from the DOM or hidden from the screen.\n * @see https://floating-ui.com/docs/autoUpdate\n */\nfunction autoUpdate(reference, floating, update, options) {\n if (options === void 0) {\n options = {};\n }\n const {\n ancestorScroll = true,\n ancestorResize = true,\n elementResize = typeof ResizeObserver === 'function',\n layoutShift = typeof IntersectionObserver === 'function',\n animationFrame = false\n } = options;\n const referenceEl = unwrapElement(reference);\n const ancestors = ancestorScroll || ancestorResize ? [...(referenceEl ? getOverflowAncestors(referenceEl) : []), ...getOverflowAncestors(floating)] : [];\n ancestors.forEach(ancestor => {\n ancestorScroll && ancestor.addEventListener('scroll', update, {\n passive: true\n });\n ancestorResize && ancestor.addEventListener('resize', update);\n });\n const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;\n let reobserveFrame = -1;\n let resizeObserver = null;\n if (elementResize) {\n resizeObserver = new ResizeObserver(_ref => {\n let [firstEntry] = _ref;\n if (firstEntry && firstEntry.target === referenceEl && resizeObserver) {\n // Prevent update loops when using the `size` middleware.\n // https://github.com/floating-ui/floating-ui/issues/1740\n resizeObserver.unobserve(floating);\n cancelAnimationFrame(reobserveFrame);\n reobserveFrame = requestAnimationFrame(() => {\n var _resizeObserver;\n (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);\n });\n }\n update();\n });\n if (referenceEl && !animationFrame) {\n resizeObserver.observe(referenceEl);\n }\n resizeObserver.observe(floating);\n }\n let frameId;\n let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;\n if (animationFrame) {\n frameLoop();\n }\n function frameLoop() {\n const nextRefRect = getBoundingClientRect(reference);\n if (prevRefRect && (nextRefRect.x !== prevRefRect.x || nextRefRect.y !== prevRefRect.y || nextRefRect.width !== prevRefRect.width || nextRefRect.height !== prevRefRect.height)) {\n update();\n }\n prevRefRect = nextRefRect;\n frameId = requestAnimationFrame(frameLoop);\n }\n update();\n return () => {\n var _resizeObserver2;\n ancestors.forEach(ancestor => {\n ancestorScroll && ancestor.removeEventListener('scroll', update);\n ancestorResize && ancestor.removeEventListener('resize', update);\n });\n cleanupIo == null || cleanupIo();\n (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();\n resizeObserver = null;\n if (animationFrame) {\n cancelAnimationFrame(frameId);\n }\n };\n}\n\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = autoPlacement$1;\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = shift$1;\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = flip$1;\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = size$1;\n\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = hide$1;\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = arrow$1;\n\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = inline$1;\n\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = limitShift$1;\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a given reference element.\n */\nconst computePosition = (reference, floating, options) => {\n // This caches the expensive `getClippingElementAncestors` function so that\n // multiple lifecycle resets re-use the same result. It only lives for a\n // single call. If other functions become expensive, we can add them as well.\n const cache = new Map();\n const mergedOptions = {\n platform,\n ...options\n };\n const platformWithCache = {\n ...mergedOptions.platform,\n _c: cache\n };\n return computePosition$1(reference, floating, {\n ...mergedOptions,\n platform: platformWithCache\n });\n};\n\nexport { arrow, autoPlacement, autoUpdate, computePosition, flip, hide, inline, limitShift, platform, shift, size };\n","export const widgetHTML = `<div id=\"langchat-chat-widget__header\"><div id=\"langchat-chat-widget__title\"><svg height=\"19\" id=\"langchat-chat-widget__title_icon\" viewBox=\"0 0 24 19\" width=\"24\"><path d=\"M9 6C9.55229 6 10 6.44772 10 7V9C10 9.55228 9.55229 10 9 10C8.44771 10 8 9.55228 8 9V7C8 6.44772 8.44771 6 9 6Z\"/><path d=\"M16 7C16 6.44772 15.5523 6 15 6C14.4477 6 14 6.44772 14 7V9C14 9.55228 14.4477 10 15 10C15.5523 10 16 9.55228 16 9V7Z\"/><path d=\"M19.2099 16C19.0086 16 18.815 16.0768 18.6684 16.2147L16.4858 18.269C15.2525 19.4298 13.2248 18.6278 13.1191 16.9374C13.0862 16.4105 12.6493 16 12.1213 16H5C3.34315 16 2 14.6569 2 13V9C2 9.55228 1.55228 10 1 10C0.447715 10 0 9.55228 0 9V6C0 5.44772 0.447715 5 1 5C1.55228 5 2 5.44772 2 6V3C2 1.34315 3.34315 0 5 0H19C20.6569 0 22 1.34315 22 3V6C22 5.44772 22.4477 5 23 5C23.5523 5 24 5.44772 24 6V9C24 9.55228 23.5523 10 23 10C22.4477 10 22 9.55228 22 9V13.2099C22 14.7508 20.7508 16 19.2099 16ZM5 2C4.44772 2 4 2.44772 4 3V13C4 13.5523 4.44772 14 5 14H12.1213C13.7053 14 15.0163 15.2315 15.1152 16.8124L17.2977 14.7583C17.8152 14.2712 18.4992 14 19.2099 14C19.6463 14 20 13.6463 20 13.2099V3C20 2.44772 19.5523 2 19 2H5Z\"/></svg></div><div><a href=\"https://github.com/tycoding/langchat\" id=\"langchat-chat-widget__branding\" target=\"_blank\">Powered by&nbsp;<span>LangChat</span></a></div></div><div id=\"langchat-chat-widget__body\"><form id=\"langchat-chat-widget__form\"><input aria-label=\"Message\" autocomplete=\"off\" id=\"langchat-chat-widget__input\" name=\"message\" placeholder=\"Ask me a question…\" required type=\"text\"><button id=\"langchat-chat-widget__submit\" type=\"submit\"><svg height=\"26\" viewBox=\"0 0 26 26\" width=\"26\" xmlns=\"http://www.w3.org/2000/svg\"><g fill=\"none\"><path d=\"M24 0v24H0V0zM12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035q-.016-.005-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427q-.004-.016-.017-.018m.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093q.019.005.029-.008l.004-.014l-.034-.614q-.005-.019-.02-.022m-.715.002a.02.02 0 0 0-.027.006l-.006.014l-.034.614q.001.018.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01z\"></path><path d=\"m21.433 4.861l-6 15.5a1 1 0 0 1-1.624.362l-3.382-3.235l-2.074 2.073a.5.5 0 0 1-.853-.354v-4.519L2.309 9.723a1 1 0 0 1 .442-1.691l17.5-4.5a1 1 0 0 1 1.181 1.329ZM19 6.001L8.032 13.152l1.735 1.66L19 6Z\" fill=\"currentColor\"></path></g></svg></button></form></div>`;\n","import {createFocusTrap} from \"focus-trap\";\nimport {marked} from \"marked\";\nimport css from \"./widget.css\";\nimport {autoUpdate, computePosition, flip, shift} from \"@floating-ui/dom\";\nimport {widgetHTML} from \"./widgetHtmlString\";\n\nconst WIDGET_BACKDROP_ID = \"langchat-chat-widget__backdrop\";\nconst WIDGET_CONTAINER_ID = \"langchat-chat-widget__container\";\nconst WIDGET_MESSAGES_HISTORY_CONTAINER_ID =\n \"langchat-chat-widget__messages_history\";\nconst WIDGET_THINKING_BUBBLE_ID = \"langchat-chat-widget__thinking_bubble\";\n\nexport type WidgetConfig = {\n url: string;\n apiKey: string;\n threadId: string | null;\n responseIsAStream: boolean;\n user: Record<any, any>;\n widgetTitle: string;\n greetingMessage: string | null;\n disableErrorAlert: boolean;\n closeOnOutsideClick: boolean;\n openOnLoad: boolean;\n};\n\nconst renderer = new marked.Renderer();\nconst linkRenderer = renderer.link;\n// To open links in a new tab\nrenderer.link = (href, title, text) => {\n const parsed = linkRenderer.call(renderer, href, title, text);\n return parsed.replace(/^<a /, '<a target=\"_blank\" rel=\"nofollow\" ');\n};\n\nconst config: WidgetConfig = {\n url: \"\",\n apiKey: \"\",\n threadId: null,\n responseIsAStream: false,\n user: {},\n widgetTitle: \"LangChat\",\n greetingMessage: null,\n disableErrorAlert: false,\n closeOnOutsideClick: true,\n openOnLoad: false,\n ...(window as any).langchatChatWidget?.config,\n};\n\nlet cleanup = () => {\n};\n\nasync function init() {\n const styleElement = document.createElement(\"style\");\n styleElement.innerHTML = css;\n\n document.head.insertBefore(styleElement, document.head.firstChild);\n\n // Slight delay to allow DOMContent to be fully loaded\n // (particularly for the button to be available in the `if (config.openOnLoad)` block below).\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n document\n .querySelector(\"[data-langchat-chat-widget-button]\")\n ?.addEventListener(\"click\", open);\n\n if (config.openOnLoad) {\n const target = document.querySelector(\n \"[data-langchat-chat-widget-button]\"\n );\n open({target} as Event);\n }\n}\n\nwindow.addEventListener(\"load\", init);\n\nconst containerElement = document.createElement(\"div\");\ncontainerElement.id = WIDGET_CONTAINER_ID;\n\nconst messagesHistory = document.createElement(\"div\");\nmessagesHistory.id = WIDGET_MESSAGES_HISTORY_CONTAINER_ID;\n\nconst optionalBackdrop = document.createElement(\"div\");\noptionalBackdrop.id = WIDGET_BACKDROP_ID;\n\nconst thinkingBubble = document.createElement(\"div\");\nthinkingBubble.id = WIDGET_THINKING_BUBBLE_ID;\nthinkingBubble.innerHTML = `\n <span class=\"circle\"></span>\n <span class=\"circle\"></span>\n <span class=\"circle\"></span>\n `;\n\nconst trap = createFocusTrap(containerElement, {\n initialFocus: \"#langchat-chat-widget__input\",\n allowOutsideClick: true,\n});\n\nfunction open(e: Event) {\n if (config.closeOnOutsideClick) {\n document.body.appendChild(optionalBackdrop);\n }\n\n if (containerElement.hasChildNodes()) {\n close()\n return;\n }\n document.body.appendChild(containerElement);\n containerElement.innerHTML = widgetHTML;\n containerElement.style.display = \"block\";\n\n const chatbotHeaderTitleText = document.createElement(\"span\");\n chatbotHeaderTitleText.id = \"langchat-chat-widget__title_text\";\n chatbotHeaderTitleText.textContent = config.widgetTitle;\n const chatbotHeaderTitle = document.getElementById(\n \"langchat-chat-widget__title\"\n )!;\n chatbotHeaderTitle.appendChild(chatbotHeaderTitleText);\n\n const chatbotBody = document.getElementById(\"langchat-chat-widget__body\")!;\n chatbotBody.prepend(messagesHistory);\n if (config.greetingMessage && messagesHistory.children.length === 0) {\n createNewMessageEntry(config.greetingMessage, Date.now(), \"system\");\n }\n\n const target = (e?.target as HTMLElement) || document.body;\n cleanup = autoUpdate(target, containerElement, () => {\n computePosition(target, containerElement, {\n placement: \"top-start\",\n middleware: [flip(), shift({crossAxis: true, padding: 8})],\n strategy: \"fixed\",\n }).then(({x, y}) => {\n Object.assign(containerElement.style, {\n left: `${x}px`,\n top: `${y - 10}px`,\n });\n });\n });\n\n trap.activate();\n\n if (config.closeOnOutsideClick) {\n document\n .getElementById(WIDGET_BACKDROP_ID)!\n .addEventListener(\"click\", close);\n }\n\n document\n .getElementById(\"langchat-chat-widget__form\")!\n .addEventListener(\"submit\", submit);\n}\n\nfunction close() {\n trap.deactivate();\n\n containerElement.innerHTML = \"\";\n\n containerElement.remove();\n optionalBackdrop.remove();\n cleanup();\n cleanup = () => {\n };\n}\n\nasync function createNewMessageEntry(\n message: string,\n timestamp: number,\n from: \"system\" | \"user\"\n) {\n const messageElement = document.createElement(\"div\");\n messageElement.classList.add(\"langchat-chat-widget__message\");\n messageElement.classList.add(`langchat-chat-widget__message--${from}`);\n messageElement.id = `langchat-chat-widget__message--${from}--${timestamp}`;\n\n const messageText = document.createElement(\"p\");\n messageText.innerHTML = await marked(message, {renderer});\n messageElement.appendChild(messageText);\n\n const messageTimestamp = document.createElement(\"p\");\n messageTimestamp.classList.add(\"langchat-chat-widget__message-timestamp\");\n messageTimestamp.textContent =\n (\"0\" + new Date(timestamp).getHours()).slice(-2) + // Hours (padded with 0 if needed)\n \":\" +\n (\"0\" + new Date(timestamp).getMinutes()).slice(-2); // Minutes (padded with 0 if needed)\n messageElement.appendChild(messageTimestamp);\n\n messagesHistory.prepend(messageElement);\n}\n\nconst handleStandardResponse = async (res: Response) => {\n if (res.ok) {\n const {\n message: responseMessage,\n threadId: responseThreadId,\n }: {\n message: string | undefined;\n threadId: string | undefined;\n } = await res.json();\n\n if (typeof responseThreadId !== \"string\") {\n console.error(\"LangChat Chat Widget: Server error\", res);\n if (!config.disableErrorAlert)\n alert(\n `Received an OK response but \"threadId\" was of incompatible type (expected 'string', received '${typeof responseThreadId}'). Please make sure the API response is configured correctly.\n\nYou can learn more here: https://github.com/rowyio/langchat-chat-widget?tab=readme-ov-file#connecting-the-widget-to-your-langchat-workflow`\n );\n return;\n }\n\n if (typeof responseMessage !== \"string\") {\n console.error(\"LangChat Chat Widget: Server error\", res);\n if (!config.disableErrorAlert)\n alert(\n `Received an OK response but \"message\" was of incompatible type (expected 'string', received '${typeof responseMessage}'). Please make sure the API response is configured correctly.\n\nYou can learn more here: https://github.com/rowyio/langchat-chat-widget?tab=readme-ov-file#connecting-the-widget-to-your-langchat-workflow`\n );\n return;\n }\n\n if (!responseMessage && responseMessage !== \"\") {\n console.error(\"LangChat Chat Widget: Server error\", res);\n if (!config.disableErrorAlert)\n alert(\n `Received an OK response but no message was found. Please make sure the API response is configured correctly. You can learn more here:\\n\\nhttps://github.com/rowyio/langchat-chat-widget?tab=readme-ov-file#connecting-the-widget-to-your-langchat-workflow`\n );\n return;\n }\n\n await createNewMessageEntry(responseMessage, Date.now(), \"system\");\n config.threadId = config.threadId ?? responseThreadId ?? null;\n } else {\n console.error(\"LangChat Chat Widget: Server error\", res);\n if (!config.disableErrorAlert)\n alert(`Could not send message: ${res.statusText}`);\n }\n};\n\nasync function streamResponseToMessageEntry(\n message: string,\n timestamp: number,\n from: \"system\" | \"user\"\n) {\n const existingMessageElement = messagesHistory.querySelector(\n `#langchat-chat-widget__message--${from}--${timestamp}`\n );\n if (existingMessageElement) {\n // If the message element already exists, update the text\n const messageText = existingMessageElement.querySelector(\"p\")!;\n messageText.innerHTML = await marked(message, {renderer});\n return;\n } else {\n // If the message element doesn't exist yet, create a new one\n await createNewMessageEntry(message, timestamp, from);\n }\n}\n\nconst handleStreamedResponse = async (res: Response) => {\n if (!res.body) {\n console.error(\"LangChat Chat Widget: Streamed response has no body\", res);\n if (!config.disableErrorAlert)\n alert(\n `Received a streamed response but no body was found. Please make sure the API response is configured correctly.`\n );\n return;\n }\n\n const threadIdFromHeader = res.headers.get(\"x-thread-id\");\n\n let responseMessage = \"\";\n let responseThreadId = \"\";\n let responseMessageComplete = false;\n let ts = Date.now();\n const reader = res.body.getReader();\n\n while (true) {\n const {value, done} = await reader.read();\n if (done || value === undefined) {\n break;\n }\n const decoded = new TextDecoder().decode(value, {stream: true});\n\n const messages = decoded.split('\\n');\n\n for (const item of messages) {\n const message = item\n if (message.startsWith('data:{') || message.startsWith('{')) {\n let data = '';\n if (message.startsWith('data:{')) {\n data = message.slice(5).trim();\n }\n if (message.startsWith('{')) {\n data = message.trim();\n }\n\n try {\n const jsonData = JSON.parse(data);\n const choice = jsonData.choices[0];\n\n if (choice.finishReason === 'STOP') {\n responseMessageComplete = true;\n return;\n }\n const content = choice.delta.content;\n responseMessage += content;\n } catch (error) {\n responseMessageComplete = true;\n console.error('Failed to parse JSON:', error);\n }\n }\n }\n\n await streamResponseToMessageEntry(responseMessage, ts, \"system\");\n }\n\n config.threadId =\n config.threadId ??\n threadIdFromHeader ?? // If the threadId isn't set, use the one from the header\n (responseThreadId !== \"\" ? responseThreadId : null); // If the threadId isn't set and one isn't included in the header, use the one from the response\n};\n\nasync function submit(e: Event) {\n e.preventDefault();\n const target = e.target as HTMLFormElement;\n\n if (!config.url) {\n console.error(\"LangChat Chat Widget: No URL provided\");\n if (!config.disableErrorAlert)\n alert(\"Could not send chat message: No URL provided\");\n return;\n }\n\n const submitElement = document.getElementById(\n \"langchat-chat-widget__submit\"\n )!;\n submitElement.setAttribute(\"disabled\", \"\");\n\n const requestHeaders = new Headers();\n requestHeaders.append(\"Content-Type\", \"application/json\");\n requestHeaders.append(\"Accept\", \"text/event-stream\");\n requestHeaders.append(\"Authorization\", `Bearer ${config.apiKey}`);\n\n const message = (target.elements as any).message.value\n const data = {\n ...config.user,\n messages: [{\n role: 'user',\n content: message,\n }],\n threadId: config.threadId,\n timestamp: Date.now(),\n };\n\n await createNewMessageEntry(message, data.timestamp, \"user\");\n target.reset();\n messagesHistory.prepend(thinkingBubble);\n\n try {\n let response = await fetch(config.url, {\n method: \"POST\",\n headers: requestHeaders,\n body: JSON.stringify(data),\n });\n thinkingBubble.remove();\n\n if (config.responseIsAStream) {\n await handleStreamedResponse(response);\n } else {\n await handleStandardResponse(response);\n }\n } catch (e: any) {\n thinkingBubble.remove();\n console.error(\"LangChat Chat Widget:\", e);\n if (!config.disableErrorAlert) {\n alert(`Could not send message: ${e.message}`);\n }\n }\n\n submitElement.removeAttribute(\"disabled\");\n return false;\n}\n\nconst langchatChatWidget = {open, close, config, init};\n(window as any).langchatChatWidget = langchatChatWidget;\ndeclare global {\n interface Window {\n langchatChatWidget: typeof langchatChatWidget;\n }\n}\n\nexport default langchatChatWidget;\n"],"names":["candidateSelectors","candidateSelector","join","NoElement","Element","matches","prototype","msMatchesSelector","webkitMatchesSelector","getRootNode","element","_element$getRootNode","call","ownerDocument","isInert","node","lookUp","_node$getAttribute","inertAtt","getAttribute","parentNode","getCandidates","el","includeContainer","filter","candidates","Array","slice","apply","querySelectorAll","unshift","getCandidatesIteratively","elements","options","elementsToCheck","from","length","shift","tagName","assigned","assignedElements","nestedCandidates","children","flatten","push","scopeParent","includes","shadowRoot","getShadowRoot","validShadowRoot","shadowRootFilter","_nestedCandidates","hasTabIndex","isNaN","parseInt","getTabIndex","Error","tabIndex","test","_node$getAttribute2","attValue","isContentEditable","sortOrderedTabbables","a","b","documentOrder","isInput","isZeroArea","_node$getBoundingClie","getBoundingClientRect","width","height","isNodeMatchingSelectorFocusable","disabled","type","isHiddenInput","_ref","displayCheck","getComputedStyle","visibility","isDirectSummary","parentElement","originalNode","rootNode","assignedSlot","host","_nodeRoot","_nodeRootHost","_nodeRootHost$ownerDo","_node$ownerDocument","nodeRoot","nodeRootHost","attached","contains","_nodeRoot2","_nodeRootHost2","_nodeRootHost2$ownerD","isNodeAttached","getClientRects","isHidden","some","child","isDetailsWithSummary","i","item","isDisabledFromFieldset","isNodeMatchingSelectorTabbable","isRadio","name","radioSet","radioScope","form","queryRadios","window","CSS","escape","err","console","error","message","checked","nodes","getCheckedRadio","isTabbableRadio","isNonTabbableRadio","isValidShadowRootTabbable","shadowHostNode","sortByOrder","regularTabbables","orderedTabbables","forEach","isScope","candidateTabindex","getSortOrderTabIndex","content","sort","reduce","acc","sortable","concat","isTabbable","focusableCandidateSelector","isFocusable","isTabEvent","e","key","keyCode","isKeyForward","shiftKey","isKeyBackward","delay","fn","setTimeout","findIndex","arr","idx","every","value","valueOrHandler","_len","arguments","params","_key","getActualTarget","event","target","composedPath","internalTrapStack","_defaults","async","breaks","extensions","gfm","hooks","pedantic","renderer","silent","tokenizer","walkTokens","changeDefaults","newDefaults","min","Math","max","round","floor","createCoords","v","x","y","oppositeSideMap","left","right","bottom","top","oppositeAlignmentMap","start","end","clamp","evaluate","param","getSide","placement","split","getAlignment","getOppositeAxis","axis","getAxisLength","getSideAxis","getAlignmentAxis","getOppositeAlignmentPlacement","replace","alignment","getOppositePlacement","side","rectToClientRect","rect","computeCoordsFromPlacement","rtl","reference","floating","sideAxis","alignmentAxis","alignLength","isVertical","commonX","commonY","commonAlign","coords","detectOverflow","state","_await$platform$isEle","platform","rects","strategy","boundary","rootBoundary","elementContext","altBoundary","padding","paddingObject","expandPaddingObject","getPaddingObject","clippingClientRect","getClippingRect","isElement","contextElement","getDocumentElement","offsetParent","getOffsetParent","offsetScale","getScale","elementClientRect","convertOffsetParentRelativeRectToViewportRelativeRect","getNodeName","isNode","nodeName","toLowerCase","getWindow","defaultView","document","documentElement","Node","isHTMLElement","HTMLElement","isShadowRoot","ShadowRoot","isOverflowElement","overflow","overflowX","overflowY","display","isTableElement","isContainingBlock","webkit","isWebKit","css","transform","perspective","containerType","backdropFilter","willChange","contain","supports","isLastTraversableNode","getNodeScroll","scrollLeft","scrollTop","pageXOffset","pageYOffset","getParentNode","result","getNearestOverflowAncestor","body","getOverflowAncestors","list","traverseIframes","_node$ownerDocument2","scrollableAncestor","isBody","win","visualViewport","frameElement","getCssDimensions","parseFloat","hasOffset","offsetWidth","offsetHeight","shouldFallback","$","unwrapElement","domElement","Number","isFinite","noOffsets","getVisualOffsets","offsetLeft","offsetTop","includeScale","isFixedStrategy","clientRect","scale","visualOffsets","isFixed","floatingOffsetParent","shouldAddVisualOffsets","offsetWin","currentWin","currentIFrame","iframeScale","iframeRect","clientLeft","paddingLeft","clientTop","paddingTop","topLayerSelectors","isTopLayer","selector","getWindowScrollBarX","getClientRectFromClippingAncestor","clippingAncestor","html","clientWidth","clientHeight","visualViewportBased","getViewportRect","scroll","scrollWidth","scrollHeight","direction","getDocumentRect","getInnerBoundingClientRect","hasFixedPositionAncestor","stopNode","position","getRectRelativeToOffsetParent","isOffsetParentAnElement","offsets","offsetRect","getTrueOffsetParent","polyfill","currentNode","getContainingBlock","topLayer","clippingAncestors","cache","cachedResult","get","currentContainingBlockComputedStyle","elementIsFixed","computedStyle","currentNodeIsContaining","ancestor","set","getClippingElementAncestors","this","_c","clippingRect","accRect","getElementRects","data","getOffsetParentFn","getDimensionsFn","getDimensions","isRTL","flip","_middlewareData$arrow","_middlewareData$flip","middlewareData","initialPlacement","mainAxis","checkMainAxis","crossAxis","checkCrossAxis","fallbackPlacements","specifiedFallbackPlacements","fallbackStrategy","fallbackAxisSideDirection","flipAlignment","detectOverflowOptions","arrow","alignmentOffset","isBasePlacement","oppositePlacement","getExpandedPlacements","isStart","lr","rl","tb","bt","getSideList","map","getOppositeAxisPlacements","placements","overflows","overflowsData","sides","mainAlignmentSide","getAlignmentSides","_middlewareData$flip2","_overflowsData$filter","nextIndex","index","nextPlacement","reset","resetPlacement","d","_overflowsData$map$so","pact","_Pact","s","o","_settle","bind","then","observer","submit","preventDefault","config","url","disableErrorAlert","alert","Promise","resolve","submitElement","getElementById","setAttribute","requestHeaders","Headers","append","apiKey","_extends","user","messages","role","threadId","timestamp","Date","now","createNewMessageEntry","_temp5","removeAttribute","messagesHistory","prepend","thinkingBubble","_temp4","fetch","method","headers","JSON","stringify","response","remove","_temp3","responseIsAStream","handleStreamedResponse","handleStandardResponse","_catch","reject","onFulfilled","onRejected","callback","_this","_isSettledPact","thenable","messageElement","createElement","classList","add","id","messageText","marked","_marked","innerHTML","appendChild","messageTimestamp","textContent","getHours","getMinutes","init","styleElement","head","insertBefore","firstChild","_document$querySelect","querySelector","addEventListener","open","openOnLoad","WIDGET_BACKDROP_ID","Renderer","linkRenderer","link","href","title","text","widgetTitle","greetingMessage","closeOnOutsideClick","_window$langchatChatW","langchatChatWidget","cleanup","containerElement","optionalBackdrop","trap","userOptions","doc","trapStack","_objectSpread2","returnFocusOnDeactivate","escapeDeactivates","delayInitialFocus","containers","containerGroups","tabbableGroups","nodeFocusedBeforeActivation","mostRecentlyFocusedNode","active","paused","delayInitialFocusTimer","undefined","recentNavEvent","getOption","configOverrideOptions","optionName","configOptionName","findContainerIndex","container","tabbableNodes","find","getNodeForOption","optionValue","_len2","_key2","getInitialFocusNode","tabbableOptions","activeElement","firstTabbableGroup","firstTabbableNode","updateTabbableNodes","tabbable","focusableNodes","focusable","lastTabbableNode","firstDomTabbableNode","lastDomTabbableNode","reverse","posTabIndexesFound","nextTabbableNode","forward","nodeIdx","indexOf","group","g","getActiveElement","tryFocus","focus","preventScroll","select","isSelectableInput","getReturnFocusNode","previousActiveElement","findNextNavNode","_ref2","_ref2$isBackward","isBackward","destinationNode","containerIndex","containerGroup","startOfGroupIndex","_ref3","destinationGroup","lastOfGroupIndex","_ref4","_destinationGroup","checkPointerDown","clickOutsideDeactivates","deactivate","returnFocus","allowOutsideClick","checkFocusIn","targetContained","Document","nextNode","stopImmediatePropagation","navAcrossContainers","mruContainerIdx","mruTabIdx","n","checkKey","checkKeyNav","checkClick","addListeners","activateTrap","activeTrap","pause","trapIndex","splice","activeFocusTraps","capture","passive","removeListeners","removeEventListener","mutationObserver","MutationObserver","mutations","mutation","removedNodes","updateObservedNodes","disconnect","observe","subtree","childList","activate","activateOptions","onActivate","onPostActivate","checkCanFocusTrap","finishActivation","deactivateOptions","onDeactivate","onPostDeactivate","checkCanReturnFocus","clearTimeout","deactivateTrap","unpause","finishDeactivation","pauseOptions","onPause","onPostPause","unpauseOptions","onUnpause","onPostUnpause","updateContainerElements","containerElements","elementsAsArray","Boolean","createFocusTrap","initialFocus","hasChildNodes","close","style","chatbotHeaderTitleText","update","ancestorScroll","ancestorResize","elementResize","ResizeObserver","layoutShift","IntersectionObserver","animationFrame","referenceEl","ancestors","cleanupIo","onMove","timeoutId","io","root","_io","refresh","skip","threshold","rootMargin","isFirstUpdate","handleObserve","entries","ratio","intersectionRatio","observeMove","frameId","reobserveFrame","resizeObserver","firstEntry","unobserve","cancelAnimationFrame","requestAnimationFrame","_resizeObserver","prevRefRect","frameLoop","nextRefRect","_resizeObserver2","autoUpdate","computePosition","Map","mergedOptions","platformWithCache","middleware","validMiddleware","statefulPlacement","resetCount","nextX","nextY","computePosition$1","limiter","mainAxisCoord","crossAxisCoord","limitedCoords","Object","assign","res","ok","json","responseMessage","responseThreadId","_config$threadId","statusText","_exit","_interrupt","_temp2","_result2","_config$threadId2","threadIdFromHeader","ts","reader","getReader","_temp","shouldContinue","stage","updateValue","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","_for","read","_ref5","done","_step","_iterator","_createForOfIteratorHelperLoose","TextDecoder","decode","stream","startsWith","trim","choice","parse","choices","finishReason","delta","existingMessageElement","_marked2","streamResponseToMessageEntry"],"mappings":"8UAKA,IAAMA,EAAqB,CACzB,qBACA,sBACA,wBACA,uBACA,sBACA,oCACA,+BACA,+BACA,gEACA,6CACA,wBAEIC,iBAAoCD,EAAmBE,KAAK,KAE5DC,EAA+B,oBAAZC,QAEnBC,EAAUF,EACZ,aACAC,QAAQE,UAAUD,SAClBD,QAAQE,UAAUC,mBAClBH,QAAQE,UAAUE,sBAEhBC,GACHN,GAAaC,QAAQE,UAAUG,YAC5B,SAACC,GAAO,IAAAC,EAAA,OAAKD,SAAoBC,QAAbA,EAAPD,EAASD,mBAAT,IAAoBE,OAAbA,EAAPA,EAAAC,KAAAF,EAAwB,EACrC,SAACA,GAAO,OAAKA,aAAAA,EAAAA,EAASG,aAAa,EAUnCC,EAAU,SAAVA,EAAoBC,EAAMC,GAAe,IAAAC,OAAT,IAAND,IAAAA,GAAS,GAIvC,IAAME,EAAWH,SAAkBE,QAAdA,EAAJF,EAAMI,wBAAYF,OAAdA,EAAJA,EAAAL,KAAAG,EAAqB,SAUtC,MAT2B,KAAbG,GAAgC,SAAbA,GAORF,GAAUD,GAAQD,EAAQC,EAAKK,WAG1D,EAqBMC,EAAgB,SAAUC,EAAIC,EAAkBC,GAGpD,GAAIV,EAAQQ,GACV,MAAO,GAGT,IAAIG,EAAaC,MAAMpB,UAAUqB,MAAMC,MACrCN,EAAGO,iBAAiB5B,IAMtB,OAJIsB,GAAoBlB,EAAQO,KAAKU,EAAIrB,IACvCwB,EAAWK,QAAQR,GAERG,EAAWD,OAAOA,EAEjC,EAoCMO,EAA2B,SAA3BA,EACJC,EACAT,EACAU,GAIA,IAFA,IAAMR,EAAa,GACbS,EAAkBR,MAAMS,KAAKH,GAC5BE,EAAgBE,QAAQ,CAC7B,IAAM1B,EAAUwB,EAAgBG,QAChC,IAAIvB,EAAQJ,GAAS,GAMrB,GAAwB,S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