@kerebron/legacy-compat 0.8.7 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kerebron.cjs CHANGED
@@ -9,16 +9,22 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const require
9
9
  `))),0,0):Slice.empty;let n=e.someProp(`clipboardTextParser`,n=>n(t,a,r,e));if(n)c=n;else{let n=a.marks(),{schema:r}=e.state,o=DOMSerializer.fromSchema(r);s=document.createElement(`div`),t.split(/(?:\r\n?|\n)+/).forEach(e=>{let t=s.appendChild(document.createElement(`p`));e&&t.appendChild(o.serializeNode(r.text(e,n)))})}}else e.someProp(`transformPastedHTML`,t=>{n=t(n,e)}),s=readHTML(n),webkit&&restoreReplacedSpaces(s);let u=s&&s.querySelector(`[data-pm-slice]`),d=u&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(u.getAttribute(`data-pm-slice`)||``);if(d&&d[3])for(let e=+d[3];e>0;e--){let e=s.firstChild;for(;e&&e.nodeType!=1;)e=e.nextSibling;if(!e)break;s=e}if(c||=(e.someProp(`clipboardParser`)||e.someProp(`domParser`)||DOMParser$1.fromSchema(e.state.schema)).parseSlice(s,{preserveWhitespace:!!(l||d),context:a,ruleFromNode(e){return e.nodeName==`BR`&&!e.nextSibling&&e.parentNode&&!inlineParents.test(e.parentNode.nodeName)?{ignore:!0}:null}}),d)c=addContext(closeSlice$1(c,+d[1],+d[2]),d[4]);else if(c=Slice.maxOpen(normalizeSiblings$1(c.content,a),!0),c.openStart||c.openEnd){let e=0,t=0;for(let t=c.content.firstChild;e<c.openStart&&!t.type.spec.isolating;e++,t=t.firstChild);for(let e=c.content.lastChild;t<c.openEnd&&!e.type.spec.isolating;t++,e=e.lastChild);c=closeSlice$1(c,e,t)}return e.someProp(`transformPasted`,t=>{c=t(c,e)}),c}var inlineParents=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function normalizeSiblings$1(e,t){if(e.childCount<2)return e;for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.index(n)),a,o=[];if(e.forEach(e=>{if(!o)return;let t=r.findWrapping(e.type),n;if(!t)return o=null;if(n=o.length&&a.length&&addToSibling$1(t,a,e,o[o.length-1],0))o[o.length-1]=n;else{o.length&&(o[o.length-1]=closeRight$1(o[o.length-1],a.length));let n=withWrappers$1(e,t);o.push(n),r=r.matchType(n.type),a=t}}),o)return Fragment.from(o)}return e}function withWrappers$1(e,t,n=0){for(let r=t.length-1;r>=n;r--)e=t[r].create(null,Fragment.from(e));return e}function addToSibling$1(e,t,n,r,a){if(a<e.length&&a<t.length&&e[a]==t[a]){let o=addToSibling$1(e,t,n,r.lastChild,a+1);if(o)return r.copy(r.content.replaceChild(r.childCount-1,o));if(r.contentMatchAt(r.childCount).matchType(a==e.length-1?n.type:e[a+1]))return r.copy(r.content.append(Fragment.from(withWrappers$1(n,e,a+1))))}}function closeRight$1(e,t){if(t==0)return e;let n=e.content.replaceChild(e.childCount-1,closeRight$1(e.lastChild,t-1)),r=e.contentMatchAt(e.childCount).fillBefore(Fragment.empty,!0);return e.copy(n.append(r))}function closeRange$1(e,t,n,r,a,o){let s=t<0?e.firstChild:e.lastChild,c=s.content;return e.childCount>1&&(o=0),a<r-1&&(c=closeRange$1(c,t,n,r,a+1,o)),a>=n&&(c=t<0?s.contentMatchAt(0).fillBefore(c,o<=a).append(c):c.append(s.contentMatchAt(s.childCount).fillBefore(Fragment.empty,!0))),e.replaceChild(t<0?0:e.childCount-1,s.copy(c))}function closeSlice$1(e,t,n){return t<e.openStart&&(e=new Slice(closeRange$1(e.content,-1,t,e.openStart,0,e.openEnd),t,e.openEnd)),n<e.openEnd&&(e=new Slice(closeRange$1(e.content,1,n,e.openEnd,0,0),e.openStart,n)),e}var wrapMap={thead:[`table`],tbody:[`table`],tfoot:[`table`],caption:[`table`],colgroup:[`table`],col:[`table`,`colgroup`],tr:[`table`,`tbody`],td:[`table`,`tbody`,`tr`],th:[`table`,`tbody`,`tr`]},_detachedDoc=null;function detachedDoc(){return _detachedDoc||=document.implementation.createHTMLDocument(`title`)}var _policy=null;function maybeWrapTrusted(e){let t=window.trustedTypes;return t?(_policy||=t.defaultPolicy||t.createPolicy(`ProseMirrorClipboard`,{createHTML:e=>e}),_policy.createHTML(e)):e}function readHTML(e){let t=/^(\s*<meta [^>]*>)*/.exec(e);t&&(e=e.slice(t[0].length));let n=detachedDoc().createElement(`div`),r=/<([a-z][^>\s]+)/i.exec(e),a;if((a=r&&wrapMap[r[1].toLowerCase()])&&(e=a.map(e=>`<`+e+`>`).join(``)+e+a.map(e=>`</`+e+`>`).reverse().join(``)),n.innerHTML=maybeWrapTrusted(e),a)for(let e=0;e<a.length;e++)n=n.querySelector(a[e])||n;return n}function restoreReplacedSpaces(e){let t=e.querySelectorAll(chrome?`span:not([class]):not([style])`:`span.Apple-converted-space`);for(let n=0;n<t.length;n++){let r=t[n];r.childNodes.length==1&&r.textContent==`\xA0`&&r.parentNode&&r.parentNode.replaceChild(e.ownerDocument.createTextNode(` `),r)}}function addContext(e,t){if(!e.size)return e;let n=e.content.firstChild.type.schema,r;try{r=JSON.parse(t)}catch{return e}let{content:a,openStart:o,openEnd:s}=e;for(let e=r.length-2;e>=0;e-=2){let t=n.nodes[r[e]];if(!t||t.hasRequiredAttrs())break;a=Fragment.from(t.create(r[e+1],a)),o++,s++}return new Slice(a,o,s)}var handlers={},editHandlers={},passiveHandlers={touchstart:!0,touchmove:!0},InputState=class{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:``,button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}};function initInput(e){for(let t in handlers){let n=handlers[t];e.dom.addEventListener(t,e.input.eventHandlers[t]=t=>{eventBelongsToView(e,t)&&!runCustomHandler(e,t)&&(e.editable||!(t.type in editHandlers))&&n(e,t)},passiveHandlers[t]?{passive:!0}:void 0)}safari&&e.dom.addEventListener(`input`,()=>null),ensureListeners(e)}function setSelectionOrigin(e,t){e.input.lastSelectionOrigin=t,e.input.lastSelectionTime=Date.now()}function destroyInput(e){e.domObserver.stop();for(let t in e.input.eventHandlers)e.dom.removeEventListener(t,e.input.eventHandlers[t]);clearTimeout(e.input.composingTimeout),clearTimeout(e.input.lastIOSEnterFallbackTimeout)}function ensureListeners(e){e.someProp(`handleDOMEvents`,t=>{for(let n in t)e.input.eventHandlers[n]||e.dom.addEventListener(n,e.input.eventHandlers[n]=t=>runCustomHandler(e,t))})}function runCustomHandler(e,t){return e.someProp(`handleDOMEvents`,n=>{let r=n[t.type];return r?r(e,t)||t.defaultPrevented:!1})}function eventBelongsToView(e,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let n=t.target;n!=e.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(t))return!1;return!0}function dispatchEvent(e,t){!runCustomHandler(e,t)&&handlers[t.type]&&(e.editable||!(t.type in editHandlers))&&handlers[t.type](e,t)}editHandlers.keydown=(e,t)=>{let n=t;if(e.input.shiftKey=n.keyCode==16||n.shiftKey,!inOrNearComposition(e,n)&&(e.input.lastKeyCode=n.keyCode,e.input.lastKeyCodeTime=Date.now(),!(android&&chrome&&n.keyCode==13)))if(n.keyCode!=229&&e.domObserver.forceFlush(),ios&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let t=Date.now();e.input.lastIOSEnter=t,e.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{e.input.lastIOSEnter==t&&(e.someProp(`handleKeyDown`,t=>t(e,keyEvent(13,`Enter`))),e.input.lastIOSEnter=0)},200)}else e.someProp(`handleKeyDown`,t=>t(e,n))||captureKeyDown(e,n)?n.preventDefault():setSelectionOrigin(e,`key`)},editHandlers.keyup=(e,t)=>{t.keyCode==16&&(e.input.shiftKey=!1)},editHandlers.keypress=(e,t)=>{let n=t;if(inOrNearComposition(e,n)||!n.charCode||n.ctrlKey&&!n.altKey||mac$2&&n.metaKey)return;if(e.someProp(`handleKeyPress`,t=>t(e,n))){n.preventDefault();return}let r=e.state.selection;if(!(r instanceof TextSelection)||!r.$from.sameParent(r.$to)){let t=String.fromCharCode(n.charCode),a=()=>e.state.tr.insertText(t).scrollIntoView();!/[\r\n]/.test(t)&&!e.someProp(`handleTextInput`,n=>n(e,r.$from.pos,r.$to.pos,t,a))&&e.dispatch(a()),n.preventDefault()}};function eventCoords(e){return{left:e.clientX,top:e.clientY}}function isNear(e,t){let n=t.x-e.clientX,r=t.y-e.clientY;return n*n+r*r<100}function runHandlerOnContext(e,t,n,r,a){if(r==-1)return!1;let o=e.state.doc.resolve(r);for(let r=o.depth+1;r>0;r--)if(e.someProp(t,t=>r>o.depth?t(e,n,o.nodeAfter,o.before(r),a,!0):t(e,n,o.node(r),o.before(r),a,!1)))return!0;return!1}function updateSelection(e,t,n){if(e.focused||e.focus(),e.state.selection.eq(t))return;let r=e.state.tr.setSelection(t);n==`pointer`&&r.setMeta(`pointer`,!0),e.dispatch(r)}function selectClickedLeaf(e,t){if(t==-1)return!1;let n=e.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&NodeSelection.isSelectable(r)?(updateSelection(e,new NodeSelection(n),`pointer`),!0):!1}function selectClickedNode(e,t){if(t==-1)return!1;let n=e.state.selection,r,a;n instanceof NodeSelection&&(r=n.node);let o=e.state.doc.resolve(t);for(let e=o.depth+1;e>0;e--){let t=e>o.depth?o.nodeAfter:o.node(e);if(NodeSelection.isSelectable(t)){a=r&&n.$from.depth>0&&e>=n.$from.depth&&o.before(n.$from.depth+1)==n.$from.pos?o.before(n.$from.depth):o.before(e);break}}return a==null?!1:(updateSelection(e,NodeSelection.create(e.state.doc,a),`pointer`),!0)}function handleSingleClick(e,t,n,r,a){return runHandlerOnContext(e,`handleClickOn`,t,n,r)||e.someProp(`handleClick`,n=>n(e,t,r))||(a?selectClickedNode(e,n):selectClickedLeaf(e,n))}function handleDoubleClick(e,t,n,r){return runHandlerOnContext(e,`handleDoubleClickOn`,t,n,r)||e.someProp(`handleDoubleClick`,n=>n(e,t,r))}function handleTripleClick$1(e,t,n,r){return runHandlerOnContext(e,`handleTripleClickOn`,t,n,r)||e.someProp(`handleTripleClick`,n=>n(e,t,r))||defaultTripleClick(e,n,r)}function defaultTripleClick(e,t,n){if(n.button!=0)return!1;let r=e.state.doc;if(t==-1)return r.inlineContent?(updateSelection(e,TextSelection.create(r,0,r.content.size),`pointer`),!0):!1;let a=r.resolve(t);for(let t=a.depth+1;t>0;t--){let n=t>a.depth?a.nodeAfter:a.node(t),o=a.before(t);if(n.inlineContent)updateSelection(e,TextSelection.create(r,o+1,o+1+n.content.size),`pointer`);else if(NodeSelection.isSelectable(n))updateSelection(e,NodeSelection.create(r,o),`pointer`);else continue;return!0}}function forceDOMFlush(e){return endComposition(e)}var selectNodeModifier=mac$2?`metaKey`:`ctrlKey`;handlers.mousedown=(e,t)=>{let n=t;e.input.shiftKey=n.shiftKey;let r=forceDOMFlush(e),a=Date.now(),o=`singleClick`;a-e.input.lastClick.time<500&&isNear(n,e.input.lastClick)&&!n[selectNodeModifier]&&e.input.lastClick.button==n.button&&(e.input.lastClick.type==`singleClick`?o=`doubleClick`:e.input.lastClick.type==`doubleClick`&&(o=`tripleClick`)),e.input.lastClick={time:a,x:n.clientX,y:n.clientY,type:o,button:n.button};let s=e.posAtCoords(eventCoords(n));s&&(o==`singleClick`?(e.input.mouseDown&&e.input.mouseDown.done(),e.input.mouseDown=new MouseDown(e,s,n,!!r)):(o==`doubleClick`?handleDoubleClick:handleTripleClick$1)(e,s.pos,s.inside,n)?n.preventDefault():setSelectionOrigin(e,`pointer`))};var MouseDown=class{constructor(e,t,n,r){this.view=e,this.pos=t,this.event=n,this.flushed=r,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!n[selectNodeModifier],this.allowDefault=n.shiftKey;let a,o;if(t.inside>-1)a=e.state.doc.nodeAt(t.inside),o=t.inside;else{let n=e.state.doc.resolve(t.pos);a=n.parent,o=n.depth?n.before():0}let s=r?null:n.target,c=s?e.docView.nearestDesc(s,!0):null;this.target=c&&c.dom.nodeType==1?c.dom:null;let{selection:l}=e.state;(n.button==0&&a.type.spec.draggable&&a.type.spec.selectable!==!1||l instanceof NodeSelection&&l.from<=o&&l.to>o)&&(this.mightDrag={node:a,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&gecko&&!this.target.hasAttribute(`contentEditable`))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute(`contentEditable`,`false`)},20),this.view.domObserver.start()),e.root.addEventListener(`mouseup`,this.up=this.up.bind(this)),e.root.addEventListener(`mousemove`,this.move=this.move.bind(this)),setSelectionOrigin(e,`pointer`)}done(){this.view.root.removeEventListener(`mouseup`,this.up),this.view.root.removeEventListener(`mousemove`,this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute(`draggable`),this.mightDrag.setUneditable&&this.target.removeAttribute(`contentEditable`),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>selectionToDOM(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(eventCoords(e))),this.updateAllowDefault(e),this.allowDefault||!t?setSelectionOrigin(this.view,`pointer`):handleSingleClick(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||safari&&this.mightDrag&&!this.mightDrag.node.isAtom||chrome&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(updateSelection(this.view,Selection.near(this.view.state.doc.resolve(t.pos)),`pointer`),e.preventDefault()):setSelectionOrigin(this.view,`pointer`)}move(e){this.updateAllowDefault(e),setSelectionOrigin(this.view,`pointer`),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}};handlers.touchstart=e=>{e.input.lastTouch=Date.now(),forceDOMFlush(e),setSelectionOrigin(e,`pointer`)},handlers.touchmove=e=>{e.input.lastTouch=Date.now(),setSelectionOrigin(e,`pointer`)},handlers.contextmenu=e=>forceDOMFlush(e);function inOrNearComposition(e,t){return e.composing?!0:safari&&Math.abs(t.timeStamp-e.input.compositionEndedAt)<500?(e.input.compositionEndedAt=-2e8,!0):!1}var timeoutComposition=android?5e3:-1;editHandlers.compositionstart=editHandlers.compositionupdate=e=>{if(!e.composing){e.domObserver.flush();let{state:t}=e,n=t.selection.$to;if(t.selection instanceof TextSelection&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(e=>e.type.spec.inclusive===!1)))e.markCursor=e.state.storedMarks||n.marks(),endComposition(e,!0),e.markCursor=null;else if(endComposition(e,!t.selection.empty),gecko&&t.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let t=e.domSelectionRange();for(let n=t.focusNode,r=t.focusOffset;n&&n.nodeType==1&&r!=0;){let t=r<0?n.lastChild:n.childNodes[r-1];if(!t)break;if(t.nodeType==3){let n=e.domSelection();n&&n.collapse(t,t.nodeValue.length);break}else n=t,r=-1}}e.input.composing=!0}scheduleComposeEnd(e,timeoutComposition)},editHandlers.compositionend=(e,t)=>{e.composing&&(e.input.composing=!1,e.input.compositionEndedAt=t.timeStamp,e.input.compositionPendingChanges=e.domObserver.pendingRecords().length?e.input.compositionID:0,e.input.compositionNode=null,e.input.compositionPendingChanges&&Promise.resolve().then(()=>e.domObserver.flush()),e.input.compositionID++,scheduleComposeEnd(e,20))};function scheduleComposeEnd(e,t){clearTimeout(e.input.composingTimeout),t>-1&&(e.input.composingTimeout=setTimeout(()=>endComposition(e),t))}function clearComposition(e){for(e.composing&&(e.input.composing=!1,e.input.compositionEndedAt=timestampFromCustomEvent());e.input.compositionNodes.length>0;)e.input.compositionNodes.pop().markParentsDirty()}function findCompositionNode(e){let t=e.domSelectionRange();if(!t.focusNode)return null;let n=textNodeBefore$1(t.focusNode,t.focusOffset),r=textNodeAfter$1(t.focusNode,t.focusOffset);if(n&&r&&n!=r){let t=r.pmViewDesc,a=e.domObserver.lastChangedTextNode;if(n==a||r==a)return a;if(!t||!t.isText(r.nodeValue))return r;if(e.input.compositionNode==r){let e=n.pmViewDesc;if(!(!e||!e.isText(n.nodeValue)))return r}}return n||r}function timestampFromCustomEvent(){let e=document.createEvent(`Event`);return e.initEvent(`event`,!0,!0),e.timeStamp}function endComposition(e,t=!1){if(!(android&&e.domObserver.flushingSoon>=0)){if(e.domObserver.forceFlush(),clearComposition(e),t||e.docView&&e.docView.dirty){let n=selectionFromDOM(e),r=e.state.selection;return n&&!n.eq(r)?e.dispatch(e.state.tr.setSelection(n)):(e.markCursor||t)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?e.dispatch(e.state.tr.deleteSelection()):e.updateState(e.state),!0}return!1}}function captureCopy(e,t){if(!e.dom.parentNode)return;let n=e.dom.parentNode.appendChild(document.createElement(`div`));n.appendChild(t),n.style.cssText=`position: fixed; left: -10000px; top: 10px`;let r=getSelection(),a=document.createRange();a.selectNodeContents(t),e.dom.blur(),r.removeAllRanges(),r.addRange(a),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),e.focus()},50)}var brokenClipboardAPI=ie$1&&ie_version<15||ios&&webkit_version<604;handlers.copy=editHandlers.cut=(e,t)=>{let n=t,r=e.state.selection,a=n.type==`cut`;if(r.empty)return;let o=brokenClipboardAPI?null:n.clipboardData,{dom:s,text:c}=serializeForClipboard(e,r.content());o?(n.preventDefault(),o.clearData(),o.setData(`text/html`,s.innerHTML),o.setData(`text/plain`,c)):captureCopy(e,s),a&&e.dispatch(e.state.tr.deleteSelection().scrollIntoView().setMeta(`uiEvent`,`cut`))};function sliceSingleNode$1(e){return e.openStart==0&&e.openEnd==0&&e.content.childCount==1?e.content.firstChild:null}function capturePaste(e,t){if(!e.dom.parentNode)return;let n=e.input.shiftKey||e.state.selection.$from.parent.type.spec.code,r=e.dom.parentNode.appendChild(document.createElement(n?`textarea`:`div`));n||(r.contentEditable=`true`),r.style.cssText=`position: fixed; left: -10000px; top: 10px`,r.focus();let a=e.input.shiftKey&&e.input.lastKeyCode!=45;setTimeout(()=>{e.focus(),r.parentNode&&r.parentNode.removeChild(r),n?doPaste(e,r.value,null,a,t):doPaste(e,r.textContent,r.innerHTML,a,t)},50)}function doPaste(e,t,n,r,a){let o=parseFromClipboard(e,t,n,r,e.state.selection.$from);if(e.someProp(`handlePaste`,t=>t(e,a,o||Slice.empty)))return!0;if(!o)return!1;let s=sliceSingleNode$1(o),c=s?e.state.tr.replaceSelectionWith(s,r):e.state.tr.replaceSelection(o);return e.dispatch(c.scrollIntoView().setMeta(`paste`,!0).setMeta(`uiEvent`,`paste`)),!0}function getText$1(e){let t=e.getData(`text/plain`)||e.getData(`Text`);if(t)return t;let n=e.getData(`text/uri-list`);return n?n.replace(/\r?\n/g,` `):``}editHandlers.paste=(e,t)=>{let n=t;if(e.composing&&!android)return;let r=brokenClipboardAPI?null:n.clipboardData,a=e.input.shiftKey&&e.input.lastKeyCode!=45;r&&doPaste(e,getText$1(r),r.getData(`text/html`),a,n)?n.preventDefault():capturePaste(e,n)};var Dragging=class{constructor(e,t,n){this.slice=e,this.move=t,this.node=n}},dragCopyModifier=mac$2?`altKey`:`ctrlKey`;function dragMoves(e,t){return e.someProp(`dragCopies`,e=>!e(t))??!t[dragCopyModifier]}handlers.dragstart=(e,t)=>{let n=t,r=e.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let a=e.state.selection,o=a.empty?null:e.posAtCoords(eventCoords(n)),s;if(!(o&&o.pos>=a.from&&o.pos<=(a instanceof NodeSelection?a.to-1:a.to))){if(r&&r.mightDrag)s=NodeSelection.create(e.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let t=e.docView.nearestDesc(n.target,!0);t&&t.node.type.spec.draggable&&t!=e.docView&&(s=NodeSelection.create(e.state.doc,t.posBefore))}}let{dom:c,text:l,slice:u}=serializeForClipboard(e,(s||e.state.selection).content());(!n.dataTransfer.files.length||!chrome||chrome_version>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(brokenClipboardAPI?`Text`:`text/html`,c.innerHTML),n.dataTransfer.effectAllowed=`copyMove`,brokenClipboardAPI||n.dataTransfer.setData(`text/plain`,l),e.dragging=new Dragging(u,dragMoves(e,n),s)},handlers.dragend=e=>{let t=e.dragging;window.setTimeout(()=>{e.dragging==t&&(e.dragging=null)},50)},editHandlers.dragover=editHandlers.dragenter=(e,t)=>t.preventDefault(),editHandlers.drop=(e,t)=>{let n=t,r=e.dragging;if(e.dragging=null,!n.dataTransfer)return;let a=e.posAtCoords(eventCoords(n));if(!a)return;let o=e.state.doc.resolve(a.pos),s=r&&r.slice;s?e.someProp(`transformPasted`,t=>{s=t(s,e)}):s=parseFromClipboard(e,getText$1(n.dataTransfer),brokenClipboardAPI?null:n.dataTransfer.getData(`text/html`),!1,o);let c=!!(r&&dragMoves(e,n));if(e.someProp(`handleDrop`,t=>t(e,n,s||Slice.empty,c))){n.preventDefault();return}if(!s)return;n.preventDefault();let l=s?dropPoint(e.state.doc,o.pos,s):o.pos;l??=o.pos;let u=e.state.tr;if(c){let{node:e}=r;e?e.replace(u):u.deleteSelection()}let d=u.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,p=u.doc;if(f?u.replaceRangeWith(d,d,s.content.firstChild):u.replaceRange(d,d,s),u.doc.eq(p))return;let m=u.doc.resolve(d);if(f&&NodeSelection.isSelectable(s.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(s.content.firstChild))u.setSelection(new NodeSelection(m));else{let t=u.mapping.map(l);u.mapping.maps[u.mapping.maps.length-1].forEach((e,n,r,a)=>t=a),u.setSelection(selectionBetween(e,m,u.doc.resolve(t)))}e.focus(),e.dispatch(u.setMeta(`uiEvent`,`drop`))},handlers.focus=e=>{e.input.lastFocus=Date.now(),e.focused||(e.domObserver.stop(),e.dom.classList.add(`ProseMirror-focused`),e.domObserver.start(),e.focused=!0,setTimeout(()=>{e.docView&&e.hasFocus()&&!e.domObserver.currentSelection.eq(e.domSelectionRange())&&selectionToDOM(e)},20))},handlers.blur=(e,t)=>{let n=t;e.focused&&=(e.domObserver.stop(),e.dom.classList.remove(`ProseMirror-focused`),e.domObserver.start(),n.relatedTarget&&e.dom.contains(n.relatedTarget)&&e.domObserver.currentSelection.clear(),!1)},handlers.beforeinput=(e,t)=>{if(chrome&&android&&t.inputType==`deleteContentBackward`){e.domObserver.flushSoon();let{domChangeCount:t}=e.input;setTimeout(()=>{if(e.input.domChangeCount!=t||(e.dom.blur(),e.focus(),e.someProp(`handleKeyDown`,t=>t(e,keyEvent(8,`Backspace`)))))return;let{$cursor:n}=e.state.selection;n&&n.pos>0&&e.dispatch(e.state.tr.delete(n.pos-1,n.pos).scrollIntoView())},50)}};for(let e in editHandlers)handlers[e]=editHandlers[e];function compareObjs(e,t){if(e==t)return!0;for(let n in e)if(e[n]!==t[n])return!1;for(let n in t)if(!(n in e))return!1;return!0}var WidgetType=class e{constructor(e,t){this.toDOM=e,this.spec=t||noSpec,this.side=this.spec.side||0}map(e,t,n,r){let{pos:a,deleted:o}=e.mapResult(t.from+r,this.side<0?-1:1);return o?null:new Decoration(a-n,a-n,this)}valid(){return!0}eq(t){return this==t||t instanceof e&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&compareObjs(this.spec,t.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}},InlineType=class e{constructor(e,t){this.attrs=e,this.spec=t||noSpec}map(e,t,n,r){let a=e.map(t.from+r,this.spec.inclusiveStart?-1:1)-n,o=e.map(t.to+r,this.spec.inclusiveEnd?1:-1)-n;return a>=o?null:new Decoration(a,o,this)}valid(e,t){return t.from<t.to}eq(t){return this==t||t instanceof e&&compareObjs(this.attrs,t.attrs)&&compareObjs(this.spec,t.spec)}static is(t){return t.type instanceof e}destroy(){}},NodeType=class e{constructor(e,t){this.attrs=e,this.spec=t||noSpec}map(e,t,n,r){let a=e.mapResult(t.from+r,1);if(a.deleted)return null;let o=e.mapResult(t.to+r,-1);return o.deleted||o.pos<=a.pos?null:new Decoration(a.pos-n,o.pos-n,this)}valid(e,t){let{index:n,offset:r}=e.content.findIndex(t.from),a;return r==t.from&&!(a=e.child(n)).isText&&r+a.nodeSize==t.to}eq(t){return this==t||t instanceof e&&compareObjs(this.attrs,t.attrs)&&compareObjs(this.spec,t.spec)}destroy(){}},Decoration=class e{constructor(e,t,n){this.from=e,this.to=t,this.type=n}copy(t,n){return new e(t,n,this.type)}eq(e,t=0){return this.type.eq(e.type)&&this.from+t==e.from&&this.to+t==e.to}map(e,t,n){return this.type.map(e,this,t,n)}static widget(t,n,r){return new e(t,t,new WidgetType(n,r))}static inline(t,n,r,a){return new e(t,n,new InlineType(r,a))}static node(t,n,r,a){return new e(t,n,new NodeType(r,a))}get spec(){return this.type.spec}get inline(){return this.type instanceof InlineType}get widget(){return this.type instanceof WidgetType}},none=[],noSpec={},DecorationSet=class e{constructor(e,t){this.local=e.length?e:none,this.children=t.length?t:none}static create(e,t){return t.length?buildTree(t,e,0,noSpec):empty$1}find(e,t,n){let r=[];return this.findInner(e??0,t??1e9,r,0,n),r}findInner(e,t,n,r,a){for(let o=0;o<this.local.length;o++){let s=this.local[o];s.from<=t&&s.to>=e&&(!a||a(s.spec))&&n.push(s.copy(s.from+r,s.to+r))}for(let o=0;o<this.children.length;o+=3)if(this.children[o]<t&&this.children[o+1]>e){let s=this.children[o]+1;this.children[o+2].findInner(e-s,t-s,n,r+s,a)}}map(e,t,n){return this==empty$1||e.maps.length==0?this:this.mapInner(e,t,0,0,n||noSpec)}mapInner(t,n,r,a,o){let s;for(let e=0;e<this.local.length;e++){let c=this.local[e].map(t,r,a);c&&c.type.valid(n,c)?(s||=[]).push(c):o.onRemove&&o.onRemove(this.local[e].spec)}return this.children.length?mapChildren(this.children,s||[],t,n,r,a,o):s?new e(s.sort(byPos),none):empty$1}add(t,n){return n.length?this==empty$1?e.create(t,n):this.addInner(t,n,0):this}addInner(t,n,r){let a,o=0;t.forEach((e,t)=>{let s=t+r,c;if(c=takeSpansForNode(n,e,s)){for(a||=this.children.slice();o<a.length&&a[o]<t;)o+=3;a[o]==t?a[o+2]=a[o+2].addInner(e,c,s+1):a.splice(o,0,t,t+e.nodeSize,buildTree(c,e,s+1,noSpec)),o+=3}});let s=moveSpans(o?withoutNulls(n):n,-r);for(let e=0;e<s.length;e++)s[e].type.valid(t,s[e])||s.splice(e--,1);return new e(s.length?this.local.concat(s).sort(byPos):this.local,a||this.children)}remove(e){return e.length==0||this==empty$1?this:this.removeInner(e,0)}removeInner(t,n){let r=this.children,a=this.local;for(let e=0;e<r.length;e+=3){let a,o=r[e]+n,s=r[e+1]+n;for(let e=0,n;e<t.length;e++)(n=t[e])&&n.from>o&&n.to<s&&(t[e]=null,(a||=[]).push(n));if(!a)continue;r==this.children&&(r=this.children.slice());let c=r[e+2].removeInner(a,o+1);c==empty$1?(r.splice(e,3),e-=3):r[e+2]=c}if(a.length){for(let e=0,r;e<t.length;e++)if(r=t[e])for(let e=0;e<a.length;e++)a[e].eq(r,n)&&(a==this.local&&(a=this.local.slice()),a.splice(e--,1))}return r==this.children&&a==this.local?this:a.length||r.length?new e(a,r):empty$1}forChild(t,n){if(this==empty$1)return this;if(n.isLeaf)return e.empty;let r,a;for(let e=0;e<this.children.length;e+=3)if(this.children[e]>=t){this.children[e]==t&&(r=this.children[e+2]);break}let o=t+1,s=o+n.content.size;for(let e=0;e<this.local.length;e++){let t=this.local[e];if(t.from<s&&t.to>o&&t.type instanceof InlineType){let e=Math.max(o,t.from)-o,n=Math.min(s,t.to)-o;e<n&&(a||=[]).push(t.copy(e,n))}}if(a){let t=new e(a.sort(byPos),none);return r?new DecorationGroup([t,r]):t}return r||empty$1}eq(t){if(this==t)return!0;if(!(t instanceof e)||this.local.length!=t.local.length||this.children.length!=t.children.length)return!1;for(let e=0;e<this.local.length;e++)if(!this.local[e].eq(t.local[e]))return!1;for(let e=0;e<this.children.length;e+=3)if(this.children[e]!=t.children[e]||this.children[e+1]!=t.children[e+1]||!this.children[e+2].eq(t.children[e+2]))return!1;return!0}locals(e){return removeOverlap(this.localsInner(e))}localsInner(e){if(this==empty$1)return none;if(e.inlineContent||!this.local.some(InlineType.is))return this.local;let t=[];for(let e=0;e<this.local.length;e++)this.local[e].type instanceof InlineType||t.push(this.local[e]);return t}forEachSet(e){e(this)}};DecorationSet.empty=new DecorationSet([],[]),DecorationSet.removeOverlap=removeOverlap;var empty$1=DecorationSet.empty,DecorationGroup=class e{constructor(e){this.members=e}map(t,n){let r=this.members.map(e=>e.map(t,n,noSpec));return e.from(r)}forChild(t,n){if(n.isLeaf)return DecorationSet.empty;let r=[];for(let a=0;a<this.members.length;a++){let o=this.members[a].forChild(t,n);o!=empty$1&&(o instanceof e?r=r.concat(o.members):r.push(o))}return e.from(r)}eq(t){if(!(t instanceof e)||t.members.length!=this.members.length)return!1;for(let e=0;e<this.members.length;e++)if(!this.members[e].eq(t.members[e]))return!1;return!0}locals(e){let t,n=!0;for(let r=0;r<this.members.length;r++){let a=this.members[r].localsInner(e);if(a.length)if(!t)t=a;else{n&&=(t=t.slice(),!1);for(let e=0;e<a.length;e++)t.push(a[e])}}return t?removeOverlap(n?t:t.sort(byPos)):none}static from(t){switch(t.length){case 0:return empty$1;case 1:return t[0];default:return new e(t.every(e=>e instanceof DecorationSet)?t:t.reduce((e,t)=>e.concat(t instanceof DecorationSet?t:t.members),[]))}}forEachSet(e){for(let t=0;t<this.members.length;t++)this.members[t].forEachSet(e)}};function mapChildren(e,t,n,r,a,o,s){let c=e.slice();for(let e=0,t=o;e<n.maps.length;e++){let r=0;n.maps[e].forEach((e,n,a,o)=>{let s=o-a-(n-e);for(let a=0;a<c.length;a+=3){let o=c[a+1];if(o<0||e>o+t-r)continue;let l=c[a]+t-r;n>=l?c[a+1]=e<=l?-2:-1:e>=t&&s&&(c[a]+=s,c[a+1]+=s)}r+=s}),t=n.maps[e].map(t,-1)}let l=!1;for(let t=0;t<c.length;t+=3)if(c[t+1]<0){if(c[t+1]==-2){l=!0,c[t+1]=-1;continue}let u=n.map(e[t]+o),d=u-a;if(d<0||d>=r.content.size){l=!0;continue}let f=n.map(e[t+1]+o,-1)-a,{index:p,offset:m}=r.content.findIndex(d),h=r.maybeChild(p);if(h&&m==d&&m+h.nodeSize==f){let r=c[t+2].mapInner(n,h,u+1,e[t]+o+1,s);r==empty$1?(c[t+1]=-2,l=!0):(c[t]=d,c[t+1]=f,c[t+2]=r)}else l=!0}if(l){let l=buildTree(mapAndGatherRemainingDecorations(c,e,t,n,a,o,s),r,0,s);t=l.local;for(let e=0;e<c.length;e+=3)c[e+1]<0&&(c.splice(e,3),e-=3);for(let e=0,t=0;e<l.children.length;e+=3){let n=l.children[e];for(;t<c.length&&c[t]<n;)t+=3;c.splice(t,0,l.children[e],l.children[e+1],l.children[e+2])}}return new DecorationSet(t.sort(byPos),c)}function moveSpans(e,t){if(!t||!e.length)return e;let n=[];for(let r=0;r<e.length;r++){let a=e[r];n.push(new Decoration(a.from+t,a.to+t,a.type))}return n}function mapAndGatherRemainingDecorations(e,t,n,r,a,o,s){function c(e,t){for(let o=0;o<e.local.length;o++){let c=e.local[o].map(r,a,t);c?n.push(c):s.onRemove&&s.onRemove(e.local[o].spec)}for(let n=0;n<e.children.length;n+=3)c(e.children[n+2],e.children[n]+t+1)}for(let n=0;n<e.length;n+=3)e[n+1]==-1&&c(e[n+2],t[n]+o+1);return n}function takeSpansForNode(e,t,n){if(t.isLeaf)return null;let r=n+t.nodeSize,a=null;for(let t=0,o;t<e.length;t++)(o=e[t])&&o.from>n&&o.to<r&&((a||=[]).push(o),e[t]=null);return a}function withoutNulls(e){let t=[];for(let n=0;n<e.length;n++)e[n]!=null&&t.push(e[n]);return t}function buildTree(e,t,n,r){let a=[],o=!1;t.forEach((t,s)=>{let c=takeSpansForNode(e,t,s+n);if(c){o=!0;let e=buildTree(c,t,n+s+1,r);e!=empty$1&&a.push(s,s+t.nodeSize,e)}});let s=moveSpans(o?withoutNulls(e):e,-n).sort(byPos);for(let e=0;e<s.length;e++)s[e].type.valid(t,s[e])||(r.onRemove&&r.onRemove(s[e].spec),s.splice(e--,1));return s.length||a.length?new DecorationSet(s,a):empty$1}function byPos(e,t){return e.from-t.from||e.to-t.to}function removeOverlap(e){let t=e;for(let n=0;n<t.length-1;n++){let r=t[n];if(r.from!=r.to)for(let a=n+1;a<t.length;a++){let o=t[a];if(o.from==r.from){o.to!=r.to&&(t==e&&(t=e.slice()),t[a]=o.copy(o.from,r.to),insertAhead(t,a+1,o.copy(r.to,o.to)));continue}else{o.from<r.to&&(t==e&&(t=e.slice()),t[n]=r.copy(r.from,o.from),insertAhead(t,a,r.copy(o.from,r.to)));break}}}return t}function insertAhead(e,t,n){for(;t<e.length&&byPos(n,e[t])>0;)t++;e.splice(t,0,n)}function viewDecorations(e){let t=[];return e.someProp(`decorations`,n=>{let r=n(e.state);r&&r!=empty$1&&t.push(r)}),e.cursorWrapper&&t.push(DecorationSet.create(e.state.doc,[e.cursorWrapper.deco])),DecorationGroup.from(t)}var observeOptions={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},useCharData=ie$1&&ie_version<=11,SelectionState=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}},DOMObserver=class{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new SelectionState,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(e=>{for(let t=0;t<e.length;t++)this.queue.push(e[t]);ie$1&&ie_version<=11&&e.some(e=>e.type==`childList`&&e.removedNodes.length||e.type==`characterData`&&e.oldValue.length>e.target.nodeValue.length)?this.flushSoon():this.flush()}),useCharData&&(this.onCharData=e=>{this.queue.push({target:e.target,type:`characterData`,oldValue:e.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,observeOptions)),this.onCharData&&this.view.dom.addEventListener(`DOMCharacterDataModified`,this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;t<e.length;t++)this.queue.push(e[t]);window.setTimeout(()=>this.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener(`DOMCharacterDataModified`,this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener(`selectionchange`,this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener(`selectionchange`,this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(hasFocusAndSelection(this.view)){if(this.suppressingSelectionUpdates)return selectionToDOM(this.view);if(ie$1&&ie_version<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&isEquivalentPosition(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,n;for(let n=e.focusNode;n;n=parentNode(n))t.add(n);for(let r=e.anchorNode;r;r=parentNode(r))if(t.has(r)){n=r;break}let r=n&&this.view.docView.nearestDesc(n);if(r&&r.ignoreMutation({type:`selection`,target:n.nodeType==3?n.parentNode:n}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let n=e.domSelectionRange(),r=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(n)&&hasFocusAndSelection(e)&&!this.ignoreSelectionChange(n),a=-1,o=-1,s=!1,c=[];if(e.editable)for(let e=0;e<t.length;e++){let n=this.registerMutation(t[e],c);n&&(a=a<0?n.from:Math.min(n.from,a),o=o<0?n.to:Math.max(n.to,o),n.typeOver&&(s=!0))}if(gecko&&c.length){let t=c.filter(e=>e.nodeName==`BR`);if(t.length==2){let[e,n]=t;e.parentNode&&e.parentNode.parentNode==n.parentNode?n.remove():e.remove()}else{let{focusNode:n}=this.currentSelection;for(let r of t){let t=r.parentNode;t&&t.nodeName==`LI`&&(!n||blockParent(e,n)!=t)&&r.remove()}}}let l=null;a<0&&r&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&selectionCollapsed(n)&&(l=selectionFromDOM(e))&&l.eq(Selection.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,selectionToDOM(e),this.currentSelection.set(n),e.scrollToSelection()):(a>-1||r)&&(a>-1&&(e.docView.markDirty(a,o),checkCSS(e)),this.handleDOMChange(a,o,s,c),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(n)||selectionToDOM(e),this.currentSelection.set(n))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let n=this.view.docView.nearestDesc(e.target);if(e.type==`attributes`&&(n==this.view.docView||e.attributeName==`contenteditable`||e.attributeName==`style`&&!e.oldValue&&!e.target.getAttribute(`style`))||!n||n.ignoreMutation(e))return null;if(e.type==`childList`){for(let n=0;n<e.addedNodes.length;n++){let r=e.addedNodes[n];t.push(r),r.nodeType==3&&(this.lastChangedTextNode=r)}if(n.contentDOM&&n.contentDOM!=n.dom&&!n.contentDOM.contains(e.target))return{from:n.posBefore,to:n.posAfter};let r=e.previousSibling,a=e.nextSibling;if(ie$1&&ie_version<=11&&e.addedNodes.length)for(let t=0;t<e.addedNodes.length;t++){let{previousSibling:n,nextSibling:o}=e.addedNodes[t];(!n||Array.prototype.indexOf.call(e.addedNodes,n)<0)&&(r=n),(!o||Array.prototype.indexOf.call(e.addedNodes,o)<0)&&(a=o)}let o=r&&r.parentNode==e.target?domIndex(r)+1:0,s=n.localPosFromDOM(e.target,o,-1),c=a&&a.parentNode==e.target?domIndex(a):e.target.childNodes.length;return{from:s,to:n.localPosFromDOM(e.target,c,1)}}else if(e.type==`attributes`)return{from:n.posAtStart-n.border,to:n.posAtEnd+n.border};else return this.lastChangedTextNode=e.target,{from:n.posAtStart,to:n.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}}},cssChecked=new WeakMap,cssCheckWarned=!1;function checkCSS(e){if(!cssChecked.has(e)&&(cssChecked.set(e,null),[`normal`,`nowrap`,`pre-line`].indexOf(getComputedStyle(e.dom).whiteSpace)!==-1)){if(e.requiresGeckoHackNode=gecko,cssCheckWarned)return;console.warn(`ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.`),cssCheckWarned=!0}}function rangeToSelectionRange(e,t){let n=t.startContainer,r=t.startOffset,a=t.endContainer,o=t.endOffset,s=e.domAtPos(e.state.selection.anchor);return isEquivalentPosition(s.node,s.offset,a,o)&&([n,r,a,o]=[a,o,n,r]),{anchorNode:n,anchorOffset:r,focusNode:a,focusOffset:o}}function safariShadowSelectionRange(e,t){if(t.getComposedRanges){let n=t.getComposedRanges(e.root)[0];if(n)return rangeToSelectionRange(e,n)}let n;function r(e){e.preventDefault(),e.stopImmediatePropagation(),n=e.getTargetRanges()[0]}return e.dom.addEventListener(`beforeinput`,r,!0),document.execCommand(`indent`),e.dom.removeEventListener(`beforeinput`,r,!0),n?rangeToSelectionRange(e,n):null}function blockParent(e,t){for(let n=t.parentNode;n&&n!=e.dom;n=n.parentNode){let t=e.docView.nearestDesc(n,!0);if(t&&t.node.isBlock)return n}return null}function parseBetween(e,t,n){let{node:r,fromOffset:a,toOffset:o,from:s,to:c}=e.docView.parseRange(t,n),l=e.domSelectionRange(),u,d=l.anchorNode;if(d&&e.dom.contains(d.nodeType==1?d:d.parentNode)&&(u=[{node:d,offset:l.anchorOffset}],selectionCollapsed(l)||u.push({node:l.focusNode,offset:l.focusOffset})),chrome&&e.input.lastKeyCode===8)for(let e=o;e>a;e--){let t=r.childNodes[e-1],n=t.pmViewDesc;if(t.nodeName==`BR`&&!n){o=e;break}if(!n||n.size)break}let f=e.state.doc,p=e.someProp(`domParser`)||DOMParser$1.fromSchema(e.state.schema),m=f.resolve(s),h=null,g=p.parse(r,{topNode:m.parent,topMatch:m.parent.contentMatchAt(m.index()),topOpen:!0,from:a,to:o,preserveWhitespace:m.parent.type.whitespace==`pre`?`full`:!0,findPositions:u,ruleFromNode,context:m});if(u&&u[0].pos!=null){let e=u[0].pos,t=u[1]&&u[1].pos;t??=e,h={anchor:e+s,head:t+s}}return{doc:g,sel:h,from:s,to:c}}function ruleFromNode(e){let t=e.pmViewDesc;if(t)return t.parseRule();if(e.nodeName==`BR`&&e.parentNode){if(safari&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let e=document.createElement(`div`);return e.appendChild(document.createElement(`li`)),{skip:e}}else if(e.parentNode.lastChild==e||safari&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName==`IMG`&&e.getAttribute(`mark-placeholder`))return{ignore:!0};return null}var isInline=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function readDOMChange(e,t,n,r,a){let o=e.input.compositionPendingChanges||(e.composing?e.input.compositionID:0);if(e.input.compositionPendingChanges=0,t<0){let t=e.input.lastSelectionTime>Date.now()-50?e.input.lastSelectionOrigin:null,n=selectionFromDOM(e,t);if(n&&!e.state.selection.eq(n)){if(chrome&&android&&e.input.lastKeyCode===13&&Date.now()-100<e.input.lastKeyCodeTime&&e.someProp(`handleKeyDown`,t=>t(e,keyEvent(13,`Enter`))))return;let r=e.state.tr.setSelection(n);t==`pointer`?r.setMeta(`pointer`,!0):t==`key`&&r.scrollIntoView(),o&&r.setMeta(`composition`,o),e.dispatch(r)}return}let s=e.state.doc.resolve(t),c=s.sharedDepth(n);t=s.before(c+1),n=e.state.doc.resolve(n).after(c+1);let l=e.state.selection,u=parseBetween(e,t,n),d=e.state.doc,f=d.slice(u.from,u.to),p,m;e.input.lastKeyCode===8&&Date.now()-100<e.input.lastKeyCodeTime?(p=e.state.selection.to,m=`end`):(p=e.state.selection.from,m=`start`),e.input.lastKeyCode=null;let h=findDiff(f.content,u.doc.content,u.from,p,m);if(h&&e.input.domChangeCount++,(ios&&e.input.lastIOSEnter>Date.now()-225||android)&&a.some(e=>e.nodeType==1&&!isInline.test(e.nodeName))&&(!h||h.endA>=h.endB)&&e.someProp(`handleKeyDown`,t=>t(e,keyEvent(13,`Enter`)))){e.input.lastIOSEnter=0;return}if(!h)if(r&&l instanceof TextSelection&&!l.empty&&l.$head.sameParent(l.$anchor)&&!e.composing&&!(u.sel&&u.sel.anchor!=u.sel.head))h={start:l.from,endA:l.to,endB:l.to};else{if(u.sel){let t=resolveSelection(e,e.state.doc,u.sel);if(t&&!t.eq(e.state.selection)){let n=e.state.tr.setSelection(t);o&&n.setMeta(`composition`,o),e.dispatch(n)}}return}e.state.selection.from<e.state.selection.to&&h.start==h.endB&&e.state.selection instanceof TextSelection&&(h.start>e.state.selection.from&&h.start<=e.state.selection.from+2&&e.state.selection.from>=u.from?h.start=e.state.selection.from:h.endA<e.state.selection.to&&h.endA>=e.state.selection.to-2&&e.state.selection.to<=u.to&&(h.endB+=e.state.selection.to-h.endA,h.endA=e.state.selection.to)),ie$1&&ie_version<=11&&h.endB==h.start+1&&h.endA==h.start&&h.start>u.from&&u.doc.textBetween(h.start-u.from-1,h.start-u.from+1)==` \xA0`&&(h.start--,h.endA--,h.endB--);let g=u.doc.resolveNoCache(h.start-u.from),_=u.doc.resolveNoCache(h.endB-u.from),v=d.resolve(h.start),y=g.sameParent(_)&&g.parent.inlineContent&&v.end()>=h.endA,b;if((ios&&e.input.lastIOSEnter>Date.now()-225&&(!y||a.some(e=>e.nodeName==`DIV`||e.nodeName==`P`))||!y&&g.pos<u.doc.content.size&&(!g.sameParent(_)||!g.parent.inlineContent)&&!/\S/.test(u.doc.textBetween(g.pos,_.pos,``,``))&&(b=Selection.findFrom(u.doc.resolve(g.pos+1),1,!0))&&b.head>g.pos)&&e.someProp(`handleKeyDown`,t=>t(e,keyEvent(13,`Enter`)))){e.input.lastIOSEnter=0;return}if(e.state.selection.anchor>h.start&&looksLikeBackspace(d,h.start,h.endA,g,_)&&e.someProp(`handleKeyDown`,t=>t(e,keyEvent(8,`Backspace`)))){android&&chrome&&e.domObserver.suppressSelectionUpdates();return}chrome&&h.endB==h.start&&(e.input.lastChromeDelete=Date.now()),android&&!y&&g.start()!=_.start()&&_.parentOffset==0&&g.depth==_.depth&&u.sel&&u.sel.anchor==u.sel.head&&u.sel.head==h.endA&&(h.endB-=2,_=u.doc.resolveNoCache(h.endB-u.from),setTimeout(()=>{e.someProp(`handleKeyDown`,function(t){return t(e,keyEvent(13,`Enter`))})},20));let x=h.start,S=h.endA,w=t=>{let n=t||e.state.tr.replace(x,S,u.doc.slice(h.start-u.from,h.endB-u.from));if(u.sel){let t=resolveSelection(e,n.doc,u.sel);t&&!(chrome&&e.composing&&t.empty&&(h.start!=h.endB||e.input.lastChromeDelete<Date.now()-100)&&(t.head==x||t.head==n.mapping.map(S)-1)||ie$1&&t.empty&&t.head==x)&&n.setSelection(t)}return o&&n.setMeta(`composition`,o),n.scrollIntoView()},E;if(y){if(g.pos==_.pos){ie$1&&ie_version<=11&&g.parentOffset==0&&(e.domObserver.suppressSelectionUpdates(),setTimeout(()=>selectionToDOM(e),20));let t=w(e.state.tr.delete(x,S)),n=d.resolve(h.start).marksAcross(d.resolve(h.endA));n&&t.ensureMarks(n),e.dispatch(t)}else if(h.endA==h.endB&&(E=isMarkChange(g.parent.content.cut(g.parentOffset,_.parentOffset),v.parent.content.cut(v.parentOffset,h.endA-v.start())))){let t=w(e.state.tr);E.type==`add`?t.addMark(x,S,E.mark):t.removeMark(x,S,E.mark),e.dispatch(t)}else if(g.parent.child(g.index()).isText&&g.index()==_.index()-+!_.textOffset){let t=g.parent.textBetween(g.parentOffset,_.parentOffset),n=()=>w(e.state.tr.insertText(t,x,S));e.someProp(`handleTextInput`,r=>r(e,x,S,t,n))||e.dispatch(n())}}else e.dispatch(w())}function resolveSelection(e,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:selectionBetween(e,t.resolve(n.anchor),t.resolve(n.head))}function isMarkChange(e,t){let n=e.firstChild.marks,r=t.firstChild.marks,a=n,o=r,s,c,l;for(let e=0;e<r.length;e++)a=r[e].removeFromSet(a);for(let e=0;e<n.length;e++)o=n[e].removeFromSet(o);if(a.length==1&&o.length==0)c=a[0],s=`add`,l=e=>e.mark(c.addToSet(e.marks));else if(a.length==0&&o.length==1)c=o[0],s=`remove`,l=e=>e.mark(c.removeFromSet(e.marks));else return null;let u=[];for(let e=0;e<t.childCount;e++)u.push(l(t.child(e)));if(Fragment.from(u).eq(e))return{mark:c,type:s}}function looksLikeBackspace(e,t,n,r,a){if(n-t<=a.pos-r.pos||skipClosingAndOpening(r,!0,!1)<a.pos)return!1;let o=e.resolve(t);if(!r.parent.isTextblock){let e=o.nodeAfter;return e!=null&&n==t+e.nodeSize}if(o.parentOffset<o.parent.content.size||!o.parent.isTextblock)return!1;let s=e.resolve(skipClosingAndOpening(o,!0,!0));return!s.parent.isTextblock||s.pos>n||skipClosingAndOpening(s,!0,!1)<n?!1:r.parent.content.cut(r.parentOffset).eq(s.parent.content)}function skipClosingAndOpening(e,t,n){let r=e.depth,a=t?e.end():e.pos;for(;r>0&&(t||e.indexAfter(r)==e.node(r).childCount);)r--,a++,t=!1;if(n){let t=e.node(r).maybeChild(e.indexAfter(r));for(;t&&!t.isLeaf;)t=t.firstChild,a++}return a}function findDiff(e,t,n,r,a){let o=e.findDiffStart(t,n);if(o==null)return null;let{a:s,b:c}=e.findDiffEnd(t,n+e.size,n+t.size);if(a==`end`){let e=Math.max(0,o-Math.min(s,c));r-=s+e-o}if(s<o&&e.size<t.size){let e=r<=o&&r>=s?o-r:0;o-=e,o&&o<t.size&&isSurrogatePair(t.textBetween(o-1,o+1))&&(o+=e?1:-1),c=o+(c-s),s=o}else if(c<o){let t=r<=o&&r>=c?o-r:0;o-=t,o&&o<e.size&&isSurrogatePair(e.textBetween(o-1,o+1))&&(o+=t?1:-1),s=o+(s-c),c=o}return{start:o,endA:s,endB:c}}function isSurrogatePair(e){if(e.length!=2)return!1;let t=e.charCodeAt(0),n=e.charCodeAt(1);return t>=56320&&t<=57343&&n>=55296&&n<=56319}var EditorView=class{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new InputState,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(checkStateComponent$1),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement(`div`),e&&(e.appendChild?e.appendChild(this.dom):typeof e==`function`?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=getEditable$1(this),updateCursorWrapper(this),this.nodeViews=buildNodeViews$1(this),this.docView=docViewDesc(this.state.doc,computeDocDeco(this),viewDecorations(this),this.dom,this),this.domObserver=new DOMObserver(this,(e,t,n,r)=>readDOMChange(this,e,t,n,r)),this.domObserver.start(),initInput(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&ensureListeners(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(checkStateComponent$1),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let e in this._props)t[e]=this._props[e];t.state=this.state;for(let n in e)t[n]=e[n];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var n;let r=this.state,a=!1,o=!1;e.storedMarks&&this.composing&&(clearComposition(this),o=!0),this.state=e;let s=r.plugins!=e.plugins||this._props.plugins!=t.plugins;if(s||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let e=buildNodeViews$1(this);changedNodeViews$1(e,this.nodeViews)&&(this.nodeViews=e,a=!0)}(s||t.handleDOMEvents!=this._props.handleDOMEvents)&&ensureListeners(this),this.editable=getEditable$1(this),updateCursorWrapper(this);let c=viewDecorations(this),l=computeDocDeco(this),u=r.plugins!=e.plugins&&!r.doc.eq(e.doc)?`reset`:e.scrollToSelection>r.scrollToSelection?`to selection`:`preserve`,d=a||!this.docView.matchesNode(e.doc,l,c);(d||!e.selection.eq(r.selection))&&(o=!0);let f=u==`preserve`&&o&&this.dom.style.overflowAnchor==null&&storeScrollPos(this);if(o){this.domObserver.stop();let t=d&&(ie$1||chrome)&&!this.composing&&!r.selection.empty&&!e.selection.empty&&selectionContextChanged(r.selection,e.selection);if(d){let n=chrome?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=findCompositionNode(this)),(a||!this.docView.update(e.doc,l,c,this))&&(this.docView.updateOuterDeco(l),this.docView.destroy(),this.docView=docViewDesc(e.doc,l,c,this.dom,this)),n&&!this.trackWrites&&(t=!0)}t||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&anchorInRightPlace(this))?selectionToDOM(this,t):(syncNodeSelection(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(r),this.dragging?.node&&!r.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,r),u==`reset`?this.dom.scrollTop=0:u==`to selection`?this.scrollToSelection():f&&resetScrollPos(f)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))&&!this.someProp(`handleScrollToSelection`,e=>e(this)))if(this.state.selection instanceof NodeSelection){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&scrollRectIntoView(this,t.getBoundingClientRect(),e)}else scrollRectIntoView(this,this.coordsAtPos(this.state.selection.head,1),e)}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let e=0;e<this.directPlugins.length;e++){let t=this.directPlugins[e];t.spec.view&&this.pluginViews.push(t.spec.view(this))}for(let e=0;e<this.state.plugins.length;e++){let t=this.state.plugins[e];t.spec.view&&this.pluginViews.push(t.spec.view(this))}}else for(let t=0;t<this.pluginViews.length;t++){let n=this.pluginViews[t];n.update&&n.update(this,e)}}updateDraggedNode(e,t){let n=e.node,r=-1;if(this.state.doc.nodeAt(n.from)==n.node)r=n.from;else{let e=n.from+(this.state.doc.content.size-t.doc.content.size);(e>0&&this.state.doc.nodeAt(e))==n.node&&(r=e)}this.dragging=new Dragging(e.slice,e.move,r<0?void 0:NodeSelection.create(this.state.doc,r))}someProp(e,t){let n=this._props&&this._props[e],r;if(n!=null&&(r=t?t(n):n))return r;for(let n=0;n<this.directPlugins.length;n++){let a=this.directPlugins[n].props[e];if(a!=null&&(r=t?t(a):a))return r}let a=this.state.plugins;if(a)for(let n=0;n<a.length;n++){let o=a[n].props[e];if(o!=null&&(r=t?t(o):o))return r}}hasFocus(){if(ie$1){let e=this.root.activeElement;if(e==this.dom)return!0;if(!e||!this.dom.contains(e))return!1;for(;e&&this.dom!=e&&this.dom.contains(e);){if(e.contentEditable==`false`)return!1;e=e.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&focusPreventScroll(this.dom),selectionToDOM(this),this.domObserver.start()}get root(){let e=this._root;if(e==null){for(let e=this.dom.parentNode;e;e=e.parentNode)if(e.nodeType==9||e.nodeType==11&&e.host)return e.getSelection||(Object.getPrototypeOf(e).getSelection=()=>e.ownerDocument.getSelection()),this._root=e}return e||document}updateRoot(){this._root=null}posAtCoords(e){return posAtCoords(this,e)}coordsAtPos(e,t=1){return coordsAtPos(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,n=-1){let r=this.docView.posFromDOM(e,t,n);if(r==null)throw RangeError(`DOM position not inside the editor`);return r}endOfTextblock(e,t){return endOfTextblock(this,t||this.state,e)}pasteHTML(e,t){return doPaste(this,``,e,!1,t||new ClipboardEvent(`paste`))}pasteText(e,t){return doPaste(this,e,null,!0,t||new ClipboardEvent(`paste`))}serializeForClipboard(e){return serializeForClipboard(this,e)}destroy(){this.docView&&(destroyInput(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],viewDecorations(this),this),this.dom.textContent=``):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,clearReusedRange())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return dispatchEvent(this,e)}domSelectionRange(){let e=this.domSelection();return e?safari&&this.root.nodeType===11&&deepActiveElement(this.dom.ownerDocument)==this.dom&&safariShadowSelectionRange(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}};EditorView.prototype.dispatch=function(e){let t=this._props.dispatchTransaction;t?t.call(this,e):this.updateState(this.state.apply(e))};function computeDocDeco(e){let t=Object.create(null);return t.class=`ProseMirror`,t.contenteditable=String(e.editable),e.someProp(`attributes`,n=>{if(typeof n==`function`&&(n=n(e.state)),n)for(let e in n)e==`class`?t.class+=` `+n[e]:e==`style`?t.style=(t.style?t.style+`;`:``)+n[e]:!t[e]&&e!=`contenteditable`&&e!=`nodeName`&&(t[e]=String(n[e]))}),t.translate||=`no`,[Decoration.node(0,e.state.doc.content.size,t)]}function updateCursorWrapper(e){if(e.markCursor){let t=document.createElement(`img`);t.className=`ProseMirror-separator`,t.setAttribute(`mark-placeholder`,`true`),t.setAttribute(`alt`,``),e.cursorWrapper={dom:t,deco:Decoration.widget(e.state.selection.from,t,{raw:!0,marks:e.markCursor})}}else e.cursorWrapper=null}function getEditable$1(e){return!e.someProp(`editable`,t=>t(e.state)===!1)}function selectionContextChanged(e,t){let n=Math.min(e.$anchor.sharedDepth(e.head),t.$anchor.sharedDepth(t.head));return e.$anchor.start(n)!=t.$anchor.start(n)}function buildNodeViews$1(e){let t=Object.create(null);function n(e){for(let n in e)Object.prototype.hasOwnProperty.call(t,n)||(t[n]=e[n])}return e.someProp(`nodeViews`,n),e.someProp(`markViews`,n),t}function changedNodeViews$1(e,t){let n=0,r=0;for(let r in e){if(e[r]!=t[r])return!0;n++}for(let e in t)r++;return n!=r}function checkStateComponent$1(e){if(e.spec.state||e.spec.filterTransaction||e.spec.appendTransaction)throw RangeError(`Plugins passed directly to the view must not have a state component`)}var WorkspaceImpl=class extends EventTarget{files=new Map;constructor(){super()}async restart(){this.files.clear(),this.dispatchEvent(new CustomEvent(`restart`))}getFiles(){return Array.from(this.files.keys())}getFile(e){return this.files.get(e)||null}openFile(e){this.files.set(e.uri,e),this.dispatchEvent(new CustomEvent(`openFile`,{detail:e}))}modifyFile(e){let t=this.files.get(e.uri)||e;t.lang=e.lang,t.version=e.version,t.getContentMapper=e.getContentMapper,this.files.set(e.uri,t),this.dispatchEvent(new CustomEvent(`modifyFile`,{detail:e}))}closeFile(e){this.dispatchEvent(new CustomEvent(`closeFile`,{detail:{uri:e}})),this.files.delete(e)}},MAX_MATCH=500,InputRule=class{regex;handler;undoable;inCode;constructor(e,t,n={}){this.regex=e,this.regex=e,this.handler=typeof t==`string`?stringHandler(t):t,this.undoable=n.undoable!==!1,this.inCode=n.inCode||!1}};function stringHandler(e){return function(t,n,r,a,o){t||=n.tr;let s=e;if(r[1]){let e=r[0].lastIndexOf(r[1]);s+=r[0].slice(e+r[1].length),a+=e;let t=a-o;t>0&&(s=r[0].slice(e-t,e)+s,a=o)}return t.insertText(s,a,o)}}var InputRulesPlugin=class extends Plugin{constructor(e){super({key:new PluginKey(`input-rules`),state:{init(){return null},apply(e,t){return e.getMeta(this)||(e.selectionSet||e.docChanged?null:t)}},props:{handleTextInput(e,t,n,r){return runInputRulesRange(t,n,r)(e.state,t=>{e.dispatch(t)},e)},handleDOMEvents:{compositionend:e=>{setTimeout(()=>{let{$cursor:t}=e.state.selection;if(t)return runInputRulesRange(t.pos,t.pos,``)(e.state,t=>{e.dispatch(t)},e)})}}},rules:e,isInputRules:!0})}},runInputRulesTexts=()=>{let e=(e,t,n)=>{let r=e.plugins.find(e=>e.spec.isInputRules);if(!r)return!1;let a=r.spec.rules;if(n?.composing)return!1;let o=e.doc,s=e.tr;for(let t=0;t<a.length;t++){let n=a[t],c=[];if(o.descendants((e,t)=>{e.isText&&c.push({pos:t,node:e})}),c.length===0)return!1;for(let t=c.length-1;t>=0;t--){let{pos:a,node:l}=c[t];if(!l.isText||!l.text)continue;let u=l.text;if(l.type.spec.code){if(!n.inCode)continue}else if(n.inCode===`only`)continue;let d=n.regex.exec(u);if(!d)continue;let f=d.index,p=a+f,m=a+f+d[0].length,h=n.handler(s,e,d,p,m);h&&(s=h,o=s.doc,n.undoable&&s.setMeta(r,{transform:s,from:p,to:m,text:u}))}}return t&&t(s),s.docChanged};return e.displayName=`runInputRulesTexts`,e},runInputRulesRange=(e,t,n)=>{let r=(r,a,o)=>{let s=r.plugins.find(e=>e.spec.isInputRules);if(!s)return!1;let c=s.spec.rules;if(o?.composing)return!1;let l=r.doc.resolve(e),u=l.parent.textBetween(Math.max(0,l.parentOffset-MAX_MATCH),l.parentOffset,null,``)+n,d=r.tr;for(let a=0;a<c.length;a++){let o=c[a];if(l.parent.type.spec.code){if(!o.inCode)continue}else if(o.inCode===`only`)continue;let f=o.regex.exec(u);if(!f)continue;let p=o.handler(d,r,f,d.mapping.map(e-(f[0].length-n.length)),d.mapping.map(t));if(p){d=p,o.undoable&&d.setMeta(s,{transform:d,from:e,to:t,text:n});break}}return d.docChanged?(a?.(d),!0):!1};return r.displayName=`runInputRulesRange`,r},undoInputRuleCommand=(e,t)=>{let n=e.plugins.find(e=>e.spec.isInputRules);if(!n)return!1;let r=n.getState(e);if(!r)return!1;if(t){let n=e.tr,a=r.transform;for(let e=a.steps.length-1;e>=0;e--)n.step(a.steps[e].invert(a.docs[e]));if(r.text){let t=n.doc.resolve(r.from).marks();n.replaceWith(r.from,r.to,e.schema.text(r.text,t))}else n.delete(r.from,r.to);t(n)}return!0},base={8:`Backspace`,9:`Tab`,10:`Enter`,12:`NumLock`,13:`Enter`,16:`Shift`,17:`Control`,18:`Alt`,20:`CapsLock`,27:`Escape`,32:` `,33:`PageUp`,34:`PageDown`,35:`End`,36:`Home`,37:`ArrowLeft`,38:`ArrowUp`,39:`ArrowRight`,40:`ArrowDown`,44:`PrintScreen`,45:`Insert`,46:`Delete`,59:`;`,61:`=`,91:`Meta`,92:`Meta`,106:`*`,107:`+`,108:`,`,109:`-`,110:`.`,111:`/`,144:`NumLock`,145:`ScrollLock`,160:`Shift`,161:`Shift`,162:`Control`,163:`Control`,164:`Alt`,165:`Alt`,173:`-`,186:`;`,187:`=`,188:`,`,189:`-`,190:`.`,191:`/`,192:"`",219:`[`,220:`\\`,221:`]`,222:`'`},shift={48:`)`,49:`!`,50:`@`,51:`#`,52:`$`,53:`%`,54:`^`,55:`&`,56:`*`,57:`(`,59:`:`,61:`+`,173:`_`,186:`:`,187:`+`,188:`<`,189:`_`,190:`>`,191:`?`,192:`~`,219:`{`,220:`|`,221:`}`,222:`"`},mac$1=typeof navigator<`u`&&/Mac/.test(navigator.platform),ie=typeof navigator<`u`&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(let e=0;e<10;e++)base[48+e]=base[96+e]=String(e);for(let e=1;e<=24;e++)base[e+111]=`F`+e;for(let e=65;e<=90;e++)base[e]=String.fromCharCode(e+32),shift[e]=String.fromCharCode(e);for(let e in base)Object.prototype.hasOwnProperty.call(shift,e)||(shift[e]=base[e]);function keyName(e){let t=!(mac$1&&e.metaKey&&e.shiftKey&&!e.ctrlKey&&!e.altKey||ie&&e.shiftKey&&e.key&&e.key.length==1||e.key==`Unidentified`)&&e.key||(e.shiftKey?shift:base)[e.keyCode]||e.key||`Unidentified`;return t==`Esc`&&(t=`Escape`),t==`Del`&&(t=`Delete`),t==`Left`&&(t=`ArrowLeft`),t==`Up`&&(t=`ArrowUp`),t==`Right`&&(t=`ArrowRight`),t==`Down`&&(t=`ArrowDown`),t}var mac=typeof navigator<`u`&&/Mac|iP(hone|[oa]d)/.test(navigator?.platform),windows=typeof navigator<`u`&&/Win/.test(navigator?.platform);function normalizeKeyName(e){let t=e.split(/-(?!$)/),n=t[t.length-1];n==`Space`&&(n=` `);let r,a,o,s;for(let e=0;e<t.length-1;e++){let n=t[e];if(/^(cmd|meta|m)$/i.test(n))s=!0;else if(/^a(lt)?$/i.test(n))r=!0;else if(/^(c|ctrl|control)$/i.test(n))a=!0;else if(/^s(hift)?$/i.test(n))o=!0;else if(/^mod$/i.test(n))mac?s=!0:a=!0;else throw Error(`Unrecognized modifier name: `+n)}return r&&(n=`Alt-`+n),a&&(n=`Ctrl-`+n),s&&(n=`Meta-`+n),o&&(n=`Shift-`+n),n}function normalize(e){let t=Object.create(null);for(let n in e)t[normalizeKeyName(n)]=e[n];return t}function modifiers(e,t,n=!0){return t.altKey&&(e=`Alt-`+e),t.ctrlKey&&(e=`Ctrl-`+e),t.metaKey&&(e=`Meta-`+e),n&&t.shiftKey&&(e=`Shift-`+e),e}var KeymapPlugin=class extends Plugin{constructor(e){super({key:new PluginKey(`keymap`),props:{handleKeyDown:keydownHandler(e)}})}};function keydownHandler(e){let t=normalize(e);return function(e,n){let r=keyName(n),a,o=t[modifiers(r,n)];if(o&&o(e.state,e.dispatch,e))return!0;if(r.length==1&&r!=` `){if(n.shiftKey){let a=t[modifiers(r,n,!1)];if(a&&a(e.state,e.dispatch,e))return!0}if((n.altKey||n.metaKey||n.ctrlKey)&&!(windows&&n.ctrlKey&&n.altKey)&&(a=base[n.keyCode])&&a!=r){let r=t[modifiers(a,n)];if(r&&r(e.state,e.dispatch,e))return!0}}return!1}}function firstCommand$1(...e){let t=function(t,n,r){for(let a=0;a<e.length;a++)if(e[a](t,n,r))return e[a].displayName!==`first`&&console.debug(`firstCommand: `,e[a].displayName||e[a]),!0;return!1};return t.displayName=`first`,t}function getHtmlAttributes(e,t){let n={};if(e.attributes)for(let[r,a]of Object.entries(e.attributes))t.attrs[r]===void 0?a.toDom?n[r]=a.toDom(t):n[r]=a.default:n[r]=t.attrs[r];return n}function setHtmlAttributes(e,t){let n={};if(e.attributes)for(let[r,a]of Object.entries(e.attributes))a.fromDom?n[r]=a.fromDom(t):n[r]=a.default;return n}function addAttributesToSchema(e,t){if(t.attributes){e.attrs||={};for(let[n,r]of Object.entries(t.attributes))e.attrs[n]=r,r.toDom||=e=>e.attrs[n]}}var TrackSelecionPlugin=class extends Plugin{constructor(e){super({key:new PluginKey(`track-selection`),view(t){return{update(t,n){let r=t.state,a=n.selection,o=r.selection;if(!a.eq(o)){let t=new CustomEvent(`selection`,{detail:{selection:o}});e.dispatchEvent(t)}}}}})}},yaml_exports=require_rolldown_runtime.n({fromJSON:()=>fromJSON,parse:()=>parse$1,setPathValue:()=>setPathValue,stringify:()=>stringify,toJSON:()=>toJSON}),findUnquotedColon=e=>{let t=!1,n=!1;for(let r=0;r<e.length;r++){let a=e[r];if(a===`"`&&!t)n=!n;else if(a===`'`&&!n)t=!t;else if(a===`:`&&!t&&!n)return r}return-1};function parse$1(e){let t=e.replace(/\r\n/g,`
10
10
  `).split(`
11
11
  `).filter(e=>e.trim().length>0&&!e.trim().startsWith(`#`)),n=e=>(e=e.trim(),e===``||e===`null`?null:e===`true`?!0:e===`false`?!1:isNaN(Number(e))?e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e:Number(e)),r=0,a=e=>{let o=null,s=null;for(;r<t.length;){let c=t[r],l=c.match(/^ */)?.[0].length??0;if(l<e)break;let u=c.trim();if(u.startsWith(`-`)){if(o===null&&(o=[],s=!0),s===!1)throw Error(`Mixed array/object structure`);s=!0;let e=u.slice(1).trim();if(e===``)r++,o.push(a(l+2));else{let s=findUnquotedColon(e);if(s===-1)o.push(n(e)),r++;else{let c=new Map,u=e.slice(0,s).trim(),d=e.slice(s+1).trim();for(r++,c.set(u,d===``?a(l+2):n(d));r<t.length;){let e=t[r],o=e.match(/^ */)?.[0].length??0;if(o<=l)break;let s=e.trim(),u=findUnquotedColon(s);if(u===-1)break;let d=s.slice(0,u).trim(),f=s.slice(u+1).trim();r++,c.set(d,f===``?a(o+2):n(f))}o.push(c)}}continue}let d=u.indexOf(`:`);if(d===-1)throw Error(`Invalid line: ${c}`);if(o===null&&(o=new Map,s=!1),s===!0)throw Error(`Mixed array/object structure`);let f=u.slice(0,d).trim(),p=u.slice(d+1).trim();r++,o.set(f,p===``?a(l+2):n(p))}return o??new Map};return a(0)}function stringify(e,t=2){e=fromJSON(e);let n=e=>` `.repeat(e*t),r=e=>typeof e==`object`&&!!e&&!Array.isArray(e),a=[];function o(e,t,c){let l=c===void 0?n(t):n(t)+c+`: `;if(e===null){a.push(l+`null`);return}if(typeof e==`number`||typeof e==`boolean`){a.push(l+String(e));return}if(typeof e==`string`){let t=/[:\s]/.test(e)?`"${e}"`:e;a.push(l+t);return}if(Array.isArray(e)){c!==void 0&&(a.push(n(t)+c+`:`),t++);for(let c of e)Array.isArray(c)||r(c)?(a.push(n(t)+`-`),o(c,t+1)):a.push(n(t)+`- `+s(c));return}if(r(e)){c!==void 0&&(a.push(n(t)+c+`:`),t++);for(let[n,r]of e)o(r,t,n);return}a.push(l+String(e))}function s(e){return e===null?`null`:typeof e==`string`?/[:\s]/.test(e)?`"${e}"`:e:String(e)}return o(e,0),a.join(`
12
- `)}function fromJSON(e){if(e===null)return null;if(Array.isArray(e))return e.map(fromJSON);if(typeof e==`object`){if(e instanceof Map)return e;let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,fromJSON(r));return t}if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;throw Error(`Unsupported JSON value: ${typeof e}`)}function toJSON(e){if(e instanceof Map){let t={};for(let[n,r]of e)t[n]=toJSON(r);return t}return Array.isArray(e)?e.map(toJSON):e}function setPathValue(e,t,n){let r=t.match(/[^.\[\]]+|\[\d+\]/g)?.map(e=>e.startsWith(`[`)?Number(e.slice(1,-1)):e)??[];if(r.length===0)throw Error(`empty path`);if(!(e instanceof Map)&&!Array.isArray(e))throw Error(`root must be Map or array`);let a=e;for(let e=0;e<r.length-1;e++){let n=r[e],o=typeof n==`number`?Array.isArray(a)?a[n]:void 0:a instanceof Map?a.get(n):void 0;if(!(o instanceof Map)&&!Array.isArray(o)){if(o!=null)throw console.log(`next`,o),Error(`"${n}" #${e} of "${t}" not container`);o=typeof r[e+1]==`number`?[]:new Map,typeof n==`number`?a[n]=o:a.set(n,o)}a=o}let o=r[r.length-1];if(typeof o==`number`){if(!Array.isArray(a))throw Error(`target not array`);for(;a.length<=o;)a.push(null);a[o]=n}else{if(!(a instanceof Map))throw Error(`target not map`);a.set(o,n)}}var SearchQuery=class{search;caseSensitive;literal;regexp;replace;valid;wholeWord;filter;impl;constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||``,this.valid=!!this.search&&!(this.regexp&&!validRegExp(this.search)),this.wholeWord=!!e.wholeWord,this.filter=e.filter||null,this.impl=this.valid?this.regexp?new RegExpQuery(this):new StringQuery(this):nullQuery}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord}findNext(e,t=0,n=e.doc.content.size){for(;;){if(t>=n)return null;let r=this.impl.findNext(e,t,n);if(!r||this.checkResult(e,r))return r;t=r.from+1}}findPrev(e,t=e.doc.content.size,n=0){for(;;){if(t<=n)return null;let r=this.impl.findPrev(e,t,n);if(!r||this.checkResult(e,r))return r;t=r.to-1}}checkResult(e,t){return(!this.wholeWord||checkWordBoundary(e,t.from)&&checkWordBoundary(e,t.to))&&(!this.filter||this.filter(e,t))}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(e,t)=>t==`n`?`
13
- `:t==`r`?`\r`:t==`t`?` `:`\\`)}getReplacements(e,t){let n=e.doc.resolve(t.from).marksAcross(e.doc.resolve(t.to)),r=[],a=Fragment.empty,o=t.from,{match:s}=t,c=s?getGroupIndices(s):[[0,t.to-t.from]],l=parseReplacement(this.unquote(this.replace)),u;for(let s of l)if(typeof s==`string`)a=a.addToEnd(e.schema.text(s,n));else if(u=c[s.group],u){let n=t.matchStart+u[0],c=t.matchStart+u[1];s.copy?a=a.append(e.doc.slice(n,c).content):((a!=Fragment.empty||n>o)&&(r.push({from:o,to:n,insert:new Slice(a,0,0)}),a=Fragment.empty),o=c)}return(a!=Fragment.empty||o<t.to)&&r.push({from:o,to:t.to,insert:new Slice(a,0,0)}),r}},nullQuery=new class{findNext(){return null}findPrev(){return null}},StringQuery=class{query;string;constructor(e){this.query=e;let t=e.unquote(e.search);e.caseSensitive||(t=t.toLowerCase()),this.string=t}findNext(e,t,n){return scanTextblocks(e.doc,t,n,(e,r)=>{let a=Math.max(t,r),o=textContent(e).slice(a-r,Math.min(e.content.size,n-r)),s=(this.query.caseSensitive?o:o.toLowerCase()).indexOf(this.string);return s<0?null:{from:a+s,to:a+s+this.string.length,match:null,matchStart:r}})}findPrev(e,t,n){return scanTextblocks(e.doc,t,n,(e,r)=>{let a=Math.max(r,n),o=textContent(e).slice(a-r,Math.min(e.content.size,t-r));this.query.caseSensitive||(o=o.toLowerCase());let s=o.lastIndexOf(this.string);return s<0?null:{from:a+s,to:a+s+this.string.length,match:null,matchStart:r}})}},baseFlags=`g`+(/x/.unicode==null?``:`u`)+(/x/.hasIndices==null?``:`d`),RegExpQuery=class{query;regexp;constructor(e){this.query=e,this.regexp=new RegExp(e.search,baseFlags+(e.caseSensitive?``:`i`))}findNext(e,t,n){return scanTextblocks(e.doc,t,n,(e,r)=>{let a=textContent(e).slice(0,Math.min(e.content.size,n-r));this.regexp.lastIndex=t-r;let o=this.regexp.exec(a);return o?{from:r+o.index,to:r+o.index+o[0].length,match:o,matchStart:r}:null})}findPrev(e,t,n){return scanTextblocks(e.doc,t,n,(e,n)=>{let r=textContent(e).slice(0,Math.min(e.content.size,t-n)),a;for(let e=0;;){this.regexp.lastIndex=e;let t=this.regexp.exec(r);if(!t)break;a=t,e=t.index+1}return a?{from:n+a.index,to:n+a.index+a[0].length,match:a,matchStart:n}:null})}};function getGroupIndices(e){if(e.indices)return e.indices;let t=[[0,e[0].length]];for(let n=1,r=0;n<e.length;n++){let a=e[n]?e[0].indexOf(e[n],r):-1;t.push(a<0?void 0:[a,r=a+e[n].length])}return t}function parseReplacement(e){let t=[],n=-1;function r(e){let n=t.length-1;n>-1&&typeof t[n]==`string`?t[n]+=e:t.push(e)}for(;e.length;){let a=/\$([$&\d+])/.exec(e);if(!a)return r(e),t;if(a.index>0&&r(e.slice(0,a.index+ +(a[1]==`$`))),a[1]!=`$`){let e=a[1]==`&`?0:+a[1];n>=e?t.push({group:e,copy:!0}):(n=e||1e3,t.push({group:e,copy:!1}))}e=e.slice(a.index+a[0].length)}return t}function validRegExp(e){try{return new RegExp(e,baseFlags),!0}catch{return!1}}var TextContentCache=new WeakMap;function textContent(e){let t=TextContentCache.get(e);if(t)return t;let n=``;for(let t=0;t<e.childCount;t++){let r=e.child(t);r.isText?n+=r.text:r.isLeaf?n+=``:n+=` `+textContent(r)+` `}return TextContentCache.set(e,n),n}function scanTextblocks(e,t,n,r,a=0){if(e.inlineContent)return r(e,a);if(!e.isLeaf)if(t>n)for(let o=e.childCount-1,s=a+e.content.size;o>=0&&s>n;o--){let a=e.child(o);if(s-=a.nodeSize,s<t){let e=scanTextblocks(a,t,n,r,s+1);if(e!=null)return e}}else for(let o=0,s=a;o<e.childCount&&s<n;o++){let a=e.child(o),c=s;if(s+=a.nodeSize,s>t){let e=scanTextblocks(a,t,n,r,c+1);if(e!=null)return e}}return null}function checkWordBoundary(e,t){let n=e.doc.resolve(t),r=n.nodeBefore,a=n.nodeAfter;return!r||!a||!r.isText||!a.isText?!0:!/\p{L}$/u.test(r.text)||!/^\p{L}/u.test(a.text)}var SearchState=class{query;range;deco;constructor(e,t,n){this.query=e,this.range=t,this.deco=n}};function buildMatchDeco(e,t,n){if(!t.valid)return DecorationSet.empty;let r=[],a=e.selection;for(let o=n?n.from:0,s=n?n.to:e.doc.content.size;;){let n=t.findNext(e,o,s);if(!n)break;let c=n.from==a.from&&n.to==a.to?`kb-active-search-match`:`kb-search-match`;r.push(Decoration.inline(n.from,n.to,{class:c})),o=n.to}return DecorationSet.create(e.doc,r)}var searchKey=new PluginKey(`search`);function createSearchPlugin(e={}){return new Plugin({key:searchKey,state:{init(t,n){let r=e.initialQuery||new SearchQuery({search:``}),a=e.initialRange||null;return new SearchState(r,a,buildMatchDeco(n,r,a))},apply(e,t,n,r){let a=e.getMeta(searchKey);if(a)return new SearchState(a.query,a.range,buildMatchDeco(r,a.query,a.range));if(e.docChanged||e.selectionSet){let n=t.range;if(n){let t=e.mapping.map(n.from,1),r=e.mapping.map(n.to,-1);n=t<r?{from:t,to:r}:null}t=new SearchState(t.query,n,buildMatchDeco(r,t.query,n))}return t}},props:{decorations:e=>searchKey.getState(e).deco}})}function setSearchState(e,t,n=null){return e.setMeta(searchKey,{query:t,range:n})}function nextMatch(e,t,n,r,a){let o=e.range||{from:0,to:t.doc.content.size},s=e.query.findNext(t,Math.max(a,o.from),o.to);return!s&&n&&(s=e.query.findNext(t,o.from,Math.min(r,o.to))),s}function prevMatch(e,t,n,r,a){let o=e.range||{from:0,to:t.doc.content.size},s=e.query.findPrev(t,Math.min(r,o.to),o.from);return!s&&n&&(s=e.query.findPrev(t,o.to,Math.max(a,o.from))),s}function findCommand(e,t){return(n,r)=>{let a=searchKey.getState(n);if(!a||!a.query.valid)return!1;let{from:o,to:s}=n.selection,c=t>0?nextMatch(a,n,e,o,s):prevMatch(a,n,e,o,s);if(!c)return!1;let l=TextSelection.create(n.doc,c.from,c.to);return r&&r(n.tr.setSelection(l).scrollIntoView()),!0}}var findNext=findCommand(!0,1),findNextNoWrap=findCommand(!1,1),findPrev=findCommand(!0,-1),findPrevNoWrap=findCommand(!1,-1);function replaceCommand(e,t){return(n,r)=>{let a=searchKey.getState(n);if(!a||!a.query.valid)return!1;let{from:o}=n.selection,s=nextMatch(a,n,e,o,o);if(!s)return!1;if(!r)return!0;if(n.selection.from==s.from&&n.selection.to==s.to){let o=n.tr,c=a.query.getReplacements(n,s);for(let e=c.length-1;e>=0;e--){let{from:t,to:n,insert:r}=c[e];o.replace(t,n,r)}let l=t&&nextMatch(a,n,e,s.from,s.to);l?o.setSelection(TextSelection.create(o.doc,o.mapping.map(l.from,1),o.mapping.map(l.to,-1))):o.setSelection(TextSelection.create(o.doc,s.from,o.mapping.map(s.to,1))),r(o.scrollIntoView())}else if(t)r(n.tr.setSelection(TextSelection.create(n.doc,s.from,s.to)).scrollIntoView());else return!1;return!0}}var replaceNext=replaceCommand(!0,!0),replaceNextNoWrap=replaceCommand(!1,!0),replaceCurrent=replaceCommand(!1,!1),replaceAll=(e,t)=>{let n=searchKey.getState(e);if(!n)return!1;let r=[],a=n.range||{from:0,to:e.doc.content.size};for(let t=a.from;;){let o=n.query.findNext(e,t,a.to);if(!o)break;r.push(o),t=o.to}if(t){let a=e.tr;for(let t=r.length-1;t>=0;t--){let o=r[t],s=n.query.getReplacements(e,o);for(let e=s.length-1;e>=0;e--){let{from:t,to:n,insert:r}=s[e];a.replace(t,n,r)}}t(a)}return!0},searchFactory=(e,t=null)=>(n,r)=>{let a=n.tr;return setSearchState(a,e,t),r&&r(a),!0},searchCommandFactories={search:searchFactory,findNext:()=>findNext,findNextNoWrap:()=>findNextNoWrap,findPrev:()=>findPrev,findPrevNoWrap:()=>findPrevNoWrap,replaceNext:()=>replaceNext,replaceNextNoWrap:()=>replaceNextNoWrap,replaceCurrent:()=>replaceCurrent,replaceAll:()=>replaceAll};function splitExtensions(e){return{baseExtensions:Array.from(e).filter(e=>e.type===`extension`),nodeExtensions:Array.from(e).filter(e=>e.type===`node`),markExtensions:Array.from(e).filter(e=>e.type===`mark`)}}var ExtensionManager=class{editorKits;debug;extensions=new Set;plugins=[];nodeViews={};converters={};constructor(e,t=!1){this.editorKits=e,this.debug=t;let n=e.reduce((e,t)=>e.concat(t.getExtensions()),[]);this.setupExtensions(new Set(n))}initPlugins(e,t){let n=[],r=new Map,a=(t,n)=>{for(let n in t){if(!t[n])continue;let a=e.commandFactories[t[n]];if(!a){console.warn(`No command constructor: ${t[n]}`);continue}let o=a(),s=r.get(n);s?r.set(n,firstCommand$1(o,s)):r.set(n,o)}},o={};for(let r of this.extensions){if(r.setEditor(e),r.type===`node`){let s=t.nodes[r.name];n.push(...r.getInputRules(s)),this.plugins.push(...r.getProseMirrorPlugins()),e.mergeCommandFactories(r.getCommandFactories(e,s),r.name),a(r.getKeyboardShortcuts(e),r.name),o={...o,...r.getConverters(e,t)};let c=r.getNodeView(e);c&&(this.nodeViews[r.name]=c)}if(r.type===`mark`){let o=t.marks[r.name];n.push(...r.getInputRules(o)),e.mergeCommandFactories(r.getCommandFactories(e,o),r.name),a(r.getKeyboardShortcuts(e),r.name)}r.type===`extension`&&(this.plugins.push(...r.getProseMirrorPlugins()),e.mergeCommandFactories(r.getCommandFactories(e),r.name),a(r.getKeyboardShortcuts(e),r.name),o={...o,...r.getConverters(e,t)})}if(this.debug)for(let e in r){let t=r.get(e);t&&r.set(e,firstCommand$1((t,n,r)=>(console.debug(`Key: ${e}`),!0),t))}this.converters=o,this.plugins.push(new InputRulesPlugin(n)),this.plugins.push(new KeymapPlugin(Object.fromEntries(r))),this.plugins.push(createSearchPlugin()),this.plugins.push(new TrackSelecionPlugin(e))}setupExtensions(e){let t=new Map,n=e=>{for(let r of e){if(`name`in r){let e=t.get(r.name);if(e&&`type`in e&&r.type!==e.type)throw Error(`Duplicate mark/node: ${r.name}`);t.set(r.name,r)}if(`requires`in r){let e=Array.from(r.requires).filter(e=>typeof e!=`string`);n(new Set(e))}}};n(e);let r=new Set,a=e=>{this.debug&&console.info(`Initialize ${e.type} ${e.name}`),this.extensions.add(e)};function o(e){if(!(`name`in e&&r.has(e.name))){if(`requires`in e){let n=(e.requires||[]).map(e=>typeof e==`string`?e:`name`in e?e.name:``);for(let a of n)if(!r.has(a)){let n=t.get(a);if(!n)throw Error(`Required extension for (${`name`in e?e.name:e}) not found: ${a}`);o(n)}}`name`in e&&(a(e),r.add(e.name),t.delete(e.name))}}for(let e of t.values())o(e);if(t.size>0)throw Error(`Not all extensions initialized: `+Array.from(t.keys()).join(`, `))}getSchemaByResolvedExtensions(){let{nodeExtensions:e,markExtensions:t,baseExtensions:n}=splitExtensions(this.extensions),r={},a=``;for(let t of e){if(r[t.name]=t.getNodeSpec(),r[t.name].EMPTY_DOC){if(a)throw Error(`Multiple topNodes: ${t.name}, ${a}`);a=t.name}addAttributesToSchema(r[t.name],t)}let o={};for(let e of t)o[e.name]=e.getMarkSpec(),addAttributesToSchema(o[e.name],e);let s={topNode:a||`doc`,nodes:r,marks:o};for(let e of n)`setupSpec`in n&&e.setupSpec(s);return new Schema(s)}created(e,t){let{nodeExtensions:n,markExtensions:r,baseExtensions:a}=splitExtensions(this.extensions);for(let e of a){if(Array.isArray(e.overrides))for(let t of e.overrides)for(let e of this.extensions)e.name===t&&this.extensions.delete(e);if(Array.isArray(e.conflicts)){for(let t of e.conflicts)if(a.find(e=>e.name===t))throw Error(`Extension conflict: ${e.name} vs ${t}`)}}for(let t of a)e.ci.register(t.name,t);e.ci.register(`yaml`,yaml_exports),e.ci.register(`workspace`,new WorkspaceImpl),this.initPlugins(e,t);for(let e of this.extensions)e.created()}};function createChainableState(e,t){let{selection:n}=e,{doc:r}=e,{storedMarks:a}=e;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return a},get selection(){return n},get doc(){return r},get tr(){return n=e.selection,r=e.doc,a=e.storedMarks,e}}}var wrapInList=(e,t=null)=>function(n,r,a){let{$from:o,$to:s}=n.selection,c=o.blockRange(s);if(!c)return!1;let l=r?n.tr:null;return wrapRangeInList(l,c,e,t).apply(this,[n,r])?(r&&r(l.scrollIntoView()),!0):!1},wrapRangeInList=(e,t,n,r=null)=>()=>{let a=!1,o=t,s=t.$from.doc;if(t.depth>=2&&t.$from.node(t.depth-1).type.compatibleContent(n)&&t.startIndex==0){if(t.$from.index(t.depth-1)==0)return!1;let e=s.resolve(t.start-2);o=new NodeRange(e,e,t.depth),t.endIndex<t.parent.childCount&&(t=new NodeRange(t.$from,s.resolve(t.$to.end(t.depth)),t.depth)),a=!0}let c=findWrapping(o,n,r,t);return c?(e&&doWrapInList(e,t,c,a,n),!0):!1};function doWrapInList(e,t,n,r,a){let o=Fragment.empty;for(let e=n.length-1;e>=0;e--)o=Fragment.from(n[e].type.create(n[e].attrs,o));e.step(new ReplaceAroundStep(t.start-(r?2:0),t.end,t.start,t.end,new Slice(o,0,0),n.length,!0));let s=0;for(let e=0;e<n.length;e++)n[e].type==a&&(s=e+1);let c=n.length-s,l=t.start+n.length-(r?2:0),u=t.parent;for(let n=t.startIndex,r=t.endIndex,a=!0;n<r;n++,a=!1)!a&&canSplit(e.doc,l,c)&&(e.split(l,c),l+=2*c),l+=u.child(n).nodeSize;return e}var deleteSelection=()=>(e,t)=>e.selection.empty?!1:(t&&t(e.tr.deleteSelection().scrollIntoView()),!0);function atBlockStart(e,t){let{$cursor:n}=e.selection;return!n||(t?!t.endOfTextblock(`backward`,e):n.parentOffset>0)?null:n}var joinBackward=()=>(e,t,n)=>{let r=atBlockStart(e,n);if(!r)return!1;let a=findCutBefore(r);if(!a){let n=r.blockRange(),a=n&&liftTarget(n);return a==null?!1:(t&&t(e.tr.lift(n,a).scrollIntoView()),!0)}let o=a.nodeBefore;if(deleteBarrier(e,a,t,-1))return!0;if(r.parent.content.size==0&&(textblockAt(o,`end`)||NodeSelection.isSelectable(o)))for(let n=r.depth;;n--){let s=replaceStep(e.doc,r.before(n),r.after(n),Slice.empty);if(s&&s.slice.size<s.to-s.from){if(t){let n=e.tr.step(s);n.setSelection(textblockAt(o,`end`)?Selection.findFrom(n.doc.resolve(n.mapping.map(a.pos,-1)),-1):NodeSelection.create(n.doc,a.pos-o.nodeSize)),t(n.scrollIntoView())}return!0}if(n==1||r.node(n-1).childCount>1)break}return o.isAtom&&a.depth==r.depth-1?(t&&t(e.tr.delete(a.pos-o.nodeSize,a.pos).scrollIntoView()),!0):!1},joinTextblockBackward=()=>(e,t,n)=>{let r=atBlockStart(e,n);if(!r)return!1;let a=findCutBefore(r);return a?joinTextblocksAround(e,a,t):!1},joinTextblockForward=()=>(e,t,n)=>{let r=atBlockEnd(e,n);if(!r)return!1;let a=findCutAfter(r);return a?joinTextblocksAround(e,a,t):!1};function joinTextblocksAround(e,t,n){let r=t.nodeBefore,a=t.pos-1;for(;!r.isTextblock;a--){if(r.type.spec.isolating)return!1;let e=r.lastChild;if(!e)return!1;r=e}let o=t.nodeAfter,s=t.pos+1;for(;!o.isTextblock;s++){if(o.type.spec.isolating)return!1;let e=o.firstChild;if(!e)return!1;o=e}let c=replaceStep(e.doc,a,s,Slice.empty);if(!c||c.from!=a||c instanceof ReplaceStep&&c.slice.size>=s-a)return!1;if(n){let t=e.tr.step(c);t.setSelection(TextSelection.create(t.doc,a)),n(t.scrollIntoView())}return!0}function textblockAt(e,t,n=!1){for(let r=e;r;r=t==`start`?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}var selectNodeBackward=()=>(e,t,n)=>{let{$head:r,empty:a}=e.selection,o=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock(`backward`,e):r.parentOffset>0)return!1;o=findCutBefore(r)}let s=o&&o.nodeBefore;return!s||!NodeSelection.isSelectable(s)?!1:(t&&t(e.tr.setSelection(NodeSelection.create(e.doc,o.pos-s.nodeSize)).scrollIntoView()),!0)};function findCutBefore(e){if(!e.parent.type.spec.isolating)for(let t=e.depth-1;t>=0;t--){if(e.index(t)>0)return e.doc.resolve(e.before(t+1));if(e.node(t).type.spec.isolating)break}return null}function atBlockEnd(e,t){let{$cursor:n}=e.selection;return!n||(t?!t.endOfTextblock(`forward`,e):n.parentOffset<n.parent.content.size)?null:n}var joinForward=()=>(e,t,n)=>{let r=atBlockEnd(e,n);if(!r)return!1;let a=findCutAfter(r);if(!a)return!1;let o=a.nodeAfter;if(deleteBarrier(e,a,t,1))return!0;if(r.parent.content.size==0&&(textblockAt(o,`start`)||NodeSelection.isSelectable(o))){let n=replaceStep(e.doc,r.before(),r.after(),Slice.empty);if(n&&n.slice.size<n.to-n.from){if(t){let r=e.tr.step(n);r.setSelection(textblockAt(o,`start`)?Selection.findFrom(r.doc.resolve(r.mapping.map(a.pos)),1):NodeSelection.create(r.doc,r.mapping.map(a.pos))),t(r.scrollIntoView())}return!0}}return o.isAtom&&a.depth==r.depth-1?(t&&t(e.tr.delete(a.pos,a.pos+o.nodeSize).scrollIntoView()),!0):!1},selectNodeForward=()=>(e,t,n)=>{let{$head:r,empty:a}=e.selection,o=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock(`forward`,e):r.parentOffset<r.parent.content.size)return!1;o=findCutAfter(r)}let s=o&&o.nodeAfter;return!s||!NodeSelection.isSelectable(s)?!1:(t&&t(e.tr.setSelection(NodeSelection.create(e.doc,o.pos)).scrollIntoView()),!0)};function findCutAfter(e){if(!e.parent.type.spec.isolating)for(let t=e.depth-1;t>=0;t--){let n=e.node(t);if(e.index(t)+1<n.childCount)return e.doc.resolve(e.after(t+1));if(n.type.spec.isolating)break}return null}var joinUp=()=>(e,t)=>{let n=e.selection,r=n instanceof NodeSelection,a;if(r){if(n.node.isTextblock||!canJoin(e.doc,n.from))return!1;a=n.from}else if(a=joinPoint(e.doc,n.from,-1),a==null)return!1;if(t){let n=e.tr.join(a);r&&n.setSelection(NodeSelection.create(n.doc,a-e.doc.resolve(a).nodeBefore.nodeSize)),t(n.scrollIntoView())}return!0},joinDown=()=>(e,t)=>{let n=e.selection,r;if(n instanceof NodeSelection){if(n.node.isTextblock||!canJoin(e.doc,n.to))return!1;r=n.to}else if(r=joinPoint(e.doc,n.to,1),r==null)return!1;return t&&t(e.tr.join(r).scrollIntoView()),!0},lift=()=>(e,t)=>{let{$from:n,$to:r}=e.selection,a=n.blockRange(r),o=a&&liftTarget(a);return o==null?!1:(t&&t(e.tr.lift(a,o).scrollIntoView()),!0)},newlineInCode=()=>{let e=(e,t)=>{let{$head:n,$anchor:r}=e.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(t&&t(e.tr.insertText(`
14
- `).scrollIntoView()),!0)};return e.displayName=`newlineInCode()`,e};function defaultBlockAt(e){console.log(`defaultBlockAt`,e);for(let t=0;t<e.edgeCount;t++){let{type:n}=e.edge(t);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}var exitCode=()=>(e,t)=>{let{$head:n,$anchor:r}=e.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let a=n.node(-1),o=n.indexAfter(-1),s=defaultBlockAt(a.contentMatchAt(o));if(!s||!a.canReplaceWith(o,o,s))return!1;if(t){let r=n.after(),a=e.tr.replaceWith(r,r,s.createAndFill());a.setSelection(Selection.near(a.doc.resolve(r),1)),t(a.scrollIntoView())}return!0},createParagraphNear=()=>{let e=(e,t)=>{let n=e.selection,{$from:r,$to:a}=n;if(n instanceof AllSelection||r.parent.inlineContent||a.parent.inlineContent)return!1;let o=defaultBlockAt(a.parent.contentMatchAt(a.indexAfter()));if(!o||!o.isTextblock)return!1;if(t){let n=(!r.parentOffset&&a.index()<a.parent.childCount?r:a).pos,s=e.tr.insert(n,o.createAndFill());s.setSelection(TextSelection.create(s.doc,n+1)),t(s.scrollIntoView())}return!0};return e.displayName=`createParagraphNear()`,e},liftEmptyBlock=()=>{let e=(e,t)=>{let{$cursor:n}=e.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let r=n.before();if(canSplit(e.doc,r))return t&&t(e.tr.split(r).scrollIntoView()),!0}let r=n.blockRange(),a=r&&liftTarget(r);return a==null?!1:(t&&t(e.tr.lift(r,a).scrollIntoView()),!0)};return e.displayName=`liftEmptyBlock()`,e},splitBlockAs=e=>{let t=(t,n)=>{let{$from:r,$to:a}=t.selection;if(t.selection instanceof NodeSelection&&t.selection.node.isBlock)return!r.parentOffset||!canSplit(t.doc,r.pos)?!1:(n&&n(t.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let o=[],s,c,l=!1,u=!1;for(let t=r.depth;;t--)if(r.node(t).isBlock){l=r.end(t)==r.pos+(r.depth-t),u=r.start(t)==r.pos-(r.depth-t),c=defaultBlockAt(r.node(t-1).contentMatchAt(r.indexAfter(t-1)));let n=e&&e(a.parent,l,r);o.unshift(n||(l&&c?{type:c}:null)),s=t;break}else{if(t==1)return!1;o.unshift(null)}let d=t.tr;(t.selection instanceof TextSelection||t.selection instanceof AllSelection)&&d.deleteSelection();let f=d.mapping.map(r.pos),p=canSplit(d.doc,f,o.length,o);if(p||=(o[0]=c?{type:c}:null,canSplit(d.doc,f,o.length,o)),d.split(f,o.length,o),!l&&u&&r.node(s).type!=c){let e=d.mapping.map(r.before(s)),t=d.doc.resolve(e);c&&r.node(s-1).canReplaceWith(t.index(),t.index()+1,c)&&d.setNodeMarkup(d.mapping.map(r.before(s)),c)}return n&&n(d.scrollIntoView()),!0};return t.displayName=`splitBlockAs()`,t},splitBlock=()=>splitBlockAs(),splitBlockKeepMarks=()=>(e,t)=>splitBlockAs().apply(void 0,[e,t&&(n=>{let r=e.storedMarks||e.selection.$to.parentOffset&&e.selection.$from.marks();r&&n.ensureMarks(r),t(n)})]),selectParentNode=()=>(e,t)=>{let{$from:n,to:r}=e.selection,a,o=n.sharedDepth(r);return o==0?!1:(a=n.before(o),t&&t(e.tr.setSelection(NodeSelection.create(e.doc,a))),!0)},selectAll$1=()=>(e,t)=>(t&&t(e.tr.setSelection(new AllSelection(e.doc))),!0);function joinMaybeClear(e,t,n){let r=t.nodeBefore,a=t.nodeAfter,o=t.index();return!r||!a||!r.type.compatibleContent(a.type)?!1:!r.content.size&&t.parent.canReplace(o-1,o)?(n&&n(e.tr.delete(t.pos-r.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(o,o+1)||!(a.isTextblock||canJoin(e.doc,t.pos))?!1:(n&&n(e.tr.join(t.pos).scrollIntoView()),!0)}function deleteBarrier(e,t,n,r){let a=t.nodeBefore,o=t.nodeAfter,s,c,l=a.type.spec.isolating||o.type.spec.isolating;if(!l&&joinMaybeClear(e,t,n))return!0;let u=!l&&t.parent.canReplace(t.index(),t.index()+1);if(u&&(s=(c=a.contentMatchAt(a.childCount)).findWrapping(o.type))&&c.matchType(s[0]||o.type).validEnd){if(n){let r=t.pos+o.nodeSize,c=Fragment.empty;for(let e=s.length-1;e>=0;e--)c=Fragment.from(s[e].create(null,c));c=Fragment.from(a.copy(c));let l=e.tr.step(new ReplaceAroundStep(t.pos-1,r,t.pos,r,new Slice(c,1,0),s.length,!0)),u=l.doc.resolve(r+2*s.length);u.nodeAfter&&u.nodeAfter.type==a.type&&canJoin(l.doc,u.pos)&&l.join(u.pos),n(l.scrollIntoView())}return!0}let d=o.type.spec.isolating||r>0&&l?null:Selection.findFrom(t,1),f=d&&d.$from.blockRange(d.$to),p=f&&liftTarget(f);if(p!=null&&p>=t.depth)return n&&n(e.tr.lift(f,p).scrollIntoView()),!0;if(u&&textblockAt(o,`start`,!0)&&textblockAt(a,`end`)){let r=a,s=[];for(;s.push(r),!r.isTextblock;)r=r.lastChild;let c=o,l=1;for(;!c.isTextblock;c=c.firstChild)l++;if(r.canReplace(r.childCount,r.childCount,c.content)){if(n){let r=Fragment.empty;for(let e=s.length-1;e>=0;e--)r=Fragment.from(s[e].copy(r));n(e.tr.step(new ReplaceAroundStep(t.pos-s.length,t.pos+o.nodeSize,t.pos+l,t.pos+o.nodeSize-l,new Slice(r,s.length,0),0,!0)).scrollIntoView())}return!0}}return!1}function selectTextblockSide(e){return function(t,n){let r=t.selection,a=e<0?r.$from:r.$to,o=a.depth;for(;a.node(o).isInline;){if(!o)return!1;o--}return a.node(o).isTextblock?(n&&n(t.tr.setSelection(TextSelection.create(t.doc,e<0?a.start(o):a.end(o)))),!0):!1}}var wrapIn=(e,t=null)=>function(n,r){let{$from:a,$to:o}=n.selection,s=a.blockRange(o),c=s&&findWrapping(s,e,t);return c?(r&&r(n.tr.wrap(s,c).scrollIntoView()),!0):!1},setBlockType=(e,t=null)=>function(n,r){let a=!1;for(let r=0;r<n.selection.ranges.length&&!a;r++){let{$from:{pos:o},$to:{pos:s}}=n.selection.ranges[r];n.doc.nodesBetween(o,s,(r,o)=>{if(a)return!1;if(!(!r.isTextblock||r.hasMarkup(e,t)))if(r.type==e)a=!0;else{let t=n.doc.resolve(o),r=t.index();a=t.parent.canReplaceWith(r,r+1,e)}})}if(!a)return!1;if(r){let a=n.tr;for(let r=0;r<n.selection.ranges.length;r++){let{$from:{pos:o},$to:{pos:s}}=n.selection.ranges[r];a.setBlockType(o,s,e,t)}r(a.scrollIntoView())}return!0};function markApplies(e,t,n,r){for(let a=0;a<t.length;a++){let{$from:o,$to:s}=t[a],c=o.depth==0?e.inlineContent&&e.type.allowsMarkType(n):!1;if(e.nodesBetween(o.pos,s.pos,(e,t)=>{if(c||!r&&e.isAtom&&e.isInline&&t>=o.pos&&t+e.nodeSize<=s.pos)return!1;c=e.inlineContent&&e.type.allowsMarkType(n)}),c)return!0}return!1}function removeInlineAtoms(e){let t=[];for(let n=0;n<e.length;n++){let{$from:r,$to:a}=e[n];r.doc.nodesBetween(r.pos,a.pos,(e,n)=>{if(e.isAtom&&e.content.size&&e.isInline&&n>=r.pos&&n+e.nodeSize<=a.pos)return n+1>r.pos&&t.push(new SelectionRange(r,r.doc.resolve(n+1))),r=r.doc.resolve(n+1+e.content.size),!1}),r.pos<a.pos&&t.push(new SelectionRange(r,a))}return t}function toggleMark(e,t=null,n){let r=(n&&n.removeWhenPresent)!==!1,a=(n&&n.enterInlineAtoms)!==!1,o=!(n&&n.includeWhitespace);return function(n,s){let{empty:c,$cursor:l,ranges:u}=n.selection;if(c&&!l||!markApplies(n.doc,u,e,a))return!1;if(s)if(l)e.isInSet(n.storedMarks||l.marks())?s(n.tr.removeStoredMark(e)):s(n.tr.addStoredMark(e.create(t)));else{let c,l=n.tr;a||(u=removeInlineAtoms(u)),c=r?!u.some(t=>n.doc.rangeHasMark(t.$from.pos,t.$to.pos,e)):!u.every(t=>{let n=!1;return l.doc.nodesBetween(t.$from.pos,t.$to.pos,(r,a,o)=>{if(n)return!1;n=!e.isInSet(r.marks)&&!!o&&o.type.allowsMarkType(e)&&!(r.isText&&/^\s*$/.test(r.textBetween(Math.max(0,t.$from.pos-a),Math.min(r.nodeSize,t.$to.pos-a))))}),!n});for(let n=0;n<u.length;n++){let{$from:r,$to:a}=u[n];if(!c)l.removeMark(r.pos,a.pos,e);else{let n=r.pos,s=a.pos,c=r.nodeAfter,u=a.nodeBefore,d=o&&c&&c.isText?/^\s*/.exec(c.text)[0].length:0,f=o&&u&&u.isText?/\s*$/.exec(u.text)[0].length:0;n+d<s&&(n+=d,s-=f),l.addMark(n,s,e.create(t))}}s(l.scrollIntoView())}return!0}}var undoInputRule=()=>undoInputRuleCommand,command=e=>(...t)=>e.apply(void 0,t),baseCommandFactories={wrapInList,wrapRangeInList,deleteSelection,joinBackward,joinTextblockBackward,joinTextblockForward,joinForward,joinUp,joinDown,lift,newlineInCode,exitCode,createParagraphNear,liftEmptyBlock,splitBlockAs,splitBlock,splitBlockKeepMarks,selectAll:selectAll$1,selectParentNode,selectNodeBackward,selectNodeForward,selectTextblockStart:()=>selectTextblockSide(-1),selectTextblockEnd:()=>selectTextblockSide(1),wrapIn,setBlockType,toggleMark,undoInputRule,runInputRulesRange,runInputRulesTexts,command};function firstCommand(...e){let t=function(t,n,r){for(let a=0;a<e.length;a++)if(e[a](t,n,r))return e[a].displayName!==`first`&&console.debug(`firstCommand: `,e[a].displayName||e[a]),!0;return!1};return t.displayName=`first`,t}var backspace=firstCommand(baseCommandFactories.undoInputRule(),baseCommandFactories.deleteSelection(),baseCommandFactories.joinBackward(),baseCommandFactories.selectNodeBackward()),del=firstCommand(baseCommandFactories.deleteSelection(),baseCommandFactories.joinForward(),baseCommandFactories.selectNodeForward()),enter=firstCommand(baseCommandFactories.newlineInCode(),baseCommandFactories.createParagraphNear(),baseCommandFactories.liftEmptyBlock(),baseCommandFactories.splitBlock()),keyCommandFactories={backspace:()=>backspace,del:()=>del,enter:()=>enter},replaceRangeText=(e,t)=>(n,r)=>{let a=n.tr,o=a.mapping.map(e.from),s=a.mapping.map(e.to);if(t.length>0){let e=new Slice(Fragment.from(n.schema.text(t)),0,0);a.replace(o,s,e)}else{let e=new Slice(Fragment.from(n.schema.topNodeType.createAndFill()),0,0);a.replace(o,s,e)}return r&&r(a),!0},replaceRangeSlice=(e,t)=>(n,r)=>{let a=n.tr,o=a.mapping.map(e.from),s=a.mapping.map(e.to);return a.replace(o,s,t),r&&r(a),!0};function getTopMostBlockStartForOffset(e,t){let{doc:n}=e,r=n.resolve(t),a=r.before(r.depth);return r.depth===1?a:r.start(1)}function getTopMostBlockEndForOffset(e,t){let{doc:n}=e;return n.resolve(t).end(1)}function getAdjacentTopBlock(e,t){let{doc:n}=e;if(t<0||t>n.content.size)throw RangeError(`Offset is outside the document`);let r=n.resolve(t);return r.pos===r.start(r.depth)?getTopMostBlockStartForOffset(e,t):getTopMostBlockEndForOffset(e,t)}var insertBlockBefore=(e,t)=>(n,r)=>{let a=n.tr,o=getTopMostBlockStartForOffset(n,a.mapping.map(e));return a.insert(o,t),r&&r(a),!0},insertBlockAfter=(e,t)=>(n,r)=>{let a=n.tr,o=getTopMostBlockEndForOffset(n,a.mapping.map(e));return a.insert(o,t),r&&r(a),!0},insertBlockSmart=(e,t)=>(n,r)=>{let a=n.tr,o=getAdjacentTopBlock(n,a.mapping.map(e));return a.insert(o,t),r&&r(a),!0},replaceCommandFactories={replaceRangeText,replaceRangeSlice,insertBlockBefore,insertBlockAfter,insertBlockSmart},CommandManager=class{editor;commandFactories={};run={};debug=!0;constructor(e){this.editor=e,this.mergeCommandFactories(baseCommandFactories,`baseCommand`),this.mergeCommandFactories(keyCommandFactories,`key`),this.mergeCommandFactories(replaceCommandFactories,`replace`),this.mergeCommandFactories(searchCommandFactories,`search`)}mergeCommandFactories(e,t){for(let n in e){let r=e[n];r&&this.overwriteCommandFactory(t,n,r)}}overwriteCommandFactory(e,t,n){if(this.debug){let r=(...r)=>{let a=n(...r);return(n,o,s)=>(o&&console.debug(`Command: ${e}.${t}`,...r),a.apply({editor:this.editor},[n,o,s]))};this.commandFactories[t]=r}else this.commandFactories[t]=n;this.run[t]=(...e)=>{let n=this.commandFactories[t],r=n(...e),a=this.editor.state,o=this.editor.view;return o instanceof EditorView?r.apply({editor:this.editor},[a,o.dispatch,o]):r.apply({editor:this.editor},[a,o.dispatch])}}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){let{commandFactories:n,editor:r}=this,a=this.editor.state,{view:o}=r,s=[],c=!!e,l=e||a.tr;l.setMeta(`isCommand`,!0);let u=createChainableState(l,a),d=()=>void 0,f={...Object.fromEntries(Object.entries(n).map(([e,n])=>[e,(...e)=>{let r=n(...e).apply({editor:this.editor},[u,t?d:void 0]);return s.push(r),f}])),run:()=>(!c&&t&&!l.getMeta(`preventDispatch`)&&o.dispatch(l),s.every(e=>e===!0)),chain:()=>this.createChain(l,t)};return f}createCan(e){return this.createChain(e,!1)}},SmartOutput=class{_rowPos=0;_colPos=0;_pos=0;chunks=[];metas=[];log(e,t){if(e.length===0)return;this.chunks.push(e),this.metas.push({pos:this._pos,colPos:this._colPos,rowPos:this._rowPos,item:t});let n=e.split(`
12
+ `)}function fromJSON(e){if(e===null)return null;if(Array.isArray(e))return e.map(fromJSON);if(typeof e==`object`){if(e instanceof Map)return e;let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,fromJSON(r));return t}if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;throw Error(`Unsupported JSON value: ${typeof e}`)}function toJSON(e){if(e instanceof Map){let t={};for(let[n,r]of e)t[n]=toJSON(r);return t}return Array.isArray(e)?e.map(toJSON):e}function setPathValue(e,t,n){let r=t.match(/[^.\[\]]+|\[\d+\]/g)?.map(e=>e.startsWith(`[`)?Number(e.slice(1,-1)):e)??[];if(r.length===0)throw Error(`empty path`);if(!(e instanceof Map)&&!Array.isArray(e))throw Error(`root must be Map or array`);let a=e;for(let e=0;e<r.length-1;e++){let n=r[e],o=typeof n==`number`?Array.isArray(a)?a[n]:void 0:a instanceof Map?a.get(n):void 0;if(!(o instanceof Map)&&!Array.isArray(o)){if(o!=null)throw console.log(`next`,o),Error(`"${n}" #${e} of "${t}" not container`);o=typeof r[e+1]==`number`?[]:new Map,typeof n==`number`?a[n]=o:a.set(n,o)}a=o}let o=r[r.length-1];if(typeof o==`number`){if(!Array.isArray(a))throw Error(`target not array`);for(;a.length<=o;)a.push(null);a[o]=n}else{if(!(a instanceof Map))throw Error(`target not map`);a.set(o,n)}}var FrontmatterMap=class extends Map{origMap;origString=``;constructor(){super()}},FrontmatterServiceImpl=class{constructor(e){this.yamlService=e}parse(e){let t=new FrontmatterMap;t.origString=e;let n=e.indexOf(`
13
+ ---
14
+ `,4);if(e.startsWith(`---
15
+ `)&&n>-1){let r=this.yamlService.parse(e.substring(4,n));if(r instanceof Map){t.origMap=r;for(let[e,n]of r)t.set(e,structuredClone(n))}}return t}stringify(e){return e?e.origMap?.entries===e.entries?e.origString:`---
16
+ ${this.yamlService.stringify(e)}
17
+ ---
18
+ `:``}},BlankFrontmatterServiceImpl=class{constructor(){}parse(e){}stringify(e){return``}},SearchQuery=class{search;caseSensitive;literal;regexp;replace;valid;wholeWord;filter;impl;constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||``,this.valid=!!this.search&&!(this.regexp&&!validRegExp(this.search)),this.wholeWord=!!e.wholeWord,this.filter=e.filter||null,this.impl=this.valid?this.regexp?new RegExpQuery(this):new StringQuery(this):nullQuery}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord}findNext(e,t=0,n=e.doc.content.size){for(;;){if(t>=n)return null;let r=this.impl.findNext(e,t,n);if(!r||this.checkResult(e,r))return r;t=r.from+1}}findPrev(e,t=e.doc.content.size,n=0){for(;;){if(t<=n)return null;let r=this.impl.findPrev(e,t,n);if(!r||this.checkResult(e,r))return r;t=r.to-1}}checkResult(e,t){return(!this.wholeWord||checkWordBoundary(e,t.from)&&checkWordBoundary(e,t.to))&&(!this.filter||this.filter(e,t))}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(e,t)=>t==`n`?`
19
+ `:t==`r`?`\r`:t==`t`?` `:`\\`)}getReplacements(e,t){let n=e.doc.resolve(t.from).marksAcross(e.doc.resolve(t.to)),r=[],a=Fragment.empty,o=t.from,{match:s}=t,c=s?getGroupIndices(s):[[0,t.to-t.from]],l=parseReplacement(this.unquote(this.replace)),u;for(let s of l)if(typeof s==`string`)a=a.addToEnd(e.schema.text(s,n));else if(u=c[s.group],u){let n=t.matchStart+u[0],c=t.matchStart+u[1];s.copy?a=a.append(e.doc.slice(n,c).content):((a!=Fragment.empty||n>o)&&(r.push({from:o,to:n,insert:new Slice(a,0,0)}),a=Fragment.empty),o=c)}return(a!=Fragment.empty||o<t.to)&&r.push({from:o,to:t.to,insert:new Slice(a,0,0)}),r}},nullQuery=new class{findNext(){return null}findPrev(){return null}},StringQuery=class{query;string;constructor(e){this.query=e;let t=e.unquote(e.search);e.caseSensitive||(t=t.toLowerCase()),this.string=t}findNext(e,t,n){return scanTextblocks(e.doc,t,n,(e,r)=>{let a=Math.max(t,r),o=textContent(e).slice(a-r,Math.min(e.content.size,n-r)),s=(this.query.caseSensitive?o:o.toLowerCase()).indexOf(this.string);return s<0?null:{from:a+s,to:a+s+this.string.length,match:null,matchStart:r}})}findPrev(e,t,n){return scanTextblocks(e.doc,t,n,(e,r)=>{let a=Math.max(r,n),o=textContent(e).slice(a-r,Math.min(e.content.size,t-r));this.query.caseSensitive||(o=o.toLowerCase());let s=o.lastIndexOf(this.string);return s<0?null:{from:a+s,to:a+s+this.string.length,match:null,matchStart:r}})}},baseFlags=`g`+(/x/.unicode==null?``:`u`)+(/x/.hasIndices==null?``:`d`),RegExpQuery=class{query;regexp;constructor(e){this.query=e,this.regexp=new RegExp(e.search,baseFlags+(e.caseSensitive?``:`i`))}findNext(e,t,n){return scanTextblocks(e.doc,t,n,(e,r)=>{let a=textContent(e).slice(0,Math.min(e.content.size,n-r));this.regexp.lastIndex=t-r;let o=this.regexp.exec(a);return o?{from:r+o.index,to:r+o.index+o[0].length,match:o,matchStart:r}:null})}findPrev(e,t,n){return scanTextblocks(e.doc,t,n,(e,n)=>{let r=textContent(e).slice(0,Math.min(e.content.size,t-n)),a;for(let e=0;;){this.regexp.lastIndex=e;let t=this.regexp.exec(r);if(!t)break;a=t,e=t.index+1}return a?{from:n+a.index,to:n+a.index+a[0].length,match:a,matchStart:n}:null})}};function getGroupIndices(e){if(e.indices)return e.indices;let t=[[0,e[0].length]];for(let n=1,r=0;n<e.length;n++){let a=e[n]?e[0].indexOf(e[n],r):-1;t.push(a<0?void 0:[a,r=a+e[n].length])}return t}function parseReplacement(e){let t=[],n=-1;function r(e){let n=t.length-1;n>-1&&typeof t[n]==`string`?t[n]+=e:t.push(e)}for(;e.length;){let a=/\$([$&\d+])/.exec(e);if(!a)return r(e),t;if(a.index>0&&r(e.slice(0,a.index+ +(a[1]==`$`))),a[1]!=`$`){let e=a[1]==`&`?0:+a[1];n>=e?t.push({group:e,copy:!0}):(n=e||1e3,t.push({group:e,copy:!1}))}e=e.slice(a.index+a[0].length)}return t}function validRegExp(e){try{return new RegExp(e,baseFlags),!0}catch{return!1}}var TextContentCache=new WeakMap;function textContent(e){let t=TextContentCache.get(e);if(t)return t;let n=``;for(let t=0;t<e.childCount;t++){let r=e.child(t);r.isText?n+=r.text:r.isLeaf?n+=``:n+=` `+textContent(r)+` `}return TextContentCache.set(e,n),n}function scanTextblocks(e,t,n,r,a=0){if(e.inlineContent)return r(e,a);if(!e.isLeaf)if(t>n)for(let o=e.childCount-1,s=a+e.content.size;o>=0&&s>n;o--){let a=e.child(o);if(s-=a.nodeSize,s<t){let e=scanTextblocks(a,t,n,r,s+1);if(e!=null)return e}}else for(let o=0,s=a;o<e.childCount&&s<n;o++){let a=e.child(o),c=s;if(s+=a.nodeSize,s>t){let e=scanTextblocks(a,t,n,r,c+1);if(e!=null)return e}}return null}function checkWordBoundary(e,t){let n=e.doc.resolve(t),r=n.nodeBefore,a=n.nodeAfter;return!r||!a||!r.isText||!a.isText?!0:!/\p{L}$/u.test(r.text)||!/^\p{L}/u.test(a.text)}var SearchState=class{query;range;deco;constructor(e,t,n){this.query=e,this.range=t,this.deco=n}};function buildMatchDeco(e,t,n){if(!t.valid)return DecorationSet.empty;let r=[],a=e.selection;for(let o=n?n.from:0,s=n?n.to:e.doc.content.size;;){let n=t.findNext(e,o,s);if(!n)break;let c=n.from==a.from&&n.to==a.to?`kb-active-search-match`:`kb-search-match`;r.push(Decoration.inline(n.from,n.to,{class:c})),o=n.to}return DecorationSet.create(e.doc,r)}var searchKey=new PluginKey(`search`);function createSearchPlugin(e={}){return new Plugin({key:searchKey,state:{init(t,n){let r=e.initialQuery||new SearchQuery({search:``}),a=e.initialRange||null;return new SearchState(r,a,buildMatchDeco(n,r,a))},apply(e,t,n,r){let a=e.getMeta(searchKey);if(a)return new SearchState(a.query,a.range,buildMatchDeco(r,a.query,a.range));if(e.docChanged||e.selectionSet){let n=t.range;if(n){let t=e.mapping.map(n.from,1),r=e.mapping.map(n.to,-1);n=t<r?{from:t,to:r}:null}t=new SearchState(t.query,n,buildMatchDeco(r,t.query,n))}return t}},props:{decorations:e=>searchKey.getState(e).deco}})}function setSearchState(e,t,n=null){return e.setMeta(searchKey,{query:t,range:n})}function nextMatch(e,t,n,r,a){let o=e.range||{from:0,to:t.doc.content.size},s=e.query.findNext(t,Math.max(a,o.from),o.to);return!s&&n&&(s=e.query.findNext(t,o.from,Math.min(r,o.to))),s}function prevMatch(e,t,n,r,a){let o=e.range||{from:0,to:t.doc.content.size},s=e.query.findPrev(t,Math.min(r,o.to),o.from);return!s&&n&&(s=e.query.findPrev(t,o.to,Math.max(a,o.from))),s}function findCommand(e,t){return(n,r)=>{let a=searchKey.getState(n);if(!a||!a.query.valid)return!1;let{from:o,to:s}=n.selection,c=t>0?nextMatch(a,n,e,o,s):prevMatch(a,n,e,o,s);if(!c)return!1;let l=TextSelection.create(n.doc,c.from,c.to);return r&&r(n.tr.setSelection(l).scrollIntoView()),!0}}var findNext=findCommand(!0,1),findNextNoWrap=findCommand(!1,1),findPrev=findCommand(!0,-1),findPrevNoWrap=findCommand(!1,-1);function replaceCommand(e,t){return(n,r)=>{let a=searchKey.getState(n);if(!a||!a.query.valid)return!1;let{from:o}=n.selection,s=nextMatch(a,n,e,o,o);if(!s)return!1;if(!r)return!0;if(n.selection.from==s.from&&n.selection.to==s.to){let o=n.tr,c=a.query.getReplacements(n,s);for(let e=c.length-1;e>=0;e--){let{from:t,to:n,insert:r}=c[e];o.replace(t,n,r)}let l=t&&nextMatch(a,n,e,s.from,s.to);l?o.setSelection(TextSelection.create(o.doc,o.mapping.map(l.from,1),o.mapping.map(l.to,-1))):o.setSelection(TextSelection.create(o.doc,s.from,o.mapping.map(s.to,1))),r(o.scrollIntoView())}else if(t)r(n.tr.setSelection(TextSelection.create(n.doc,s.from,s.to)).scrollIntoView());else return!1;return!0}}var replaceNext=replaceCommand(!0,!0),replaceNextNoWrap=replaceCommand(!1,!0),replaceCurrent=replaceCommand(!1,!1),replaceAll=(e,t)=>{let n=searchKey.getState(e);if(!n)return!1;let r=[],a=n.range||{from:0,to:e.doc.content.size};for(let t=a.from;;){let o=n.query.findNext(e,t,a.to);if(!o)break;r.push(o),t=o.to}if(t){let a=e.tr;for(let t=r.length-1;t>=0;t--){let o=r[t],s=n.query.getReplacements(e,o);for(let e=s.length-1;e>=0;e--){let{from:t,to:n,insert:r}=s[e];a.replace(t,n,r)}}t(a)}return!0},searchFactory=(e,t=null)=>(n,r)=>{let a=n.tr;return setSearchState(a,e,t),r&&r(a),!0},searchCommandFactories={search:searchFactory,findNext:()=>findNext,findNextNoWrap:()=>findNextNoWrap,findPrev:()=>findPrev,findPrevNoWrap:()=>findPrevNoWrap,replaceNext:()=>replaceNext,replaceNextNoWrap:()=>replaceNextNoWrap,replaceCurrent:()=>replaceCurrent,replaceAll:()=>replaceAll};function splitExtensions(e){return{baseExtensions:Array.from(e).filter(e=>e.type===`extension`),nodeExtensions:Array.from(e).filter(e=>e.type===`node`),markExtensions:Array.from(e).filter(e=>e.type===`mark`)}}var ExtensionManager=class{editorKits;debug;extensions=new Set;plugins=[];nodeViews={};converters={};constructor(e,t=!1){this.editorKits=e,this.debug=t;let n=e.reduce((e,t)=>e.concat(t.getExtensions()),[]);this.setupExtensions(new Set(n))}initPlugins(e,t){let n=[],r=new Map,a=(t,n)=>{for(let n in t){if(!t[n])continue;let a=e.commandFactories[t[n]];if(!a){console.warn(`No command constructor: ${t[n]}`);continue}let o=a(),s=r.get(n);s?r.set(n,firstCommand$1(o,s)):r.set(n,o)}},o={};for(let r of this.extensions){if(r.setEditor(e),r.type===`node`){let s=t.nodes[r.name];n.push(...r.getInputRules(s)),this.plugins.push(...r.getProseMirrorPlugins()),e.mergeCommandFactories(r.getCommandFactories(e,s),r.name),a(r.getKeyboardShortcuts(e),r.name),o={...o,...r.getConverters(e,t)};let c=r.getNodeView(e);c&&(this.nodeViews[r.name]=c)}if(r.type===`mark`){let o=t.marks[r.name];n.push(...r.getInputRules(o)),e.mergeCommandFactories(r.getCommandFactories(e,o),r.name),a(r.getKeyboardShortcuts(e),r.name)}r.type===`extension`&&(this.plugins.push(...r.getProseMirrorPlugins()),e.mergeCommandFactories(r.getCommandFactories(e),r.name),a(r.getKeyboardShortcuts(e),r.name),o={...o,...r.getConverters(e,t)})}if(this.debug)for(let e in r){let t=r.get(e);t&&r.set(e,firstCommand$1((t,n,r)=>(console.debug(`Key: ${e}`),!0),t))}this.converters=o,this.plugins.push(new InputRulesPlugin(n)),this.plugins.push(new KeymapPlugin(Object.fromEntries(r))),this.plugins.push(createSearchPlugin()),this.plugins.push(new TrackSelecionPlugin(e))}setupExtensions(e){let t=new Map,n=e=>{for(let r of e){if(`name`in r){let e=t.get(r.name);if(e&&`type`in e&&r.type!==e.type)throw Error(`Duplicate mark/node: ${r.name}`);t.set(r.name,r)}if(`requires`in r){let e=Array.from(r.requires).filter(e=>typeof e!=`string`);n(new Set(e))}}};n(e);let r=new Set,a=e=>{this.debug&&console.info(`Initialize ${e.type} ${e.name}`),this.extensions.add(e)};function o(e){if(!(`name`in e&&r.has(e.name))){if(`requires`in e){let n=(e.requires||[]).map(e=>typeof e==`string`?e:`name`in e?e.name:``);for(let a of n)if(!r.has(a)){let n=t.get(a);if(!n)throw Error(`Required extension for (${`name`in e?e.name:e}) not found: ${a}`);o(n)}}`name`in e&&(a(e),r.add(e.name),t.delete(e.name))}}for(let e of t.values())o(e);if(t.size>0)throw Error(`Not all extensions initialized: `+Array.from(t.keys()).join(`, `))}getSchemaByResolvedExtensions(){let{nodeExtensions:e,markExtensions:t,baseExtensions:n}=splitExtensions(this.extensions),r={},a=``;for(let t of e){if(r[t.name]=t.getNodeSpec(),r[t.name].EMPTY_DOC){if(a)throw Error(`Multiple topNodes: ${t.name}, ${a}`);a=t.name}addAttributesToSchema(r[t.name],t)}let o={};for(let e of t)o[e.name]=e.getMarkSpec(),addAttributesToSchema(o[e.name],e);let s={topNode:a||`doc`,nodes:r,marks:o};for(let e of n)`setupSpec`in n&&e.setupSpec(s);return new Schema(s)}created(e,t){let{nodeExtensions:n,markExtensions:r,baseExtensions:a}=splitExtensions(this.extensions);for(let e of a){if(Array.isArray(e.overrides))for(let t of e.overrides)for(let e of this.extensions)e.name===t&&this.extensions.delete(e);if(Array.isArray(e.conflicts)){for(let t of e.conflicts)if(a.find(e=>e.name===t))throw Error(`Extension conflict: ${e.name} vs ${t}`)}}for(let t of a)e.ci.register(t.name,t);e.ci.register(`yaml`,yaml_exports),e.ci.register(`frontmatter`,new FrontmatterServiceImpl(yaml_exports)),e.ci.register(`workspace`,new WorkspaceImpl),this.initPlugins(e,t);for(let e of this.extensions)e.created()}};function createChainableState(e,t){let{selection:n}=e,{doc:r}=e,{storedMarks:a}=e;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return a},get selection(){return n},get doc(){return r},get tr(){return n=e.selection,r=e.doc,a=e.storedMarks,e}}}var liftListItemParagraph=()=>(e,t)=>{let{$cursor:n}=e.selection;if(!n||n.parentOffset>0||!n.parent.isTextblock)return!1;for(let r=n.depth;r>0;r--){let a=n.node(r);if(a.type.name===`list_item`||a.type.name===`bullet_list`||a.type.name===`task_item`||a.type.name===`task_list`){let o=a.type.name===`list_item`?r:r-1;if(a.type.name===`list_item`||n.node(r-1),n.index(o)===0)return!1;let s=n.blockRange();if(!s)return!1;let c=liftTarget(s);return c==null?!1:(t&&t(e.tr.lift(s,c).scrollIntoView()),!0)}}return!1},wrapInList=(e,t=null)=>function(n,r,a){let{$from:o,$to:s}=n.selection,c=o.blockRange(s);if(!c)return!1;let l=r?n.tr:null;return wrapRangeInList(l,c,e,t).apply(this,[n,r])?(r&&r(l.scrollIntoView()),!0):!1},wrapRangeInList=(e,t,n,r=null)=>()=>{let a=!1,o=t,s=t.$from.doc;if(t.depth>=2&&t.$from.node(t.depth-1).type.compatibleContent(n)&&t.startIndex==0){if(t.$from.index(t.depth-1)==0)return!1;let e=s.resolve(t.start-2);o=new NodeRange(e,e,t.depth),t.endIndex<t.parent.childCount&&(t=new NodeRange(t.$from,s.resolve(t.$to.end(t.depth)),t.depth)),a=!0}let c=findWrapping(o,n,r,t);return c?(e&&doWrapInList(e,t,c,a,n),!0):!1};function doWrapInList(e,t,n,r,a){let o=Fragment.empty;for(let e=n.length-1;e>=0;e--)o=Fragment.from(n[e].type.create(n[e].attrs,o));e.step(new ReplaceAroundStep(t.start-(r?2:0),t.end,t.start,t.end,new Slice(o,0,0),n.length,!0));let s=0;for(let e=0;e<n.length;e++)n[e].type==a&&(s=e+1);let c=n.length-s,l=t.start+n.length-(r?2:0),u=t.parent;for(let n=t.startIndex,r=t.endIndex,a=!0;n<r;n++,a=!1)!a&&canSplit(e.doc,l,c)&&(e.split(l,c),l+=2*c),l+=u.child(n).nodeSize;return e}var deleteSelection=()=>(e,t)=>e.selection.empty?!1:(t&&t(e.tr.deleteSelection().scrollIntoView()),!0);function atBlockStart(e,t){let{$cursor:n}=e.selection;return!n||(t?!t.endOfTextblock(`backward`,e):n.parentOffset>0)?null:n}var joinBackward=()=>(e,t,n)=>{let r=atBlockStart(e,n);if(!r)return!1;let a=findCutBefore(r);if(!a){let n=r.blockRange(),a=n&&liftTarget(n);return a==null?!1:(t&&t(e.tr.lift(n,a).scrollIntoView()),!0)}let o=a.nodeBefore;if(deleteBarrier(e,a,t,-1))return!0;if(r.parent.content.size==0&&(textblockAt(o,`end`)||NodeSelection.isSelectable(o)))for(let n=r.depth;;n--){let s=replaceStep(e.doc,r.before(n),r.after(n),Slice.empty);if(s&&s.slice.size<s.to-s.from){if(t){let n=e.tr.step(s);n.setSelection(textblockAt(o,`end`)?Selection.findFrom(n.doc.resolve(n.mapping.map(a.pos,-1)),-1):NodeSelection.create(n.doc,a.pos-o.nodeSize)),t(n.scrollIntoView())}return!0}if(n==1||r.node(n-1).childCount>1)break}return o.isAtom&&a.depth==r.depth-1?(t&&t(e.tr.delete(a.pos-o.nodeSize,a.pos).scrollIntoView()),!0):!1},joinTextblockBackward=()=>(e,t,n)=>{let r=atBlockStart(e,n);if(!r)return!1;let a=findCutBefore(r);return a?joinTextblocksAround(e,a,t):!1},joinTextblockForward=()=>(e,t,n)=>{let r=atBlockEnd(e,n);if(!r)return!1;let a=findCutAfter(r);return a?joinTextblocksAround(e,a,t):!1};function joinTextblocksAround(e,t,n){let r=t.nodeBefore,a=t.pos-1;for(;!r.isTextblock;a--){if(r.type.spec.isolating)return!1;let e=r.lastChild;if(!e)return!1;r=e}let o=t.nodeAfter,s=t.pos+1;for(;!o.isTextblock;s++){if(o.type.spec.isolating)return!1;let e=o.firstChild;if(!e)return!1;o=e}let c=replaceStep(e.doc,a,s,Slice.empty);if(!c||c.from!=a||c instanceof ReplaceStep&&c.slice.size>=s-a)return!1;if(n){let t=e.tr.step(c);t.setSelection(TextSelection.create(t.doc,a)),n(t.scrollIntoView())}return!0}function textblockAt(e,t,n=!1){for(let r=e;r;r=t==`start`?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}var selectNodeBackward=()=>(e,t,n)=>{let{$head:r,empty:a}=e.selection,o=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock(`backward`,e):r.parentOffset>0)return!1;o=findCutBefore(r)}let s=o&&o.nodeBefore;return!s||!NodeSelection.isSelectable(s)?!1:(t&&t(e.tr.setSelection(NodeSelection.create(e.doc,o.pos-s.nodeSize)).scrollIntoView()),!0)};function findCutBefore(e){if(!e.parent.type.spec.isolating)for(let t=e.depth-1;t>=0;t--){if(e.index(t)>0)return e.doc.resolve(e.before(t+1));if(e.node(t).type.spec.isolating)break}return null}function atBlockEnd(e,t){let{$cursor:n}=e.selection;return!n||(t?!t.endOfTextblock(`forward`,e):n.parentOffset<n.parent.content.size)?null:n}var joinForward=()=>(e,t,n)=>{let r=atBlockEnd(e,n);if(!r)return!1;let a=findCutAfter(r);if(!a)return!1;let o=a.nodeAfter;if(deleteBarrier(e,a,t,1))return!0;if(r.parent.content.size==0&&(textblockAt(o,`start`)||NodeSelection.isSelectable(o))){let n=replaceStep(e.doc,r.before(),r.after(),Slice.empty);if(n&&n.slice.size<n.to-n.from){if(t){let r=e.tr.step(n);r.setSelection(textblockAt(o,`start`)?Selection.findFrom(r.doc.resolve(r.mapping.map(a.pos)),1):NodeSelection.create(r.doc,r.mapping.map(a.pos))),t(r.scrollIntoView())}return!0}}return o.isAtom&&a.depth==r.depth-1?(t&&t(e.tr.delete(a.pos,a.pos+o.nodeSize).scrollIntoView()),!0):!1},selectNodeForward=()=>(e,t,n)=>{let{$head:r,empty:a}=e.selection,o=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock(`forward`,e):r.parentOffset<r.parent.content.size)return!1;o=findCutAfter(r)}let s=o&&o.nodeAfter;return!s||!NodeSelection.isSelectable(s)?!1:(t&&t(e.tr.setSelection(NodeSelection.create(e.doc,o.pos)).scrollIntoView()),!0)};function findCutAfter(e){if(!e.parent.type.spec.isolating)for(let t=e.depth-1;t>=0;t--){let n=e.node(t);if(e.index(t)+1<n.childCount)return e.doc.resolve(e.after(t+1));if(n.type.spec.isolating)break}return null}var joinUp=()=>(e,t)=>{let n=e.selection,r=n instanceof NodeSelection,a;if(r){if(n.node.isTextblock||!canJoin(e.doc,n.from))return!1;a=n.from}else if(a=joinPoint(e.doc,n.from,-1),a==null)return!1;if(t){let n=e.tr.join(a);r&&n.setSelection(NodeSelection.create(n.doc,a-e.doc.resolve(a).nodeBefore.nodeSize)),t(n.scrollIntoView())}return!0},joinDown=()=>(e,t)=>{let n=e.selection,r;if(n instanceof NodeSelection){if(n.node.isTextblock||!canJoin(e.doc,n.to))return!1;r=n.to}else if(r=joinPoint(e.doc,n.to,1),r==null)return!1;return t&&t(e.tr.join(r).scrollIntoView()),!0},lift=()=>(e,t)=>{let{$from:n,$to:r}=e.selection,a=n.blockRange(r),o=a&&liftTarget(a);return o==null?!1:(t&&t(e.tr.lift(a,o).scrollIntoView()),!0)},newlineInCode=()=>{let e=(e,t)=>{let{$head:n,$anchor:r}=e.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(t&&t(e.tr.insertText(`
20
+ `).scrollIntoView()),!0)};return e.displayName=`newlineInCode()`,e};function defaultBlockAt(e){console.log(`defaultBlockAt`,e);for(let t=0;t<e.edgeCount;t++){let{type:n}=e.edge(t);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}var exitCode=()=>(e,t)=>{let{$head:n,$anchor:r}=e.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let a=n.node(-1),o=n.indexAfter(-1),s=defaultBlockAt(a.contentMatchAt(o));if(!s||!a.canReplaceWith(o,o,s))return!1;if(t){let r=n.after(),a=e.tr.replaceWith(r,r,s.createAndFill());a.setSelection(Selection.near(a.doc.resolve(r),1)),t(a.scrollIntoView())}return!0},createParagraphNear=()=>{let e=(e,t)=>{let n=e.selection,{$from:r,$to:a}=n;if(n instanceof AllSelection||r.parent.inlineContent||a.parent.inlineContent)return!1;let o=defaultBlockAt(a.parent.contentMatchAt(a.indexAfter()));if(!o||!o.isTextblock)return!1;if(t){let n=(!r.parentOffset&&a.index()<a.parent.childCount?r:a).pos,s=e.tr.insert(n,o.createAndFill());s.setSelection(TextSelection.create(s.doc,n+1)),t(s.scrollIntoView())}return!0};return e.displayName=`createParagraphNear()`,e},liftEmptyBlock=()=>{let e=(e,t)=>{let{$cursor:n}=e.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let r=n.before();if(canSplit(e.doc,r))return t&&t(e.tr.split(r).scrollIntoView()),!0}let r=n.blockRange(),a=r&&liftTarget(r);return a==null?!1:(t&&t(e.tr.lift(r,a).scrollIntoView()),!0)};return e.displayName=`liftEmptyBlock()`,e},splitBlockAs=e=>{let t=(t,n)=>{let{$from:r,$to:a}=t.selection;if(t.selection instanceof NodeSelection&&t.selection.node.isBlock)return!r.parentOffset||!canSplit(t.doc,r.pos)?!1:(n&&n(t.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let o=[],s,c,l=!1,u=!1;for(let t=r.depth;;t--)if(r.node(t).isBlock){l=r.end(t)==r.pos+(r.depth-t),u=r.start(t)==r.pos-(r.depth-t),c=defaultBlockAt(r.node(t-1).contentMatchAt(r.indexAfter(t-1)));let n=e&&e(a.parent,l,r);o.unshift(n||(l&&c?{type:c}:null)),s=t;break}else{if(t==1)return!1;o.unshift(null)}let d=t.tr;(t.selection instanceof TextSelection||t.selection instanceof AllSelection)&&d.deleteSelection();let f=d.mapping.map(r.pos),p=canSplit(d.doc,f,o.length,o);if(p||=(o[0]=c?{type:c}:null,canSplit(d.doc,f,o.length,o)),d.split(f,o.length,o),!l&&u&&r.node(s).type!=c){let e=d.mapping.map(r.before(s)),t=d.doc.resolve(e);c&&r.node(s-1).canReplaceWith(t.index(),t.index()+1,c)&&d.setNodeMarkup(d.mapping.map(r.before(s)),c)}return n&&n(d.scrollIntoView()),!0};return t.displayName=`splitBlockAs()`,t},splitBlock=()=>splitBlockAs(),splitBlockKeepMarks=()=>(e,t)=>splitBlockAs().apply(void 0,[e,t&&(n=>{let r=e.storedMarks||e.selection.$to.parentOffset&&e.selection.$from.marks();r&&n.ensureMarks(r),t(n)})]),selectParentNode=()=>(e,t)=>{let{$from:n,to:r}=e.selection,a,o=n.sharedDepth(r);return o==0?!1:(a=n.before(o),t&&t(e.tr.setSelection(NodeSelection.create(e.doc,a))),!0)},selectAll$1=()=>(e,t)=>(t&&t(e.tr.setSelection(new AllSelection(e.doc))),!0);function joinMaybeClear(e,t,n){let r=t.nodeBefore,a=t.nodeAfter,o=t.index();return!r||!a||!r.type.compatibleContent(a.type)?!1:!r.content.size&&t.parent.canReplace(o-1,o)?(n&&n(e.tr.delete(t.pos-r.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(o,o+1)||!(a.isTextblock||canJoin(e.doc,t.pos))?!1:(n&&n(e.tr.join(t.pos).scrollIntoView()),!0)}function deleteBarrier(e,t,n,r){let a=t.nodeBefore,o=t.nodeAfter,s,c,l=a.type.spec.isolating||o.type.spec.isolating;if(!l&&joinMaybeClear(e,t,n))return!0;let u=!l&&t.parent.canReplace(t.index(),t.index()+1);if(u&&(s=(c=a.contentMatchAt(a.childCount)).findWrapping(o.type))&&c.matchType(s[0]||o.type).validEnd){if(n){let r=t.pos+o.nodeSize,c=Fragment.empty;for(let e=s.length-1;e>=0;e--)c=Fragment.from(s[e].create(null,c));c=Fragment.from(a.copy(c));let l=e.tr.step(new ReplaceAroundStep(t.pos-1,r,t.pos,r,new Slice(c,1,0),s.length,!0)),u=l.doc.resolve(r+2*s.length);u.nodeAfter&&u.nodeAfter.type==a.type&&canJoin(l.doc,u.pos)&&l.join(u.pos),n(l.scrollIntoView())}return!0}let d=o.type.spec.isolating||r>0&&l?null:Selection.findFrom(t,1),f=d&&d.$from.blockRange(d.$to),p=f&&liftTarget(f);if(p!=null&&p>=t.depth)return n&&n(e.tr.lift(f,p).scrollIntoView()),!0;if(u&&textblockAt(o,`start`,!0)&&textblockAt(a,`end`)){let r=a,s=[];for(;s.push(r),!r.isTextblock;)r=r.lastChild;let c=o,l=1;for(;!c.isTextblock;c=c.firstChild)l++;if(r.canReplace(r.childCount,r.childCount,c.content)){if(n){let r=Fragment.empty;for(let e=s.length-1;e>=0;e--)r=Fragment.from(s[e].copy(r));n(e.tr.step(new ReplaceAroundStep(t.pos-s.length,t.pos+o.nodeSize,t.pos+l,t.pos+o.nodeSize-l,new Slice(r,s.length,0),0,!0)).scrollIntoView())}return!0}}return!1}function selectTextblockSide(e){return function(t,n){let r=t.selection,a=e<0?r.$from:r.$to,o=a.depth;for(;a.node(o).isInline;){if(!o)return!1;o--}return a.node(o).isTextblock?(n&&n(t.tr.setSelection(TextSelection.create(t.doc,e<0?a.start(o):a.end(o)))),!0):!1}}var wrapIn=(e,t=null)=>function(n,r){let{$from:a,$to:o}=n.selection,s=a.blockRange(o),c=s&&findWrapping(s,e,t);return c?(r&&r(n.tr.wrap(s,c).scrollIntoView()),!0):!1},setBlockType=(e,t=null)=>function(n,r){let a=!1;for(let r=0;r<n.selection.ranges.length&&!a;r++){let{$from:{pos:o},$to:{pos:s}}=n.selection.ranges[r];n.doc.nodesBetween(o,s,(r,o)=>{if(a)return!1;if(!(!r.isTextblock||r.hasMarkup(e,t)))if(r.type==e)a=!0;else{let t=n.doc.resolve(o),r=t.index();a=t.parent.canReplaceWith(r,r+1,e)}})}if(!a)return!1;if(r){let a=n.tr;for(let r=0;r<n.selection.ranges.length;r++){let{$from:{pos:o},$to:{pos:s}}=n.selection.ranges[r];a.setBlockType(o,s,e,t)}r(a.scrollIntoView())}return!0};function markApplies(e,t,n,r){for(let a=0;a<t.length;a++){let{$from:o,$to:s}=t[a],c=o.depth==0?e.inlineContent&&e.type.allowsMarkType(n):!1;if(e.nodesBetween(o.pos,s.pos,(e,t)=>{if(c||!r&&e.isAtom&&e.isInline&&t>=o.pos&&t+e.nodeSize<=s.pos)return!1;c=e.inlineContent&&e.type.allowsMarkType(n)}),c)return!0}return!1}function removeInlineAtoms(e){let t=[];for(let n=0;n<e.length;n++){let{$from:r,$to:a}=e[n];r.doc.nodesBetween(r.pos,a.pos,(e,n)=>{if(e.isAtom&&e.content.size&&e.isInline&&n>=r.pos&&n+e.nodeSize<=a.pos)return n+1>r.pos&&t.push(new SelectionRange(r,r.doc.resolve(n+1))),r=r.doc.resolve(n+1+e.content.size),!1}),r.pos<a.pos&&t.push(new SelectionRange(r,a))}return t}function toggleMark(e,t=null,n){let r=(n&&n.removeWhenPresent)!==!1,a=(n&&n.enterInlineAtoms)!==!1,o=!(n&&n.includeWhitespace);return function(n,s){let{empty:c,$cursor:l,ranges:u}=n.selection;if(c&&!l||!markApplies(n.doc,u,e,a))return!1;if(s)if(l)e.isInSet(n.storedMarks||l.marks())?s(n.tr.removeStoredMark(e)):s(n.tr.addStoredMark(e.create(t)));else{let c,l=n.tr;a||(u=removeInlineAtoms(u)),c=r?!u.some(t=>n.doc.rangeHasMark(t.$from.pos,t.$to.pos,e)):!u.every(t=>{let n=!1;return l.doc.nodesBetween(t.$from.pos,t.$to.pos,(r,a,o)=>{if(n)return!1;n=!e.isInSet(r.marks)&&!!o&&o.type.allowsMarkType(e)&&!(r.isText&&/^\s*$/.test(r.textBetween(Math.max(0,t.$from.pos-a),Math.min(r.nodeSize,t.$to.pos-a))))}),!n});for(let n=0;n<u.length;n++){let{$from:r,$to:a}=u[n];if(!c)l.removeMark(r.pos,a.pos,e);else{let n=r.pos,s=a.pos,c=r.nodeAfter,u=a.nodeBefore,d=o&&c&&c.isText?/^\s*/.exec(c.text)[0].length:0,f=o&&u&&u.isText?/\s*$/.exec(u.text)[0].length:0;n+d<s&&(n+=d,s-=f),l.addMark(n,s,e.create(t))}}s(l.scrollIntoView())}return!0}}var isList$1=e=>e.type.name===`bullet_list`||e.type.name===`ordered_list`||e.type.name===`task_list`,keepRange=(e,t)=>(n,r)=>{let a=n.doc.resolve(e),o=n.doc.resolve(t);for(let t=a.depth;t>0;t--)if(isList$1(a.node(t))){e=a.before(t);break}for(let e=o.depth;e>0;e--)if(isList$1(o.node(e))){t=o.after(e);break}if(!r)return!0;let s=n.doc.slice(e,t),c=n.tr.replace(0,n.doc.content.size,s);return c=c.setSelection(TextSelection.atStart(c.doc)),r&&r(c),!0},keepSelection=()=>(e,t)=>{if(!t)return!0;let n=e.selection.content(),r=e.tr.replace(0,e.doc.content.size,n);return r.setSelection(TextSelection.atStart(r.doc)),t&&t(r),!0},undoInputRule=()=>undoInputRuleCommand,command=e=>(...t)=>e.apply(void 0,t),baseCommandFactories={keepRange,keepSelection,wrapInList,wrapRangeInList,deleteSelection,joinBackward,joinTextblockBackward,joinTextblockForward,joinForward,joinUp,joinDown,lift,liftListItemParagraph,newlineInCode,exitCode,createParagraphNear,liftEmptyBlock,splitBlockAs,splitBlock,splitBlockKeepMarks,selectAll:selectAll$1,selectParentNode,selectNodeBackward,selectNodeForward,selectTextblockStart:()=>selectTextblockSide(-1),selectTextblockEnd:()=>selectTextblockSide(1),wrapIn,setBlockType,toggleMark,undoInputRule,runInputRulesRange,runInputRulesTexts,command};function firstCommand(...e){let t=function(t,n,r){for(let a=0;a<e.length;a++)if(e[a](t,n,r))return e[a].displayName!==`first`&&console.debug(`firstCommand: `,e[a].displayName||e[a]),!0;return!1};return t.displayName=`first`,t}var backspace=firstCommand(baseCommandFactories.undoInputRule(),baseCommandFactories.deleteSelection(),baseCommandFactories.liftListItemParagraph(),baseCommandFactories.joinBackward(),baseCommandFactories.selectNodeBackward()),del=firstCommand(baseCommandFactories.deleteSelection(),baseCommandFactories.joinForward(),baseCommandFactories.selectNodeForward()),enter=firstCommand(baseCommandFactories.newlineInCode(),baseCommandFactories.createParagraphNear(),baseCommandFactories.liftEmptyBlock(),baseCommandFactories.splitBlock()),keyCommandFactories={backspace:()=>backspace,del:()=>del,enter:()=>enter},replaceRangeText=(e,t)=>(n,r)=>{let a=n.tr,o=a.mapping.map(e.from),s=a.mapping.map(e.to);if(t.length>0){let e=new Slice(Fragment.from(n.schema.text(t)),0,0);a.replace(o,s,e)}else{let e=new Slice(Fragment.from(n.schema.topNodeType.createAndFill()),0,0);a.replace(o,s,e)}return r&&r(a),!0},replaceRangeSlice=(e,t)=>(n,r)=>{let a=n.tr,o=a.mapping.map(e.from),s=a.mapping.map(e.to);return a.replace(o,s,t),r&&r(a),!0};function getTopMostBlockStartForOffset(e,t){let{doc:n}=e,r=n.resolve(t),a=r.before(r.depth);return r.depth===1?a:r.start(1)}function getTopMostBlockEndForOffset(e,t){let{doc:n}=e;return n.resolve(t).end(1)}function getAdjacentTopBlock(e,t){let{doc:n}=e;if(t<0||t>n.content.size)throw RangeError(`Offset is outside the document`);let r=n.resolve(t);return r.pos===r.start(r.depth)?getTopMostBlockStartForOffset(e,t):getTopMostBlockEndForOffset(e,t)}var insertBlockBefore=(e,t)=>(n,r)=>{let a=n.tr,o=getTopMostBlockStartForOffset(n,a.mapping.map(e));return a.insert(o,t),r&&r(a),!0},insertBlockAfter=(e,t)=>(n,r)=>{let a=n.tr,o=getTopMostBlockEndForOffset(n,a.mapping.map(e));return a.insert(o,t),r&&r(a),!0},insertBlockSmart=(e,t)=>(n,r)=>{let a=n.tr,o=getAdjacentTopBlock(n,a.mapping.map(e));return a.insert(o,t),r&&r(a),!0},replaceCommandFactories={replaceRangeText,replaceRangeSlice,insertBlockBefore,insertBlockAfter,insertBlockSmart},CommandManager=class{editor;commandFactories={};run={};debug=!0;constructor(e){this.editor=e,this.mergeCommandFactories(baseCommandFactories,`baseCommand`),this.mergeCommandFactories(keyCommandFactories,`key`),this.mergeCommandFactories(replaceCommandFactories,`replace`),this.mergeCommandFactories(searchCommandFactories,`search`)}mergeCommandFactories(e,t){for(let n in e){let r=e[n];r&&this.overwriteCommandFactory(t,n,r)}}overwriteCommandFactory(e,t,n){if(this.debug){let r=(...r)=>{let a=n(...r);return(n,o,s)=>(o&&console.debug(`Command: ${e}.${t}`,...r),a.apply({editor:this.editor},[n,o,s]))};this.commandFactories[t]=r}else this.commandFactories[t]=n;this.run[t]=(...e)=>{let n=this.commandFactories[t],r=n(...e),a=this.editor.state,o=this.editor.view;return o instanceof EditorView?r.apply({editor:this.editor},[a,o.dispatch,o]):r.apply({editor:this.editor},[a,o.dispatch])}}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){let{commandFactories:n,editor:r}=this,a=this.editor.state,{view:o}=r,s=[],c=!!e,l=e||a.tr;l.setMeta(`isCommand`,!0);let u=createChainableState(l,a),d=()=>void 0,f={...Object.fromEntries(Object.entries(n).map(([e,n])=>[e,(...e)=>{let r=n(...e).apply({editor:this.editor},[u,t?d:void 0]);return s.push(r),f}])),run:()=>(!c&&t&&!l.getMeta(`preventDispatch`)&&o.dispatch(l),s.every(e=>e===!0)),chain:()=>this.createChain(l,t)};return f}createCan(e){return this.createChain(e,!1)}},SmartOutput=class{_rowPos=0;_colPos=0;_pos=0;chunks=[];metas=[];log(e,t){if(e.length===0)return;this.chunks.push(e),this.metas.push({pos:this._pos,colPos:this._colPos,rowPos:this._rowPos,item:t});let n=e.split(`
15
21
  `);n.length===1?this._colPos+=n[n.length-1].length:(this._rowPos+=n.length-1,this._colPos=n[n.length-1].length),this._pos+=e.length}getMetas(){return this.metas}get chunkPos(){return this.chunks.length}rollback(e){this.chunks.splice(e),this.metas.splice(e)}get rowPos(){return this._rowPos}get colPos(){return this._colPos}get pos(){return this._pos}backspace(e){let t=[],n=[];for(;e>0&&this.chunks[0].length>0;){let r=this.metas.pop(),a=this.chunks.pop();if(!a||!r)break;let o=a.length;a=a.substring(0,Math.max(0,a.length-e)),t.unshift(r),n.unshift(a),e-=o-a.length}this.chunks.push(...n),this.metas.push(...t)}endsWith(e){return this.chunks.join(``).endsWith(e)}toString(){return this.chunks.join(``)}getSourceMap(e){let t=[],n=-1,r=-1,a=0,o=0,s=0,c=0;for(let l of this.metas){for(;l.rowPos>=t.length;)t.push([]);if(n!=l.rowPos||r!=l.colPos){let r=t[l.rowPos];n!=l.rowPos&&(c=0);let u=e(l.rowPos,l.colPos,l.pos,l.item);u&&(r.push([l.colPos-c,u.sourceNo-a,u.sourceRowPos-o,u.sourceColPos-s]),c=l.colPos,a=u.sourceNo,o=u.sourceRowPos,s=u.sourceColPos)}n=l.rowPos,r=l.colPos}return{version:3,file:``,sourceRoot:``,sources:[],sourcesContent:[],names:[],mappings:t.map(e=>e.map(e=>encode(e)).join(`,`)).join(`;`)}}},char_to_integer={},integer_to_char={};`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=`.split(``).forEach(function(e,t){char_to_integer[e]=t,integer_to_char[t]=e});function encode(e){if(typeof e==`number`)return encode_integer(e);let t=``;for(let n=0;n<e.length;n+=1)t+=encode_integer(e[n]);return t}function encode_integer(e){let t=``;e<0?e=-e<<1|1:e<<=1;do{let n=e&31;e>>>=5,e>0&&(n|=32),t+=integer_to_char[n]}while(e>0);return t}function trimText(e,t=20){return e=e.replaceAll(`
16
22
  `,`\\n`),e.length<=t?e:e.slice(0,t)+`...`}function nodeToTreeStringOutput(e,t,n=0,r=0){let a=``;for(let e=0;e<n;e++)a+=` `;if(Array.isArray(t)){for(let o of t)e.log(a,{node:o,pos:r}),nodeToTreeStringOutput(e,o,n+1,r);return}let o=``;if(`type`in t){o+=` - [${t.type.name}] `,o+=`pos: ${r}, `,o+=`nodeSize: ${t.nodeSize}, `,o+=`epos: ${r+t.nodeSize}, `,t.content&&(o+=`fragment.size: ${t.content.size}, `),e.log(a+o+`
17
23
  `,{node:t,pos:r});let n=``;if(t.marks)for(let e of t.marks)n+=`(${e.type.name}), `;n&&e.log(a+` `+n+`
18
24
  `,{node:t,pos:r}),t.text&&e.log(a+` "`+trimText(t.text)+`"
19
- `,{node:t,pos:r})}return t.forEach((t,a)=>{nodeToTreeStringOutput(e,t,n+1,r+a+1)}),e}function nodeToTreeString(e){let t=new SmartOutput;return nodeToTreeStringOutput(t,e),t.toString()}var DummyEditorView=class{_props;directPlugins;nodeViews;prevDirectPlugins=[];pluginViews=[];state;focused=!1;constructor(e){this._props=e,this.state=e.state,this.directPlugins=e.plugins||[],this.directPlugins.forEach(checkStateComponent),this.dispatch=this.dispatch.bind(this),this.editable=getEditable(this),this.nodeViews=buildNodeViews(this),this.updatePluginViews()}editable;get composing(){return!1}get dom(){return{addEventListener(){},removeEventListener(){}}}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(checkStateComponent),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let e in this._props)t[e]=this._props[e];t.state=this.state;for(let n in e)t[n]=e[n];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){let n=this.state,r=!1,a=!1;if(e.storedMarks&&this.composing,this.state=e,n.plugins!=e.plugins||this._props.plugins!=t.plugins||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let e=buildNodeViews(this);changedNodeViews(e,this.nodeViews)&&(this.nodeViews=e,r=!0)}this.editable=getEditable(this),r||e.selection.eq(n.selection),this.updatePluginViews(n)}scrollToSelection(){}destroyPluginViews(){let e=this.pluginViews.pop();for(;e;)e.destroy&&e.destroy(),e=this.pluginViews.pop()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let e=0;e<this.directPlugins.length;e++){let t=this.directPlugins[e];t.spec.view&&this.pluginViews.push(t.spec.view(this))}for(let e=0;e<this.state.plugins.length;e++){let t=this.state.plugins[e];t.spec.view&&this.pluginViews.push(t.spec.view(this))}}else for(let t=0;t<this.pluginViews.length;t++){let n=this.pluginViews[t];n.update&&n.update(this,e)}}someProp(e,t){let n=this._props&&this._props[e],r;if(n!=null&&(r=t?t(n):n))return r;for(let n=0;n<this.directPlugins.length;n++){let a=this.directPlugins[n].props[e];if(a!=null&&(r=t?t(a):a))return r}let a=this.state.plugins;if(a)for(let n=0;n<a.length;n++){let o=a[n].props[e];if(o!=null&&(r=t?t(o):o))return r}}hasFocus(){return this.focused}focus(){this.focused=!0}destroy(){this.destroyPluginViews()}get isDestroyed(){return!1}dispatchEvent(e){}};DummyEditorView.prototype.dispatch=function(e){let t=this.props.dispatchTransaction;t?t.call(this,e):this.updateState(this.state.apply(e))};function getEditable(e){return!e.someProp(`editable`,t=>t(e.state)===!1)}function buildNodeViews(e){let t=Object.create(null);function n(e){for(let n in e)Object.prototype.hasOwnProperty.call(t,n)||(t[n]=e[n])}return e.someProp(`nodeViews`,n),e.someProp(`markViews`,n),t}function changedNodeViews(e,t){let n=0,r=0;for(let r in e){if(e[r]!=t[r])return!0;n++}for(let e in t)r++;return n!=r}function checkStateComponent(e){if(e.spec.state||e.spec.filterTransaction||e.spec.appendTransaction)throw RangeError(`Plugins passed directly to the view must not have a state component`)}function createNodeFromObject(e,t,n){try{let r=t.nodeFromJSON(e);return n?.errorOnInvalidContent&&r.check(),r}catch(r){if(n?.errorOnInvalidContent)throw Error(`Invalid JSON content: `+r.message,{cause:r});return console.warn(`Invalid content.`,`Passed value:`,e,`Error:`,r),t.topNodeType.createAndFill(null,[])}}function defaultUi(e){return{showMessage(e){globalThis.alert(e)},showError(e){globalThis.alert(e.message),console.error(e)},focus(){},select({anchor:e,scrollIntoView:t,userEvent:n}){}}}var Container=class{items=new Map;register(e,t){this.items.set(e,t)}resolve(e){return this.items.get(e)}};function ensureDocSchema(e,t){if(e.type.schema===t)return e;let n=e.toJSON();return Node$3.fromJSON(t,n)}var CoreEditor=class e extends EventTarget{schema;extensionManager;config;commandManager;view;state;ui=defaultUi(this);linkListener;linkSource;ci=new Container;version=0;constructor(e,t,n){super(),this.schema=t,this.extensionManager=n,this.config={...e},this.commandManager=new CommandManager(this)}static create(t){let n=new ExtensionManager(t.editorKits,t.debug),r=n.getSchemaByResolvedExtensions(),a=new e(t,r,n);n.created(a,r);let o=t.content?t.content:r.topNodeType.spec.EMPTY_DOC;return a.createView(o),a.setupPlugins(),a.dispatchEvent(new CustomEvent(`ready`)),a}clone(t){let n=new ExtensionManager(this.extensionManager.editorKits,(t||this.config).debug),r=new e({...t},this.schema,n);n.created(r,this.schema);let a=this.getJSON();return r.createView(a),r.setupPlugins(),r}getExtension(e){return this.ci.resolve(e)}get run(){return this.commandManager.run}get commandFactories(){return this.commandManager.commandFactories}chain(e){return this.commandManager.createChain(e)}can(e){return this.commandManager.createCan(e)}link(e){if(e===this)throw Error(`You cannot chain editor to itself`);this.unlink(),this.state=EditorState.create({doc:e.getDocument()});let{commandFactories:t}=this.commandManager,n=[],r={...Object.fromEntries(Object.entries(t).map(([e,t])=>[e,(...e)=>{let a=t(...e);return n.push(a),r}])),run:()=>{this.linkSource=e,this.linkListener=()=>{let t=e.state,r=e=>{t=t.apply(e)};for(let e of n)if(!e(t,r))return;this.state=t.reconfigure({plugins:this.extensionManager.plugins}),this.view&&this.view.updateState(this.state);let a=new CustomEvent(`changed`,{detail:{editor:this}});this.dispatchEvent(a)},e.addEventListener(`changed`,this.linkListener)}};return r}unlink(){this.linkListener&&this.linkSource&&(this.linkSource.removeEventListener(`changed`,this.linkListener),this.linkListener=void 0,this.linkSource=void 0)}createView(e){let t=createNodeFromObject(e,this.schema);if(this.state=EditorState.create({doc:t}),this.config.element){let e=new EditorView(this.config.element,{state:this.state,attributes:{class:`kb-editor`},dispatchTransaction:e=>this.dispatchTransaction(e),editable:()=>!this.config.readOnly});if(this.view=e,this.config.element.parentNode){let t=new MutationObserver(n=>{for(let r of n)for(let n of r.removedNodes)if(n.contains(e.dom)){t.disconnect(),e.destroy();return}})}}else this.view=new DummyEditorView({state:this.state,dispatchTransaction:e=>this.dispatchTransaction(e)});let n=new CustomEvent(`doc:loaded`,{detail:{editor:this,doc:t}});this.dispatchEvent(n)}dispatchTransaction(e){if(this.state=this.state.apply(e),e.docChanged&&this.version++,this.view){this.view.updateState(this.state);let t=new CustomEvent(`transaction`,{detail:{editor:this,transaction:e}});this.dispatchEvent(t)}if(e.docChanged){let e=new CustomEvent(`changed`,{detail:{editor:this}});this.dispatchEvent(e)}}setupPlugins(){this.state=this.state.reconfigure({plugins:this.extensionManager.plugins}),this.view&&(this.view.updateState(this.state),this.view.setProps({nodeViews:this.extensionManager.nodeViews}))}clearDocument(){let e={type:this.schema.topNodeType.name,content:this.schema.topNodeType.spec.EMPTY_DOC.content};this.setDocument(e)}setDocument(e){let t=createNodeFromObject(e,this.schema,{errorOnInvalidContent:!0});t=ensureDocSchema(t,this.schema),this.state=EditorState.create({doc:t,plugins:this.state.plugins,storedMarks:this.state.storedMarks}),this.view&&this.view.updateState(this.state);let n=new CustomEvent(`doc:loaded`,{detail:{editor:this,doc:t}});this.dispatchEvent(n)}getConverter(e){let t=this.extensionManager.converters[e];if(!t)throw Error(`Converter not found for: `+e);return t}getDocument(){return this.state.doc}loadDocumentText(e,t){return this.loadDocument(e,new TextEncoder().encode(t))}async loadDocument(e,t){let n=await this.getConverter(e).toDoc(t),r=EditorState.create({doc:n,plugins:this.state.plugins,storedMarks:this.state.storedMarks});runInputRulesTexts()(r,e=>{r=r.apply(e)}),this.state=r,this.view&&(this.view.updateState(this.state),this.view.dispatch(this.view.state.tr));let a=new CustomEvent(`doc:loaded`,{detail:{editor:this,doc:this.state.doc}});this.dispatchEvent(a)}async saveDocument(e){let t=this.getConverter(e),n=this.state.doc.toJSON(),r=Node$3.fromJSON(this.state.schema,n);return await t.fromDoc(r)}async patchDocument(e,t){let n=await this.getConverter(e).toDoc(t),r=this.state.tr;r.replaceWith(0,this.state.doc.content.size,n.content),this.dispatchTransaction(r)}getMediaTypes(){return Object.keys(this.extensionManager.converters)}patchDocumentText(e,t){return this.patchDocument(e,new TextEncoder().encode(t))}getJSON(){return this.state.doc.toJSON()}debug(e){e||=this.state.doc,console.debug(nodeToTreeString(e))}destroy(){let e=new CustomEvent(`beforeDestroy`,{detail:{}});if(this.dispatchEvent(e),this.config.element){let e=this.config.element,t=e.cloneNode(!0);e.replaceWith(t)}this.view.destroy()}mergeCommandFactories(e,t){this.commandManager.mergeCommandFactories(e,t)}get editable(){return this.view.editable}},Extension=class{config;type=`extension`;editor;conflicts;overrides;constructor(e={}){this.config=e}setEditor(e){this.editor=e}getEditor(){return this.editor}created(){}getInputRules(){return[]}getProseMirrorPlugins(){return[]}getCommandFactories(e){return{}}getKeyboardShortcuts(e){return{}}getConverters(e,t){return{}}setupSpec(e){}},Mark=class{config;type=`mark`;name=`node`;editor;attributes={};constructor(e={}){this.config=e}setEditor(e){this.editor=e}created(){}getMarkSpec(){throw Error(`MarkSpec not defined: `+this.name)}getInputRules(e){return[]}getCommandFactories(e,t){return{}}getKeyboardShortcuts(e){return{}}},Node$2=class{config;type=`node`;name=`node`;editor;attributes={};constructor(e={}){this.config=e}setEditor(e){this.editor=e}created(){}getNodeSpec(){throw Error(`NodeSpec not defined: `+this.name)}getInputRules(e){return[]}getProseMirrorPlugins(){return[]}getCommandFactories(e,t){return{}}getKeyboardShortcuts(e){return{}}getNodeView(e){}getConverters(e,t){return{}}};function getShadowRoot(e){let t=e;for(;t;){if(t.toString()===`[object ShadowRoot]`)return t;if(t instanceof ShadowRoot&&t.host)return t.host.shadowRoot||void 0;t=t.parentElement||(t instanceof ShadowRoot?t.host:void 0)}}function debounce(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function normalizeSiblings(e,t){if(e.childCount<2)return e;for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.index(n)),a,o=[];if(e.forEach(e=>{if(!o)return;let t=r.findWrapping(e.type),n;if(!t)return o=null;if(n=o.length&&a.length&&addToSibling(t,a,e,o[o.length-1],0))o[o.length-1]=n;else{o.length&&(o[o.length-1]=closeRight(o[o.length-1],a.length));let n=withWrappers(e,t);o.push(n),r=r.matchType(n.type),a=t}}),o)return Fragment.from(o)}return e}function withWrappers(e,t,n=0){for(let r=t.length-1;r>=n;r--)e=t[r].create(null,Fragment.from(e));return e}function addToSibling(e,t,n,r,a){if(a<e.length&&a<t.length&&e[a]==t[a]){let o=addToSibling(e,t,n,r.lastChild,a+1);if(o)return r.copy(r.content.replaceChild(r.childCount-1,o));if(r.contentMatchAt(r.childCount).matchType(a==e.length-1?n.type:e[a+1]))return r.copy(r.content.append(Fragment.from(withWrappers(n,e,a+1))))}}function closeRight(e,t){if(t==0)return e;let n=e.content.replaceChild(e.childCount-1,closeRight(e.lastChild,t-1)),r=e.contentMatchAt(e.childCount).fillBefore(Fragment.empty,!0);return e.copy(n.append(r))}function closeRange(e,t,n,r,a,o){let s=t<0?e.firstChild:e.lastChild,c=s.content;return e.childCount>1&&(o=0),a<r-1&&(c=closeRange(c,t,n,r,a+1,o)),a>=n&&(c=t<0?s.contentMatchAt(0).fillBefore(c,o<=a).append(c):c.append(s.contentMatchAt(s.childCount).fillBefore(Fragment.empty,!0))),e.replaceChild(t<0?0:e.childCount-1,s.copy(c))}function closeSlice(e,t,n){return t<e.openStart&&(e=new Slice(closeRange(e.content,-1,t,e.openStart,0,e.openEnd),t,e.openEnd)),n<e.openEnd&&(e=new Slice(closeRange(e.content,1,n,e.openEnd,0,0),e.openStart,n)),e}function sliceSingleNode(e){return e.openStart==0&&e.openEnd==0&&e.content.childCount==1?e.content.firstChild:null}function fixSlice(e,t){if(e=Slice.maxOpen(normalizeSiblings(e.content,t),!0),e.openStart||e.openEnd){let t=0,n=0;for(let n=e.content.firstChild;t<e.openStart&&!n.type.spec.isolating;t++,n=n.firstChild);for(let t=e.content.lastChild;n<e.openEnd&&!t.type.spec.isolating;n++,t=t.lastChild);e=closeSlice(e,t,n)}return e}function sliceHasOnlyText(e){return e.content.content.every(e=>e.isInline)}var selectAll=()=>function(e,t,n){let r=e.tr.setSelection(new AllSelection(e.doc));return n&&n.dispatch(r),!0};function textPositionsToResolvedPos(e,t,n){let r=e.map(e=>-1),a=0,o=!1;function s(t,n,s,c){if(o){for(let n=0;n<e.length;n++){let o=e[n];o>=a&&o<a+c&&(r[n]=t+(o-a))}a+=c}}function c(e,t=0,r=0,a=0){t===1&&r===n&&(o=!0);let l=0;e.isText&&e.text?l=e.text?.length:e.isLeaf&&(l=1),l>0&&s(a,t,r,l),e.forEach((e,n,r)=>{c(e,t+1,r,a+n+1)})}if(c(t),o)for(let n=0;n<e.length;n++){let o=e[n];r[n]===-1&&(o<a?r[n]=1:r[n]=t.nodeSize-1)}return r.map(e=>t.resolve(e-1))}var selectText=(e,t,n=0)=>function(r,a,o){let[s,c]=textPositionsToResolvedPos([e+t,e],r.doc,n),l=r.tr.setSelection(new TextSelection(c,s));return o&&o.dispatch(l),!0},ExtensionSelection=class extends Extension{name=`selection`;extractSelection(){let e=this.editor.state,{from:t,to:n}=e.selection,r=e.doc.slice(t,n);if(sliceHasOnlyText(r)){let t=e.schema.nodes.paragraph.create(null,r.content);return e.schema.topNodeType.createAndFill(null,[t])}return e.schema.topNodeType.createAndFill(null,r.content)}replaceSelection(e){let t=!1,n=this.editor.view,r=this.editor.state,a;e.type?.name===`doc`&&(e=createNodeFromObject(e.toJSON(),this.editor.schema)),a=new Slice(e.content,1,1);let o=r.selection.$from;a=fixSlice(a,o);let s=sliceSingleNode(a),c=s?r.tr.replaceSelectionWith(s,!1):r.tr.replaceSelection(a);n.dispatch(c.scrollIntoView())}appendSelection(e){let t=this.editor.view,{state:n}=t,r;e.type?.name===`doc`&&(e=createNodeFromObject(e.toJSON(),this.editor.schema)),r=new Slice(e.content,1,1);let a=t.state.selection.$from;r=fixSlice(r,a);let o=n.tr.insert(t.state.selection.to,r.content);t.dispatch(o.scrollIntoView())}getCommandFactories(e){return this.editor=e,{selectAll:()=>selectAll(),selectText:(...e)=>selectText(...e)}}},pcBaseKeymap={"Mod-Enter":`exitCode`,Backspace:`backspace`,"Mod-Backspace":`backspace`,"Shift-Backspace":`backspace`,Delete:`del`,"Mod-Delete":`del`,"Mod-a":`selectAll`},macBaseKeymap={...pcBaseKeymap,"Ctrl-h":pcBaseKeymap.Backspace,"Alt-Backspace":pcBaseKeymap[`Mod-Backspace`],"Ctrl-d":pcBaseKeymap.Delete,"Ctrl-Alt-Backspace":pcBaseKeymap[`Mod-Delete`],"Alt-Delete":pcBaseKeymap[`Mod-Delete`],"Alt-d":pcBaseKeymap[`Mod-Delete`],"Ctrl-a":`selectTextblockStart`,"Ctrl-e":`selectTextblockEnd`},baseKeymap=/(Mac|iPhone|iPod|iPad)/i.test(navigator?.platform)?macBaseKeymap:pcBaseKeymap,ExtensionBaseKeymap=class extends Extension{name=`base-keymap`;getKeyboardShortcuts(){let e={Enter:`enter`,"Alt-ArrowUp":`joinUp`,"Alt-ArrowDown":`joinDown`,"Mod-BracketLeft":`lift`,Escape:`selectParentNode`};for(let t in baseKeymap)e[t]=baseKeymap[t];return e}};function dropCursor(e={}){return new Plugin({key:new PluginKey(`drop-cursor`),view(t){return new DropCursorView(t,e)}})}var DropCursorView=class{editorView;width;color;class;cursorPos=null;element=null;timeout=-1;handlers;constructor(e,t){this.editorView=e,this.width=t.width??1,this.color=t.color===!1?void 0:t.color||`black`,this.class=t.class,this.handlers=[`dragover`,`dragend`,`drop`,`dragleave`].map(t=>{let n=e=>{this[t](e)};return e.dom.addEventListener(t,n),{name:t,handler:n}})}destroy(){this.handlers.forEach(({name:e,handler:t})=>this.editorView.dom.removeEventListener(e,t))}update(e,t){this.cursorPos!=null&&t.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),t=!e.parent.inlineContent,n,r=this.editorView.dom,a=r.getBoundingClientRect(),o=a.width/r.offsetWidth,s=a.height/r.offsetHeight;if(t){let t=e.nodeBefore,r=e.nodeAfter;if(t||r){let e=this.editorView.nodeDOM(this.cursorPos-(t?t.nodeSize:0));if(e){let a=e.getBoundingClientRect(),o=t?a.bottom:a.top;t&&r&&(o=(o+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let c=this.width/2*s;n={left:a.left,right:a.right,top:o-c,bottom:o+c}}}}if(!n){let e=this.editorView.coordsAtPos(this.cursorPos),t=this.width/2*o;n={left:e.left-t,right:e.left+t,top:e.top,bottom:e.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement(`div`)),this.class&&(this.element.className=this.class),this.element.style.cssText=`position: absolute; z-index: 50; pointer-events: none;`,this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle(`prosemirror-dropcursor-block`,t),this.element.classList.toggle(`prosemirror-dropcursor-inline`,!t);let l,u;if(!c||c==document.body&&getComputedStyle(c).position==`static`)l=-pageXOffset,u=-pageYOffset;else{let e=c.getBoundingClientRect(),t=e.width/c.offsetWidth,n=e.height/c.offsetHeight;l=e.left-c.scrollLeft*t,u=e.top-c.scrollTop*n}this.element.style.left=(n.left-l)/o+`px`,this.element.style.top=(n.top-u)/s+`px`,this.element.style.width=(n.right-n.left)/o+`px`,this.element.style.height=(n.bottom-n.top)/s+`px`}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let t=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),n=t&&t.inside>=0&&this.editorView.state.doc.nodeAt(t.inside),r=n&&n.type.spec.disableDropCursor,a=typeof r==`function`?r(this.editorView,t,e):r;if(t&&!a){let e=t.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let t=dropPoint(this.editorView.state.doc,e,this.editorView.dragging.slice);t!=null&&(e=t)}this.setCursor(e),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}},ExtensionDropcursor=class extends Extension{name=`dropcursor`;options={color:`currentColor`,width:1,class:void 0};getProseMirrorPlugins(){return[dropCursor(this.options)]}},GapCursor=class e extends Selection{constructor(e){super(e,e),this.visible=!1}map(t,n){let r=t.resolve(n.map(this.head));return e.valid(r)?new e(r):Selection.near(r)}content(){return Slice.empty}eq(t){return t instanceof e&&t.head==this.head}toJSON(){return{type:`gapcursor`,pos:this.head}}static fromJSONToGapCursor(t,n){if(typeof n.pos!=`number`)throw RangeError(`Invalid input for GapCursor.fromJSON`);return new e(t.resolve(n.pos))}getBookmark(){return new GapBookmark(this.anchor)}static valid(e){let t=e.parent;if(t.isTextblock||!closedBefore(e)||!closedAfter(e))return!1;let n=t.type.spec.allowGapCursor;if(n!=null)return n;let r=t.contentMatchAt(e.index()).defaultType;return r&&r.isTextblock}static findGapCursorFrom(t,n,r=!1){search:for(;;){if(!r&&e.valid(t))return t;let a=t.pos,o=null;for(let r=t.depth;;r--){let s=t.node(r);if(n>0?t.indexAfter(r)<s.childCount:t.index(r)>0){o=s.child(n>0?t.indexAfter(r):t.index(r)-1);break}else if(r==0)return null;a+=n;let c=t.doc.resolve(a);if(e.valid(c))return c}for(;;){let s=n>0?o.firstChild:o.lastChild;if(!s){if(o.isAtom&&!o.isText&&!NodeSelection.isSelectable(o)){t=t.doc.resolve(a+o.nodeSize*n),r=!1;continue search}break}o=s,a+=n;let c=t.doc.resolve(a);if(e.valid(c))return c}return null}}};Selection.jsonID(`gapcursor`,GapCursor);var GapBookmark=class e{pos;constructor(e){this.pos=e}map(t){return new e(t.map(this.pos))}resolve(e){let t=e.resolve(this.pos);return GapCursor.valid(t)?new GapCursor(t):Selection.near(t)}};function closedBefore(e){for(let t=e.depth;t>=0;t--){let n=e.index(t),r=e.node(t);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let e=r.child(n-1);;e=e.lastChild){if(e.childCount==0&&!e.inlineContent||e.isAtom||e.type.spec.isolating)return!0;if(e.inlineContent)return!1}}return!0}function closedAfter(e){for(let t=e.depth;t>=0;t--){let n=e.indexAfter(t),r=e.node(t);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let e=r.child(n);;e=e.firstChild){if(e.childCount==0&&!e.inlineContent||e.isAtom||e.type.spec.isolating)return!0;if(e.inlineContent)return!1}}return!0}function gapCursor(){return new Plugin({key:new PluginKey(`gap-cursor`),props:{decorations:drawGapCursor,createSelectionBetween(e,t,n){return t.pos==n.pos&&GapCursor.valid(n)?new GapCursor(n):null},handleClick,handleKeyDown:handleKeyDown$1,handleDOMEvents:{beforeinput}}})}var handleKeyDown$1=keydownHandler({ArrowLeft:arrow$1(`horiz`,-1),ArrowRight:arrow$1(`horiz`,1),ArrowUp:arrow$1(`vert`,-1),ArrowDown:arrow$1(`vert`,1)});function arrow$1(e,t){let n=e==`vert`?t>0?`down`:`up`:t>0?`right`:`left`;return function(e,r,a){let o=e.selection,s=t>0?o.$to:o.$from,c=o.empty;if(o instanceof TextSelection){if(!a.endOfTextblock(n)||s.depth==0)return!1;c=!1,s=e.doc.resolve(t>0?s.after():s.before())}let l=GapCursor.findGapCursorFrom(s,t,c);return l?(r&&r(e.tr.setSelection(new GapCursor(l))),!0):!1}}function handleClick(e,t,n){if(!e||!e.editable)return!1;let r=e.state.doc.resolve(t);if(!GapCursor.valid(r))return!1;let a=e.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&NodeSelection.isSelectable(e.state.doc.nodeAt(a.inside))?!1:(e.dispatch(e.state.tr.setSelection(new GapCursor(r))),!0)}function beforeinput(e,t){if(t.inputType!=`insertCompositionText`||!(e.state.selection instanceof GapCursor))return!1;let{$from:n}=e.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(e.state.schema.nodes.text);if(!r)return!1;let a=Fragment.empty;for(let e=r.length-1;e>=0;e--)a=Fragment.from(r[e].createAndFill(null,a));let o=e.state.tr.replace(n.pos,n.pos,new Slice(a,0,0));return o.setSelection(TextSelection.near(o.doc.resolve(n.pos+1))),e.dispatch(o),!1}function drawGapCursor(e){if(!(e.selection instanceof GapCursor))return null;let t=document.createElement(`div`);return t.className=`kb-gapcursor`,DecorationSet.create(e.doc,[Decoration.widget(e.selection.head,t,{key:`gapcursor`})])}var ExtensionGapcursor=class extends Extension{name=`gapcursor`;options={color:`currentColor`,width:1,class:void 0};getProseMirrorPlugins(){return[gapCursor()]}},ExtensionTextAlign=class extends Extension{name=`textAlign`;getCommandFactories(e){let t=e=>(t,n)=>{let{selection:r,tr:a}=t,{from:o,to:s}=r,c=!1;return t.doc.nodesBetween(o,s,(t,n)=>{t.isBlock&&t.type.spec.attrs&&`textAlign`in t.type.spec.attrs&&(a.setNodeMarkup(n,void 0,{...t.attrs,textAlign:e}),c=!0)}),c&&n&&n(a),c};return{setTextAlignLeft:()=>t(`left`),setTextAlignCenter:()=>t(`center`),setTextAlignRight:()=>t(`right`),setTextAlignJustify:()=>t(`justify`)}}},userColors=[{dark:`#30bced`,light:`#30bced`},{dark:`#6eeb83`,light:`#6eeb83`},{dark:`#ffbc42`,light:`#ffbc42`},{dark:`#ecd444`,light:`#ecd444`},{dark:`#ee6352`,light:`#ee6352`},{dark:`#9ac2c9`,light:`#9ac2c9`},{dark:`#8acb88`,light:`#8acb88`},{dark:`#1be7ff`,light:`#1be7ff`}];function hashString(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)}var defaultColorMapper=(e,t)=>{let n=hashString(t.id),r=hashString(e.id);return n===r&&r++,userColors[r%userColors.length]};function generateBlankUser(){return{id:``,name:`User unset`}}function generateRandomUser(){let e=Math.random()*100;return{id:`random:`+e,name:`Anonymous `+Math.floor(e)}}var userPluginKey=new PluginKey(`user`),createUserPlugin=()=>new Plugin({key:userPluginKey,state:{init(){return{user:generateRandomUser()}},apply:(e,t)=>{let n=e.getMeta(`changeUser`);return n&&(t.user={...n.user}),t}}}),ExtensionUser=class extends Extension{name=`user`;getCommandFactories(){return{changeUser:e=>(t,n)=>{let r=t.tr;return r.setMeta(`changeUser`,{user:e}),n&&n(r),!0}}}getProseMirrorPlugins(){return[createUserPlugin()]}},remoteSelectionPluginKey=new PluginKey(`remote-selection`),defaultCursorBuilder=(e,t,n)=>{let r=n(e,t).light,a=document.createElement(`span`);a.classList.add(`kb-yjs__cursor`),a.setAttribute(`style`,`border-color: ${r};`);let o=document.createElement(`div`);o.setAttribute(`style`,`background-color: ${r}`),o.insertBefore(document.createTextNode(e.name),null);let s=document.createTextNode(`⁠`),c=document.createTextNode(`⁠`);return a.insertBefore(s,null),a.insertBefore(o,null),a.insertBefore(c,null),a},defaultSelectionBuilder=(e,t,n)=>({style:`background-color: ${n(e,t).light}70`,class:`kb-yjs__selection`}),createDecorations=(e,t,n,r)=>{let a=[],o=t.remoteStates;for(let s of o)if(s.cursor!=null){let o=s.user,c=s.cursor,l=c.anchor||null,u=c.head||null;if(l!==null&&u!==null){let c=Math.max(e.doc.content.size-1,0);l=Math.min(l,c),u=Math.min(u,c),a.push(Decoration.widget(u,()=>n(o,t.me,t.colorMapper),{key:s.clientId+o.id+o.name,side:10}));let d=Math.min(l,u),f=Math.max(l,u);a.push(Decoration.inline(d,f,r(o,t.me,t.colorMapper),{inclusiveEnd:!0,inclusiveStart:!1}))}}return DecorationSet.create(e.doc,a)},remoteSelectionPlugin=({cursorBuilder:e=defaultCursorBuilder,selectionBuilder:t=defaultSelectionBuilder}={})=>new Plugin({key:remoteSelectionPluginKey,state:{init(){return{remoteStates:[],me:generateBlankUser(),colorMapper:defaultColorMapper}},apply(e,t){let n=e.getMeta(`changeUser`);n&&(t.me={...n.user});let r=e.getMeta(`setColorMapper`);r&&(t.colorMapper=r.colorMapper);let a=e.getMeta(`remoteSelectionChange`);return a&&(t.remoteStates=[...a.remoteStates]),t}},props:{decorations(n){let r=this.getState(n);return r?createDecorations(n,r,e,t):DecorationSet.empty}}}),ExtensionRemoteSelection=class extends Extension{name=`remote-selection`;getProseMirrorPlugins(){return[remoteSelectionPlugin()]}};function generateId(){return String(Math.random())}function buildPairingTransaction(e,t,n){let{doc:r}=e,a=new Map,o=[];r.descendants((e,n)=>{e.type.name===t&&o.push({node:e,pos:n})});let s=!1;for(let{node:e,pos:t}of o){let r=e.attrs.content?.trim();if(!r)continue;let o=r.match(/^[^0-9a-z\/]*(\/?)[\s]*([\w]+)/i);if(!o)continue;let c=o[1]===`/`,l=o[2];if(!c)a.has(l)||a.set(l,[]),a.get(l).push({node:e,pos:t});else{let r=a.get(l);if(r&&r.length>0){let a=r.pop(),o=generateId();n.setNodeMarkup(a.pos,void 0,{...a.node.attrs,id:o,nesting:1,error:void 0}),n.setNodeMarkup(t,void 0,{...e.attrs,id:o,nesting:-1,error:void 0})}else n.setNodeMarkup(t,void 0,{...e.attrs,error:`Closing shortcode without matching opening`,nesting:-1});s=!0}}for(let[,e]of a.entries())for(let{node:t,pos:r}of e)n.setNodeMarkup(r,void 0,{...t.attrs,nesting:0,id:void 0}),s=!0;return s?n:null}var createPairingPlugin=e=>new Plugin({appendTransaction(t,n,r){let a=new Set;for(let r of t)if(r.docChanged){for(let t of r.steps)if((t instanceof ReplaceStep||t instanceof ReplaceAroundStep)&&(t.slice&&t.slice.content.descendants(t=>{e.includes(t.type.name)&&a.add(t.type.name)}),t.from!=null&&t.to!=null&&t.from!==t.to&&n.doc.nodesBetween(t.from,t.to,t=>{e.includes(t.type.name)&&a.add(t.type.name)}),a.size===e.length))break;if(a.size===e.length)break}if(a.size===0)return null;let o=r.tr;for(let e of a)buildPairingTransaction(r,e,o);return o}}),ExtensionPairing=class extends Extension{name=`pairing-nodes`;getProseMirrorPlugins(){return[createPairingPlugin([`shortcode_inline`])]}};function getHTMLFromFragment(e,t){let n=globalThis.document,r=DOMSerializer.fromSchema(t).serializeFragment(e,{document:n}),a=n.implementation.createHTMLDocument().createElement(`div`);return a.appendChild(r),a.innerHTML}var removeWhitespaces$1=e=>{let t=e.childNodes;for(let n=t.length-1;n>=0;--n){let r=t[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?e.removeChild(r):r.nodeType===1&&removeWhitespaces$1(r)}return e};function elementFromString$1(e){let t=`<html lang="en"><body>${e}</body></html>`,n=new globalThis.DOMParser().parseFromString(t,`text/html`).body;return removeWhitespaces$1(n)}var ExtensionHtml=class extends Extension{name=`html`;getConverters(e,t){return{"text/html":{fromDoc:async t=>{let n=getHTMLFromFragment(t.content,e.schema);return new TextEncoder().encode(n)},toDoc:async e=>{let n=elementFromString$1(new TextDecoder().decode(e));return DOMParser$1.fromSchema(t).parse(n)}}}}},mediaUploadKey=new PluginKey(`mediaUpload`);function fileToDataURL(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=n,r.readAsDataURL(e)})}function fileToObjectURL(e){return URL.createObjectURL(e)}function isImage(e,t){return t.some(t=>e.type.match(t))}function isVideo(e,t){return t.some(t=>e.type.match(t))}function insertImage(e,t,n,r,a){let{schema:o}=e.state,s=o.nodes.image;if(!s){console.warn(`Image node type not found in schema`);return}let c=s.create({src:n,alt:r,title:a}),l=e.state.tr.insert(t,c);e.dispatch(l)}function insertVideo(e,t,n,r,a,o){let{schema:s}=e.state,c=s.nodes.video;if(!c){console.warn(`Video node type not found in schema`);return}let l=c.create({src:n,title:r,width:a,height:o,controls:!0}),u=e.state.tr.insert(t,l);e.dispatch(u)}async function handleMediaFiles(e,t,n,r){let{maxFileSize:a=10*1024*1024,maxVideoFileSize:o=50*1024*1024,allowedImageTypes:s=[`^image/`],allowedVideoTypes:c=[`^video/`],uploadHandler:l}=r;for(let u of t){let t=isImage(u,s),d=isVideo(u,c);if(!t&&!d)continue;let f=d?o:a;if(u.size>f){console.warn(`${d?`Video`:`Image`} file "${u.name}" is too large (${(u.size/1024/1024).toFixed(2)}MB). Maximum size is ${(f/1024/1024).toFixed(2)}MB.`);continue}try{console.log(`Processing ${d?`video`:`image`}: ${u.name} (${(u.size/1024/1024).toFixed(2)}MB, ${u.type})`);let t;l?t=await l(u):d&&r.useObjectURLForVideos!==!1?(t=fileToObjectURL(u),console.log(`Using object URL for video:`,t)):(t=await fileToDataURL(u),console.log(`${d?`Video`:`Image`} converted to data URL, length: ${t.length} characters`)),d?(insertVideo(e,n,t,u.name),console.log(`Video inserted into editor`)):(insertImage(e,n,t,u.name),console.log(`Image inserted into editor`)),n+=1}catch(e){console.error(`Failed to process ${d?`video`:`image`} "${u.name}":`,e)}}}function createMediaUploadPlugin(e={}){return new Plugin({key:mediaUploadKey,state:{init(){return e},apply(e,t){return e.isGeneric?t:e.getMeta(`setMediaUploadOptions`)||t}},props:{handleDrop(e,t,n,r){if(r)return!1;let a=Array.from(t.dataTransfer?.files||[]);if(a.length===0)return!1;let o=mediaUploadKey.getState(e.state)||{},{allowedImageTypes:s=[`^image/`],allowedVideoTypes:c=[`^video/`]}=o;if(a.some(e=>isImage(e,s)||isVideo(e,c))){t.preventDefault();let n={left:t.clientX,top:t.clientY},r=e.posAtCoords(n);return r?(handleMediaFiles(e,a,r.pos,o),!0):!1}},handlePaste(t,n,r){let a=Array.from(n.clipboardData?.items||[]).filter(e=>e.type.startsWith(`image/`));if(a.length>0){n.preventDefault();let r=[];for(let e of a){let t=e.getAsFile();t&&r.push(t)}if(r.length===0)return!1;let{from:o}=t.state.selection;return handleMediaFiles(t,r,o,e),!0}}}})}var ExtensionMediaUpload=class extends Extension{config;name=`mediaUpload`;constructor(e={}){super(e),this.config=e}getProseMirrorPlugins(){return[createMediaUploadPlugin(this.config)]}};function getStringByXPath(e,t){return t.ownerDocument.evaluate(e,t,null,XPathResult.STRING_TYPE,null).stringValue}function getElementsByXPath(e,t){let n=t.ownerDocument.evaluate(e,t,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),r=[];for(let e=0;e<n.snapshotLength;e++){let t=n.snapshotItem(e);t&&r.push(t)}return r}var PasteState=class{editor;pasteRules=[];constructor(e){this.editor=e}handleCommands(e,t){if(!e)return!1;if(e.getPasteRules)return e.getPasteRules(this.pasteRules),!0;if(e.setPasteRules)return console.log(`setPasteRules`,e.setPasteRules),this.pasteRules=e.setPasteRules,!0;if(e.pasteHtml){let{from:t,html:n}=e.pasteHtml,r=elementFromString$1(n),a=this.editor,o=!1,s=[],c=a.ci.resolve(`yaml`);for(let e of this.pasteRules){if(typeof e.match==`string`){if(getElementsByXPath(e.match,r).length===0)continue}else if(!e.match(r))continue;for(let t of e.steps){let e;if(typeof t.match==`string`)switch(t.result||``){case`string`:e=getStringByXPath(t.match,r);break;default:e=getElementsByXPath(t.match,r);break}else e=t.match(r);switch(console.log(`step`,e,t),t.op){case`remove`:for(let t of e)t.parentNode?.removeChild(t);break;case`replaceTag`:for(let n of e){let e=n.ownerDocument.createElement(t.tag);e.innerHTML=n.innerHTML,n.parentNode?.replaceChild(e,n)}break;case`replaceBody`:for(let t of e)r.innerHTML=``,r.appendChild(t);break;case`console.debug`:console.debug(e);break;case`meta.set`:s.push({path:t.path,value:e});break}}o=!!e.replaceDocument;break}let l=DOMParser$1.fromSchema(this.editor.schema).parse(r);return setTimeout(async()=>{let e=this.editor.state.tr;o?e.replaceWith(0,this.editor.state.doc.content.size,l):e.insert(t,l);{let t=await new Promise(e=>this.editor.chain().getMeta(e).run())||new Map;for(let e of s)c.setPathValue(t,e.path,e.value);e.setDocAttribute(`meta`,t)}this.editor.dispatchTransaction(e)},0),!0}return!1}},PastePluginKey=new PluginKey(`paste`),ExtensionPaste=class extends Extension{name=`paste`;getProseMirrorPlugins(){let e=this.editor;return[new Plugin({key:PastePluginKey,state:{init(){return PastePluginKey.getState(e.state)||new PasteState(e)},apply(e,t,n,r){if(e.isGeneric)return t;let a=e.getMeta(PastePluginKey);return t.handleCommands(a,e),t}},props:{handlePaste(t,n,r){let{clipboardData:a}=n;if(!a)return!1;if(a.types.includes(`text/html`)){let{from:e}=t.state.selection,r=a.getData(`text/html`);n.preventDefault();let o=t.state.tr.setMeta(PastePluginKey,{pasteHtml:{from:e,html:r}});return t.dispatch(o),!0}[...a.items].map(e=>e.getAsFile()).filter(e=>!!e);let o=Array.from(n.clipboardData?.files||[]);if(o.length===1){let t=o[0];if(e.getMediaTypes().includes(t.type))return t.bytes().then(n=>{e.loadDocument(t.type,n)}),!0}},handleDrop(t,n,r,a){let o=Array.from(n.dataTransfer?.files||[]);if(o.length===1){let t=o[0];if(e.getMediaTypes().includes(t.type))return t.bytes().then(n=>{e.loadDocument(t.type,n)}),!0}}}})]}getCommandFactories(e){return{getPasteRules:e=>(t,n)=>{let r=t.tr;return r.setMeta(PastePluginKey,{getPasteRules:e}),n&&n(r),!0},setPasteRules:e=>(t,n)=>{let r=t.tr;return r.setMeta(PastePluginKey,{setPasteRules:e}),n&&n(r),!0}}}},MarkLink=class extends Mark{name=`link`;requires=[`doc`];getMarkSpec(){return{attrs:{href:{},title:{default:void 0},origUrl:{default:void 0},mdTemplate:{default:void 0}},inclusive:!1,parseDOM:[{tag:`a[href]`,getAttrs(e){return{href:e.getAttribute(`href`),title:e.getAttribute(`title`)}}}],toDOM(e){let{href:t,title:n}=e.attrs;return[`a`,{href:t,title:n},0]}}}},MarkStrong=class extends Mark{name=`strong`;requires=[`doc`];getMarkSpec(){return{parseDOM:[{tag:`strong`},{tag:`b`,getAttrs:e=>e.style.fontWeight!=`normal`&&null},{style:`font-weight=400`,clearMark:e=>e.type.name==`strong`},{style:`font-weight`,getAttrs:e=>/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}],toDOM(){return[`strong`,0]}}}getCommandFactories(e,t){return{toggleStrong:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-b":`toggleStrong`,"Mod-B":`toggleStrong`}}},MarkItalic=class extends Mark{name=`em`;requires=[`doc`];getMarkSpec(){return{parseDOM:[{tag:`i`},{tag:`em`},{style:`font-assets=italic`},{style:`font-assets=normal`,clearMark:e=>e.type.name==`em`}],toDOM(){return[`em`,0]}}}getCommandFactories(e,t){return{toggleItalic:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-i":`toggleItalic`,"Mod-I":`toggleItalic`}}},MarkUnderline=class extends Mark{name=`underline`;requires=[`doc`];getMarkSpec(){return{parseDOM:[{tag:`u`}],toDOM(){return[`u`,0]}}}getCommandFactories(e,t){return{toggleUnderline:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-u":`toggleUnderline`,"Mod-U":`toggleUnderline`}}},MarkStrike=class extends Mark{name=`strike`;requires=[`doc`];getMarkSpec(){return{parseDOM:[{tag:`strike`}],toDOM(){return[`strike`,0]}}}getCommandFactories(e,t){return{toggleStrike:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-s":`toggleStrike`,"Mod-S":`toggleStrike`}}},MarkCode=class extends Mark{name=`code`;requires=[`doc`];getMarkSpec(){return{parseDOM:[{tag:`code`}],toDOM(){return[`code`,0]}}}getCommandFactories(e,t){return{toggleCode:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-`":`toggleCode`}}},MarkChange=class extends Mark{name=`change`;requires=[`doc`];getMarkSpec(){return{parseDOM:[],toDOM(){return[`change`,0]}}}},MarkBookmark=class extends Mark{name=`bookmark`;requires=[`doc`];getMarkSpec(){return{attrs:{id:{}},parseDOM:[],toDOM(e){return[`a`,{id:e.attrs.id},0]}}}},MarkTextColor=class extends Mark{name=`textColor`;getMarkSpec(){return{attrs:{color:{default:null}},parseDOM:[{tag:`span[style*="color"]`,getAttrs(e){let t=e.style.color;return t?{color:t}:!1}}],toDOM(e){let{color:t}=e.attrs;return t?[`span`,{style:`color: ${t}`},0]:[`span`,0]}}}},MarkHighlight=class extends Mark{name=`highlight`;getMarkSpec(){return{attrs:{color:{default:null}},parseDOM:[{tag:`mark`,getAttrs(e){let t=e.style.backgroundColor;return t?{color:t}:{color:`yellow`}}},{tag:`span[style*="background-color"]`,getAttrs(e){let t=e.style.backgroundColor;return t?{color:t}:!1}}],toDOM(e){let{color:t}=e.attrs;return[`mark`,{style:`background-color: ${t||`yellow`}; color: inherit;`},0]}}}},MarkSuperscript=class extends Mark{name=`superscript`;requires=[`doc`];getMarkSpec(){return{excludes:`subscript`,parseDOM:[{tag:`sup`},{style:`vertical-align`,getAttrs:e=>e===`super`&&null}],toDOM(){return[`sup`,0]}}}getCommandFactories(e,t){return{toggleSuperscript:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-Shift-.":`toggleSuperscript`}}},MarkSubscript=class extends Mark{name=`subscript`;requires=[`doc`];getMarkSpec(){return{excludes:`superscript`,parseDOM:[{tag:`sub`},{style:`vertical-align`,getAttrs:e=>e===`sub`&&null}],toDOM(){return[`sub`,0]}}}getCommandFactories(e,t){return{toggleSubscript:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-Shift-,":`toggleSubscript`}}},NodeDocument=class extends Node$2{name=`doc`;getNodeSpec(){return{content:`block+`,attrs:{meta:{default:null}},marks:`code em strong link bookmark`,EMPTY_DOC:{type:this.name,content:[{type:`paragraph`,content:[]}]}}}getCommandFactories(e,t){return{getMeta:e=>(t,n)=>(e(structuredClone(t.doc.attrs.meta)),!0),setMeta:e=>(t,n)=>{let r=t.tr;return r.setDocAttribute(`meta`,e),n&&n(r),r.docChanged},updateMeta:e=>(t,n)=>{let r=t.tr;return r.setDocAttribute(`meta`,e(t.doc.attrs.meta)),n&&n(r),r.docChanged}}}},NodeText=class extends Node$2{name=`text`;getNodeSpec(){return{group:`inline`}}};function wrappingInputRule(e,t,n=null,r){return new InputRule(e,(e,a,o,s,c)=>{e||=a.tr;let l=n instanceof Function?n(o):n;e=e.delete(s,c);let u=e.doc.resolve(s).blockRange(),d=u&&findWrapping(u,t,l);if(!d)return null;e.wrap(u,d);let f=e.doc.resolve(s-1).nodeBefore;return f&&f.type==t&&canJoin(e.doc,s-1)&&(!r||r(o,f))&&e.join(s-1),e})}function textblockTypeInputRule(e,t,n=null){return new InputRule(e,(e,r,a,o,s)=>{e||=r.tr;let c=r.doc.resolve(o),l=n instanceof Function?n(a):n;return c.node(-1).canReplaceWith(c.index(-1),c.indexAfter(-1),t)?e.delete(o,s).setBlockType(o,o,t,l):null})}function replaceInlineNode(e,t,n=null){return new InputRule(e,(e,r,a,o,s)=>{e||=r.tr;let c=n instanceof Function?n(a):n;if(r.doc.resolve(o).parent.type===r.schema.nodes.code_block)return e;let l=t.createAndFill(c),u=e.mapping.map(o),d=e.mapping.map(s);return e.replaceWith(u,d,Fragment.from(l))})}var NodeCodeBlock$1=class extends Node$2{name=`code_block`;getNodeSpec(){return{content:`text*`,marks:``,group:`block`,code:!0,defining:!0,attrs:{lang:{default:void 0}},parseDOM:[{tag:`pre`,preserveWhitespace:`full`,getAttrs(e){return{lang:e.getAttribute(`lang`)}}}],toDOM(e){let{lang:t}=e.attrs;return[`pre`,{lang:t},[`code`,0]]}}}getInputRules(e){return[textblockTypeInputRule(/^```$/,e)]}},NodeBookmark=class extends Node$2{name=`node_bookmark`;requires=[`doc`];getNodeSpec(){return{inline:!0,group:`inline`,selectable:!1,atom:!0,attrs:{id:{},nesting:{default:0}},parseDOM:[],toDOM(e){return[`a`,{id:e.attrs.id},0]}}}},NodeParagraph=class extends Node$2{name=`paragraph`;requires=[`doc`];getNodeSpec(){return{content:`inline*`,group:`block`,attrs:{textAlign:{default:void 0}},parseDOM:[{tag:`p`,getAttrs(e){let t=e.style.textAlign;return t===`center`||t===`right`||t===`justify`?{textAlign:t}:!1}}],toDOM(e){let t=e.attrs.textAlign||`left`;return[`center`,`right`,`justify`].includes(t)?[`p`,{style:`text-align: ${t}`},0]:[`p`,0]}}}getCommandFactories(e,t){return{setParagraph:()=>e.commandFactories.setBlockType(t)}}getKeyboardShortcuts(){return{"Shift-Ctrl-0":`setParagraph`}}},NodeHardBreak=class extends Node$2{name=`br`;requires=[`doc`];options={keepMarks:!0};getNodeSpec(){return{inline:!0,group:`inline`,selectable:!1,linebreakReplacement:!0,parseDOM:[{tag:`br`}],toDOM(){return[`br`]}}}getCommandFactories(e,t){let n=firstCommand(e.run.exitCode);return{setHardBreak:()=>n}}getKeyboardShortcuts(){let e=typeof navigator<`u`?/Mac|iP(hone|[oa]d)/.test(navigator?.platform):!1,t={"Ctrl-Enter":`setHardBreak`};return e&&(t[`Mod-Enter`]=`setHardBreak`,t[`Shift-Enter`]=`setHardBreak`),t}},NodeSoftBreak=class extends Node$2{name=`softbreak`;requires=[`doc`];getNodeSpec(){return{inline:!0,group:`inline`,selectable:!1,parseDOM:[{tag:`wbr`}],toDOM(){return[`wbr`]}}}},NodeHorizontalRule=class extends Node$2{name=`hr`;requires=[`doc`];getNodeSpec(){return{inline:!0,group:`inline`,parseDOM:[{tag:`hr`}],toDOM(){return[`hr`]}}}getCommandFactories(e,t){return{setHorizontalRule:()=>(e,n)=>(n&&n(e.tr.replaceSelectionWith(t.create()).scrollIntoView()),!0)}}getKeyboardShortcuts(){return{"Mod-_":`setHorizontalRule`}}},NodeImage=class extends Node$2{name=`image`;requires=[`doc`];getNodeSpec(){return{inline:!0,attrs:{src:{},alt:{default:null},title:{default:null},width:{default:null},height:{default:null},origUrl:{default:void 0},mdTemplate:{default:void 0}},group:`inline`,draggable:!0,parseDOM:[{tag:`img[src]`,getAttrs(e){return{src:e.getAttribute(`src`),title:e.getAttribute(`title`),alt:e.getAttribute(`alt`),width:e.getAttribute(`width`)||e.style.width||null,height:e.getAttribute(`height`)||e.style.height||null}}}],toDOM(e){let{src:t,alt:n,title:r,width:a,height:o}=e.attrs,s={src:t};return n&&(s.alt=n),r&&(s.title=r),a&&(s.width=a),o&&(s.height=o),[`img`,s]}}}getNodeView(e){return(e,t,n)=>{let r=document.createElement(`span`);r.className=`kb-image-wrapper`,r.contentEditable=`false`;let a=document.createElement(`img`);a.src=e.attrs.src,e.attrs.alt&&(a.alt=e.attrs.alt),e.attrs.title&&(a.title=e.attrs.title),e.attrs.width&&(a.style.width=typeof e.attrs.width==`number`?`${e.attrs.width}px`:e.attrs.width),e.attrs.height&&(a.style.height=typeof e.attrs.height==`number`?`${e.attrs.height}px`:e.attrs.height),a.draggable=!1,r.appendChild(a);let o=[`nw`,`ne`,`sw`,`se`],s=[];for(let e of o){let t=document.createElement(`span`);t.className=`kb-image-resize-handle kb-image-resize-handle-${e}`,t.dataset.position=e,s.push(t),r.appendChild(t)}let c=!1,l=0,u=0,d=0,f=0,p=1,m=null,h=e=>{let t=e.target;if(!t.classList.contains(`kb-image-resize-handle`))return;e.preventDefault(),e.stopPropagation(),c=!0,m=t.dataset.position||null,l=e.clientX,u=e.clientY;let n=a.getBoundingClientRect();d=n.width,f=n.height,p=d/f,r.classList.add(`kb-image-resizing`),document.addEventListener(`mousemove`,g),document.addEventListener(`mouseup`,_)},g=e=>{if(!c)return;let t=e.clientX-l,n=e.clientY-u,r=d,o=f;switch(m){case`se`:r=d+t,o=e.shiftKey?f+n:r/p;break;case`sw`:r=d-t,o=e.shiftKey?f+n:r/p;break;case`ne`:r=d+t,o=e.shiftKey?f-n:r/p;break;case`nw`:r=d-t,o=e.shiftKey?f-n:r/p;break}r=Math.max(50,r),o=Math.max(50,o),a.style.width=`${Math.round(r)}px`,a.style.height=`${Math.round(o)}px`},_=()=>{if(!c)return;c=!1,m=null,r.classList.remove(`kb-image-resizing`),document.removeEventListener(`mousemove`,g),document.removeEventListener(`mouseup`,_);let o=Math.round(a.getBoundingClientRect().width),s=Math.round(a.getBoundingClientRect().height),l=n();if(typeof l==`number`){let n=t.state.tr.setNodeMarkup(l,void 0,{...e.attrs,width:`${o}px`,height:`${s}px`});t.dispatch(n)}};return r.addEventListener(`mousedown`,h),r.addEventListener(`click`,e=>{e.preventDefault();let r=n();if(typeof r==`number`){let e=t.state.doc.resolve(r),n=Selection.near(e);t.dispatch(t.state.tr.setSelection(n))}}),{dom:r,update:e=>e.type.name===`image`?(a.src=e.attrs.src,e.attrs.alt&&(a.alt=e.attrs.alt),e.attrs.title&&(a.title=e.attrs.title),e.attrs.width?a.style.width=typeof e.attrs.width==`number`?`${e.attrs.width}px`:e.attrs.width:a.style.width=``,e.attrs.height?a.style.height=typeof e.attrs.height==`number`?`${e.attrs.height}px`:e.attrs.height:a.style.height=``,!0):!1,destroy:()=>{r.removeEventListener(`mousedown`,h),document.removeEventListener(`mousemove`,g),document.removeEventListener(`mouseup`,_)},stopEvent:e=>e.type===`mousedown`&&e.target.classList.contains(`kb-image-resize-handle`),ignoreMutation:()=>!0}}}},NodeVideo=class extends Node$2{name=`video`;requires=[`doc`];getNodeSpec(){return{attrs:{src:{},title:{default:null},controls:{default:!0},width:{default:null},height:{default:null}},group:`block`,draggable:!0,parseDOM:[{tag:`video[src]`,getAttrs(e){return{src:e.getAttribute(`src`),title:e.getAttribute(`title`),controls:e.hasAttribute(`controls`),width:e.getAttribute(`width`),height:e.getAttribute(`height`)}}}],toDOM(e){let{src:t,title:n,controls:r,width:a,height:o}=e.attrs,s={src:t};return n&&(s.title=n),r&&(s.controls=``),a&&(s.width=a),o&&(s.height=o),[`video`,s]}}}},NodeBlockquote=class extends Node$2{name=`blockquote`;requires=[`doc`];getNodeSpec(){return{content:`block+`,group:`block`,defining:!0,parseDOM:[{tag:`blockquote`}],toDOM(){return[`blockquote`,0]}}}getInputRules(e){return[wrappingInputRule(/^\s*>\s$/,e)]}getCommandFactories(e,t){return{toggleBlockquote:()=>e.commandFactories.wrapInList(t)}}getKeyboardShortcuts(){return{"Ctrl->":`toggleBlockquote`}}},NodeAside=class extends Node$2{name=`aside`;requires=[`doc`];getNodeSpec(){return{content:`block+`,group:`block`,defining:!0,parseDOM:[{tag:`aside`}],toDOM(){return[`aside`,0]}}}},maxLevel=6,NodeHeading=class extends Node$2{name=`heading`;requires=[`doc`];getNodeSpec(){return{attrs:{level:{default:1}},content:`inline*`,group:`block`,defining:!0,parseDOM:[{tag:`h1`,attrs:{level:1}},{tag:`h2`,attrs:{level:2}},{tag:`h3`,attrs:{level:3}},{tag:`h4`,attrs:{level:4}},{tag:`h5`,attrs:{level:5}},{tag:`h6`,attrs:{level:6}}],toDOM(e){return[`h`+e.attrs.level,0]}}}getInputRules(e){return[textblockTypeInputRule(RegExp(`^(#{1,6})\\s$`),e,e=>({level:e[1].length}))]}getCommandFactories(e,t){let n={};for(let r=1;r<=maxLevel;r++)n[`setHeading`+r]=()=>e.commandFactories.setBlockType(t,{level:r});return n}getKeyboardShortcuts(){let e={};for(let t=1;t<=maxLevel;t++)e[`Shift-Ctrl-`+t]=`setHeading`+t;return e}},NodeMath=class extends Node$2{name=`math`;requires=[`doc`];getNodeSpec(){return{inline:!0,attrs:{lang:{default:`mathml`},content:{}},group:`inline`,draggable:!0,parseDOM:[{tag:`math`,getAttrs:e=>({lang:`mathml`,content:new XMLSerializer().serializeToString(e)})}],toDOM(e){let t=new DOMParser().parseFromString(e.attrs.content,`application/xml`);return t.getElementsByTagName(`parsererror`).length>0?[`span`,{class:`mathml-error`},`Invalid MathML`]:document.importNode(t.documentElement,!0)}}}},NodeDefinitionList=class extends Node$2{name=`dl`;requires=[`doc`];getNodeSpec(){return{content:`dt+|dd+`,group:`block`,parseDOM:[{tag:`dl`}],toDOM(){return[`dl`,0]}}}getInputRules(e){return[]}getCommandFactories(e,t){return{toggleDefinitionList:()=>e.commandFactories.wrapInList(t)}}getKeyboardShortcuts(){return{}}},NodeDefinitionTerm=class extends Node$2{name=`dt`;requires=[`dl`];getNodeSpec(){return{content:`inline*`,group:`block`,parseDOM:[{tag:`dt`}],defining:!0,toDOM(){return[`dt`,0]}}}},NodeDefinitionDesc=class extends Node$2{name=`dd`;requires=[`dl`];getNodeSpec(){return{content:`inline*`,group:`block`,parseDOM:[{tag:`dd`}],defining:!0,toDOM(){return[`dd`,0]}}}};function fixCharacters$1(e){return e.replace(/’/g,`'`).replace(/“/g,`"`).replace(/”/g,`"`).replace(/\x0b/g,` `).replace(/\u201d/g,`"`).replace(/\u201c/g,`"`)}function replaceAllNodesOfType(e,t,n,r){let a=[];t.descendants((e,t)=>{e.type===n&&a.push({node:e,pos:t})});for(let t=a.length-1;t>=0;t--){let{node:n,pos:o}=a[t],s=r(n,e.doc.type.schema);e=e.replaceWith(o,o+n.nodeSize,s)}return e}var NodeInlineShortCode=class extends Node$2{name=`shortcode_inline`;requires=[`doc`];getNodeSpec(){return{inline:!0,group:`inline`,selectable:!0,atom:!0,attrs:{id:{default:void 0},content:{default:``},nesting:{default:0},error:{default:``}},parseDOM:[{tag:`span.kb-shortcode-inline`,getAttrs:e=>({content:e.textContent||null})}],toDOM(e){return[`span`,{class:`kb-shortcode-inline`},e.attrs.content||``]}}}getInputRules(e){return[replaceInlineNode(/\{\{[^}]+\}\}/,e,e=>({content:fixCharacters$1(e[0].substring(2,e[0].length-2))}))]}getCommandFactories(e,t){return{renderShortCode:e=>(n,r)=>{let a=n.tr;return a=replaceAllNodesOfType(a,n.doc,t,e),a.docChanged&&r&&r(a),!0}}}},NodeIframe=class extends Node$2{name=`iframe`;requires=[`doc`];getNodeSpec(){return{inline:!0,attrs:{src:{},class:{default:null},alt:{default:null},title:{default:null}},group:`inline`,draggable:!0,parseDOM:[{tag:`iframe[src]`,getAttrs(e){return{src:e.getAttribute(`src`),title:e.getAttribute(`title`),alt:e.getAttribute(`alt`)}}}],toDOM(e){let{src:t,alt:n,title:r}=e.attrs;return[`iframe`,{src:t,alt:n,title:r,class:e.attrs.class}]}}}};function collectCommentAnchors(e){let t=new Map,n=new Map;return e.descendants((e,r)=>{e.type.name===`comment`&&(e.attrs.nesting===1&&t.set(e.attrs.id,r),e.attrs.nesting===-1&&n.set(e.attrs.id,r))}),{starts:t,ends:n}}function buildCommentRanges(e){let{starts:t,ends:n}=collectCommentAnchors(e),r=[];for(let[e,a]of t){let t=n.get(e);!t||t<=a||r.push({id:e,from:a+1,to:t})}return r}function buildDecorations(e){let t=buildCommentRanges(e);return DecorationSet.create(e,t.map(({id:e,from:t,to:n})=>Decoration.inline(t,n,{class:`comment-highlight`,"data-comment-id":e})))}function commentsPlugin(){return new Plugin({state:{init(e,{doc:t}){return buildDecorations(t)},apply(e,t,n,r){return e.docChanged?buildDecorations(r.doc):t}},props:{decorations(e){return this.getState(e)}}})}var addCommentBoundary=e=>(t,n)=>{let{schema:r,selection:a}=t,{from:o,to:s}=a,c=r.nodes.comment;if(!c)return!1;let l=c.create({id:e,nesting:1}),u=c.create({id:e,nesting:-1}),d=t.tr;return d.insert(s,u),d.insert(o,l),n&&n(d),!0},NodeCommentAnchor=class extends Node$2{name=`comment`;requires=[`doc`];options={keepMarks:!0};getNodeSpec(){return{inline:!0,group:`inline`,selectable:!1,atom:!0,attrs:{id:{},active:{default:!1},nesting:{default:1}},parseDOM:[{tag:`span[data-comment-id]`,getAttrs(e){return{id:e.getAttribute(`data-comment-id`),nesting:parseInt(e.getAttribute(`data-nesting`)||`1`),active:e.hasAttribute(`data-active`)}}}],toDOM:e=>[`span`,{"data-comment-id":e.attrs.id,"data-active":e.attrs.active?`true`:void 0,"data-nesting":e.attrs.nesting}]}}getCommandFactories(e,t){return{addComment:(e,t)=>addCommentBoundary(e,t)}}getProseMirrorPlugins(){return[commentsPlugin()]}};function splitListItem(e,t){let n=function(n,r){let{$from:a,$to:o,node:s}=n.selection;if(s&&s.isBlock||a.depth<2||!a.sameParent(o))return!1;let c=a.node(-1);if(c.type!=e)return!1;if(a.parent.content.size==0&&a.node(-1).childCount==a.indexAfter(-1)){if(a.depth==3||a.node(-3).type!=e||a.index(-2)!=a.node(-2).childCount-1)return!1;if(r){let t=Fragment.empty,o=a.index(-1)?1:a.index(-2)?2:3;for(let e=a.depth-o;e>=a.depth-3;e--)t=Fragment.from(a.node(e).copy(t));let s=a.indexAfter(-1)<a.node(-2).childCount?1:a.indexAfter(-2)<a.node(-3).childCount?2:3;t=t.append(Fragment.from(e.createAndFill()));let c=a.before(a.depth-(o-1)),l=n.tr.replace(c,a.after(-s),new Slice(t,4-o,0)),u=-1;l.doc.nodesBetween(c,l.doc.content.size,(e,t)=>{if(u>-1)return!1;e.isTextblock&&e.content.size==0&&(u=t+1)}),u>-1&&l.setSelection(Selection.near(l.doc.resolve(u))),r(l.scrollIntoView())}return!0}let l=o.pos==a.end()?c.contentMatchAt(0).defaultType:null,u=n.tr.delete(a.pos,o.pos),d=l?[t?{type:e,attrs:t}:null,{type:l}]:void 0;return canSplit(u.doc,a.pos,2,d)?(r&&r(u.split(a.pos,2,d).scrollIntoView()),!0):!1};return n.displayName=`splitListItem(${e.name})`,n}function liftListItem(e){return function(t,n){let{$from:r,$to:a}=t.selection,o=r.blockRange(a,t=>t.childCount>0&&t.firstChild.type==e);return o?n?r.node(o.depth-1).type==e?liftToOuterList(t,n,e,o):liftOutOfList(t,n,o):!0:!1}}function liftToOuterList(e,t,n,r){let a=e.tr,o=r.end,s=r.$to.end(r.depth);o<s&&(a.step(new ReplaceAroundStep(o-1,s,o,s,new Slice(Fragment.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new NodeRange(a.doc.resolve(r.$from.pos),a.doc.resolve(s),r.depth));let c=liftTarget(r);if(c==null)return!1;a.lift(r,c);let l=a.doc.resolve(a.mapping.map(o,-1)-1);return canJoin(a.doc,l.pos)&&l.nodeBefore.type==l.nodeAfter.type&&a.join(l.pos),t(a.scrollIntoView()),!0}function liftOutOfList(e,t,n){let r=e.tr,a=n.parent;for(let e=n.end,t=n.endIndex-1,o=n.startIndex;t>o;t--)e-=a.child(t).nodeSize,r.delete(e-1,e+1);let o=r.doc.resolve(n.start),s=o.nodeAfter;if(r.mapping.map(n.end)!=n.start+o.nodeAfter.nodeSize)return!1;let c=n.startIndex==0,l=n.endIndex==a.childCount,u=o.node(-1),d=o.index(-1);if(!u.canReplace(d+ +!c,d+1,s.content.append(l?Fragment.empty:Fragment.from(a))))return!1;let f=o.pos,p=f+s.nodeSize;return r.step(new ReplaceAroundStep(f-+!!c,p+ +!!l,f+1,p-1,new Slice((c?Fragment.empty:Fragment.from(a.copy(Fragment.empty))).append(l?Fragment.empty:Fragment.from(a.copy(Fragment.empty))),+!c,+!l),+!c)),t(r.scrollIntoView()),!0}function sinkListItem(e){return function(t,n){let{$from:r,$to:a}=t.selection,o=r.blockRange(a,t=>t.childCount>0&&t.firstChild.type==e);if(!o)return!1;let s=o.startIndex;if(s==0)return!1;let c=o.parent,l=c.child(s-1);if(l.type!=e)return!1;if(n){let r=l.lastChild&&l.lastChild.type==c.type,a=Fragment.from(r?e.create():null),s=new Slice(Fragment.from(e.create(null,Fragment.from(c.type.create(null,a)))),r?3:1,0),u=o.start,d=o.end;n(t.tr.step(new ReplaceAroundStep(u-(r?3:1),d,u,d,s,1,!0)).scrollIntoView())}return!0}}var isList=e=>e.endsWith(`_list`),clearNodes=()=>(e,t)=>{let n=e.tr,{selection:r}=n,{ranges:a}=r;return t&&a.forEach(({$from:t,$to:r})=>{e.doc.nodesBetween(t.pos,r.pos,(e,t)=>{if(e.type.isText)return;let{doc:r,mapping:a}=n,o=r.resolve(a.map(t)),s=r.resolve(a.map(t+e.nodeSize)),c=o.blockRange(s);if(!c)return;let l=liftTarget(c);if(e.type.isTextblock){let{defaultType:e}=o.parent.contentMatchAt(o.index());n.setNodeMarkup(c.start,e)}(l||l===0)&&n.lift(c,l)})}),!0};function findParentNodeClosestToPos(e,t){for(let n=e.depth;n>0;--n){let r=e.node(n);if(t(r))return{pos:n>0?e.before(n):0,start:e.start(n),depth:n,node:r}}}function findParentNode(e){return t=>findParentNodeClosestToPos(t.$from,e)}var joinListBackwards=(e,t)=>{let n=findParentNode(e=>e.type===t)(e.selection);if(!n)return!0;let r=e.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;let a=e.doc.nodeAt(r);return n.node.type===a?.type&&canJoin(e.doc,n.pos)&&e.join(n.pos),!0},joinListForwards=(e,t)=>{let n=findParentNode(e=>e.type===t)(e.selection);if(!n)return!0;let r=e.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;let a=e.doc.nodeAt(r);return n.node.type===a?.type&&canJoin(e.doc,r)&&e.join(r),!0},toggleList=(e,t,n,r={})=>function(a,o,s){if(!this)throw Error(`Call this with Function.apply`);let c=this.editor,l=Object.keys(a.schema.marks).filter(e=>e!==`link`),u=a.schema.nodes[e],d=a.schema.nodes[t],{selection:f,storedMarks:p}=a,{$from:m,$to:h}=f,g=m.blockRange(h),_=p||(f.$to.parentOffset?f.$from.marks():[]);if(!g)return!1;let v=findParentNode(e=>isList(e.type.name))(f),y=a.tr;if(g.depth>=1&&v&&g.depth-v.depth<=1){if(v.node.type===u)return liftListItem(d).apply(this,[a,o,s]);if(isList(v.node.type.name)&&u.validContent(v.node.content)&&o)return c.chain(y).command(()=>(y.setNodeMarkup(v.pos,u),!0)).command(()=>joinListBackwards(y,u)).command(()=>joinListForwards(y,u)).command(()=>o(y)).run()}return!n||!_||!o?c.chain(y).command(()=>c.can().wrapInList(u,r).run()?!0:c.chain(y).lift().run()).wrapInList(u,r).command(()=>joinListBackwards(y,u)).command(()=>joinListForwards(y,u)).command(()=>(o&&o(y),!0)).run():c.chain(y).command(()=>{let e=c.can().wrapInList(u,r).run(),t=_.filter(e=>l.includes(e.type.name));return y.ensureMarks(t),e?!0:(v&&y.setSelection(NodeSelection.create(a.doc,v.pos)),clearNodes().apply(this,[a,o,s]))}).wrapInList(u,r).command(()=>joinListBackwards(y,u)).command(()=>joinListForwards(y,u)).command(()=>(o&&o(y),!0)).run()},NodeOrderedList=class extends Node$2{name=`ordered_list`;requires=[`doc`];attributes={type:{default:`1`,fromDom(e){return e.hasAttribute(`type`)?e.getAttribute(`type`):`1`}},start:{default:void 0,fromDom(e){return e.hasAttribute(`start`)?+e.getAttribute(`start`):void 0}},id:{default:void 0},continue:{default:void 0},odtMarginLeft:{default:void 0}};getNodeSpec(){return{content:`list_item+`,group:`block list`,parseDOM:[{tag:`ol`,getAttrs:e=>setHtmlAttributes(this,e)}],toDOM:e=>[`ol`,getHtmlAttributes(this,e),0]}}getInputRules(e){return[wrappingInputRule(/^(\d+)\.\s$/,e,e=>({order:+e[1]}),(e,t)=>t.childCount+t.attrs.order==+e[1])]}getCommandFactories(e,t){let n=!1;return{toggleOrderedList:()=>toggleList(`ordered_list`,`list_item`,!1)}}getKeyboardShortcuts(){return{"Shift-Ctrl-7":`toggleOrderedList`}}},NodeBulletList=class extends Node$2{name=`bullet_list`;requires=[`doc`];attributes={toc:{default:void 0},odtMarginLeft:{default:void 0}};getNodeSpec(){return{content:`list_item+`,group:`block list`,parseDOM:[{tag:`ul`}],toDOM(){return[`ul`,0]}}}getInputRules(e){return[wrappingInputRule(/^\s*([-+*])\s$/,e)]}getCommandFactories(e,t){let n=!1;return{toggleBulletList:()=>toggleList(`bullet_list`,`list_item`,!1)}}getKeyboardShortcuts(){return{"Shift-Ctrl-8":`toggleBulletList`}}},NodeListItem=class extends Node$2{name=`list_item`;requires=[`doc`];attributes={value:{default:void 0},type:{default:void 0,fromDom(e){return e.hasAttribute(`type`)?e.getAttribute(`type`):void 0},toDom(e){return e.attrs.type}}};getNodeSpec(){return{content:`paragraph block*`,defining:!0,parseDOM:[{tag:`li`,getAttrs:e=>setHtmlAttributes(this,e)}],toDOM:e=>[`li`,getHtmlAttributes(this,e),0]}}getCommandFactories(e,t){return{splitListItem:()=>splitListItem(t),liftListItem:()=>liftListItem(t),sinkListItem:()=>sinkListItem(t)}}getKeyboardShortcuts(){return{Enter:`splitListItem`,Tab:`sinkListItem`,"Shift-Tab":`liftListItem`}}},NodeTaskList=class extends Node$2{name=`task_list`;requires=[`doc`];getNodeSpec(){return{content:`task_item+`,group:`block list`,parseDOM:[{tag:`ul[data-type="${this.name}"]`}],toDOM:()=>[`ul`,{"data-type":this.name},0]}}getCommandFactories(){return{toggleTaskList:()=>toggleList(`task_list`,`task_item`)}}getKeyboardShortcuts(){return{"Shift-Ctrl-9":`toggleTaskList`}}},NodeViewTaskItem=class e{editor;dom;contentDOM;checkbox;node;view;getPos;config={};constructor(e,...t){this.editor=e,this.node=t[0],this.view=t[1],this.getPos=t[2];let n=document.createElement(`li`);this.dom=n;let r=document.createElement(`label`);r.contentEditable=`false`;let a=document.createElement(`input`);this.checkbox=a,a.type=`checkbox`,a.checked=this.node.attrs.checked,r.append(a);let o=document.createElement(`div`);this.contentDOM=o,n.append(r,o),n.dataset.checked=this.node.attrs.checked,a.addEventListener(`mousedown`,e=>e.preventDefault()),a.addEventListener(`change`,t=>{let n=this.getPos();if(typeof n!=`number`)return;this.editor.view.editable;let{checked:r}=t.target,a=e.state.tr,o=a.doc.nodeAt(n);a.setNodeMarkup(n,void 0,{...o?.attrs,checked:r}),e.dispatchTransaction(a)})}static create=(t,...n)=>new e(t,...n);update(e){return e.type.name===this.node.type.name?(this.dom.dataset.checked=e.attrs.checked,this.checkbox.checked=e.attrs.checked,!0):!1}},NodeTaskItem=class extends Node$2{config;name=`task_item`;requires=[`doc`];constructor(e={nested:!0}){super(e),this.config=e}getNodeSpec(){return{attrs:{checked:{default:!1}},content:this.config.nested?`paragraph block*`:`paragraph+`,defining:!0,parseDOM:[{tag:`li[data-checked]`,getAttrs(e){return{checked:e.getAttribute(`data-checked`)===`true`}}}],toDOM:e=>[`li`,{"data-type":this.name,"data-checked":e.attrs.checked},[`label`,[`input`,{type:`checkbox`,checked:e.attrs.checked?`checked`:null},[`span`]],[`div`,0]]]}}getCommandFactories(e,t){return{splitListItem:()=>splitListItem(t),liftListItem:()=>liftListItem(t),sinkListItem:()=>sinkListItem(t)}}getNodeView(e){return(...t)=>NodeViewTaskItem.create(e,...t)}getKeyboardShortcuts(){return{Enter:`splitListItem`,Tab:`sinkListItem`,"Shift-Tab":`liftListItem`}}getInputRules(e){return[wrappingInputRule(/^\s*(\[([( |x])?\])\s$/,e,e=>({checked:e[e.length-1]===`x`}))]}},BasicEditorKit=class{getExtensions(){return[new ExtensionBaseKeymap,new ExtensionDropcursor,new ExtensionGapcursor,new ExtensionHtml,new ExtensionMediaUpload,new ExtensionRemoteSelection,new ExtensionSelection,new ExtensionTextAlign,new ExtensionPairing,new ExtensionUser,new ExtensionPaste,new NodeDocument,new NodeText,new NodeParagraph,new NodeHardBreak,new NodeSoftBreak,new NodeCodeBlock$1,new NodeBookmark,new NodeHorizontalRule,new NodeOrderedList,new NodeBulletList,new NodeListItem,new NodeTaskList,new NodeTaskItem,new NodeDefinitionList,new NodeDefinitionTerm,new NodeDefinitionDesc,new NodeTaskList,new NodeTaskItem,new NodeImage,new NodeVideo,new NodeBlockquote,new NodeAside,new NodeHeading,new NodeMath,new NodeInlineShortCode,new NodeIframe,new NodeCommentAnchor,new MarkLink,new MarkItalic,new MarkStrong,new MarkUnderline,new MarkStrike,new MarkCode,new MarkChange,new MarkBookmark,new MarkTextColor,new MarkHighlight,new MarkSuperscript,new MarkSubscript]}},kit=new BasicEditorKit,ExtensionBasicEditor=class extends Extension{name=`basic-editor`;requires=kit.getExtensions()},GOOD_LEAF_SIZE=200,RopeSequence=class e{append(t){return t.length?(t=e.from(t),!this.length&&t||t.length<GOOD_LEAF_SIZE&&this.leafAppend(t)||this.length<GOOD_LEAF_SIZE&&t.leafPrepend(this)||this.appendInner(t)):this}prepend(t){return t.length?e.from(t).append(this):this}appendInner(e){return new Append(this,e)}slice(e=0,t=this.length){return e>=t?emptyRopeSequence():this.sliceInner(Math.max(0,e),Math.min(this.length,t))}get(e){if(!(e<0||e>=this.length))return this.getInner(e)}forEach(e,t=0,n=this.length){t<=n?this.forEachInner(e,t,n,0):this.forEachInvertedInner(e,t,n,0)}map(e,t=0,n=this.length){let r=[];return this.forEach((t,n)=>(r.push(e(t,n)),t),t,n),r}static from(t){return t instanceof e?t:t&&t.length?new Leaf(t):emptyRopeSequence()}},Leaf=class e extends RopeSequence{values;constructor(e){super(),this.values=e}flatten(){return this.values}sliceInner(t,n){return t==0&&n==this.length?this:new e(this.values.slice(t,n))}getInner(e){return this.values[e]}forEachInner(e,t,n,r){for(let a=t;a<n;a++)if(e(this.values[a],r+a)===!1)return!1;return!0}forEachInvertedInner(e,t,n,r){for(let a=t-1;a>=n;a--)if(e(this.values[a],r+a)===!1)return!1;return!0}leafAppend(t){if(this.length+t.length<=GOOD_LEAF_SIZE)return new e(this.values.concat(t.flatten()))}leafPrepend(t){if(this.length+t.length<=GOOD_LEAF_SIZE)return new e(t.flatten().concat(this.values))}get length(){return this.values.length}get depth(){return 0}};function emptyRopeSequence(){return new Leaf([])}var Append=class e extends RopeSequence{left;right;depth;length;constructor(e,t){super(),this.left=e,this.right=t,this.length=e.length+t.length,this.depth=Math.max(e.depth,t.depth)+1}flatten(){return this.left.flatten().concat(this.right.flatten())}getInner(e){return e<this.left.length?this.left.get(e):this.right.get(e-this.left.length)}forEachInner(e,t,n,r){let a=this.left.length;return!(t<a&&this.left.forEachInner(e,t,Math.min(n,a),r)===!1||n>a&&this.right.forEachInner(e,Math.max(t-a,0),Math.min(this.length,n)-a,r+a)===!1)}forEachInvertedInner(e,t,n,r){let a=this.left.length;return!(t>a&&this.right.forEachInvertedInner(e,t-a,Math.max(n,a)-a,r+a)===!1||n<a&&this.left.forEachInvertedInner(e,Math.min(t,a),n,r)===!1)}sliceInner(e,t){if(e==0&&t==this.length)return this;let n=this.left.length;return t<=n?this.left.slice(e,t):e>=n?this.right.slice(e-n,t-n):this.left.slice(e,n).append(this.right.slice(0,t-n))}leafAppend(t){let n=this.right.leafAppend(t);if(n)return new e(this.left,n)}leafPrepend(t){let n=this.left.leafPrepend(t);if(n)return new e(n,this.right)}appendInner(t){return this.left.depth>=Math.max(this.right.depth,t.depth)+1?new e(this.left,new e(this.right,t)):new e(this,t)}},max_empty_items=500,Branch=class e{items;eventCount;constructor(e,t){this.items=e,this.eventCount=t}popEvent(t,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let a,o;n&&(a=this.remapping(r,this.items.length),o=a.maps.length);let s=t.tr,c,l,u=[],d=[];return this.items.forEach((t,n)=>{if(!t.step)return a||(a=this.remapping(r,n+1),o=a.maps.length),o--,d.push(t),t;if(a){d.push(new Item(t.map));let e=t.step.map(a.slice(o)),n;e&&s.maybeStep(e).doc&&(n=s.mapping.maps[s.mapping.maps.length-1],u.push(new Item(n,void 0,void 0,u.length+d.length))),o--,n&&a.appendMap(n,o)}else s.maybeStep(t.step);return t.selection?(c=a?t.selection.map(a.slice(o)):t.selection,l=new e(this.items.slice(0,r).append(d.reverse().concat(u)),this.eventCount-1),!1):t},this.items.length,0),{remaining:l,transform:s,selection:c}}addTransform(t,n,r,a){let o=[],s=this.eventCount,c=this.items,l=!a&&c.length?c.get(c.length-1):null;for(let e=0;e<t.steps.length;e++){let r=t.steps[e].invert(t.docs[e]),u=new Item(t.mapping.maps[e],r,n),d;(d=l&&l.merge(u))&&(u=d,e?o.pop():c=c.slice(0,c.length-1)),o.push(u),n&&=(s++,void 0),a||(l=u)}let u=s-r.depth;return u>DEPTH_OVERFLOW&&(c=cutOffEvents(c,u),s-=u),new e(c.append(o),s)}remapping(e,t){let n=new Mapping;return this.items.forEach((t,r)=>{let a=t.mirrorOffset!=null&&r-t.mirrorOffset>=e?n.maps.length-t.mirrorOffset:void 0;return n.appendMap(t.map,a),t},e,t),n}addMaps(t){return this.eventCount==0?this:new e(this.items.append(t.map(e=>new Item(e))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],a=Math.max(0,this.items.length-n),o=t.mapping,s=t.steps.length,c=this.eventCount;this.items.forEach(e=>(e.selection&&c--,e),a);let l=n;this.items.forEach(e=>{let n=o.getMirror(--l);if(n==null)return!1;s=Math.min(s,n);let a=o.maps[n];if(e.step){let s=t.steps[n].invert(t.docs[n]),u=e.selection&&e.selection.map(o.slice(l+1,n));u&&c++,r.push(new Item(a,s,u))}else r.push(new Item(a));return e},a);let u=[];for(let e=n;e<s;e++)u.push(new Item(o.maps[e]));let d=new e(this.items.slice(0,a).append(u).append(r),c);return d.emptyItemCount()>max_empty_items&&(d=d.compress(this.items.length-r.length)),d}emptyItemCount(){let e=0;return this.items.forEach(t=>(t.step||e++,t)),e}compress(t=this.items.length){let n=this.remapping(0,t),r=n.maps.length,a=[],o=0;return this.items.forEach((e,s)=>{if(s>=t)a.push(e),e.selection&&o++;else if(e.step){let t=e.step.map(n.slice(r)),s=t&&t.getMap();if(r--,s&&n.appendMap(s,r),t){let c=e.selection&&e.selection.map(n.slice(r));c&&o++;let l=new Item(s.invert(),t,c),u,d=a.length-1;(u=a.length&&a[d].merge(l))?a[d]=u:a.push(l)}}else e.map&&r--;return e},this.items.length,0),new e(RopeSequence.from(a.reverse()),o)}static empty=new e(emptyRopeSequence(),0)};function cutOffEvents(e,t){let n;return e.forEach((e,r)=>e.selection&&t--==0?(n=r,!1):e),e.slice(n)}var Item=class e{map;step;selection;mirrorOffset;constructor(e,t,n,r){this.map=e,this.step=t,this.selection=n,this.mirrorOffset=r}merge(t){if(this.step&&t.step&&!t.selection){let n=t.step.merge(this.step);if(n)return new e(n.getMap().invert(),n,this.selection)}}},HistoryState=class{done;undone;prevRanges;prevTime;prevComposition;constructor(e,t,n,r,a){this.done=e,this.undone=t,this.prevRanges=n,this.prevTime=r,this.prevComposition=a}},DEPTH_OVERFLOW=20;function applyTransaction(e,t,n,r){let a=n.getMeta(historyKey),o;if(a)return a.historyState;n.getMeta(closeHistoryKey)&&(e=new HistoryState(e.done,e.undone,null,0,-1));let s=n.getMeta(`appendedTransaction`);if(n.steps.length==0)return e;if(s&&s.getMeta(historyKey))return s.getMeta(historyKey).redo?new HistoryState(e.done.addTransform(n,void 0,r,mustPreserveItems(t)),e.undone,rangesFor(n.mapping.maps),e.prevTime,e.prevComposition):new HistoryState(e.done,e.undone.addTransform(n,void 0,r,mustPreserveItems(t)),null,e.prevTime,e.prevComposition);if(n.getMeta(`addToHistory`)!==!1&&!(s&&s.getMeta(`addToHistory`)===!1)){let a=n.getMeta(`composition`),o=e.prevTime==0||!s&&e.prevComposition!=a&&(e.prevTime<(n.time||0)-r.newGroupDelay||!isAdjacentTo(n,e.prevRanges)),c=s?mapRanges(e.prevRanges,n.mapping):rangesFor(n.mapping.maps);return new HistoryState(e.done.addTransform(n,o?t.selection.getBookmark():void 0,r,mustPreserveItems(t)),Branch.empty,c,n.time,a??e.prevComposition)}else if(o=n.getMeta(`rebased`))return new HistoryState(e.done.rebased(n,o),e.undone.rebased(n,o),mapRanges(e.prevRanges,n.mapping),e.prevTime,e.prevComposition);else return new HistoryState(e.done.addMaps(n.mapping.maps),e.undone.addMaps(n.mapping.maps),mapRanges(e.prevRanges,n.mapping),e.prevTime,e.prevComposition)}function isAdjacentTo(e,t){if(!t)return!1;if(!e.docChanged)return!0;let n=!1;return e.mapping.maps[0].forEach((e,r)=>{for(let a=0;a<t.length;a+=2)e<=t[a+1]&&r>=t[a]&&(n=!0)}),n}function rangesFor(e){let t=[];for(let n=e.length-1;n>=0&&t.length==0;n--)e[n].forEach((e,n,r,a)=>t.push(r,a));return t}function mapRanges(e,t){if(!e)return null;let n=[];for(let r=0;r<e.length;r+=2){let a=t.map(e[r],1),o=t.map(e[r+1],-1);a<=o&&n.push(a,o)}return n}function histTransaction(e,t,n){let r=mustPreserveItems(t),a=historyKey.get(t).spec.config,o=(n?e.undone:e.done).popEvent(t,r);if(!o)return null;let s=o.selection.resolve(o.transform.doc),c=(n?e.done:e.undone).addTransform(o.transform,t.selection.getBookmark(),a,r),l=new HistoryState(n?c:o.remaining,n?o.remaining:c,null,0,-1);return o.transform.setSelection(s).setMeta(historyKey,{redo:n,historyState:l})}var cachedPreserveItems=!1,cachedPreserveItemsPlugins=null;function mustPreserveItems(e){let t=e.plugins;if(cachedPreserveItemsPlugins!=t){cachedPreserveItems=!1,cachedPreserveItemsPlugins=t;for(let e=0;e<t.length;e++)if(t[e].spec.historyPreserveItems){cachedPreserveItems=!0;break}}return cachedPreserveItems}var historyKey=new PluginKey(`history`),closeHistoryKey=new PluginKey(`closeHistory`);function history$1(e={}){return e={depth:e.depth||100,newGroupDelay:e.newGroupDelay||500},new Plugin({key:historyKey,state:{init(){return new HistoryState(Branch.empty,Branch.empty,null,0,-1)},apply(t,n,r){return applyTransaction(n,r,t,e)}},config:e,props:{handleDOMEvents:{beforeinput(e,t){let n=t.inputType,r=n==`historyUndo`?undo:n==`historyRedo`?redo:null;return!r||!e.editable?!1:(t.preventDefault(),r(e.state,e.dispatch))}}}})}function buildCommand(e,t){return(n,r)=>{let a=historyKey.getState(n);if(!a||(e?a.undone:a.done).eventCount==0)return!1;if(r){let o=histTransaction(a,n,e);o&&r(t?o.scrollIntoView():o)}return!0}}var undo=buildCommand(!1,!0),redo=buildCommand(!0,!0),undoNoScroll=buildCommand(!1,!1),redoNoScroll=buildCommand(!0,!1),ExtensionHistory$1=class extends Extension{name=`history`;options={depth:100,newGroupDelay:500};getCommandFactories(e){return{undo:()=>undo,redo:()=>redo}}getKeyboardShortcuts(){let e=typeof navigator<`u`?/Mac|iP(hone|[oa]d)/.test(navigator?.platform):!1,t={"Mod-z":`undo`,"Mod-y":`redo`};return e||(t[`Mod-y`]=`redo`),t}getProseMirrorPlugins(){return[history$1(this.options)]}},Token=class{type;tag;nesting;attrs=null;map=null;level=0;children=null;content=``;markup=``;info=``;meta=null;block=!1;hidden=!1;constructor(e,t,n){this.type=e,this.tag=t,this.nesting=n}attrIndex(e){if(!this.attrs)return-1;let t=this.attrs;for(let n=0,r=t.length;n<r;n++)if(t[n][0]===e)return n;return-1}attrPush(e){this.attrs?this.attrs.push(e):this.attrs=[e]}attrSet(e,t){let n=this.attrIndex(e),r=[e,t];n<0||!this.attrs?this.attrPush(r):this.attrs[n]=r}attrGet(e){let t=this.attrIndex(e),n=null;return t>=0&&this.attrs&&(n=this.attrs[t][1]),n}attrJoin(e,t){let n=this.attrIndex(e);n<0||!this.attrs?this.attrPush([e,t]):this.attrs[n][1]=this.attrs[n][1]+` `+t}},Brackets={left:[`(`,`[`,`{`,`|`,`‖`,`⟨`,`⌊`,`⌈`,`⌜`],right:[`)`,`]`,`}`,`|`,`‖`,`⟩`,`⌋`,`⌉`,`⌝`],isPair:function(e,t){let n=this.left.indexOf(e);return t===this.right[n]},contains:function(e){return this.isLeft(e)||this.isRight(e)},isLeft:function(e){return this.left.indexOf(e)>-1},isRight:function(e){return this.right.indexOf(e)>-1},parseLeft:function(e,t=!0){if(this.left.indexOf(e)<0)return e;let n=``;switch(e){case`(`:case`[`:case`|`:n=`\\left${e}`;break;case`‖`:n=`\\left\\|`;break;case`{`:n=`\\left\\{`;break;case`⟨`:n=`\\left\\langle `;break;case`⌊`:n=`\\left\\lfloor `;break;case`⌈`:n=`\\left\\lceil `;break;case`⌜`:n=`\\left\\ulcorner `;break}return t?n:n.replace(`\\left`,``)},parseRight:function(e,t=!0){if(this.right.indexOf(e)<0)return e;let n=``;switch(e){case`)`:case`]`:case`|`:n=`\\right${e}`;break;case`‖`:n=`\\right\\|`;break;case`}`:n=`\\right\\}`;break;case`⟩`:n=` \\right\\rangle`;break;case`⌋`:n=` \\right\\rfloor`;break;case`⌉`:n=` \\right\\rceil`;break;case`⌝`:n=` \\right\\urcorner`;break}return t?n:n.replace(`\\right`,``)}},MathSymbol={parseIdentifier:function(e){if(e.length===0)return``;if(e.length===1){let t=e.charCodeAt(0),n=this.greekLetter.decimals.indexOf(t);return n>-1?this.greekLetter.scripts[n]+` `:e}else return this.parseMathFunction(e)},parseOperator:function(e){if(e.length===0)return``;if(e.length===1){let t=e.charCodeAt(0),n=[this.bigCommand,this.relation,this.binaryOperation,this.setAndLogic,this.delimiter,this.other],r=[!1,!0,!0,!1,!1,!1];for(let e=0;e<n.length;e++){let a=n[e],o=a.decimals.indexOf(t);if(o>-1)return r[e]?[` `,a.scripts[o],` `].join(``):a.scripts[o]+` `}return e}else return this.parseMathFunction(e)},parseMathFunction:function(e){let t=T.createMarker(),n=[];return this.mathFunction.names.forEach((r,a)=>{let o=new RegExp(r,`g`);e.match(o)&&(n.push(this.mathFunction.scripts[a]),e=e.replace(o,t.next()+` `))}),t.replaceBack(e,n)},overScript:{decimals:[9182],templates:[`\\overbrace{@v}`]},underScript:{decimals:[9183],templates:[`\\underbrace{@v}`]},bigCommand:{decimals:[8721,8719,8720,10753,10754,10752,8899,8898,10756,10758,8897,8896,8747,8750,8748,8749,10764,8747],scripts:[`\\sum`,`\\prod`,`\\coprod`,`\\bigoplus`,`\\bigotimes`,`\\bigodot`,`\\bigcup`,`\\bigcap`,`\\biguplus`,`\\bigsqcup`,`\\bigvee`,`\\bigwedge`,`\\int`,`\\oint`,`\\iint`,`\\iiint`,`\\iiiint`,`\\idotsint`]},relation:{decimals:[60,62,61,8741,8742,8804,8805,8784,8781,8904,8810,8811,8801,8866,8867,8834,8835,8776,8712,8715,8838,8839,8773,8995,8994,8840,8841,8771,8872,8713,8847,8848,126,8764,8869,8739,8849,8850,8733,8826,8827,10927,10928,8800,8738,8737],scripts:`<.>.=.\\parallel.\\nparallel.\\leq.\\geq.\\doteq.\\asymp.\\bowtie.\\ll.\\gg.\\equiv.\\vdash.\\dashv.\\subset.\\supset.\\approx.\\in.\\ni.\\subseteq.\\supseteq.\\cong.\\smile.\\frown.\\nsubseteq.\\nsupseteq.\\simeq.\\models.\\notin.\\sqsubset.\\sqsupset.\\sim.\\sim.\\perp.\\mid.\\sqsubseteq.\\sqsupseteq.\\propto.\\prec.\\succ.\\preceq.\\succeq.\\neq.\\sphericalangle.\\measuredangle`.split(`.`)},binaryOperation:{decimals:[43,45,177,8745,8900,8853,8723,8746,9651,8854,215,8846,9661,8855,247,8851,9667,8856,8727,8852,9657,8857,8902,8744,9711,8728,8224,8743,8729,8726,8225,8901,8768,10815],scripts:`+.-.\\pm.\\cap.\\diamond.\\oplus.\\mp.\\cup.\\bigtriangleup.\\ominus.\\times.\\uplus.\\bigtriangledown.\\otimes.\\div.\\sqcap.\\triangleleft.\\oslash.\\ast.\\sqcup.\\triangleright.\\odot.\\star.\\vee.\\bigcirc.\\circ.\\dagger.\\wedge.\\bullet.\\setminus.\\ddagger.\\cdot.\\wr.\\amalg`.split(`.`)},setAndLogic:{decimals:[8707,8594,8594,8708,8592,8592,8704,8614,172,10233,8834,8658,10233,8835,8596,8712,10234,8713,8660,8715,8868,8743,8869,8744,8709,8709],scripts:`\\exists.\\rightarrow.\\to.\\nexists.\\leftarrow.\\gets.\\forall.\\mapsto.\\neg.\\implies.\\subset.\\Rightarrow.\\implies.\\supset.\\leftrightarrow.\\in.\\iff.\\notin.\\Leftrightarrow.\\ni.\\top.\\land.\\bot.\\lor.\\emptyset.\\varnothing`.split(`.`)},delimiter:{decimals:[124,8739,8214,47,8726,123,125,10216,10217,8593,8657,8968,8969,8595,8659,8970,8971],scripts:[`|`,`\\mid`,`\\|`,`/`,`\\backslash`,`\\{`,`\\}`,`\\langle`,`\\rangle`,`\\uparrow`,`\\Uparrow`,`\\lceil`,`\\rceil`,`\\downarrow`,`\\Downarrow`,`\\lfloor`,`\\rfloor`]},greekLetter:{decimals:[913,945,925,957,914,946,926,958,915,947,927,959,916,948,928,960,982,917,1013,949,929,961,1009,918,950,931,963,962,919,951,932,964,920,952,977,933,965,921,953,934,981,966,922,954,1008,935,967,923,955,936,968,924,956,937,969],scripts:`A.\\alpha.N.\\nu.B.\\beta.\\Xi.\\xi.\\Gamma.\\gamma.O.o.\\Delta.\\delta.\\Pi.\\pi.\\varpi.E.\\epsilon.\\varepsilon.P.\\rho.\\varrho.Z.\\zeta.\\Sigma.\\sigma.\\varsigma.H.\\eta.T.\\tau.\\Theta.\\theta.\\vartheta.\\Upsilon.\\upsilon.I.\\iota.\\Phi.\\phi.\\varphi.K.\\kappa.\\varkappa.X.\\chi.\\Lambda.\\lambda.\\Psi.\\psi.M.\\mu.\\Omega.\\omega`.split(`.`)},other:{decimals:[8706,305,8476,8711,8501,240,567,8465,9723,8502,8463,8467,8472,8734,8503],scripts:[`\\partial`,`\\imath`,`\\Re`,`\\nabla`,`\\aleph`,`\\eth`,`\\jmath`,`\\Im`,`\\Box`,`\\beth`,`\\hbar`,`\\ell`,`\\wp`,`\\infty`,`\\gimel`]},mathFunction:{names:`arcsin.sinh.sin.sec.arccos.cosh.cos.csc.arctan.tanh.tan.arccot.coth.cot.limsup.liminf.exp.ker.deg.gcd.lg.ln.Pr.sup.det.hom.lim.log.arg.dim.inf.max.min`.split(`.`),scripts:`\\arcsin.\\sinh.\\sin.\\sec.\\arccos.\\cosh.\\cos.\\csc.\\arctan.\\tanh.\\tan.\\arccot.\\coth.\\cot.\\limsup.\\liminf.\\exp.\\ker.\\deg.\\gcd.\\lg.\\ln.\\Pr.\\sup.\\det.\\hom.\\lim.\\log.\\arg.\\dim.\\inf.\\max.\\min`.split(`.`)}},T={};T.createMarker=function(){return{idx:-1,reReplace:/@\[\[(\d+)\]\]/gm,next:function(){return`@[[${++this.idx}]]`},replaceBack:function(e,t){return e.replace(this.reReplace,(e,n)=>t[parseInt(n)])}}};var root=typeof window<`u`?window:{};function canParseHTMLNatively(){let e=root.DOMParser,t=!1;try{new e().parseFromString(``,`text/html`)&&(t=!0)}catch{}return t}function createHTMLParser(){let e=function(){};return shouldUseActiveX()?e.prototype.parseFromString=function(e){let t=new window.ActiveXObject(`htmlfile`);return t.designMode=`on`,t.open(),t.write(e),t.close(),t}:e.prototype.parseFromString=function(e){let t=document.implementation.createHTMLDocument(``);return t.open(),t.write(e),t.close(),t},e}function shouldUseActiveX(){let e=!1;try{document.implementation.createHTMLDocument(``).open()}catch{window.ActiveXObject&&(e=!0)}return e}var HTMLParser=canParseHTMLNatively()?root.DOMParser:createHTMLParser(),NodeTool={parseMath:function(e){return new HTMLParser().parseFromString(e,`text/html`).querySelector(`math`)},getChildren:function(e){return e.children},getNodeName:function(e){return e.tagName.toLowerCase()},getNodeText:function(e){return e.textContent},getAttr:function(e,t,n){let r=e.getAttribute(t);return r===null?n:r},getPrevNode:function(e){return e.previousElementSibling},getNextNode:function(e){return e.nextElementSibling}};function convert(e){return toLatex(parse(NodeTool.parseMath(e)))}function toLatex(e){return e=e.replace(/\\left\(\\DELETE_BRACKET_L/g,``),e=e.replace(/\\DELETE_BRACKET_R\\right\)/g,``),e=e.replace(/\\DELETE_BRACKET_L/g,``),e=e.replace(/\\DELETE_BRACKET_R/g,``),e}function parse(e){let t=NodeTool.getChildren(e);return!t||t.length===0?parseLeaf(e):parseContainer(e,t)}function parseLeaf(e){let t=``;switch(NodeTool.getNodeName(e)){case`mi`:t=parseElementMi(e);break;case`mn`:t=parseElementMn(e);break;case`mo`:t=parseOperator(e);break;case`ms`:t=parseElementMs(e);break;case`mtext`:t=parseElementMtext(e);break;case`mglyph`:t=parseElementMglyph(e);break;case`mprescripts`:t=``;break;case`mspace`:t=parseElementMspace();case`none`:t=`\\:`;break;default:t=escapeSpecialChars(NodeTool.getNodeText(e).trim());break}return t}function parseOperator(e){let t=NodeTool.getNodeText(e).trim();return t=MathSymbol.parseOperator(t),escapeSpecialChars(t)}function parseElementMi(e){let t=NodeTool.getNodeText(e).trim();return t=MathSymbol.parseIdentifier(t),escapeSpecialChars(t)}function parseElementMn(e){return escapeSpecialChars(NodeTool.getNodeText(e).trim())}function parseElementMs(e){return[`"`,escapeSpecialChars(NodeTool.getNodeText(e).trimRight()),`"`].join(``)}function parseElementMtext(e){return`\\text{${escapeSpecialChars(NodeTool.getNodeText(e))}}`}function parseElementMglyph(e){return escapeSpecialChars([`"`,NodeTool.getAttr(e,`alt`,``),`"`].join(``))}function parseElementMspace(e){return``}function escapeSpecialChars(e){return e=e.replace(/\$|%|_|&|#|\{|\}/g,e=>`\\${e}`),e}function parseContainer(e,t){let n=getRender(e);if(n)return n(e,t);throw Error(`Couldn't get render function for container node: ${NodeTool.getNodeName(e)}`)}function renderChildren(e){let t=[],n=[];if(Array.prototype.forEach.call(e,e=>{if(NodeTool.getNodeName(e)===`mo`){let r=NodeTool.getNodeText(e).trim();if(Brackets.contains(r)){let a=NodeTool.getAttr(e,`stretchy`,`true`);if(a=[``,`true`].indexOf(a)>-1,Brackets.isRight(r)){let e=n[n.length-1];e&&Brackets.isPair(e,r)?(t.push(Brackets.parseRight(r,a)),n.pop()):Brackets.isLeft(r)?(t.push(Brackets.parseLeft(r,a)),n.push(r)):console.error(`bracket not match`)}else t.push(Brackets.parseLeft(r,a)),n.push(r)}else t.push(parseOperator(e))}else t.push(parse(e))}),n.length>0)for(let e=0;e<n.length;e++)t.push(`\\right.`);return n=void 0,t}function getRender(e){let t;switch(NodeTool.getNodeName(e)){case`msub`:t=getRender_default(`@1_{@2}`);break;case`msup`:t=getRender_default(`@1^{@2}`);break;case`msubsup`:t=getRender_default(`@1_{@2}^{@3}`);break;case`mover`:t=renderMover;break;case`munder`:t=renderMunder;break;case`munderover`:t=getRender_default(`@1\\limits_{@2}^{@3}`);break;case`mmultiscripts`:t=renderMmultiscripts;break;case`mroot`:t=getRender_default(`\\sqrt[@2]{@1}`);break;case`msqrt`:t=getRender_joinSeparator(`\\sqrt{@content}`);break;case`mtable`:t=renderTable;break;case`mtr`:t=getRender_joinSeparator(`@content \\\\ `,` & `);break;case`mtd`:t=getRender_joinSeparator(`@content`);break;case`mfrac`:t=renderMfrac;break;case`mfenced`:t=renderMfenced;break;case`mi`:case`mn`:case`mo`:case`ms`:case`mtext`:t=getRender_joinSeparator(`@content`);break;case`mphantom`:t=renderMphantom;break;default:t=getRender_joinSeparator(`@content`);break}return t}function renderTable(e,t){return getRender_joinSeparator(`\\begin{matrix} @content \\end{matrix}`)(e,t)}function renderMfrac(e,t){let[n,r]=[NodeTool.getAttr(e,`linethickness`,`medium`),NodeTool.getAttr(e,`bevelled`,`false`)],a=null;if(r===`true`)a=getRender_default(`{}^{@1}/_{@2}`);else if([`0`,`0px`].indexOf(n)>-1){let[t,n]=[NodeTool.getPrevNode(e),NodeTool.getNextNode(e)];a=t&&NodeTool.getNodeText(t).trim()===`(`&&n&&NodeTool.getNodeText(n).trim()===`)`?getRender_default(`\\DELETE_BRACKET_L\\binom{@1}{@2}\\DELETE_BRACKET_R`):getRender_default(`{}_{@2}^{@1}`)}else a=getRender_default(`\\frac{@1}{@2}`);return a(e,t)}function renderMfenced(e,t){let[n,r,a]=[NodeTool.getAttr(e,`open`,`(`),NodeTool.getAttr(e,`close`,`)`),NodeTool.getAttr(e,`separators`,`,`)],[o,s]=[Brackets.parseLeft(n),Brackets.parseRight(r)],c=a.split(``).filter(e=>e.trim().length===1);return getRender_joinSeparators(`${o}@content${s}`,c)(e,t)}function renderMmultiscripts(e,t){if(t.length===0)return``;let n=-1,r=null;Array.prototype.forEach.call(t,e=>{NodeTool.getNodeName(e)===`mprescripts`&&(r=e)}),r&&(n=Array.prototype.indexOf.call(t,r));let a=renderChildren(t),o=(e,t)=>[e.slice(0,t),e.slice(t+1,e.length)],s=e=>{if(e.length>0){let t=[],n=[];return e.forEach((e,r)=>{(r+1)%2==0?n.push(e):t.push(e)}),[t.length>0?`_{${t.join(` `)}}`:``,n.length>0?`^{${n.join(` `)}}`:``].join(``)}else return``},c=a.shift(),l=[],u=[];return n===-1?u=a:[u,l]=o(a,n-1),[s(l),c,s(u)].join(``)}function renderMover(e,t){let n=flattenNodeTreeByNodeName(e,`mover`),r;for(let e=0;e<n.length-1;e++){r||=parse(n[e]);let t=parse(n[e+1]);r=renderTemplate(getMatchValueByChar({decimals:MathSymbol.overScript.decimals,values:MathSymbol.overScript.templates,judgeChar:t,defaultValue:`@1\\limits^{@2}`}).replace(`@v`,`@1`),[r,t])}return r}function renderMunder(e,t){let n=flattenNodeTreeByNodeName(e,`munder`),r;for(let e=0;e<n.length-1;e++){r||=parse(n[e]);let t=parse(n[e+1]);r=renderTemplate(getMatchValueByChar({decimals:MathSymbol.underScript.decimals,values:MathSymbol.underScript.templates,judgeChar:t,defaultValue:`@1\\limits_{@2}`}).replace(`@v`,`@1`),[r,t])}return r}function flattenNodeTreeByNodeName(e,t){let n=[],r=NodeTool.getChildren(e);return Array.prototype.forEach.call(r,e=>{NodeTool.getNodeName(e)===t?n=n.concat(flattenNodeTreeByNodeName(e,t)):n.push(e)}),n}function getMatchValueByChar(e){let{decimals:t,values:n,judgeChar:r,defaultValue:a=null}=e;if(r&&r.length===1){let e=t.indexOf(r.charCodeAt(0));if(e>-1)return n[e]}return a}function renderMphantom(e,t){return``}function getRender_default(e){return function(t,n){return renderTemplate(e,renderChildren(n))}}function renderTemplate(e,t){return e.replace(/\@\d+/g,e=>t[parseInt(e.substring(1,e.length))-1])}function getRender_joinSeparator(e,t=``){return function(n,r){let a=renderChildren(r);return e.replace(`@content`,a.join(t))}}function getRender_joinSeparators(e,t){return function(n,r){let a=renderChildren(r),o=``;return o=t.length===0?a.join(``):a.reduce((e,n,r)=>(e+=n,r<a.length-1&&(e+=t[r]||t[t.length-1]),e),``),e.replace(`@content`,o)}}var mathml2latex={convert};function fixCharacters(e){return e.replace(/’/g,`'`).replace(/“/g,`"`).replace(/”/g,`"`).replace(/\x0b/g,` `).replace(/\u201d/g,`"`).replace(/\u201c/g,`"`)}function numberString(e,t=`1`){return[`a`].includes(t)?String.fromCharCode(97+e-1)+`. `:[`A`].includes(t)?String.fromCharCode(65+e-1)+`. `:[`I`].includes(t)?`${romanize(e)}. `:[`i`].includes(t)?`${romanize(e).toLowerCase()}. `:([`1`].includes(t),`${e}. `)}function romanize(e){let t=[[`M`,1e3],[`CM`,900],[`D`,500],[`CD`,400],[`C`,100],[`XC`,90],[`L`,50],[`XL`,40],[`X`,10],[`IX`,9],[`V`,5],[`IV`,4],[`I`,1]],n=``;for(let[r,a]of t)for(;e>=a;)n+=r,e-=a;return n}function escapeMarkdown(e){let t=[{char:`\\`,escape:`\\\\`},{char:`#`,escape:`\\#`},{char:`<`,escape:`\\<`},{char:`…`,escape:`...`},{char:`©`,escape:`(c)`},{char:`®`,escape:`(r)`},{char:`™`,escape:`(tm)`},{char:`±`,escape:`+-`},{char:`—`,escape:`---`}],n=e.map&&e.map.length>0?e.map[0]:0;if(!n){let n=fixCharacters(e.content);for(let{char:e,escape:r}of t)n=n.replaceAll(e,r);return[[n,e]]}let r=fixCharacters(e.content).split(``),a=[],o=Object.fromEntries(t.map(e=>[e.char,e.escape])),s=0,c=``,l=``,u=()=>{if(l.length>0){let t=structuredClone(e);t.map=[n+s],a.push([l,t]),s=c.length}l=``};for(let e=0;e<r.length;e++){let t=r[e];c+=t,o[t]&&u(),l+=o[t]||t,o[t]&&u()}return u(),a}function getLinkTokensHandlers(){return{text:[(e,t)=>{t.current.meta.link_text+=e.content,e.content&&!t.current.meta.link_token_token&&(t.current.meta.link_token_token=e)}],link_close:[(e,t)=>{{let n=t.current.meta.link_open_token,r=n.attrGet(`href`)||``,a=n.attrGet(`title`)||``,o=n.attrGet(`origUrl`)||r,s=t.current.meta.link_text;o===s&&(s=r);let c=n.attrGet(`mdTemplate`);if(c){let n=r.split(`/`).pop();c=c.replaceAll(`$href`,r),c=c.replaceAll(`$basename`,n||``),c=c.replaceAll(`$label`,t.current.meta.link_text),c=c.replaceAll(`$title`,a||``),t.current.log(c,e)}else!a&&s===r?t.current.log(r,e):!a&&!r?(t.current.log(`[`,e),t.current.log(s,t.current.meta.link_token_token),t.current.log(`]${a}`,e)):(t.current.log(`[`,e),t.current.log(s,t.current.meta.link_token_token),a?t.current.log(`](${r} ${a})`,e):t.current.log(`](${r})`,e));t.unstash(`getLinkTokensHandlers.link_close`)}}],default:[(e,t)=>{}]}}function getInlineTokensHandlers(){return{text:[(e,t)=>{if(e.meta===`noEscText`)t.current.log(e.content);else for(let n of escapeMarkdown(e))t.current.log(n[0],n[1])}],strong_open:[(e,t)=>{t.current.log(e.markup||`**`,e)}],strong_close:[(e,t)=>{t.current.log(e.markup||`**`,e)}],em_open:[(e,t)=>{t.current.log(e.markup||`*`,e)}],em_close:[(e,t)=>{t.current.log(e.markup||`*`,e)}],underline_open:[(e,t)=>{t.current.log(e.markup||`_`,e)}],underline_close:[(e,t)=>{t.current.log(e.markup||`_`,e)}],strike_open:[(e,t)=>{t.current.log(e.markup||`~`,e)}],strike_close:[(e,t)=>{t.current.log(e.markup||`~`,e)}],link_open:[(e,t)=>{t.stash(`getInlineTokensHandlers.link_open`),t.current.handlers=getLinkTokensHandlers(),t.current.meta.link_open_token=e,t.current.meta.link_text=``,t.current.meta.link_token_token=null}],code_open:[(e,t)=>{t.current.log("`",e)}],code_close:[(e,t)=>{t.current.log("`",e)}],code_inline:[(e,t)=>{t.current.log("`"+e.content+"`",e)}],math:[(e,t)=>{let n=e.content;if(e.attrGet(`lang`)===`mathml`){let e=n.replace(/<annotation[\s\S]*?<\/annotation>/g,``);n=mathml2latex.convert(e)}t.current.log(`$`+n+`$`,e)}],hardbreak:[(e,t)=>{t.current.log(t.current.lineBreak+`
25
+ `,{node:t,pos:r})}return t.forEach((t,a)=>{nodeToTreeStringOutput(e,t,n+1,r+a+1)}),e}function nodeToTreeString(e){let t=new SmartOutput;return nodeToTreeStringOutput(t,e),t.toString()}var DummyEditorView=class{_props;directPlugins;nodeViews;prevDirectPlugins=[];pluginViews=[];state;focused=!1;constructor(e){this._props=e,this.state=e.state,this.directPlugins=e.plugins||[],this.directPlugins.forEach(checkStateComponent),this.dispatch=this.dispatch.bind(this),this.editable=getEditable(this),this.nodeViews=buildNodeViews(this),this.updatePluginViews()}editable;get composing(){return!1}get dom(){return{addEventListener(){},removeEventListener(){}}}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(checkStateComponent),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let e in this._props)t[e]=this._props[e];t.state=this.state;for(let n in e)t[n]=e[n];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){let n=this.state,r=!1,a=!1;if(e.storedMarks&&this.composing,this.state=e,n.plugins!=e.plugins||this._props.plugins!=t.plugins||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let e=buildNodeViews(this);changedNodeViews(e,this.nodeViews)&&(this.nodeViews=e,r=!0)}this.editable=getEditable(this),r||e.selection.eq(n.selection),this.updatePluginViews(n)}scrollToSelection(){}destroyPluginViews(){let e=this.pluginViews.pop();for(;e;)e.destroy&&e.destroy(),e=this.pluginViews.pop()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let e=0;e<this.directPlugins.length;e++){let t=this.directPlugins[e];t.spec.view&&this.pluginViews.push(t.spec.view(this))}for(let e=0;e<this.state.plugins.length;e++){let t=this.state.plugins[e];t.spec.view&&this.pluginViews.push(t.spec.view(this))}}else for(let t=0;t<this.pluginViews.length;t++){let n=this.pluginViews[t];n.update&&n.update(this,e)}}someProp(e,t){let n=this._props&&this._props[e],r;if(n!=null&&(r=t?t(n):n))return r;for(let n=0;n<this.directPlugins.length;n++){let a=this.directPlugins[n].props[e];if(a!=null&&(r=t?t(a):a))return r}let a=this.state.plugins;if(a)for(let n=0;n<a.length;n++){let o=a[n].props[e];if(o!=null&&(r=t?t(o):o))return r}}hasFocus(){return this.focused}focus(){this.focused=!0}destroy(){this.destroyPluginViews()}get isDestroyed(){return!1}dispatchEvent(e){}};DummyEditorView.prototype.dispatch=function(e){let t=this.props.dispatchTransaction;t?t.call(this,e):this.updateState(this.state.apply(e))};function getEditable(e){return!e.someProp(`editable`,t=>t(e.state)===!1)}function buildNodeViews(e){let t=Object.create(null);function n(e){for(let n in e)Object.prototype.hasOwnProperty.call(t,n)||(t[n]=e[n])}return e.someProp(`nodeViews`,n),e.someProp(`markViews`,n),t}function changedNodeViews(e,t){let n=0,r=0;for(let r in e){if(e[r]!=t[r])return!0;n++}for(let e in t)r++;return n!=r}function checkStateComponent(e){if(e.spec.state||e.spec.filterTransaction||e.spec.appendTransaction)throw RangeError(`Plugins passed directly to the view must not have a state component`)}function createNodeFromObject(e,t,n){try{let r=t.nodeFromJSON(e);return n?.errorOnInvalidContent&&r.check(),r}catch(r){if(n?.errorOnInvalidContent)throw Error(`Invalid JSON content: `+r.message,{cause:r});return console.warn(`Invalid content.`,`Passed value:`,e,`Error:`,r),t.topNodeType.createAndFill(null,[])}}function defaultUi(e){return{showMessage(e){globalThis.alert(e)},showError(e){globalThis.alert(e.message),console.error(e)},focus(){},select({anchor:e,scrollIntoView:t,userEvent:n}){}}}var Container=class{items=new Map;register(e,t){this.items.set(e,t)}resolve(e){return this.items.get(e)}};function ensureDocSchema(e,t){if(e.type.schema===t)return e;let n=e.toJSON();return Node$3.fromJSON(t,n)}var CoreEditor=class e extends EventTarget{schema;extensionManager;config;commandManager;view;state;ui=defaultUi(this);linkListener;linkSource;ci=new Container;version=0;constructor(e,t,n){super(),this.schema=t,this.extensionManager=n,this.config={...e},this.commandManager=new CommandManager(this)}static create(t){let n=new ExtensionManager(t.editorKits,t.debug),r=n.getSchemaByResolvedExtensions(),a=new e(t,r,n);n.created(a,r);let o=t.content?t.content:r.topNodeType.spec.EMPTY_DOC;return a.createView(o),a.setupPlugins(),a.dispatchEvent(new CustomEvent(`ready`)),a}clone(t){let n=new ExtensionManager(this.extensionManager.editorKits,(t||this.config).debug),r=new e({assetLoad:this.config.assetLoad,...t},this.schema,n);n.created(r,this.schema);let a=this.getJSON(),o=this.state.selection;return r.createView(a,o),r.setupPlugins(),r}getExtension(e){return this.ci.resolve(e)}get run(){return this.commandManager.run}get commandFactories(){return this.commandManager.commandFactories}chain(e){return this.commandManager.createChain(e)}can(e){return this.commandManager.createCan(e)}link(e){if(e===this)throw Error(`You cannot chain editor to itself`);this.unlink(),this.state=EditorState.create({doc:e.getDocument()});let{commandFactories:t}=this.commandManager,n=[],r={...Object.fromEntries(Object.entries(t).map(([e,t])=>[e,(...e)=>{let a=t(...e);return n.push(a),r}])),run:()=>{this.linkSource=e,this.linkListener=()=>{let t=e.state,r=e=>{t=t.apply(e)};for(let e of n)if(!e(t,r))return;this.state=t.reconfigure({plugins:this.extensionManager.plugins}),this.view&&this.view.updateState(this.state);let a=new CustomEvent(`changed`,{detail:{editor:this}});this.dispatchEvent(a)},e.addEventListener(`changed`,this.linkListener)}};return r}unlink(){this.linkListener&&this.linkSource&&(this.linkSource.removeEventListener(`changed`,this.linkListener),this.linkListener=void 0,this.linkSource=void 0)}createView(e,t){let n=createNodeFromObject(e,this.schema);if(this.state=EditorState.create({doc:n,selection:t}),this.config.element){let e=new EditorView(this.config.element,{state:this.state,attributes:{class:`kb-editor`},dispatchTransaction:e=>this.dispatchTransaction(e),editable:()=>!this.config.readOnly});if(this.view=e,this.config.element.parentNode){let t=new MutationObserver(n=>{for(let r of n)for(let n of r.removedNodes)if(n.contains(e.dom)){t.disconnect(),e.destroy();return}})}}else this.view=new DummyEditorView({state:this.state,dispatchTransaction:e=>this.dispatchTransaction(e)});let r=new CustomEvent(`doc:loaded`,{detail:{editor:this,doc:n}});this.dispatchEvent(r)}dispatchTransaction(e){if(this.state=this.state.apply(e),e.docChanged&&this.version++,this.view){this.view.updateState(this.state);let t=new CustomEvent(`transaction`,{detail:{editor:this,transaction:e}});this.dispatchEvent(t)}if(e.docChanged){let e=new CustomEvent(`changed`,{detail:{editor:this}});this.dispatchEvent(e)}}setupPlugins(){this.state=this.state.reconfigure({plugins:this.extensionManager.plugins}),this.view&&(this.view.updateState(this.state),this.view.setProps({nodeViews:this.extensionManager.nodeViews}))}clearDocument(){let e={type:this.schema.topNodeType.name,content:this.schema.topNodeType.spec.EMPTY_DOC.content};this.setDocument(e)}setDocument(e){let t=createNodeFromObject(e,this.schema,{errorOnInvalidContent:!0});t=ensureDocSchema(t,this.schema),this.state=EditorState.create({doc:t,plugins:this.state.plugins,storedMarks:this.state.storedMarks}),this.view&&this.view.updateState(this.state);let n=new CustomEvent(`doc:loaded`,{detail:{editor:this,doc:t}});this.dispatchEvent(n)}getConverter(e){let t=this.extensionManager.converters[e];if(!t)throw Error(`Converter not found for: `+e);return t}getDocument(){return this.state.doc}loadDocumentText(e,t){return this.loadDocument(e,new TextEncoder().encode(t))}async loadDocument(e,t){let n=await this.getConverter(e).toDoc(t),r=EditorState.create({doc:n,plugins:this.state.plugins,storedMarks:this.state.storedMarks});runInputRulesTexts()(r,e=>{r=r.apply(e)}),this.state=r,this.view&&(this.view.updateState(this.state),this.view.dispatch(this.view.state.tr));let a=new CustomEvent(`doc:loaded`,{detail:{editor:this,doc:this.state.doc}});this.dispatchEvent(a)}async saveDocument(e){let t=this.getConverter(e),n=this.state.doc.toJSON(),r=Node$3.fromJSON(this.state.schema,n);return await t.fromDoc(r)}async patchDocument(e,t){let n=await this.getConverter(e).toDoc(t),r=this.state.tr;r.replaceWith(0,this.state.doc.content.size,n.content),this.dispatchTransaction(r)}getMediaTypes(){return Object.keys(this.extensionManager.converters)}patchDocumentText(e,t){return this.patchDocument(e,new TextEncoder().encode(t))}getJSON(){return this.state.doc.toJSON()}debug(e){e||=this.state.doc,console.debug(nodeToTreeString(e))}destroy(){let e=new CustomEvent(`beforeDestroy`,{detail:{}});if(this.dispatchEvent(e),this.config.element){let e=this.config.element,t=e.cloneNode(!0);e.replaceWith(t)}this.view.destroy()}mergeCommandFactories(e,t){this.commandManager.mergeCommandFactories(e,t)}get editable(){return this.view.editable}},Extension=class{config;type=`extension`;editor;conflicts;overrides;constructor(e={}){this.config=e}setEditor(e){this.editor=e}getEditor(){return this.editor}created(){}getInputRules(){return[]}getProseMirrorPlugins(){return[]}getCommandFactories(e){return{}}getKeyboardShortcuts(e){return{}}getConverters(e,t){return{}}setupSpec(e){}},Mark=class{config;type=`mark`;name=`node`;editor;attributes={};constructor(e={}){this.config=e}setEditor(e){this.editor=e}created(){}getMarkSpec(){throw Error(`MarkSpec not defined: `+this.name)}getInputRules(e){return[]}getCommandFactories(e,t){return{}}getKeyboardShortcuts(e){return{}}},Node$2=class{config;type=`node`;name=`node`;editor;attributes={};constructor(e={}){this.config=e}setEditor(e){this.editor=e}created(){}getNodeSpec(){throw Error(`NodeSpec not defined: `+this.name)}getInputRules(e){return[]}getProseMirrorPlugins(){return[]}getCommandFactories(e,t){return{}}getKeyboardShortcuts(e){return{}}getNodeView(e){}getConverters(e,t){return{}}};function getShadowRoot(e){let t=e;for(;t;){if(t.toString()===`[object ShadowRoot]`)return t;if(t instanceof ShadowRoot&&t.host)return t.host.shadowRoot||void 0;t=t.parentElement||(t instanceof ShadowRoot?t.host:void 0)}}function debounce(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function normalizeSiblings(e,t){if(e.childCount<2)return e;for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.index(n)),a,o=[];if(e.forEach(e=>{if(!o)return;let t=r.findWrapping(e.type),n;if(!t)return o=null;if(n=o.length&&a.length&&addToSibling(t,a,e,o[o.length-1],0))o[o.length-1]=n;else{o.length&&(o[o.length-1]=closeRight(o[o.length-1],a.length));let n=withWrappers(e,t);o.push(n),r=r.matchType(n.type),a=t}}),o)return Fragment.from(o)}return e}function withWrappers(e,t,n=0){for(let r=t.length-1;r>=n;r--)e=t[r].create(null,Fragment.from(e));return e}function addToSibling(e,t,n,r,a){if(a<e.length&&a<t.length&&e[a]==t[a]){let o=addToSibling(e,t,n,r.lastChild,a+1);if(o)return r.copy(r.content.replaceChild(r.childCount-1,o));if(r.contentMatchAt(r.childCount).matchType(a==e.length-1?n.type:e[a+1]))return r.copy(r.content.append(Fragment.from(withWrappers(n,e,a+1))))}}function closeRight(e,t){if(t==0)return e;let n=e.content.replaceChild(e.childCount-1,closeRight(e.lastChild,t-1)),r=e.contentMatchAt(e.childCount).fillBefore(Fragment.empty,!0);return e.copy(n.append(r))}function closeRange(e,t,n,r,a,o){let s=t<0?e.firstChild:e.lastChild,c=s.content;return e.childCount>1&&(o=0),a<r-1&&(c=closeRange(c,t,n,r,a+1,o)),a>=n&&(c=t<0?s.contentMatchAt(0).fillBefore(c,o<=a).append(c):c.append(s.contentMatchAt(s.childCount).fillBefore(Fragment.empty,!0))),e.replaceChild(t<0?0:e.childCount-1,s.copy(c))}function closeSlice(e,t,n){return t<e.openStart&&(e=new Slice(closeRange(e.content,-1,t,e.openStart,0,e.openEnd),t,e.openEnd)),n<e.openEnd&&(e=new Slice(closeRange(e.content,1,n,e.openEnd,0,0),e.openStart,n)),e}function sliceSingleNode(e){return e.openStart==0&&e.openEnd==0&&e.content.childCount==1?e.content.firstChild:null}function fixSlice(e,t){if(e=Slice.maxOpen(normalizeSiblings(e.content,t),!0),e.openStart||e.openEnd){let t=0,n=0;for(let n=e.content.firstChild;t<e.openStart&&!n.type.spec.isolating;t++,n=n.firstChild);for(let t=e.content.lastChild;n<e.openEnd&&!t.type.spec.isolating;n++,t=t.lastChild);e=closeSlice(e,t,n)}return e}function sliceHasOnlyText(e){return e.content.content.every(e=>e.isInline)}var selectAll=()=>function(e,t,n){let r=e.tr.setSelection(new AllSelection(e.doc));return n&&n.dispatch(r),!0};function textPositionsToResolvedPos(e,t,n){let r=e.map(e=>-1),a=0,o=!1;function s(t,n,s,c){if(o){for(let n=0;n<e.length;n++){let o=e[n];o>=a&&o<a+c&&(r[n]=t+(o-a))}a+=c}}function c(e,t=0,r=0,a=0){t===1&&r===n&&(o=!0);let l=0;e.isText&&e.text?l=e.text?.length:e.isLeaf&&(l=1),l>0&&s(a,t,r,l),e.forEach((e,n,r)=>{c(e,t+1,r,a+n+1)})}if(c(t),o)for(let n=0;n<e.length;n++){let o=e[n];r[n]===-1&&(o<a?r[n]=1:r[n]=t.nodeSize-1)}return r.map(e=>t.resolve(e-1))}var selectText=(e,t,n=0)=>function(r,a,o){let[s,c]=textPositionsToResolvedPos([e+t,e],r.doc,n),l=r.tr.setSelection(new TextSelection(c,s));return o&&o.dispatch(l),!0},ExtensionSelection=class extends Extension{name=`selection`;extractSelection(){let e=this.editor.state,{from:t,to:n}=e.selection,r=e.doc.slice(t,n);if(sliceHasOnlyText(r)){let t=e.schema.nodes.paragraph.create(null,r.content);return e.schema.topNodeType.createAndFill(null,[t])}return e.schema.topNodeType.createAndFill(null,r.content)}replaceSelection(e){let t=!1,n=this.editor.view,r=this.editor.state,a;e.type?.name===`doc`&&(e=createNodeFromObject(e.toJSON(),this.editor.schema)),a=new Slice(e.content,1,1);let o=r.selection.$from;a=fixSlice(a,o);let s=sliceSingleNode(a),c=s?r.tr.replaceSelectionWith(s,!1):r.tr.replaceSelection(a);n.dispatch(c.scrollIntoView())}appendSelection(e){let t=this.editor.view,{state:n}=t,r;e.type?.name===`doc`&&(e=createNodeFromObject(e.toJSON(),this.editor.schema)),r=new Slice(e.content,1,1);let a=t.state.selection.$from;r=fixSlice(r,a);let o=n.tr.insert(t.state.selection.to,r.content);t.dispatch(o.scrollIntoView())}getCommandFactories(e){return this.editor=e,{selectAll:()=>selectAll(),selectText:(...e)=>selectText(...e)}}},pcBaseKeymap={"Mod-Enter":`exitCode`,Backspace:`backspace`,"Mod-Backspace":`backspace`,"Shift-Backspace":`backspace`,Delete:`del`,"Mod-Delete":`del`,"Mod-a":`selectAll`},macBaseKeymap={...pcBaseKeymap,"Ctrl-h":pcBaseKeymap.Backspace,"Alt-Backspace":pcBaseKeymap[`Mod-Backspace`],"Ctrl-d":pcBaseKeymap.Delete,"Ctrl-Alt-Backspace":pcBaseKeymap[`Mod-Delete`],"Alt-Delete":pcBaseKeymap[`Mod-Delete`],"Alt-d":pcBaseKeymap[`Mod-Delete`],"Ctrl-a":`selectTextblockStart`,"Ctrl-e":`selectTextblockEnd`},baseKeymap=/(Mac|iPhone|iPod|iPad)/i.test(navigator?.platform)?macBaseKeymap:pcBaseKeymap,ExtensionBaseKeymap=class extends Extension{name=`base-keymap`;getKeyboardShortcuts(){let e={Enter:`enter`,"Alt-ArrowUp":`joinUp`,"Alt-ArrowDown":`joinDown`,"Mod-BracketLeft":`lift`,Escape:`selectParentNode`};for(let t in baseKeymap)e[t]=baseKeymap[t];return e}};function dropCursor(e={}){return new Plugin({key:new PluginKey(`drop-cursor`),view(t){return new DropCursorView(t,e)}})}var DropCursorView=class{editorView;width;color;class;cursorPos=null;element=null;timeout=-1;handlers;constructor(e,t){this.editorView=e,this.width=t.width??1,this.color=t.color===!1?void 0:t.color||`black`,this.class=t.class,this.handlers=[`dragover`,`dragend`,`drop`,`dragleave`].map(t=>{let n=e=>{this[t](e)};return e.dom.addEventListener(t,n),{name:t,handler:n}})}destroy(){this.handlers.forEach(({name:e,handler:t})=>this.editorView.dom.removeEventListener(e,t))}update(e,t){this.cursorPos!=null&&t.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),t=!e.parent.inlineContent,n,r=this.editorView.dom,a=r.getBoundingClientRect(),o=a.width/r.offsetWidth,s=a.height/r.offsetHeight;if(t){let t=e.nodeBefore,r=e.nodeAfter;if(t||r){let e=this.editorView.nodeDOM(this.cursorPos-(t?t.nodeSize:0));if(e){let a=e.getBoundingClientRect(),o=t?a.bottom:a.top;t&&r&&(o=(o+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let c=this.width/2*s;n={left:a.left,right:a.right,top:o-c,bottom:o+c}}}}if(!n){let e=this.editorView.coordsAtPos(this.cursorPos),t=this.width/2*o;n={left:e.left-t,right:e.left+t,top:e.top,bottom:e.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement(`div`)),this.class&&(this.element.className=this.class),this.element.style.cssText=`position: absolute; z-index: 50; pointer-events: none;`,this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle(`prosemirror-dropcursor-block`,t),this.element.classList.toggle(`prosemirror-dropcursor-inline`,!t);let l,u;if(!c||c==document.body&&getComputedStyle(c).position==`static`)l=-pageXOffset,u=-pageYOffset;else{let e=c.getBoundingClientRect(),t=e.width/c.offsetWidth,n=e.height/c.offsetHeight;l=e.left-c.scrollLeft*t,u=e.top-c.scrollTop*n}this.element.style.left=(n.left-l)/o+`px`,this.element.style.top=(n.top-u)/s+`px`,this.element.style.width=(n.right-n.left)/o+`px`,this.element.style.height=(n.bottom-n.top)/s+`px`}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let t=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),n=t&&t.inside>=0&&this.editorView.state.doc.nodeAt(t.inside),r=n&&n.type.spec.disableDropCursor,a=typeof r==`function`?r(this.editorView,t,e):r;if(t&&!a){let e=t.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let t=dropPoint(this.editorView.state.doc,e,this.editorView.dragging.slice);t!=null&&(e=t)}this.setCursor(e),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}},ExtensionDropcursor=class extends Extension{name=`dropcursor`;options={color:`currentColor`,width:1,class:void 0};getProseMirrorPlugins(){return[dropCursor(this.options)]}},GapCursor=class e extends Selection{constructor(e){super(e,e),this.visible=!1}map(t,n){let r=t.resolve(n.map(this.head));return e.valid(r)?new e(r):Selection.near(r)}content(){return Slice.empty}eq(t){return t instanceof e&&t.head==this.head}toJSON(){return{type:`gapcursor`,pos:this.head}}static fromJSONToGapCursor(t,n){if(typeof n.pos!=`number`)throw RangeError(`Invalid input for GapCursor.fromJSON`);return new e(t.resolve(n.pos))}getBookmark(){return new GapBookmark(this.anchor)}static valid(e){let t=e.parent;if(t.isTextblock||!closedBefore(e)||!closedAfter(e))return!1;let n=t.type.spec.allowGapCursor;if(n!=null)return n;let r=t.contentMatchAt(e.index()).defaultType;return r&&r.isTextblock}static findGapCursorFrom(t,n,r=!1){search:for(;;){if(!r&&e.valid(t))return t;let a=t.pos,o=null;for(let r=t.depth;;r--){let s=t.node(r);if(n>0?t.indexAfter(r)<s.childCount:t.index(r)>0){o=s.child(n>0?t.indexAfter(r):t.index(r)-1);break}else if(r==0)return null;a+=n;let c=t.doc.resolve(a);if(e.valid(c))return c}for(;;){let s=n>0?o.firstChild:o.lastChild;if(!s){if(o.isAtom&&!o.isText&&!NodeSelection.isSelectable(o)){t=t.doc.resolve(a+o.nodeSize*n),r=!1;continue search}break}o=s,a+=n;let c=t.doc.resolve(a);if(e.valid(c))return c}return null}}};Selection.jsonID(`gapcursor`,GapCursor);var GapBookmark=class e{pos;constructor(e){this.pos=e}map(t){return new e(t.map(this.pos))}resolve(e){let t=e.resolve(this.pos);return GapCursor.valid(t)?new GapCursor(t):Selection.near(t)}};function closedBefore(e){for(let t=e.depth;t>=0;t--){let n=e.index(t),r=e.node(t);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let e=r.child(n-1);;e=e.lastChild){if(e.childCount==0&&!e.inlineContent||e.isAtom||e.type.spec.isolating)return!0;if(e.inlineContent)return!1}}return!0}function closedAfter(e){for(let t=e.depth;t>=0;t--){let n=e.indexAfter(t),r=e.node(t);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let e=r.child(n);;e=e.firstChild){if(e.childCount==0&&!e.inlineContent||e.isAtom||e.type.spec.isolating)return!0;if(e.inlineContent)return!1}}return!0}function gapCursor(){return new Plugin({key:new PluginKey(`gap-cursor`),props:{decorations:drawGapCursor,createSelectionBetween(e,t,n){return t.pos==n.pos&&GapCursor.valid(n)?new GapCursor(n):null},handleClick,handleKeyDown:handleKeyDown$1,handleDOMEvents:{beforeinput}}})}var handleKeyDown$1=keydownHandler({ArrowLeft:arrow$1(`horiz`,-1),ArrowRight:arrow$1(`horiz`,1),ArrowUp:arrow$1(`vert`,-1),ArrowDown:arrow$1(`vert`,1)});function arrow$1(e,t){let n=e==`vert`?t>0?`down`:`up`:t>0?`right`:`left`;return function(e,r,a){let o=e.selection,s=t>0?o.$to:o.$from,c=o.empty;if(o instanceof TextSelection){if(!a.endOfTextblock(n)||s.depth==0)return!1;c=!1,s=e.doc.resolve(t>0?s.after():s.before())}let l=GapCursor.findGapCursorFrom(s,t,c);return l?(r&&r(e.tr.setSelection(new GapCursor(l))),!0):!1}}function handleClick(e,t,n){if(!e||!e.editable)return!1;let r=e.state.doc.resolve(t);if(!GapCursor.valid(r))return!1;let a=e.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&NodeSelection.isSelectable(e.state.doc.nodeAt(a.inside))?!1:(e.dispatch(e.state.tr.setSelection(new GapCursor(r))),!0)}function beforeinput(e,t){if(t.inputType!=`insertCompositionText`||!(e.state.selection instanceof GapCursor))return!1;let{$from:n}=e.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(e.state.schema.nodes.text);if(!r)return!1;let a=Fragment.empty;for(let e=r.length-1;e>=0;e--)a=Fragment.from(r[e].createAndFill(null,a));let o=e.state.tr.replace(n.pos,n.pos,new Slice(a,0,0));return o.setSelection(TextSelection.near(o.doc.resolve(n.pos+1))),e.dispatch(o),!1}function drawGapCursor(e){if(!(e.selection instanceof GapCursor))return null;let t=document.createElement(`div`);return t.className=`kb-gapcursor`,DecorationSet.create(e.doc,[Decoration.widget(e.selection.head,t,{key:`gapcursor`})])}var ExtensionGapcursor=class extends Extension{name=`gapcursor`;options={color:`currentColor`,width:1,class:void 0};getProseMirrorPlugins(){return[gapCursor()]}},ExtensionTextAlign=class extends Extension{name=`textAlign`;getCommandFactories(e){let t=e=>(t,n)=>{let{selection:r,tr:a}=t,{from:o,to:s}=r,c=!1;return t.doc.nodesBetween(o,s,(t,n)=>{t.isBlock&&t.type.spec.attrs&&`textAlign`in t.type.spec.attrs&&(a.setNodeMarkup(n,void 0,{...t.attrs,textAlign:e}),c=!0)}),c&&n&&n(a),c};return{setTextAlignLeft:()=>t(`left`),setTextAlignCenter:()=>t(`center`),setTextAlignRight:()=>t(`right`),setTextAlignJustify:()=>t(`justify`)}}},userColors=[{dark:`#30bced`,light:`#30bced`},{dark:`#6eeb83`,light:`#6eeb83`},{dark:`#ffbc42`,light:`#ffbc42`},{dark:`#ecd444`,light:`#ecd444`},{dark:`#ee6352`,light:`#ee6352`},{dark:`#9ac2c9`,light:`#9ac2c9`},{dark:`#8acb88`,light:`#8acb88`},{dark:`#1be7ff`,light:`#1be7ff`}];function hashString(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)}var defaultColorMapper=(e,t)=>{let n=hashString(t.id),r=hashString(e.id);return n===r&&r++,userColors[r%userColors.length]};function generateBlankUser(){return{id:``,name:`User unset`}}function generateRandomUser(){let e=Math.random()*100;return{id:`random:`+e,name:`Anonymous `+Math.floor(e)}}var userPluginKey=new PluginKey(`user`),createUserPlugin=()=>new Plugin({key:userPluginKey,state:{init(){return{user:generateRandomUser()}},apply:(e,t)=>{let n=e.getMeta(`changeUser`);return n&&(t.user={...n.user}),t}}}),ExtensionUser=class extends Extension{name=`user`;getCommandFactories(){return{changeUser:e=>(t,n)=>{let r=t.tr;return r.setMeta(`changeUser`,{user:e}),n&&n(r),!0}}}getProseMirrorPlugins(){return[createUserPlugin()]}},remoteSelectionPluginKey=new PluginKey(`remote-selection`),defaultCursorBuilder=(e,t,n)=>{let r=n(e,t).light,a=document.createElement(`span`);a.classList.add(`kb-yjs__cursor`),a.setAttribute(`style`,`border-color: ${r};`);let o=document.createElement(`div`);o.setAttribute(`style`,`background-color: ${r}`),o.insertBefore(document.createTextNode(e.name),null);let s=document.createTextNode(`⁠`),c=document.createTextNode(`⁠`);return a.insertBefore(s,null),a.insertBefore(o,null),a.insertBefore(c,null),a},defaultSelectionBuilder=(e,t,n)=>({style:`background-color: ${n(e,t).light}70`,class:`kb-yjs__selection`}),createDecorations=(e,t,n,r)=>{let a=[],o=t.remoteStates;for(let s of o)if(s.cursor!=null){let o=s.user,c=s.cursor,l=c.anchor||null,u=c.head||null;if(l!==null&&u!==null){let c=Math.max(e.doc.content.size-1,0);l=Math.min(l,c),u=Math.min(u,c),a.push(Decoration.widget(u,()=>n(o,t.me,t.colorMapper),{key:s.clientId+o.id+o.name,side:10}));let d=Math.min(l,u),f=Math.max(l,u);a.push(Decoration.inline(d,f,r(o,t.me,t.colorMapper),{inclusiveEnd:!0,inclusiveStart:!1}))}}return DecorationSet.create(e.doc,a)},remoteSelectionPlugin=({cursorBuilder:e=defaultCursorBuilder,selectionBuilder:t=defaultSelectionBuilder}={})=>new Plugin({key:remoteSelectionPluginKey,state:{init(){return{remoteStates:[],me:generateBlankUser(),colorMapper:defaultColorMapper}},apply(e,t){let n=e.getMeta(`changeUser`);n&&(t.me={...n.user});let r=e.getMeta(`setColorMapper`);r&&(t.colorMapper=r.colorMapper);let a=e.getMeta(`remoteSelectionChange`);return a&&(t.remoteStates=[...a.remoteStates]),t}},props:{decorations(n){let r=this.getState(n);return r?createDecorations(n,r,e,t):DecorationSet.empty}}}),ExtensionRemoteSelection=class extends Extension{name=`remote-selection`;getProseMirrorPlugins(){return[remoteSelectionPlugin()]}};function generateId(){return String(Math.random())}function buildPairingTransaction(e,t,n){let{doc:r}=e,a=new Map,o=[];r.descendants((e,n)=>{e.type.name===t&&o.push({node:e,pos:n})});let s=!1;for(let{node:e,pos:t}of o){let r=e.attrs.content?.trim();if(!r)continue;let o=r.match(/^[^0-9a-z\/]*(\/?)[\s]*([\w]+)/i);if(!o)continue;let c=o[1]===`/`,l=o[2];if(!c)a.has(l)||a.set(l,[]),a.get(l).push({node:e,pos:t});else{let r=a.get(l);if(r&&r.length>0){let a=r.pop(),o=generateId();n.setNodeMarkup(a.pos,void 0,{...a.node.attrs,id:o,nesting:1,error:void 0}),n.setNodeMarkup(t,void 0,{...e.attrs,id:o,nesting:-1,error:void 0})}else n.setNodeMarkup(t,void 0,{...e.attrs,error:`Closing shortcode without matching opening`,nesting:-1});s=!0}}for(let[,e]of a.entries())for(let{node:t,pos:r}of e)n.setNodeMarkup(r,void 0,{...t.attrs,nesting:0,id:void 0}),s=!0;return s?n:null}var createPairingPlugin=e=>new Plugin({appendTransaction(t,n,r){let a=new Set;for(let r of t)if(r.docChanged){for(let t of r.steps)if((t instanceof ReplaceStep||t instanceof ReplaceAroundStep)&&(t.slice&&t.slice.content.descendants(t=>{e.includes(t.type.name)&&a.add(t.type.name)}),t.from!=null&&t.to!=null&&t.from!==t.to&&n.doc.nodesBetween(t.from,t.to,t=>{e.includes(t.type.name)&&a.add(t.type.name)}),a.size===e.length))break;if(a.size===e.length)break}if(a.size===0)return null;let o=r.tr;for(let e of a)buildPairingTransaction(r,e,o);return o}}),ExtensionPairing=class extends Extension{name=`pairing-nodes`;getProseMirrorPlugins(){return[createPairingPlugin([`shortcode_inline`])]}};function getHTMLFromFragment(e,t){let n=globalThis.document,r=DOMSerializer.fromSchema(t).serializeFragment(e,{document:n}),a=n.implementation.createHTMLDocument().createElement(`div`);return a.appendChild(r),a.innerHTML}var removeWhitespaces$1=e=>{let t=e.childNodes;for(let n=t.length-1;n>=0;--n){let r=t[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?e.removeChild(r):r.nodeType===1&&removeWhitespaces$1(r)}return e};function elementFromString$1(e){let t=`<html lang="en"><body>${e}</body></html>`,n=new globalThis.DOMParser().parseFromString(t,`text/html`).body;return removeWhitespaces$1(n)}var ExtensionHtml=class extends Extension{name=`html`;getConverters(e,t){return{"text/html":{fromDoc:async t=>{let n=getHTMLFromFragment(t.content,e.schema);return new TextEncoder().encode(n)},toDoc:async e=>{let n=elementFromString$1(new TextDecoder().decode(e));return DOMParser$1.fromSchema(t).parse(n)}}}}},mediaUploadKey=new PluginKey(`mediaUpload`);function fileToDataURL(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=n,r.readAsDataURL(e)})}function fileToObjectURL(e){return URL.createObjectURL(e)}function isImage(e,t){return t.some(t=>e.type.match(t))}function isVideo(e,t){return t.some(t=>e.type.match(t))}function insertImage(e,t,n,r,a){let{schema:o}=e.state,s=o.nodes.image;if(!s){console.warn(`Image node type not found in schema`);return}let c=s.create({src:n,alt:r,title:a}),l=e.state.tr.insert(t,c);e.dispatch(l)}function insertVideo(e,t,n,r,a,o){let{schema:s}=e.state,c=s.nodes.video;if(!c){console.warn(`Video node type not found in schema`);return}let l=c.create({src:n,title:r,width:a,height:o,controls:!0}),u=e.state.tr.insert(t,l);e.dispatch(u)}async function handleMediaFiles(e,t,n,r){let{maxFileSize:a=10*1024*1024,maxVideoFileSize:o=50*1024*1024,allowedImageTypes:s=[`^image/`],allowedVideoTypes:c=[`^video/`],uploadHandler:l}=r;for(let u of t){let t=isImage(u,s),d=isVideo(u,c);if(!t&&!d)continue;let f=d?o:a;if(u.size>f){console.warn(`${d?`Video`:`Image`} file "${u.name}" is too large (${(u.size/1024/1024).toFixed(2)}MB). Maximum size is ${(f/1024/1024).toFixed(2)}MB.`);continue}try{console.log(`Processing ${d?`video`:`image`}: ${u.name} (${(u.size/1024/1024).toFixed(2)}MB, ${u.type})`);let t;l?t=await l(u):d&&r.useObjectURLForVideos!==!1?(t=fileToObjectURL(u),console.log(`Using object URL for video:`,t)):(t=await fileToDataURL(u),console.log(`${d?`Video`:`Image`} converted to data URL, length: ${t.length} characters`)),d?(insertVideo(e,n,t,u.name),console.log(`Video inserted into editor`)):(insertImage(e,n,t,u.name),console.log(`Image inserted into editor`)),n+=1}catch(e){console.error(`Failed to process ${d?`video`:`image`} "${u.name}":`,e)}}}function createMediaUploadPlugin(e={}){return new Plugin({key:mediaUploadKey,state:{init(){return e},apply(e,t){return e.isGeneric?t:e.getMeta(`setMediaUploadOptions`)||t}},props:{handleDrop(e,t,n,r){if(r)return!1;let a=Array.from(t.dataTransfer?.files||[]);if(a.length===0)return!1;let o=mediaUploadKey.getState(e.state)||{},{allowedImageTypes:s=[`^image/`],allowedVideoTypes:c=[`^video/`]}=o;if(a.some(e=>isImage(e,s)||isVideo(e,c))){t.preventDefault();let n={left:t.clientX,top:t.clientY},r=e.posAtCoords(n);return r?(handleMediaFiles(e,a,r.pos,o),!0):!1}},handlePaste(t,n,r){if((n.clipboardData?.types||[]).includes(`text/html`))return;let a=Array.from(n.clipboardData?.items||[]).filter(e=>e.type.startsWith(`image/`));if(a.length>0){n.preventDefault();let r=[];for(let e of a){let t=e.getAsFile();t&&r.push(t)}if(r.length===0)return!1;let{from:o}=t.state.selection;return handleMediaFiles(t,r,o,e),!0}}}})}var ExtensionMediaUpload=class extends Extension{config;name=`mediaUpload`;constructor(e={}){super(e),this.config=e}getProseMirrorPlugins(){return[createMediaUploadPlugin(this.config)]}};function getStringByXPath(e,t){return t.ownerDocument.evaluate(e,t,null,XPathResult.STRING_TYPE,null).stringValue}function getElementsByXPath(e,t){let n=t.ownerDocument.evaluate(e,t,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),r=[];for(let e=0;e<n.snapshotLength;e++){let t=n.snapshotItem(e);t&&r.push(t)}return r}var PasteState=class{editor;pasteRules=[];constructor(e){this.editor=e}handleCommands(e,t){if(!e)return!1;if(e.getPasteRules)return e.getPasteRules(this.pasteRules),!0;if(e.setPasteRules)return console.log(`setPasteRules`,e.setPasteRules),this.pasteRules=e.setPasteRules,!0;if(e.pasteHtml){let{from:t,html:n}=e.pasteHtml,r=elementFromString$1(n),a=this.editor,o=!1,s=[],c=a.ci.resolve(`yaml`);for(let e of this.pasteRules){if(typeof e.match==`string`){if(getElementsByXPath(e.match,r).length===0)continue}else if(!e.match(r))continue;for(let t of e.steps){let e;if(typeof t.match==`string`)switch(t.result||``){case`string`:e=getStringByXPath(t.match,r);break;default:e=getElementsByXPath(t.match,r);break}else e=t.match(r);switch(console.log(`step`,e,t),t.op){case`remove`:for(let t of e)t.parentNode?.removeChild(t);break;case`replaceTag`:for(let n of e){let e=n.ownerDocument.createElement(t.tag);e.innerHTML=n.innerHTML,n.parentNode?.replaceChild(e,n)}break;case`replaceBody`:for(let t of e)r.innerHTML=``,r.appendChild(t);break;case`console.debug`:console.debug(e);break;case`meta.set`:s.push({path:t.path,value:e});break}}o=!!e.replaceDocument;break}let l=DOMParser$1.fromSchema(this.editor.schema).parse(r);return setTimeout(async()=>{let e=this.editor.state.tr;o?e.replaceWith(0,this.editor.state.doc.content.size,l):e.insert(t,l);{let t=await new Promise(e=>this.editor.chain().getMeta(e).run())||new Map;for(let e of s)c.setPathValue(t,e.path,e.value);e.setDocAttribute(`meta`,t)}this.editor.dispatchTransaction(e)},0),!0}return!1}},PastePluginKey=new PluginKey(`paste`),ExtensionPaste=class extends Extension{name=`paste`;getProseMirrorPlugins(){let e=this.editor;return[new Plugin({key:PastePluginKey,state:{init(){return PastePluginKey.getState(e.state)||new PasteState(e)},apply(e,t,n,r){if(e.isGeneric)return t;let a=e.getMeta(PastePluginKey);return t.handleCommands(a,e),t}},props:{handleDOMEvents:{copy(t,n){if(!n.clipboardData)return!1;let r=e.clone();return n.preventDefault(),(async()=>{r.state.selection instanceof AllSelection||r.ci.register(`frontmatter`,new BlankFrontmatterServiceImpl),r.chain().keepSelection().run();let e=new TextDecoder().decode(await r.saveDocument(`text/x-markdown`)),t=new TextDecoder().decode(await r.saveDocument(`text/html`));await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([e],{type:`text/plain`}),"text/html":new Blob([t],{type:`text/html`})})])})(),!1}},handlePaste(t,n,r){let{clipboardData:a}=n;if(!a)return!1;if(a.types.includes(`text/html`)){let{from:e}=t.state.selection,r=a.getData(`text/html`);n.preventDefault();let o=t.state.tr.setMeta(PastePluginKey,{pasteHtml:{from:e,html:r}});return t.dispatch(o),!0}[...a.items].map(e=>e.getAsFile()).filter(e=>!!e);let o=Array.from(n.clipboardData?.files||[]);if(o.length===1){let t=o[0];if(e.getMediaTypes().includes(t.type))return t.bytes().then(n=>{e.loadDocument(t.type,n)}),!0}},handleDrop(t,n,r,a){let o=Array.from(n.dataTransfer?.files||[]);if(o.length===1){let t=o[0];if(e.getMediaTypes().includes(t.type))return t.bytes().then(n=>{e.loadDocument(t.type,n)}),!0}}}})]}getCommandFactories(e){return{getPasteRules:e=>(t,n)=>{let r=t.tr;return r.setMeta(PastePluginKey,{getPasteRules:e}),n&&n(r),!0},setPasteRules:e=>(t,n)=>{let r=t.tr;return r.setMeta(PastePluginKey,{setPasteRules:e}),n&&n(r),!0}}}},MarkLink=class extends Mark{name=`link`;requires=[`doc`];getMarkSpec(){return{attrs:{href:{},title:{default:void 0},origUrl:{default:void 0},mdTemplate:{default:void 0}},inclusive:!1,parseDOM:[{tag:`a[href]`,getAttrs(e){return{href:e.getAttribute(`href`),title:e.getAttribute(`title`)}}}],toDOM(e){let{href:t,title:n}=e.attrs;return[`a`,{href:t,title:n},0]}}}},MarkStrong=class extends Mark{name=`strong`;requires=[`doc`];getMarkSpec(){return{parseDOM:[{tag:`strong`},{tag:`b`,getAttrs:e=>e.style.fontWeight!=`normal`&&null},{style:`font-weight=400`,clearMark:e=>e.type.name==`strong`},{style:`font-weight`,getAttrs:e=>/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}],toDOM(){return[`strong`,0]}}}getCommandFactories(e,t){return{toggleStrong:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-b":`toggleStrong`,"Mod-B":`toggleStrong`}}},MarkItalic=class extends Mark{name=`em`;requires=[`doc`];getMarkSpec(){return{parseDOM:[{tag:`i`},{tag:`em`},{style:`font-assets=italic`},{style:`font-assets=normal`,clearMark:e=>e.type.name==`em`}],toDOM(){return[`em`,0]}}}getCommandFactories(e,t){return{toggleItalic:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-i":`toggleItalic`,"Mod-I":`toggleItalic`}}},MarkUnderline=class extends Mark{name=`underline`;requires=[`doc`];getMarkSpec(){return{parseDOM:[{tag:`u`}],toDOM(){return[`u`,0]}}}getCommandFactories(e,t){return{toggleUnderline:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-u":`toggleUnderline`,"Mod-U":`toggleUnderline`}}},MarkStrike=class extends Mark{name=`strike`;requires=[`doc`];getMarkSpec(){return{parseDOM:[{tag:`strike`}],toDOM(){return[`strike`,0]}}}getCommandFactories(e,t){return{toggleStrike:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-s":`toggleStrike`,"Mod-S":`toggleStrike`}}},MarkCode=class extends Mark{name=`code`;requires=[`doc`];getMarkSpec(){return{parseDOM:[{tag:`code`}],toDOM(){return[`code`,0]}}}getCommandFactories(e,t){return{toggleCode:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-`":`toggleCode`}}},MarkChange=class extends Mark{name=`change`;requires=[`doc`];getMarkSpec(){return{parseDOM:[],toDOM(){return[`change`,0]}}}},MarkBookmark=class extends Mark{name=`bookmark`;requires=[`doc`];getMarkSpec(){return{attrs:{id:{}},parseDOM:[],toDOM(e){return[`a`,{id:e.attrs.id},0]}}}},MarkTextColor=class extends Mark{name=`textColor`;getMarkSpec(){return{attrs:{color:{default:null}},parseDOM:[{tag:`span[style*="color"]`,getAttrs(e){let t=e.style.color;return t?{color:t}:!1}}],toDOM(e){let{color:t}=e.attrs;return t?[`span`,{style:`color: ${t}`},0]:[`span`,0]}}}},MarkHighlight=class extends Mark{name=`highlight`;getMarkSpec(){return{attrs:{color:{default:null}},parseDOM:[{tag:`mark`,getAttrs(e){let t=e.style.backgroundColor;return t?{color:t}:{color:`yellow`}}},{tag:`span[style*="background-color"]`,getAttrs(e){let t=e.style.backgroundColor;return t?{color:t}:!1}}],toDOM(e){let{color:t}=e.attrs;return[`mark`,{style:`background-color: ${t||`yellow`}; color: inherit;`},0]}}}},MarkSuperscript=class extends Mark{name=`superscript`;requires=[`doc`];getMarkSpec(){return{excludes:`subscript`,parseDOM:[{tag:`sup`},{style:`vertical-align`,getAttrs:e=>e===`super`&&null}],toDOM(){return[`sup`,0]}}}getCommandFactories(e,t){return{toggleSuperscript:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-Shift-.":`toggleSuperscript`}}},MarkSubscript=class extends Mark{name=`subscript`;requires=[`doc`];getMarkSpec(){return{excludes:`superscript`,parseDOM:[{tag:`sub`},{style:`vertical-align`,getAttrs:e=>e===`sub`&&null}],toDOM(){return[`sub`,0]}}}getCommandFactories(e,t){return{toggleSubscript:()=>e.commandFactories.toggleMark(t)}}getKeyboardShortcuts(){return{"Mod-Shift-,":`toggleSubscript`}}},NodeDocument=class extends Node$2{name=`doc`;getNodeSpec(){return{content:`block+`,attrs:{meta:{default:null}},marks:`code em strong link bookmark`,EMPTY_DOC:{type:this.name,content:[{type:`paragraph`,content:[]}]}}}getCommandFactories(e,t){return{getMeta:e=>(t,n)=>(e(structuredClone(t.doc.attrs.meta)),!0),setMeta:e=>(t,n)=>{let r=t.tr;return r.setDocAttribute(`meta`,e),n&&n(r),r.docChanged},updateMeta:e=>(t,n)=>{let r=t.tr;return r.setDocAttribute(`meta`,e(t.doc.attrs.meta)),n&&n(r),r.docChanged}}}},NodeText=class extends Node$2{name=`text`;getNodeSpec(){return{group:`inline`}}};function wrappingInputRule(e,t,n=null,r){return new InputRule(e,(e,a,o,s,c)=>{e||=a.tr;let l=n instanceof Function?n(o):n;e=e.delete(s,c);let u=e.doc.resolve(s).blockRange(),d=u&&findWrapping(u,t,l);if(!d)return null;e.wrap(u,d);let f=e.doc.resolve(s-1).nodeBefore;return f&&f.type==t&&canJoin(e.doc,s-1)&&(!r||r(o,f))&&e.join(s-1),e})}function textblockTypeInputRule(e,t,n=null){return new InputRule(e,(e,r,a,o,s)=>{e||=r.tr;let c=r.doc.resolve(o),l=n instanceof Function?n(a):n;return c.node(-1).canReplaceWith(c.index(-1),c.indexAfter(-1),t)?e.delete(o,s).setBlockType(o,o,t,l):null})}function replaceInlineNode(e,t,n=null){return new InputRule(e,(e,r,a,o,s)=>{e||=r.tr;let c=n instanceof Function?n(a):n;if(r.doc.resolve(o).parent.type===r.schema.nodes.code_block)return e;let l=t.createAndFill(c),u=e.mapping.map(o),d=e.mapping.map(s);return e.replaceWith(u,d,Fragment.from(l))})}var NodeCodeBlock$1=class extends Node$2{name=`code_block`;getNodeSpec(){return{content:`text*`,marks:``,group:`block`,code:!0,defining:!0,attrs:{lang:{default:void 0}},parseDOM:[{tag:`pre`,preserveWhitespace:`full`,getAttrs(e){return{lang:e.getAttribute(`lang`)}}}],toDOM(e){let{lang:t}=e.attrs;return[`pre`,{lang:t},[`code`,0]]}}}getInputRules(e){return[textblockTypeInputRule(/^```$/,e)]}},NodeBookmark=class extends Node$2{name=`node_bookmark`;requires=[`doc`];getNodeSpec(){return{inline:!0,group:`inline`,selectable:!1,atom:!0,attrs:{id:{},nesting:{default:0}},parseDOM:[],toDOM(e){return[`a`,{id:e.attrs.id},0]}}}},NodeParagraph=class extends Node$2{name=`paragraph`;requires=[`doc`];getNodeSpec(){return{content:`inline*`,group:`block`,attrs:{textAlign:{default:void 0}},parseDOM:[{tag:`p`,getAttrs(e){let t=e.style.textAlign;return t===`center`||t===`right`||t===`justify`?{textAlign:t}:!1}}],toDOM(e){let t=e.attrs.textAlign||`left`;return[`center`,`right`,`justify`].includes(t)?[`p`,{style:`text-align: ${t}`},0]:[`p`,0]}}}getCommandFactories(e,t){return{setParagraph:()=>e.commandFactories.setBlockType(t)}}getKeyboardShortcuts(){return{"Shift-Ctrl-0":`setParagraph`}}},NodeHardBreak=class extends Node$2{name=`br`;requires=[`doc`];options={keepMarks:!0};getNodeSpec(){return{inline:!0,group:`inline`,selectable:!1,linebreakReplacement:!0,parseDOM:[{tag:`br`}],toDOM(){return[`br`]}}}getCommandFactories(e,t){let n=firstCommand(e.run.exitCode);return{setHardBreak:()=>n}}getKeyboardShortcuts(){let e=typeof navigator<`u`?/Mac|iP(hone|[oa]d)/.test(navigator?.platform):!1,t={"Ctrl-Enter":`setHardBreak`};return e&&(t[`Mod-Enter`]=`setHardBreak`,t[`Shift-Enter`]=`setHardBreak`),t}},NodeSoftBreak=class extends Node$2{name=`softbreak`;requires=[`doc`];getNodeSpec(){return{inline:!0,group:`inline`,selectable:!1,parseDOM:[{tag:`wbr`}],toDOM(){return[`wbr`]}}}},NodeHorizontalRule=class extends Node$2{name=`hr`;requires=[`doc`];getNodeSpec(){return{inline:!0,group:`inline`,parseDOM:[{tag:`hr`}],toDOM(){return[`hr`]}}}getCommandFactories(e,t){return{setHorizontalRule:()=>(e,n)=>(n&&n(e.tr.replaceSelectionWith(t.create()).scrollIntoView()),!0)}}getKeyboardShortcuts(){return{"Mod-_":`setHorizontalRule`}}},NodeImage=class extends Node$2{name=`image`;requires=[`doc`];getNodeSpec(){return{inline:!0,attrs:{src:{},alt:{default:null},title:{default:null},width:{default:null},height:{default:null},origUrl:{default:void 0},mdTemplate:{default:void 0}},group:`inline`,draggable:!0,parseDOM:[{tag:`img[src]`,getAttrs(e){return{src:e.getAttribute(`src`),title:e.getAttribute(`title`),alt:e.getAttribute(`alt`),width:e.getAttribute(`width`)||e.style.width||null,height:e.getAttribute(`height`)||e.style.height||null}}}],toDOM(e){let{src:t,alt:n,title:r,width:a,height:o}=e.attrs,s={src:t};return n&&(s.alt=n),r&&(s.title=r),a&&(s.width=a),o&&(s.height=o),[`img`,s]}}}getNodeView(e){return(e,t,n)=>{let r=document.createElement(`span`);r.className=`kb-image-wrapper`,r.contentEditable=`false`;let a=document.createElement(`img`);a.src=e.attrs.src,e.attrs.alt&&(a.alt=e.attrs.alt),e.attrs.title&&(a.title=e.attrs.title),e.attrs.width&&(a.style.width=typeof e.attrs.width==`number`?`${e.attrs.width}px`:e.attrs.width),e.attrs.height&&(a.style.height=typeof e.attrs.height==`number`?`${e.attrs.height}px`:e.attrs.height),a.draggable=!1,r.appendChild(a);let o=[`nw`,`ne`,`sw`,`se`],s=[];for(let e of o){let t=document.createElement(`span`);t.className=`kb-image-resize-handle kb-image-resize-handle-${e}`,t.dataset.position=e,s.push(t),r.appendChild(t)}let c=!1,l=0,u=0,d=0,f=0,p=1,m=null,h=e=>{let t=e.target;if(!t.classList.contains(`kb-image-resize-handle`))return;e.preventDefault(),e.stopPropagation(),c=!0,m=t.dataset.position||null,l=e.clientX,u=e.clientY;let n=a.getBoundingClientRect();d=n.width,f=n.height,p=d/f,r.classList.add(`kb-image-resizing`),document.addEventListener(`mousemove`,g),document.addEventListener(`mouseup`,_)},g=e=>{if(!c)return;let t=e.clientX-l,n=e.clientY-u,r=d,o=f;switch(m){case`se`:r=d+t,o=e.shiftKey?f+n:r/p;break;case`sw`:r=d-t,o=e.shiftKey?f+n:r/p;break;case`ne`:r=d+t,o=e.shiftKey?f-n:r/p;break;case`nw`:r=d-t,o=e.shiftKey?f-n:r/p;break}r=Math.max(50,r),o=Math.max(50,o),a.style.width=`${Math.round(r)}px`,a.style.height=`${Math.round(o)}px`},_=()=>{if(!c)return;c=!1,m=null,r.classList.remove(`kb-image-resizing`),document.removeEventListener(`mousemove`,g),document.removeEventListener(`mouseup`,_);let o=Math.round(a.getBoundingClientRect().width),s=Math.round(a.getBoundingClientRect().height),l=n();if(typeof l==`number`){let n=t.state.tr.setNodeMarkup(l,void 0,{...e.attrs,width:`${o}px`,height:`${s}px`});t.dispatch(n)}};return r.addEventListener(`mousedown`,h),r.addEventListener(`click`,e=>{e.preventDefault();let r=n();if(typeof r==`number`){let e=t.state.doc.resolve(r),n=Selection.near(e);t.dispatch(t.state.tr.setSelection(n))}}),{dom:r,update:e=>e.type.name===`image`?(a.src=e.attrs.src,e.attrs.alt&&(a.alt=e.attrs.alt),e.attrs.title&&(a.title=e.attrs.title),e.attrs.width?a.style.width=typeof e.attrs.width==`number`?`${e.attrs.width}px`:e.attrs.width:a.style.width=``,e.attrs.height?a.style.height=typeof e.attrs.height==`number`?`${e.attrs.height}px`:e.attrs.height:a.style.height=``,!0):!1,destroy:()=>{r.removeEventListener(`mousedown`,h),document.removeEventListener(`mousemove`,g),document.removeEventListener(`mouseup`,_)},stopEvent:e=>e.type===`mousedown`&&e.target.classList.contains(`kb-image-resize-handle`),ignoreMutation:()=>!0}}}},NodeVideo=class extends Node$2{name=`video`;requires=[`doc`];getNodeSpec(){return{attrs:{src:{},title:{default:null},controls:{default:!0},width:{default:null},height:{default:null}},group:`block`,draggable:!0,parseDOM:[{tag:`video[src]`,getAttrs(e){return{src:e.getAttribute(`src`),title:e.getAttribute(`title`),controls:e.hasAttribute(`controls`),width:e.getAttribute(`width`),height:e.getAttribute(`height`)}}}],toDOM(e){let{src:t,title:n,controls:r,width:a,height:o}=e.attrs,s={src:t};return n&&(s.title=n),r&&(s.controls=``),a&&(s.width=a),o&&(s.height=o),[`video`,s]}}}},NodeBlockquote=class extends Node$2{name=`blockquote`;requires=[`doc`];getNodeSpec(){return{content:`block+`,group:`block`,defining:!0,parseDOM:[{tag:`blockquote`}],toDOM(){return[`blockquote`,0]}}}getInputRules(e){return[wrappingInputRule(/^\s*>\s$/,e)]}getCommandFactories(e,t){return{toggleBlockquote:()=>e.commandFactories.wrapInList(t)}}getKeyboardShortcuts(){return{"Ctrl->":`toggleBlockquote`}}},NodeAside=class extends Node$2{name=`aside`;requires=[`doc`];getNodeSpec(){return{content:`block+`,group:`block`,defining:!0,parseDOM:[{tag:`aside`}],toDOM(){return[`aside`,0]}}}},maxLevel=6,NodeHeading=class extends Node$2{name=`heading`;requires=[`doc`];getNodeSpec(){return{attrs:{level:{default:1}},content:`inline*`,group:`block`,defining:!0,parseDOM:[{tag:`h1`,attrs:{level:1}},{tag:`h2`,attrs:{level:2}},{tag:`h3`,attrs:{level:3}},{tag:`h4`,attrs:{level:4}},{tag:`h5`,attrs:{level:5}},{tag:`h6`,attrs:{level:6}}],toDOM(e){return[`h`+e.attrs.level,0]}}}getInputRules(e){return[textblockTypeInputRule(RegExp(`^(#{1,6})\\s$`),e,e=>({level:e[1].length}))]}getCommandFactories(e,t){let n={};for(let r=1;r<=maxLevel;r++)n[`setHeading`+r]=()=>e.commandFactories.setBlockType(t,{level:r});return n}getKeyboardShortcuts(){let e={};for(let t=1;t<=maxLevel;t++)e[`Shift-Ctrl-`+t]=`setHeading`+t;return e}},NodeMath=class extends Node$2{name=`math`;requires=[`doc`];getNodeSpec(){return{inline:!0,attrs:{lang:{default:`mathml`},content:{}},group:`inline`,draggable:!0,parseDOM:[{tag:`math`,getAttrs:e=>({lang:`mathml`,content:new XMLSerializer().serializeToString(e)})}],toDOM(e){let t=new DOMParser().parseFromString(e.attrs.content,`application/xml`);return t.getElementsByTagName(`parsererror`).length>0?[`span`,{class:`mathml-error`},`Invalid MathML`]:document.importNode(t.documentElement,!0)}}}},NodeDefinitionList=class extends Node$2{name=`dl`;requires=[`doc`];getNodeSpec(){return{content:`dt+|dd+`,group:`block`,parseDOM:[{tag:`dl`}],toDOM(){return[`dl`,0]}}}getInputRules(e){return[]}getCommandFactories(e,t){return{toggleDefinitionList:()=>e.commandFactories.wrapInList(t)}}getKeyboardShortcuts(){return{}}},NodeDefinitionTerm=class extends Node$2{name=`dt`;requires=[`dl`];getNodeSpec(){return{content:`inline*`,group:`block`,parseDOM:[{tag:`dt`}],defining:!0,toDOM(){return[`dt`,0]}}}},NodeDefinitionDesc=class extends Node$2{name=`dd`;requires=[`dl`];getNodeSpec(){return{content:`inline*`,group:`block`,parseDOM:[{tag:`dd`}],defining:!0,toDOM(){return[`dd`,0]}}}};function fixCharacters$1(e){return e.replace(/’/g,`'`).replace(/“/g,`"`).replace(/”/g,`"`).replace(/\x0b/g,` `).replace(/\u201d/g,`"`).replace(/\u201c/g,`"`)}function replaceAllNodesOfType(e,t,n,r){let a=[];t.descendants((e,t)=>{e.type===n&&a.push({node:e,pos:t})});for(let t=a.length-1;t>=0;t--){let{node:n,pos:o}=a[t],s=r(n,e.doc.type.schema);e=e.replaceWith(o,o+n.nodeSize,s)}return e}var NodeInlineShortCode=class extends Node$2{name=`shortcode_inline`;requires=[`doc`];getNodeSpec(){return{inline:!0,group:`inline`,selectable:!0,atom:!0,attrs:{id:{default:void 0},content:{default:``},nesting:{default:0},error:{default:``}},parseDOM:[{tag:`span.kb-shortcode-inline`,getAttrs:e=>({content:e.textContent||null})}],toDOM(e){return[`span`,{class:`kb-shortcode-inline`},e.attrs.content||``]}}}getInputRules(e){return[replaceInlineNode(/\{\{[^}]+\}\}/,e,e=>({content:fixCharacters$1(e[0].substring(2,e[0].length-2))}))]}getCommandFactories(e,t){return{renderShortCode:e=>(n,r)=>{let a=n.tr;return a=replaceAllNodesOfType(a,n.doc,t,e),a.docChanged&&r&&r(a),!0}}}},NodeIframe=class extends Node$2{name=`iframe`;requires=[`doc`];getNodeSpec(){return{inline:!0,attrs:{src:{},class:{default:null},alt:{default:null},title:{default:null}},group:`inline`,draggable:!0,parseDOM:[{tag:`iframe[src]`,getAttrs(e){return{src:e.getAttribute(`src`),title:e.getAttribute(`title`),alt:e.getAttribute(`alt`)}}}],toDOM(e){let{src:t,alt:n,title:r}=e.attrs;return[`iframe`,{src:t,alt:n,title:r,class:e.attrs.class}]}}}};function collectCommentAnchors(e){let t=new Map,n=new Map;return e.descendants((e,r)=>{e.type.name===`comment`&&(e.attrs.nesting===1&&t.set(e.attrs.id,r),e.attrs.nesting===-1&&n.set(e.attrs.id,r))}),{starts:t,ends:n}}function buildCommentRanges(e){let{starts:t,ends:n}=collectCommentAnchors(e),r=[];for(let[e,a]of t){let t=n.get(e);!t||t<=a||r.push({id:e,from:a+1,to:t})}return r}function buildDecorations(e){let t=buildCommentRanges(e);return DecorationSet.create(e,t.map(({id:e,from:t,to:n})=>Decoration.inline(t,n,{class:`comment-highlight`,"data-comment-id":e})))}function commentsPlugin(){return new Plugin({state:{init(e,{doc:t}){return buildDecorations(t)},apply(e,t,n,r){return e.docChanged?buildDecorations(r.doc):t}},props:{decorations(e){return this.getState(e)}}})}var addCommentBoundary=e=>(t,n)=>{let{schema:r,selection:a}=t,{from:o,to:s}=a,c=r.nodes.comment;if(!c)return!1;let l=c.create({id:e,nesting:1}),u=c.create({id:e,nesting:-1}),d=t.tr;return d.insert(s,u),d.insert(o,l),n&&n(d),!0},NodeCommentAnchor=class extends Node$2{name=`comment`;requires=[`doc`];options={keepMarks:!0};getNodeSpec(){return{inline:!0,group:`inline`,selectable:!1,atom:!0,attrs:{id:{},active:{default:!1},nesting:{default:1}},parseDOM:[{tag:`span[data-comment-id]`,getAttrs(e){return{id:e.getAttribute(`data-comment-id`),nesting:parseInt(e.getAttribute(`data-nesting`)||`1`),active:e.hasAttribute(`data-active`)}}}],toDOM:e=>[`span`,{"data-comment-id":e.attrs.id,"data-active":e.attrs.active?`true`:void 0,"data-nesting":e.attrs.nesting}]}}getCommandFactories(e,t){return{addComment:(e,t)=>addCommentBoundary(e,t)}}getProseMirrorPlugins(){return[commentsPlugin()]}};function splitListItem(e,t){let n=function(n,r){let{$from:a,$to:o,node:s}=n.selection;if(s&&s.isBlock||a.depth<2||!a.sameParent(o))return!1;let c=a.node(-1);if(c.type!=e)return!1;if(a.parent.content.size==0&&a.node(-1).childCount==a.indexAfter(-1)){if(a.depth==3||a.node(-3).type!=e||a.index(-2)!=a.node(-2).childCount-1)return!1;if(r){let t=Fragment.empty,o=a.index(-1)?1:a.index(-2)?2:3;for(let e=a.depth-o;e>=a.depth-3;e--)t=Fragment.from(a.node(e).copy(t));let s=a.indexAfter(-1)<a.node(-2).childCount?1:a.indexAfter(-2)<a.node(-3).childCount?2:3;t=t.append(Fragment.from(e.createAndFill()));let c=a.before(a.depth-(o-1)),l=n.tr.replace(c,a.after(-s),new Slice(t,4-o,0)),u=-1;l.doc.nodesBetween(c,l.doc.content.size,(e,t)=>{if(u>-1)return!1;e.isTextblock&&e.content.size==0&&(u=t+1)}),u>-1&&l.setSelection(Selection.near(l.doc.resolve(u))),r(l.scrollIntoView())}return!0}let l=o.pos==a.end()?c.contentMatchAt(0).defaultType:null,u=n.tr.delete(a.pos,o.pos),d=l?[t?{type:e,attrs:t}:null,{type:l}]:void 0;return canSplit(u.doc,a.pos,2,d)?(r&&r(u.split(a.pos,2,d).scrollIntoView()),!0):!1};return n.displayName=`splitListItem(${e.name})`,n}function liftListItem(e){return function(t,n){let{$from:r,$to:a}=t.selection,o=r.blockRange(a,t=>t.childCount>0&&t.firstChild.type==e);return o?n?r.node(o.depth-1).type==e?liftToOuterList(t,n,e,o):liftOutOfList(t,n,o):!0:!1}}function liftToOuterList(e,t,n,r){let a=e.tr,o=r.end,s=r.$to.end(r.depth);o<s&&(a.step(new ReplaceAroundStep(o-1,s,o,s,new Slice(Fragment.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new NodeRange(a.doc.resolve(r.$from.pos),a.doc.resolve(s),r.depth));let c=liftTarget(r);if(c==null)return!1;a.lift(r,c);let l=a.doc.resolve(a.mapping.map(o,-1)-1);return canJoin(a.doc,l.pos)&&l.nodeBefore.type==l.nodeAfter.type&&a.join(l.pos),t(a.scrollIntoView()),!0}function liftOutOfList(e,t,n){let r=e.tr,a=n.parent;for(let e=n.end,t=n.endIndex-1,o=n.startIndex;t>o;t--)e-=a.child(t).nodeSize,r.delete(e-1,e+1);let o=r.doc.resolve(n.start),s=o.nodeAfter;if(r.mapping.map(n.end)!=n.start+o.nodeAfter.nodeSize)return!1;let c=n.startIndex==0,l=n.endIndex==a.childCount,u=o.node(-1),d=o.index(-1);if(!u.canReplace(d+ +!c,d+1,s.content.append(l?Fragment.empty:Fragment.from(a))))return!1;let f=o.pos,p=f+s.nodeSize;return r.step(new ReplaceAroundStep(f-+!!c,p+ +!!l,f+1,p-1,new Slice((c?Fragment.empty:Fragment.from(a.copy(Fragment.empty))).append(l?Fragment.empty:Fragment.from(a.copy(Fragment.empty))),+!c,+!l),+!c)),t(r.scrollIntoView()),!0}function sinkListItem(e){return function(t,n){let{$from:r,$to:a}=t.selection,o=r.blockRange(a,t=>t.childCount>0&&t.firstChild.type==e);if(!o)return!1;let s=o.startIndex;if(s==0)return!1;let c=o.parent,l=c.child(s-1);if(l.type!=e)return!1;if(n){let r=l.lastChild&&l.lastChild.type==c.type,a=Fragment.from(r?e.create():null),s=new Slice(Fragment.from(e.create(null,Fragment.from(c.type.create(null,a)))),r?3:1,0),u=o.start,d=o.end;n(t.tr.step(new ReplaceAroundStep(u-(r?3:1),d,u,d,s,1,!0)).scrollIntoView())}return!0}}var isList=e=>e.endsWith(`_list`),clearNodes=()=>(e,t)=>{let n=e.tr,{selection:r}=n,{ranges:a}=r;return t&&a.forEach(({$from:t,$to:r})=>{e.doc.nodesBetween(t.pos,r.pos,(e,t)=>{if(e.type.isText)return;let{doc:r,mapping:a}=n,o=r.resolve(a.map(t)),s=r.resolve(a.map(t+e.nodeSize)),c=o.blockRange(s);if(!c)return;let l=liftTarget(c);if(e.type.isTextblock){let{defaultType:e}=o.parent.contentMatchAt(o.index());n.setNodeMarkup(c.start,e)}(l||l===0)&&n.lift(c,l)})}),!0};function findParentNodeClosestToPos(e,t){for(let n=e.depth;n>0;--n){let r=e.node(n);if(t(r))return{pos:n>0?e.before(n):0,start:e.start(n),depth:n,node:r}}}function findParentNode(e){return t=>findParentNodeClosestToPos(t.$from,e)}var joinListBackwards=(e,t)=>{let n=findParentNode(e=>e.type===t)(e.selection);if(!n)return!0;let r=e.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;let a=e.doc.nodeAt(r);return n.node.type===a?.type&&canJoin(e.doc,n.pos)&&e.join(n.pos),!0},joinListForwards=(e,t)=>{let n=findParentNode(e=>e.type===t)(e.selection);if(!n)return!0;let r=e.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;let a=e.doc.nodeAt(r);return n.node.type===a?.type&&canJoin(e.doc,r)&&e.join(r),!0},toggleList=(e,t,n,r={})=>function(a,o,s){if(!this)throw Error(`Call this with Function.apply`);let c=this.editor,l=Object.keys(a.schema.marks).filter(e=>e!==`link`),u=a.schema.nodes[e],d=a.schema.nodes[t],{selection:f,storedMarks:p}=a,{$from:m,$to:h}=f,g=m.blockRange(h),_=p||(f.$to.parentOffset?f.$from.marks():[]);if(!g)return!1;let v=findParentNode(e=>isList(e.type.name))(f),y=a.tr;if(g.depth>=1&&v&&g.depth-v.depth<=1){if(v.node.type===u)return liftListItem(d).apply(this,[a,o,s]);if(isList(v.node.type.name)&&u.validContent(v.node.content)&&o)return c.chain(y).command(()=>(y.setNodeMarkup(v.pos,u),!0)).command(()=>joinListBackwards(y,u)).command(()=>joinListForwards(y,u)).command(()=>o(y)).run()}return!n||!_||!o?c.chain(y).command(()=>c.can().wrapInList(u,r).run()?!0:c.chain(y).lift().run()).wrapInList(u,r).command(()=>joinListBackwards(y,u)).command(()=>joinListForwards(y,u)).command(()=>(o&&o(y),!0)).run():c.chain(y).command(()=>{let e=c.can().wrapInList(u,r).run(),t=_.filter(e=>l.includes(e.type.name));return y.ensureMarks(t),e?!0:(v&&y.setSelection(NodeSelection.create(a.doc,v.pos)),clearNodes().apply(this,[a,o,s]))}).wrapInList(u,r).command(()=>joinListBackwards(y,u)).command(()=>joinListForwards(y,u)).command(()=>(o&&o(y),!0)).run()},NodeOrderedList=class extends Node$2{name=`ordered_list`;requires=[`doc`];attributes={type:{default:`1`,fromDom(e){return e.hasAttribute(`type`)?e.getAttribute(`type`):`1`}},start:{default:void 0,fromDom(e){return e.hasAttribute(`start`)?+e.getAttribute(`start`):void 0}},id:{default:void 0},continue:{default:void 0},odtMarginLeft:{default:void 0}};getNodeSpec(){return{content:`list_item+`,group:`block list`,parseDOM:[{tag:`ol`,getAttrs:e=>setHtmlAttributes(this,e)}],toDOM:e=>[`ol`,getHtmlAttributes(this,e),0]}}getInputRules(e){return[wrappingInputRule(/^(\d+)\.\s$/,e,e=>({order:+e[1]}),(e,t)=>t.childCount+t.attrs.order==+e[1])]}getCommandFactories(e,t){let n=!1;return{toggleOrderedList:()=>toggleList(`ordered_list`,`list_item`,!1)}}getKeyboardShortcuts(){return{"Shift-Ctrl-7":`toggleOrderedList`}}},NodeBulletList=class extends Node$2{name=`bullet_list`;requires=[`doc`];attributes={toc:{default:void 0},odtMarginLeft:{default:void 0}};getNodeSpec(){return{content:`list_item+`,group:`block list`,parseDOM:[{tag:`ul`}],toDOM(){return[`ul`,0]}}}getInputRules(e){return[wrappingInputRule(/^\s*([-+*])\s$/,e)]}getCommandFactories(e,t){let n=!1;return{toggleBulletList:()=>toggleList(`bullet_list`,`list_item`,!1)}}getKeyboardShortcuts(){return{"Shift-Ctrl-8":`toggleBulletList`}}},NodeListItem=class extends Node$2{name=`list_item`;requires=[`doc`];attributes={value:{default:void 0},type:{default:void 0,fromDom(e){return e.hasAttribute(`type`)?e.getAttribute(`type`):void 0},toDom(e){return e.attrs.type}}};getNodeSpec(){return{content:`paragraph block*`,defining:!0,parseDOM:[{tag:`li`,getAttrs:e=>setHtmlAttributes(this,e)}],toDOM:e=>[`li`,getHtmlAttributes(this,e),0]}}getCommandFactories(e,t){return{splitListItem:()=>splitListItem(t),liftListItem:()=>liftListItem(t),sinkListItem:()=>sinkListItem(t)}}getKeyboardShortcuts(){return{Enter:`splitListItem`,Tab:`sinkListItem`,"Shift-Tab":`liftListItem`}}},NodeTaskList=class extends Node$2{name=`task_list`;requires=[`doc`];getNodeSpec(){return{content:`task_item+`,group:`block list`,parseDOM:[{tag:`ul[data-type="${this.name}"]`}],toDOM:()=>[`ul`,{"data-type":this.name},0]}}getCommandFactories(){return{toggleTaskList:()=>toggleList(`task_list`,`task_item`)}}getKeyboardShortcuts(){return{"Shift-Ctrl-9":`toggleTaskList`}}},NodeViewTaskItem=class e{editor;dom;contentDOM;checkbox;node;view;getPos;config={};constructor(e,...t){this.editor=e,this.node=t[0],this.view=t[1],this.getPos=t[2];let n=document.createElement(`li`);this.dom=n;let r=document.createElement(`label`);r.contentEditable=`false`;let a=document.createElement(`input`);this.checkbox=a,a.type=`checkbox`,a.checked=this.node.attrs.checked,r.append(a);let o=document.createElement(`div`);this.contentDOM=o,n.append(r,o),n.dataset.checked=this.node.attrs.checked,a.addEventListener(`mousedown`,e=>e.preventDefault()),a.addEventListener(`change`,t=>{let n=this.getPos();if(typeof n!=`number`)return;this.editor.view.editable;let{checked:r}=t.target,a=e.state.tr,o=a.doc.nodeAt(n);a.setNodeMarkup(n,void 0,{...o?.attrs,checked:r}),e.dispatchTransaction(a)})}static create=(t,...n)=>new e(t,...n);update(e){return e.type.name===this.node.type.name?(this.dom.dataset.checked=e.attrs.checked,this.checkbox.checked=e.attrs.checked,!0):!1}},NodeTaskItem=class extends Node$2{config;name=`task_item`;requires=[`doc`];constructor(e={nested:!0}){super(e),this.config=e}getNodeSpec(){return{attrs:{checked:{default:!1}},content:this.config.nested?`paragraph block*`:`paragraph+`,defining:!0,parseDOM:[{tag:`li[data-checked]`,getAttrs(e){return{checked:e.getAttribute(`data-checked`)===`true`}}}],toDOM:e=>[`li`,{"data-type":this.name,"data-checked":e.attrs.checked},[`label`,[`input`,{type:`checkbox`,checked:e.attrs.checked?`checked`:null},[`span`]],[`div`,0]]]}}getCommandFactories(e,t){return{splitListItem:()=>splitListItem(t),liftListItem:()=>liftListItem(t),sinkListItem:()=>sinkListItem(t)}}getNodeView(e){return(...t)=>NodeViewTaskItem.create(e,...t)}getKeyboardShortcuts(){return{Enter:`splitListItem`,Tab:`sinkListItem`,"Shift-Tab":`liftListItem`}}getInputRules(e){return[wrappingInputRule(/^\s*(\[([( |x])?\])\s$/,e,e=>({checked:e[e.length-1]===`x`}))]}},BasicEditorKit=class{getExtensions(){return[new ExtensionBaseKeymap,new ExtensionDropcursor,new ExtensionGapcursor,new ExtensionHtml,new ExtensionMediaUpload,new ExtensionRemoteSelection,new ExtensionSelection,new ExtensionTextAlign,new ExtensionPairing,new ExtensionUser,new ExtensionPaste,new NodeDocument,new NodeText,new NodeParagraph,new NodeHardBreak,new NodeSoftBreak,new NodeCodeBlock$1,new NodeBookmark,new NodeHorizontalRule,new NodeOrderedList,new NodeBulletList,new NodeListItem,new NodeTaskList,new NodeTaskItem,new NodeDefinitionList,new NodeDefinitionTerm,new NodeDefinitionDesc,new NodeTaskList,new NodeTaskItem,new NodeImage,new NodeVideo,new NodeBlockquote,new NodeAside,new NodeHeading,new NodeMath,new NodeInlineShortCode,new NodeIframe,new NodeCommentAnchor,new MarkLink,new MarkItalic,new MarkStrong,new MarkUnderline,new MarkStrike,new MarkCode,new MarkChange,new MarkBookmark,new MarkTextColor,new MarkHighlight,new MarkSuperscript,new MarkSubscript]}},kit=new BasicEditorKit,ExtensionBasicEditor=class extends Extension{name=`basic-editor`;requires=kit.getExtensions()},GOOD_LEAF_SIZE=200,RopeSequence=class e{append(t){return t.length?(t=e.from(t),!this.length&&t||t.length<GOOD_LEAF_SIZE&&this.leafAppend(t)||this.length<GOOD_LEAF_SIZE&&t.leafPrepend(this)||this.appendInner(t)):this}prepend(t){return t.length?e.from(t).append(this):this}appendInner(e){return new Append(this,e)}slice(e=0,t=this.length){return e>=t?emptyRopeSequence():this.sliceInner(Math.max(0,e),Math.min(this.length,t))}get(e){if(!(e<0||e>=this.length))return this.getInner(e)}forEach(e,t=0,n=this.length){t<=n?this.forEachInner(e,t,n,0):this.forEachInvertedInner(e,t,n,0)}map(e,t=0,n=this.length){let r=[];return this.forEach((t,n)=>(r.push(e(t,n)),t),t,n),r}static from(t){return t instanceof e?t:t&&t.length?new Leaf(t):emptyRopeSequence()}},Leaf=class e extends RopeSequence{values;constructor(e){super(),this.values=e}flatten(){return this.values}sliceInner(t,n){return t==0&&n==this.length?this:new e(this.values.slice(t,n))}getInner(e){return this.values[e]}forEachInner(e,t,n,r){for(let a=t;a<n;a++)if(e(this.values[a],r+a)===!1)return!1;return!0}forEachInvertedInner(e,t,n,r){for(let a=t-1;a>=n;a--)if(e(this.values[a],r+a)===!1)return!1;return!0}leafAppend(t){if(this.length+t.length<=GOOD_LEAF_SIZE)return new e(this.values.concat(t.flatten()))}leafPrepend(t){if(this.length+t.length<=GOOD_LEAF_SIZE)return new e(t.flatten().concat(this.values))}get length(){return this.values.length}get depth(){return 0}};function emptyRopeSequence(){return new Leaf([])}var Append=class e extends RopeSequence{left;right;depth;length;constructor(e,t){super(),this.left=e,this.right=t,this.length=e.length+t.length,this.depth=Math.max(e.depth,t.depth)+1}flatten(){return this.left.flatten().concat(this.right.flatten())}getInner(e){return e<this.left.length?this.left.get(e):this.right.get(e-this.left.length)}forEachInner(e,t,n,r){let a=this.left.length;return!(t<a&&this.left.forEachInner(e,t,Math.min(n,a),r)===!1||n>a&&this.right.forEachInner(e,Math.max(t-a,0),Math.min(this.length,n)-a,r+a)===!1)}forEachInvertedInner(e,t,n,r){let a=this.left.length;return!(t>a&&this.right.forEachInvertedInner(e,t-a,Math.max(n,a)-a,r+a)===!1||n<a&&this.left.forEachInvertedInner(e,Math.min(t,a),n,r)===!1)}sliceInner(e,t){if(e==0&&t==this.length)return this;let n=this.left.length;return t<=n?this.left.slice(e,t):e>=n?this.right.slice(e-n,t-n):this.left.slice(e,n).append(this.right.slice(0,t-n))}leafAppend(t){let n=this.right.leafAppend(t);if(n)return new e(this.left,n)}leafPrepend(t){let n=this.left.leafPrepend(t);if(n)return new e(n,this.right)}appendInner(t){return this.left.depth>=Math.max(this.right.depth,t.depth)+1?new e(this.left,new e(this.right,t)):new e(this,t)}},max_empty_items=500,Branch=class e{items;eventCount;constructor(e,t){this.items=e,this.eventCount=t}popEvent(t,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let a,o;n&&(a=this.remapping(r,this.items.length),o=a.maps.length);let s=t.tr,c,l,u=[],d=[];return this.items.forEach((t,n)=>{if(!t.step)return a||(a=this.remapping(r,n+1),o=a.maps.length),o--,d.push(t),t;if(a){d.push(new Item(t.map));let e=t.step.map(a.slice(o)),n;e&&s.maybeStep(e).doc&&(n=s.mapping.maps[s.mapping.maps.length-1],u.push(new Item(n,void 0,void 0,u.length+d.length))),o--,n&&a.appendMap(n,o)}else s.maybeStep(t.step);return t.selection?(c=a?t.selection.map(a.slice(o)):t.selection,l=new e(this.items.slice(0,r).append(d.reverse().concat(u)),this.eventCount-1),!1):t},this.items.length,0),{remaining:l,transform:s,selection:c}}addTransform(t,n,r,a){let o=[],s=this.eventCount,c=this.items,l=!a&&c.length?c.get(c.length-1):null;for(let e=0;e<t.steps.length;e++){let r=t.steps[e].invert(t.docs[e]),u=new Item(t.mapping.maps[e],r,n),d;(d=l&&l.merge(u))&&(u=d,e?o.pop():c=c.slice(0,c.length-1)),o.push(u),n&&=(s++,void 0),a||(l=u)}let u=s-r.depth;return u>DEPTH_OVERFLOW&&(c=cutOffEvents(c,u),s-=u),new e(c.append(o),s)}remapping(e,t){let n=new Mapping;return this.items.forEach((t,r)=>{let a=t.mirrorOffset!=null&&r-t.mirrorOffset>=e?n.maps.length-t.mirrorOffset:void 0;return n.appendMap(t.map,a),t},e,t),n}addMaps(t){return this.eventCount==0?this:new e(this.items.append(t.map(e=>new Item(e))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],a=Math.max(0,this.items.length-n),o=t.mapping,s=t.steps.length,c=this.eventCount;this.items.forEach(e=>(e.selection&&c--,e),a);let l=n;this.items.forEach(e=>{let n=o.getMirror(--l);if(n==null)return!1;s=Math.min(s,n);let a=o.maps[n];if(e.step){let s=t.steps[n].invert(t.docs[n]),u=e.selection&&e.selection.map(o.slice(l+1,n));u&&c++,r.push(new Item(a,s,u))}else r.push(new Item(a));return e},a);let u=[];for(let e=n;e<s;e++)u.push(new Item(o.maps[e]));let d=new e(this.items.slice(0,a).append(u).append(r),c);return d.emptyItemCount()>max_empty_items&&(d=d.compress(this.items.length-r.length)),d}emptyItemCount(){let e=0;return this.items.forEach(t=>(t.step||e++,t)),e}compress(t=this.items.length){let n=this.remapping(0,t),r=n.maps.length,a=[],o=0;return this.items.forEach((e,s)=>{if(s>=t)a.push(e),e.selection&&o++;else if(e.step){let t=e.step.map(n.slice(r)),s=t&&t.getMap();if(r--,s&&n.appendMap(s,r),t){let c=e.selection&&e.selection.map(n.slice(r));c&&o++;let l=new Item(s.invert(),t,c),u,d=a.length-1;(u=a.length&&a[d].merge(l))?a[d]=u:a.push(l)}}else e.map&&r--;return e},this.items.length,0),new e(RopeSequence.from(a.reverse()),o)}static empty=new e(emptyRopeSequence(),0)};function cutOffEvents(e,t){let n;return e.forEach((e,r)=>e.selection&&t--==0?(n=r,!1):e),e.slice(n)}var Item=class e{map;step;selection;mirrorOffset;constructor(e,t,n,r){this.map=e,this.step=t,this.selection=n,this.mirrorOffset=r}merge(t){if(this.step&&t.step&&!t.selection){let n=t.step.merge(this.step);if(n)return new e(n.getMap().invert(),n,this.selection)}}},HistoryState=class{done;undone;prevRanges;prevTime;prevComposition;constructor(e,t,n,r,a){this.done=e,this.undone=t,this.prevRanges=n,this.prevTime=r,this.prevComposition=a}},DEPTH_OVERFLOW=20;function applyTransaction(e,t,n,r){let a=n.getMeta(historyKey),o;if(a)return a.historyState;n.getMeta(closeHistoryKey)&&(e=new HistoryState(e.done,e.undone,null,0,-1));let s=n.getMeta(`appendedTransaction`);if(n.steps.length==0)return e;if(s&&s.getMeta(historyKey))return s.getMeta(historyKey).redo?new HistoryState(e.done.addTransform(n,void 0,r,mustPreserveItems(t)),e.undone,rangesFor(n.mapping.maps),e.prevTime,e.prevComposition):new HistoryState(e.done,e.undone.addTransform(n,void 0,r,mustPreserveItems(t)),null,e.prevTime,e.prevComposition);if(n.getMeta(`addToHistory`)!==!1&&!(s&&s.getMeta(`addToHistory`)===!1)){let a=n.getMeta(`composition`),o=e.prevTime==0||!s&&e.prevComposition!=a&&(e.prevTime<(n.time||0)-r.newGroupDelay||!isAdjacentTo(n,e.prevRanges)),c=s?mapRanges(e.prevRanges,n.mapping):rangesFor(n.mapping.maps);return new HistoryState(e.done.addTransform(n,o?t.selection.getBookmark():void 0,r,mustPreserveItems(t)),Branch.empty,c,n.time,a??e.prevComposition)}else if(o=n.getMeta(`rebased`))return new HistoryState(e.done.rebased(n,o),e.undone.rebased(n,o),mapRanges(e.prevRanges,n.mapping),e.prevTime,e.prevComposition);else return new HistoryState(e.done.addMaps(n.mapping.maps),e.undone.addMaps(n.mapping.maps),mapRanges(e.prevRanges,n.mapping),e.prevTime,e.prevComposition)}function isAdjacentTo(e,t){if(!t)return!1;if(!e.docChanged)return!0;let n=!1;return e.mapping.maps[0].forEach((e,r)=>{for(let a=0;a<t.length;a+=2)e<=t[a+1]&&r>=t[a]&&(n=!0)}),n}function rangesFor(e){let t=[];for(let n=e.length-1;n>=0&&t.length==0;n--)e[n].forEach((e,n,r,a)=>t.push(r,a));return t}function mapRanges(e,t){if(!e)return null;let n=[];for(let r=0;r<e.length;r+=2){let a=t.map(e[r],1),o=t.map(e[r+1],-1);a<=o&&n.push(a,o)}return n}function histTransaction(e,t,n){let r=mustPreserveItems(t),a=historyKey.get(t).spec.config,o=(n?e.undone:e.done).popEvent(t,r);if(!o)return null;let s=o.selection.resolve(o.transform.doc),c=(n?e.done:e.undone).addTransform(o.transform,t.selection.getBookmark(),a,r),l=new HistoryState(n?c:o.remaining,n?o.remaining:c,null,0,-1);return o.transform.setSelection(s).setMeta(historyKey,{redo:n,historyState:l})}var cachedPreserveItems=!1,cachedPreserveItemsPlugins=null;function mustPreserveItems(e){let t=e.plugins;if(cachedPreserveItemsPlugins!=t){cachedPreserveItems=!1,cachedPreserveItemsPlugins=t;for(let e=0;e<t.length;e++)if(t[e].spec.historyPreserveItems){cachedPreserveItems=!0;break}}return cachedPreserveItems}var historyKey=new PluginKey(`history`),closeHistoryKey=new PluginKey(`closeHistory`);function history$1(e={}){return e={depth:e.depth||100,newGroupDelay:e.newGroupDelay||500},new Plugin({key:historyKey,state:{init(){return new HistoryState(Branch.empty,Branch.empty,null,0,-1)},apply(t,n,r){return applyTransaction(n,r,t,e)}},config:e,props:{handleDOMEvents:{beforeinput(e,t){let n=t.inputType,r=n==`historyUndo`?undo:n==`historyRedo`?redo:null;return!r||!e.editable?!1:(t.preventDefault(),r(e.state,e.dispatch))}}}})}function buildCommand(e,t){return(n,r)=>{let a=historyKey.getState(n);if(!a||(e?a.undone:a.done).eventCount==0)return!1;if(r){let o=histTransaction(a,n,e);o&&r(t?o.scrollIntoView():o)}return!0}}var undo=buildCommand(!1,!0),redo=buildCommand(!0,!0),undoNoScroll=buildCommand(!1,!1),redoNoScroll=buildCommand(!0,!1),ExtensionHistory$1=class extends Extension{name=`history`;options={depth:100,newGroupDelay:500};getCommandFactories(e){return{undo:()=>undo,redo:()=>redo}}getKeyboardShortcuts(){let e=typeof navigator<`u`?/Mac|iP(hone|[oa]d)/.test(navigator?.platform):!1,t={"Mod-z":`undo`,"Mod-y":`redo`};return e||(t[`Mod-y`]=`redo`),t}getProseMirrorPlugins(){return[history$1(this.options)]}},Token=class{type;tag;nesting;attrs=null;map=null;level=0;children=null;content=``;markup=``;info=``;meta=null;block=!1;hidden=!1;constructor(e,t,n){this.type=e,this.tag=t,this.nesting=n}attrIndex(e){if(!this.attrs)return-1;let t=this.attrs;for(let n=0,r=t.length;n<r;n++)if(t[n][0]===e)return n;return-1}attrPush(e){this.attrs?this.attrs.push(e):this.attrs=[e]}attrSet(e,t){let n=this.attrIndex(e),r=[e,t];n<0||!this.attrs?this.attrPush(r):this.attrs[n]=r}attrGet(e){let t=this.attrIndex(e),n=null;return t>=0&&this.attrs&&(n=this.attrs[t][1]),n}attrJoin(e,t){let n=this.attrIndex(e);n<0||!this.attrs?this.attrPush([e,t]):this.attrs[n][1]=this.attrs[n][1]+` `+t}},Brackets={left:[`(`,`[`,`{`,`|`,`‖`,`⟨`,`⌊`,`⌈`,`⌜`],right:[`)`,`]`,`}`,`|`,`‖`,`⟩`,`⌋`,`⌉`,`⌝`],isPair:function(e,t){let n=this.left.indexOf(e);return t===this.right[n]},contains:function(e){return this.isLeft(e)||this.isRight(e)},isLeft:function(e){return this.left.indexOf(e)>-1},isRight:function(e){return this.right.indexOf(e)>-1},parseLeft:function(e,t=!0){if(this.left.indexOf(e)<0)return e;let n=``;switch(e){case`(`:case`[`:case`|`:n=`\\left${e}`;break;case`‖`:n=`\\left\\|`;break;case`{`:n=`\\left\\{`;break;case`⟨`:n=`\\left\\langle `;break;case`⌊`:n=`\\left\\lfloor `;break;case`⌈`:n=`\\left\\lceil `;break;case`⌜`:n=`\\left\\ulcorner `;break}return t?n:n.replace(`\\left`,``)},parseRight:function(e,t=!0){if(this.right.indexOf(e)<0)return e;let n=``;switch(e){case`)`:case`]`:case`|`:n=`\\right${e}`;break;case`‖`:n=`\\right\\|`;break;case`}`:n=`\\right\\}`;break;case`⟩`:n=` \\right\\rangle`;break;case`⌋`:n=` \\right\\rfloor`;break;case`⌉`:n=` \\right\\rceil`;break;case`⌝`:n=` \\right\\urcorner`;break}return t?n:n.replace(`\\right`,``)}},MathSymbol={parseIdentifier:function(e){if(e.length===0)return``;if(e.length===1){let t=e.charCodeAt(0),n=this.greekLetter.decimals.indexOf(t);return n>-1?this.greekLetter.scripts[n]+` `:e}else return this.parseMathFunction(e)},parseOperator:function(e){if(e.length===0)return``;if(e.length===1){let t=e.charCodeAt(0),n=[this.bigCommand,this.relation,this.binaryOperation,this.setAndLogic,this.delimiter,this.other],r=[!1,!0,!0,!1,!1,!1];for(let e=0;e<n.length;e++){let a=n[e],o=a.decimals.indexOf(t);if(o>-1)return r[e]?[` `,a.scripts[o],` `].join(``):a.scripts[o]+` `}return e}else return this.parseMathFunction(e)},parseMathFunction:function(e){let t=T.createMarker(),n=[];return this.mathFunction.names.forEach((r,a)=>{let o=new RegExp(r,`g`);e.match(o)&&(n.push(this.mathFunction.scripts[a]),e=e.replace(o,t.next()+` `))}),t.replaceBack(e,n)},overScript:{decimals:[9182],templates:[`\\overbrace{@v}`]},underScript:{decimals:[9183],templates:[`\\underbrace{@v}`]},bigCommand:{decimals:[8721,8719,8720,10753,10754,10752,8899,8898,10756,10758,8897,8896,8747,8750,8748,8749,10764,8747],scripts:[`\\sum`,`\\prod`,`\\coprod`,`\\bigoplus`,`\\bigotimes`,`\\bigodot`,`\\bigcup`,`\\bigcap`,`\\biguplus`,`\\bigsqcup`,`\\bigvee`,`\\bigwedge`,`\\int`,`\\oint`,`\\iint`,`\\iiint`,`\\iiiint`,`\\idotsint`]},relation:{decimals:[60,62,61,8741,8742,8804,8805,8784,8781,8904,8810,8811,8801,8866,8867,8834,8835,8776,8712,8715,8838,8839,8773,8995,8994,8840,8841,8771,8872,8713,8847,8848,126,8764,8869,8739,8849,8850,8733,8826,8827,10927,10928,8800,8738,8737],scripts:`<.>.=.\\parallel.\\nparallel.\\leq.\\geq.\\doteq.\\asymp.\\bowtie.\\ll.\\gg.\\equiv.\\vdash.\\dashv.\\subset.\\supset.\\approx.\\in.\\ni.\\subseteq.\\supseteq.\\cong.\\smile.\\frown.\\nsubseteq.\\nsupseteq.\\simeq.\\models.\\notin.\\sqsubset.\\sqsupset.\\sim.\\sim.\\perp.\\mid.\\sqsubseteq.\\sqsupseteq.\\propto.\\prec.\\succ.\\preceq.\\succeq.\\neq.\\sphericalangle.\\measuredangle`.split(`.`)},binaryOperation:{decimals:[43,45,177,8745,8900,8853,8723,8746,9651,8854,215,8846,9661,8855,247,8851,9667,8856,8727,8852,9657,8857,8902,8744,9711,8728,8224,8743,8729,8726,8225,8901,8768,10815],scripts:`+.-.\\pm.\\cap.\\diamond.\\oplus.\\mp.\\cup.\\bigtriangleup.\\ominus.\\times.\\uplus.\\bigtriangledown.\\otimes.\\div.\\sqcap.\\triangleleft.\\oslash.\\ast.\\sqcup.\\triangleright.\\odot.\\star.\\vee.\\bigcirc.\\circ.\\dagger.\\wedge.\\bullet.\\setminus.\\ddagger.\\cdot.\\wr.\\amalg`.split(`.`)},setAndLogic:{decimals:[8707,8594,8594,8708,8592,8592,8704,8614,172,10233,8834,8658,10233,8835,8596,8712,10234,8713,8660,8715,8868,8743,8869,8744,8709,8709],scripts:`\\exists.\\rightarrow.\\to.\\nexists.\\leftarrow.\\gets.\\forall.\\mapsto.\\neg.\\implies.\\subset.\\Rightarrow.\\implies.\\supset.\\leftrightarrow.\\in.\\iff.\\notin.\\Leftrightarrow.\\ni.\\top.\\land.\\bot.\\lor.\\emptyset.\\varnothing`.split(`.`)},delimiter:{decimals:[124,8739,8214,47,8726,123,125,10216,10217,8593,8657,8968,8969,8595,8659,8970,8971],scripts:[`|`,`\\mid`,`\\|`,`/`,`\\backslash`,`\\{`,`\\}`,`\\langle`,`\\rangle`,`\\uparrow`,`\\Uparrow`,`\\lceil`,`\\rceil`,`\\downarrow`,`\\Downarrow`,`\\lfloor`,`\\rfloor`]},greekLetter:{decimals:[913,945,925,957,914,946,926,958,915,947,927,959,916,948,928,960,982,917,1013,949,929,961,1009,918,950,931,963,962,919,951,932,964,920,952,977,933,965,921,953,934,981,966,922,954,1008,935,967,923,955,936,968,924,956,937,969],scripts:`A.\\alpha.N.\\nu.B.\\beta.\\Xi.\\xi.\\Gamma.\\gamma.O.o.\\Delta.\\delta.\\Pi.\\pi.\\varpi.E.\\epsilon.\\varepsilon.P.\\rho.\\varrho.Z.\\zeta.\\Sigma.\\sigma.\\varsigma.H.\\eta.T.\\tau.\\Theta.\\theta.\\vartheta.\\Upsilon.\\upsilon.I.\\iota.\\Phi.\\phi.\\varphi.K.\\kappa.\\varkappa.X.\\chi.\\Lambda.\\lambda.\\Psi.\\psi.M.\\mu.\\Omega.\\omega`.split(`.`)},other:{decimals:[8706,305,8476,8711,8501,240,567,8465,9723,8502,8463,8467,8472,8734,8503],scripts:[`\\partial`,`\\imath`,`\\Re`,`\\nabla`,`\\aleph`,`\\eth`,`\\jmath`,`\\Im`,`\\Box`,`\\beth`,`\\hbar`,`\\ell`,`\\wp`,`\\infty`,`\\gimel`]},mathFunction:{names:`arcsin.sinh.sin.sec.arccos.cosh.cos.csc.arctan.tanh.tan.arccot.coth.cot.limsup.liminf.exp.ker.deg.gcd.lg.ln.Pr.sup.det.hom.lim.log.arg.dim.inf.max.min`.split(`.`),scripts:`\\arcsin.\\sinh.\\sin.\\sec.\\arccos.\\cosh.\\cos.\\csc.\\arctan.\\tanh.\\tan.\\arccot.\\coth.\\cot.\\limsup.\\liminf.\\exp.\\ker.\\deg.\\gcd.\\lg.\\ln.\\Pr.\\sup.\\det.\\hom.\\lim.\\log.\\arg.\\dim.\\inf.\\max.\\min`.split(`.`)}},T={};T.createMarker=function(){return{idx:-1,reReplace:/@\[\[(\d+)\]\]/gm,next:function(){return`@[[${++this.idx}]]`},replaceBack:function(e,t){return e.replace(this.reReplace,(e,n)=>t[parseInt(n)])}}};var root=typeof window<`u`?window:{};function canParseHTMLNatively(){let e=root.DOMParser,t=!1;try{new e().parseFromString(``,`text/html`)&&(t=!0)}catch{}return t}function createHTMLParser(){let e=function(){};return shouldUseActiveX()?e.prototype.parseFromString=function(e){let t=new window.ActiveXObject(`htmlfile`);return t.designMode=`on`,t.open(),t.write(e),t.close(),t}:e.prototype.parseFromString=function(e){let t=document.implementation.createHTMLDocument(``);return t.open(),t.write(e),t.close(),t},e}function shouldUseActiveX(){let e=!1;try{document.implementation.createHTMLDocument(``).open()}catch{window.ActiveXObject&&(e=!0)}return e}var HTMLParser=canParseHTMLNatively()?root.DOMParser:createHTMLParser(),NodeTool={parseMath:function(e){return new HTMLParser().parseFromString(e,`text/html`).querySelector(`math`)},getChildren:function(e){return e.children},getNodeName:function(e){return e.tagName.toLowerCase()},getNodeText:function(e){return e.textContent},getAttr:function(e,t,n){let r=e.getAttribute(t);return r===null?n:r},getPrevNode:function(e){return e.previousElementSibling},getNextNode:function(e){return e.nextElementSibling}};function convert(e){return toLatex(parse(NodeTool.parseMath(e)))}function toLatex(e){return e=e.replace(/\\left\(\\DELETE_BRACKET_L/g,``),e=e.replace(/\\DELETE_BRACKET_R\\right\)/g,``),e=e.replace(/\\DELETE_BRACKET_L/g,``),e=e.replace(/\\DELETE_BRACKET_R/g,``),e}function parse(e){let t=NodeTool.getChildren(e);return!t||t.length===0?parseLeaf(e):parseContainer(e,t)}function parseLeaf(e){let t=``;switch(NodeTool.getNodeName(e)){case`mi`:t=parseElementMi(e);break;case`mn`:t=parseElementMn(e);break;case`mo`:t=parseOperator(e);break;case`ms`:t=parseElementMs(e);break;case`mtext`:t=parseElementMtext(e);break;case`mglyph`:t=parseElementMglyph(e);break;case`mprescripts`:t=``;break;case`mspace`:t=parseElementMspace();case`none`:t=`\\:`;break;default:t=escapeSpecialChars(NodeTool.getNodeText(e).trim());break}return t}function parseOperator(e){let t=NodeTool.getNodeText(e).trim();return t=MathSymbol.parseOperator(t),escapeSpecialChars(t)}function parseElementMi(e){let t=NodeTool.getNodeText(e).trim();return t=MathSymbol.parseIdentifier(t),escapeSpecialChars(t)}function parseElementMn(e){return escapeSpecialChars(NodeTool.getNodeText(e).trim())}function parseElementMs(e){return[`"`,escapeSpecialChars(NodeTool.getNodeText(e).trimRight()),`"`].join(``)}function parseElementMtext(e){return`\\text{${escapeSpecialChars(NodeTool.getNodeText(e))}}`}function parseElementMglyph(e){return escapeSpecialChars([`"`,NodeTool.getAttr(e,`alt`,``),`"`].join(``))}function parseElementMspace(e){return``}function escapeSpecialChars(e){return e=e.replace(/\$|%|_|&|#|\{|\}/g,e=>`\\${e}`),e}function parseContainer(e,t){let n=getRender(e);if(n)return n(e,t);throw Error(`Couldn't get render function for container node: ${NodeTool.getNodeName(e)}`)}function renderChildren(e){let t=[],n=[];if(Array.prototype.forEach.call(e,e=>{if(NodeTool.getNodeName(e)===`mo`){let r=NodeTool.getNodeText(e).trim();if(Brackets.contains(r)){let a=NodeTool.getAttr(e,`stretchy`,`true`);if(a=[``,`true`].indexOf(a)>-1,Brackets.isRight(r)){let e=n[n.length-1];e&&Brackets.isPair(e,r)?(t.push(Brackets.parseRight(r,a)),n.pop()):Brackets.isLeft(r)?(t.push(Brackets.parseLeft(r,a)),n.push(r)):console.error(`bracket not match`)}else t.push(Brackets.parseLeft(r,a)),n.push(r)}else t.push(parseOperator(e))}else t.push(parse(e))}),n.length>0)for(let e=0;e<n.length;e++)t.push(`\\right.`);return n=void 0,t}function getRender(e){let t;switch(NodeTool.getNodeName(e)){case`msub`:t=getRender_default(`@1_{@2}`);break;case`msup`:t=getRender_default(`@1^{@2}`);break;case`msubsup`:t=getRender_default(`@1_{@2}^{@3}`);break;case`mover`:t=renderMover;break;case`munder`:t=renderMunder;break;case`munderover`:t=getRender_default(`@1\\limits_{@2}^{@3}`);break;case`mmultiscripts`:t=renderMmultiscripts;break;case`mroot`:t=getRender_default(`\\sqrt[@2]{@1}`);break;case`msqrt`:t=getRender_joinSeparator(`\\sqrt{@content}`);break;case`mtable`:t=renderTable;break;case`mtr`:t=getRender_joinSeparator(`@content \\\\ `,` & `);break;case`mtd`:t=getRender_joinSeparator(`@content`);break;case`mfrac`:t=renderMfrac;break;case`mfenced`:t=renderMfenced;break;case`mi`:case`mn`:case`mo`:case`ms`:case`mtext`:t=getRender_joinSeparator(`@content`);break;case`mphantom`:t=renderMphantom;break;default:t=getRender_joinSeparator(`@content`);break}return t}function renderTable(e,t){return getRender_joinSeparator(`\\begin{matrix} @content \\end{matrix}`)(e,t)}function renderMfrac(e,t){let[n,r]=[NodeTool.getAttr(e,`linethickness`,`medium`),NodeTool.getAttr(e,`bevelled`,`false`)],a=null;if(r===`true`)a=getRender_default(`{}^{@1}/_{@2}`);else if([`0`,`0px`].indexOf(n)>-1){let[t,n]=[NodeTool.getPrevNode(e),NodeTool.getNextNode(e)];a=t&&NodeTool.getNodeText(t).trim()===`(`&&n&&NodeTool.getNodeText(n).trim()===`)`?getRender_default(`\\DELETE_BRACKET_L\\binom{@1}{@2}\\DELETE_BRACKET_R`):getRender_default(`{}_{@2}^{@1}`)}else a=getRender_default(`\\frac{@1}{@2}`);return a(e,t)}function renderMfenced(e,t){let[n,r,a]=[NodeTool.getAttr(e,`open`,`(`),NodeTool.getAttr(e,`close`,`)`),NodeTool.getAttr(e,`separators`,`,`)],[o,s]=[Brackets.parseLeft(n),Brackets.parseRight(r)],c=a.split(``).filter(e=>e.trim().length===1);return getRender_joinSeparators(`${o}@content${s}`,c)(e,t)}function renderMmultiscripts(e,t){if(t.length===0)return``;let n=-1,r=null;Array.prototype.forEach.call(t,e=>{NodeTool.getNodeName(e)===`mprescripts`&&(r=e)}),r&&(n=Array.prototype.indexOf.call(t,r));let a=renderChildren(t),o=(e,t)=>[e.slice(0,t),e.slice(t+1,e.length)],s=e=>{if(e.length>0){let t=[],n=[];return e.forEach((e,r)=>{(r+1)%2==0?n.push(e):t.push(e)}),[t.length>0?`_{${t.join(` `)}}`:``,n.length>0?`^{${n.join(` `)}}`:``].join(``)}else return``},c=a.shift(),l=[],u=[];return n===-1?u=a:[u,l]=o(a,n-1),[s(l),c,s(u)].join(``)}function renderMover(e,t){let n=flattenNodeTreeByNodeName(e,`mover`),r;for(let e=0;e<n.length-1;e++){r||=parse(n[e]);let t=parse(n[e+1]);r=renderTemplate(getMatchValueByChar({decimals:MathSymbol.overScript.decimals,values:MathSymbol.overScript.templates,judgeChar:t,defaultValue:`@1\\limits^{@2}`}).replace(`@v`,`@1`),[r,t])}return r}function renderMunder(e,t){let n=flattenNodeTreeByNodeName(e,`munder`),r;for(let e=0;e<n.length-1;e++){r||=parse(n[e]);let t=parse(n[e+1]);r=renderTemplate(getMatchValueByChar({decimals:MathSymbol.underScript.decimals,values:MathSymbol.underScript.templates,judgeChar:t,defaultValue:`@1\\limits_{@2}`}).replace(`@v`,`@1`),[r,t])}return r}function flattenNodeTreeByNodeName(e,t){let n=[],r=NodeTool.getChildren(e);return Array.prototype.forEach.call(r,e=>{NodeTool.getNodeName(e)===t?n=n.concat(flattenNodeTreeByNodeName(e,t)):n.push(e)}),n}function getMatchValueByChar(e){let{decimals:t,values:n,judgeChar:r,defaultValue:a=null}=e;if(r&&r.length===1){let e=t.indexOf(r.charCodeAt(0));if(e>-1)return n[e]}return a}function renderMphantom(e,t){return``}function getRender_default(e){return function(t,n){return renderTemplate(e,renderChildren(n))}}function renderTemplate(e,t){return e.replace(/\@\d+/g,e=>t[parseInt(e.substring(1,e.length))-1])}function getRender_joinSeparator(e,t=``){return function(n,r){let a=renderChildren(r);return e.replace(`@content`,a.join(t))}}function getRender_joinSeparators(e,t){return function(n,r){let a=renderChildren(r),o=``;return o=t.length===0?a.join(``):a.reduce((e,n,r)=>(e+=n,r<a.length-1&&(e+=t[r]||t[t.length-1]),e),``),e.replace(`@content`,o)}}var mathml2latex={convert};function fixCharacters(e){return e.replace(/’/g,`'`).replace(/“/g,`"`).replace(/”/g,`"`).replace(/\x0b/g,` `).replace(/\u201d/g,`"`).replace(/\u201c/g,`"`)}function numberString(e,t=`1`){return[`a`].includes(t)?String.fromCharCode(97+e-1)+`. `:[`A`].includes(t)?String.fromCharCode(65+e-1)+`. `:[`I`].includes(t)?`${romanize(e)}. `:[`i`].includes(t)?`${romanize(e).toLowerCase()}. `:([`1`].includes(t),`${e}. `)}function romanize(e){let t=[[`M`,1e3],[`CM`,900],[`D`,500],[`CD`,400],[`C`,100],[`XC`,90],[`L`,50],[`XL`,40],[`X`,10],[`IX`,9],[`V`,5],[`IV`,4],[`I`,1]],n=``;for(let[r,a]of t)for(;e>=a;)n+=r,e-=a;return n}function escapeMarkdown(e){let t=[{char:`\\`,escape:`\\\\`},{char:`#`,escape:`\\#`},{char:`<`,escape:`\\<`},{char:`…`,escape:`...`},{char:`©`,escape:`(c)`},{char:`®`,escape:`(r)`},{char:`™`,escape:`(tm)`},{char:`±`,escape:`+-`},{char:`—`,escape:`---`}],n=e.map&&e.map.length>0?e.map[0]:0;if(!n){let n=fixCharacters(e.content);for(let{char:e,escape:r}of t)n=n.replaceAll(e,r);return[[n,e]]}let r=fixCharacters(e.content).split(``),a=[],o=Object.fromEntries(t.map(e=>[e.char,e.escape])),s=0,c=``,l=``,u=()=>{if(l.length>0){let t=structuredClone(e);t.map=[n+s],a.push([l,t]),s=c.length}l=``};for(let e=0;e<r.length;e++){let t=r[e];c+=t,o[t]&&u(),l+=o[t]||t,o[t]&&u()}return u(),a}function getLinkTokensHandlers(){return{text:[(e,t)=>{t.current.meta.link_text+=e.content,e.content&&!t.current.meta.link_token_token&&(t.current.meta.link_token_token=e)}],link_close:[(e,t)=>{{let n=t.current.meta.link_open_token,r=n.attrGet(`href`)||``,a=n.attrGet(`title`)||``,o=n.attrGet(`origUrl`)||r,s=t.current.meta.link_text;o===s&&(s=r);let c=n.attrGet(`mdTemplate`);if(c){let n=r.split(`/`).pop();c=c.replaceAll(`$href`,r),c=c.replaceAll(`$basename`,n||``),c=c.replaceAll(`$label`,t.current.meta.link_text),c=c.replaceAll(`$title`,a||``),t.current.log(c,e)}else!a&&s===r?t.current.log(r,e):!a&&!r?(t.current.log(`[`,e),t.current.log(s,t.current.meta.link_token_token),t.current.log(`]${a}`,e)):(t.current.log(`[`,e),t.current.log(s,t.current.meta.link_token_token),a?t.current.log(`](${r} ${a})`,e):t.current.log(`](${r})`,e));t.unstash(`getLinkTokensHandlers.link_close`)}}],default:[(e,t)=>{}]}}function getInlineTokensHandlers(){return{text:[(e,t)=>{if(e.meta===`noEscText`)t.current.log(e.content);else for(let n of escapeMarkdown(e))t.current.log(n[0],n[1])}],entity:[(e,t)=>{t.current.log(e.content)}],strong_open:[(e,t)=>{t.current.log(e.markup||`**`,e)}],strong_close:[(e,t)=>{t.current.log(e.markup||`**`,e)}],em_open:[(e,t)=>{t.current.log(e.markup||`*`,e)}],em_close:[(e,t)=>{t.current.log(e.markup||`*`,e)}],underline_open:[(e,t)=>{t.current.log(e.markup||`_`,e)}],underline_close:[(e,t)=>{t.current.log(e.markup||`_`,e)}],strike_open:[(e,t)=>{t.current.log(e.markup||`~`,e)}],strike_close:[(e,t)=>{t.current.log(e.markup||`~`,e)}],link_open:[(e,t)=>{t.stash(`getInlineTokensHandlers.link_open`),t.current.handlers=getLinkTokensHandlers(),t.current.meta.link_open_token=e,t.current.meta.link_text=``,t.current.meta.link_token_token=null}],code_open:[(e,t)=>{t.current.log("`",e)}],code_close:[(e,t)=>{t.current.log("`",e)}],code_inline:[(e,t)=>{t.current.log("`"+e.content+"`",e)}],math:[(e,t)=>{let n=e.content;if(e.attrGet(`lang`)===`mathml`){let e=n.replace(/<annotation[\s\S]*?<\/annotation>/g,``);n=mathml2latex.convert(e)}t.current.log(`$`+n+`$`,e)}],hardbreak:[(e,t)=>{t.current.log(t.current.lineBreak+`
20
26
  `,e)}],softbreak:[(e,t)=>{t.current.log(`
21
- `,e)}],image:[(e,t)=>{{let n=e.attrGet(`src`),r=e.attrGet(`alt`)||``;if(e.children)for(let t of e.children)t.type===`text`&&(r+=t.content);let a=`![$alt]`,o=e.attrGet(`title`);n&&(o?a+=`($src $title)`:a+=`($src)`),a=e.attrGet(`mdTemplate`)||a,a=a.replaceAll(`$alt`,r),a=a.replaceAll(`$label`,r),a=a.replaceAll(`$src`,n||``),a=a.replaceAll(`$title`,o||``),t.current.log(a,e)}}],html_block:[(e,t)=>{t.current.log(e.content,e)}],footnote_ref:[(e,t)=>{e.meta.label?t.current.log(`[^${e.meta.label}]`,e):t.current.log(`[^footnote_${e.meta.id}]`,e)}],shortcode_inline:[(e,t)=>{t.current.log(`{{`+e.content+`}}`,e)}],bookmark:[(e,t)=>{t.current.log(`<a id="${e.attrGet(`id`)}"></a>`,e)}]}}function escapeHtml$1(e){return e}function getHtmlInlineFormatTokensHandlers(){return{strong_open:[(e,t)=>{let n=e.tag||`strong`;t.current.log(`<${n}>`,e)}],strong_close:[(e,t)=>{let n=e.tag||`strong`;t.current.log(`</${n}>`,e)}],em_open:[(e,t)=>{let n=e.tag||`em`;t.current.log(`<${n}>`,e)}],em_close:[(e,t)=>{let n=e.tag||`em`;t.current.log(`</${n}>`,e)}],strike_open:[(e,t)=>{let n=e.tag||`strike`;t.current.log(`<${n}>`,e)}],strike_close:[(e,t)=>{let n=e.tag||`strike`;t.current.log(`</${n}>`,e)}],underline_open:[(e,t)=>{let n=e.tag||`u`;t.current.log(`<${n}>`,e)}],underline_close:[(e,t)=>{let n=e.tag||`u`;t.current.log(`</${n}>`,e)}]}}function getHtmlInlineTokensHandlers(){return{text:[(e,t)=>{t.current.log(escapeHtml$1(e.content),e)}],...getHtmlInlineFormatTokensHandlers(),link_open:[(e,t)=>{t.stash(`getHtmlInlineTokensHandlers.link_open`);let n=e.attrGet(`href`)||``,r=e.attrGet(`title`);r&&``+r,t.current.log(`<a href="${n}">`,e)}],link_close:[(e,t)=>{t.current.log(`</a>`,e),t.unstash(`getHtmlInlineTokensHandlers.link_close`)}],code_open:[(e,t)=>{let n=e.tag||`code`;t.current.log(`<${n}>`,e)}],code_close:[(e,t)=>{let n=e.tag||`code`;t.current.log(`<${n}>`,e)}],math:[(e,t)=>{t.current.log(`<math xmlns="http://www.w3.org/1998/Math/MathML">`,e),t.current.log(e.content,e),t.current.log(`</math>`,e)}],hardbreak:[(e,t)=>{let n=e.tag||`br`;t.current.log(`<${n} />`,e)}],softbreak:[(e,t)=>{let n=e.tag||`wbr`;t.current.log(`<${n} />`,e)}],image:[(e,t)=>{{let n=``;if(e.children)for(let t of e.children)t.type===`text`&&(n+=t.content);let r=e.tag||`img`;t.current.log(`<${r} />`,e)}}],html_block:[(e,t)=>{t.current.log(e.content,e)}],footnote_ref:[(e,t)=>{}],shortcode_inline:[(e,t)=>{t.current.log(`{{`+e.content+`}}`,e)}],bookmark:[(e,t)=>{t.current.log(`<a id="${e.attrGet(`id`)}"></a>`,e)}]}}function getHtmlBasicTokensHandlers(){return{frontmatter:[],heading_open:[(e,t)=>{t.current.log(`<${e.tag}>`,e)}],heading_close:[(e,t)=>{t.current.log(`</${e.tag}>\n`,e)}],paragraph_open:[(e,t)=>{t.current.log(`<p>`,e)}],paragraph_close:[(e,t)=>{t.current.log(`</p>
27
+ `,e)}],image:[(e,t)=>{{let n=e.attrGet(`src`),r=e.attrGet(`alt`)||``;if(e.children)for(let t of e.children)t.type===`text`&&(r+=t.content);let a=`![$alt]`,o=e.attrGet(`title`);n&&(o?a+=`($src $title)`:a+=`($src)`),a=e.attrGet(`mdTemplate`)||a,a=a.replaceAll(`$alt`,r),a=a.replaceAll(`$label`,r),a=a.replaceAll(`$src`,n||``),a=a.replaceAll(`$title`,o||``),t.current.log(a,e)}}],html_block:[(e,t)=>{t.current.log(e.content,e)}],footnote_ref:[(e,t)=>{e.meta.label?t.current.log(`[^${e.meta.label}]`,e):t.current.log(`[^footnote_${e.meta.id}]`,e)}],shortcode_inline:[(e,t)=>{t.current.log(`{{`+e.content+`}}`,e)}],bookmark:[(e,t)=>{t.current.log(`<a id="${e.attrGet(`id`)}"></a>`,e)}]}}function escapeHtml$1(e){return e}function getHtmlInlineFormatTokensHandlers(){return{strong_open:[(e,t)=>{let n=e.tag||`strong`;t.current.log(`<${n}>`,e)}],strong_close:[(e,t)=>{let n=e.tag||`strong`;t.current.log(`</${n}>`,e)}],em_open:[(e,t)=>{let n=e.tag||`em`;t.current.log(`<${n}>`,e)}],em_close:[(e,t)=>{let n=e.tag||`em`;t.current.log(`</${n}>`,e)}],strike_open:[(e,t)=>{let n=e.tag||`strike`;t.current.log(`<${n}>`,e)}],strike_close:[(e,t)=>{let n=e.tag||`strike`;t.current.log(`</${n}>`,e)}],underline_open:[(e,t)=>{let n=e.tag||`u`;t.current.log(`<${n}>`,e)}],underline_close:[(e,t)=>{let n=e.tag||`u`;t.current.log(`</${n}>`,e)}]}}function getHtmlInlineTokensHandlers(){return{text:[(e,t)=>{t.current.log(escapeHtml$1(e.content),e)}],entity:[(e,t)=>{t.current.log(e.content,e)}],...getHtmlInlineFormatTokensHandlers(),link_open:[(e,t)=>{t.stash(`getHtmlInlineTokensHandlers.link_open`);let n=e.attrGet(`href`)||``,r=e.attrGet(`title`);r&&``+r,t.current.log(`<a href="${n}">`,e)}],link_close:[(e,t)=>{t.current.log(`</a>`,e),t.unstash(`getHtmlInlineTokensHandlers.link_close`)}],code_open:[(e,t)=>{let n=e.tag||`code`;t.current.log(`<${n}>`,e)}],code_close:[(e,t)=>{let n=e.tag||`code`;t.current.log(`<${n}>`,e)}],math:[(e,t)=>{t.current.log(`<math xmlns="http://www.w3.org/1998/Math/MathML">`,e),t.current.log(e.content,e),t.current.log(`</math>`,e)}],hardbreak:[(e,t)=>{let n=e.tag||`br`;t.current.log(`<${n} />`,e)}],softbreak:[(e,t)=>{let n=e.tag||`wbr`;t.current.log(`<${n} />`,e)}],image:[(e,t)=>{{let n=``;if(e.children)for(let t of e.children)t.type===`text`&&(n+=t.content);let r=e.tag||`img`;t.current.log(`<${r} />`,e)}}],html_block:[(e,t)=>{t.current.log(e.content,e)}],footnote_ref:[(e,t)=>{}],shortcode_inline:[(e,t)=>{t.current.log(`{{`+e.content+`}}`,e)}],bookmark:[(e,t)=>{t.current.log(`<a id="${e.attrGet(`id`)}"></a>`,e)}]}}function getHtmlBasicTokensHandlers(){return{frontmatter:[],heading_open:[(e,t)=>{t.current.log(`<${e.tag}>`,e)}],heading_close:[(e,t)=>{t.current.log(`</${e.tag}>\n`,e)}],paragraph_open:[(e,t)=>{t.current.log(`<p>`,e)}],paragraph_close:[(e,t)=>{t.current.log(`</p>
22
28
  `,e)}],fence:[(e,t)=>{t.current.log(`<pre>`+e.content+`</pre>
23
29
  `,e)}],code_block:[(e,t)=>{t.current.log(`<pre>`+e.content+`</pre>
24
30
  `,e)}],hr:[(e,t)=>{t.current.log(`<hr />
@@ -97,10 +103,10 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const require
97
103
  `),!this.endsWithEmptyLine)){if(e.nesting!==-1&&e.level===0){let n=t[e.level];if(n?.type&&n.attrGet(`margin_after`)&&e.attrGet(`margin_before`)){let t=n.type.endsWith(`_list_close`)&&e.type.endsWith(`_list_open`),r=n.type===`bullet_list_close`&&e.type===`bullet_list_open`,a=e.attrGet(`first_level_type`)===`none`,o=n?.attrGet(`first_level_type`)===`none`;(!a&&!o&&!r||!t)&&this.ctx.current.log(`
98
104
  `)}}else if(e.nesting!==-1&&e.level===1&&e.type===`dt_open`){let n=t[e.level]?.type||``;[`dt_close`,`dd_close`].includes(n)&&this.ctx.current.log(`
99
105
  `)}}if(e.nesting!==-1&&e.level>0){let n=t[e.level]?.type||``;[`paragraph_close`].includes(n)&&this.ctx.current.blockquoteCnt===e.level&&writeIndented(this.ctx.output,`
100
- `,this.ctx.current,e)}let a=this.ctx.current.handlers[e.type]||this.ctx.current.handlers.default;if(e.type===`inline`){if(e.children){this.ctx.stash(`serializeInlineTokens()`),this.ctx.current.log=(e,t)=>{writeIndented(this.ctx.output,e,this.ctx.current,t)};try{serializeInlineTokens(this.ctx,n,e.children),this.ctx.unstash(`serializeInlineTokens()`)}catch(e){if(this.ctx.current.debug(e.message),e.message===`Rewinded before inline tokens`)return;throw e}}}else if(a){for(let t of a)if(t(e,this.ctx,n))break}else throw this.ctx.current.debug(`current.handlers`,Object.keys(this.ctx.current.handlers).sort()),Error(`Unknown token: ${e.type} `+JSON.stringify(e));t[e.level]=e,e.nesting===-1&&(t[e.level+1]=new Token(``,``,e.nesting))}),this.ctx.output}},blankMark={open:``,close:``,mixable:!0},blankNode$1={open:``,close:``};function generateInlineTokens(e){let t=[],n=-1,r=``;for(let[a,o]of e){if(r.length>0){let e=new Token(`text`,``,0);e.meta=`generateInline1`,e.map=[n],e.content=r,t.push(e)}r=``,n=o,r+=a}if(r.length>0){let e=new Token(`text`,``,0);e.meta=`generateInline2`,e.map=[n],e.content=r,t.push(e)}return t}var nullNode={isText:!1,attrs:{},text:``,marks:[]},DocumentMarkdownInlineTokenizer=class{nodes;marks;options;schema;constructor(e,t,n,r){this.nodes=e,this.marks=t,this.options=n,this.schema=r}getMark(e){return this.marks[e]||blankMark}async renderInline(e,t,n){let r=[],a=[],o=[],s=async(s,c,l)=>{let u=t+c,d=s?s.marks:[];`type`in s&&s.type.name===this.options.hardBreakNodeName&&(d=d.filter(t=>{if(l+1==e.childCount)return!1;let n=e.child(l+1);return t.isInSet(n.marks)&&(!n.isText||/\S/.test(n.text))}));let f=a.splice(0,a.length);if(s?.isText&&d.some(e=>{let t=this.getMark(e.type.name);return t&&t.expelEnclosingWhitespace&&!e.isInSet(r)})){let[e,t,n]=/^(\s*)(.*)$/m.exec(s.text);t&&(f.push([t,u]),s=n?this.schema.text(n,s.marks):nullNode,s||(d=r))}if(s&&s.isText&&d.some(t=>{let n=this.getMark(t.type.name);return n&&n.expelEnclosingWhitespace&&(l==e.childCount-1||!t.isInSet(e.child(l+1).marks))})){let[e,t,n]=/^(.*?)(\s*)$/m.exec(s.text);n&&(a.push([n,u]),s=t?this.schema.text(t,s.marks):nullNode,s||(d=r))}let p=d.length?d[d.length-1]:null,m=p&&this.getMark(p.type.name).escape===!1,h=d.length-+!!m;outer:for(let e=0;e<h;e++){let t=d[e];if(!this.getMark(t.type.name).mixable)break;for(let n=0;n<r.length;n++){let a=r[n];if(!this.getMark(a.type.name).mixable)break;if(t.eq(a)){e>n?d=d.slice(0,n).concat(t).concat(d.slice(n,e)).concat(d.slice(e+1,h)):n>e&&(d=d.slice(0,e).concat(d.slice(e+1,n)).concat(t).concat(d.slice(n,h)));continue outer}}}let g=0;for(;g<Math.min(r.length,h)&&d[g].eq(r[g]);)++g;for(;g<r.length;){let e=r.pop();await this.markString(e,!1,o)}for(o.push(...generateInlineTokens(f.splice(0,f.length)));r.length<h;){let e=d[r.length];r.push(e),await this.markString(e,!0,o)}if(m&&s.isText){if(await this.markString(p,!0,o),s.text){let e=new Token(`text`,``,0);e.meta=`noEscText`,e.map=[u],e.content=s.text,o.push(e)}await this.markString(p,!1,o)}else{let e=`type`in s&&this.nodes[s.type.name]?this.nodes[s.type.name](s,t):blankNode$1,r=``;if(`type`in s&&s.type.spec.toDOM){let e=s.type.spec.toDOM(s);Array.isArray(e)&&e.length>0&&(r=e[0])}if(e.selfClose){if(typeof e.selfClose==`string`){let t=new Token(e.selfClose,r,0);t.meta=`nodeSpec.selfClose`,t.level=n,t.map=[u],o.push(t)}else if(`type`in s){let t=await e.selfClose(s,u,l);t.meta=`!nodeSpec.selfClose`,t.level=n,t.map=[u],o.push(t)}}}},c=0;for(let t=0;t<e.childCount;t++){let n=e.child(t);await s(n,c,t),c+=n.nodeSize}for(;r.length>0;){let e=r.pop();await this.markString(e,!1,o)}return o.push(...generateInlineTokens(a.splice(0,a.length))),o}async markString(e,t,n){let r=this.getMark(e.type.name),a=t?r.open:r.close;if(!a){if([`highlight`,`textColor`].includes(e.type.name))return;console.warn(`Unsupported mark type for markdown: `+e.type.name+`, available types: `+Object.keys(this.marks).join(`, `)+`. Mark will be ignored.`);return}typeof a==`string`||a(e);let o=``;if(e.type.spec.toDOM){let t=e.type.spec.toDOM(e,!0);Array.isArray(t)&&t.length>0&&(o=t[0])}if(typeof a==`string`){let e=new Token(a,o,t?1:-1);e.meta=`markString`,n.push(e)}else{let t=await a(e);t&&(t.meta=t.meta||`markString()`,n.push(t))}}},blankNode={open:``,close:``},DocumentMarkdownTokenizer=class{nodes;marks;schema;options;tokens=[];inlineTokenizer;constructor(e,t,n,r={hardBreakNodeName:`hard_break`}){this.nodes=e,this.marks=t,this.schema=n,this.options=r,this.inlineTokenizer=new DocumentMarkdownInlineTokenizer(e,t,r,n)}async iterateNode(e,t,n=0,r=-1){let a=this.nodes[e.type.name]?this.nodes[e.type.name](e,t):blankNode,o=``;if(e.type.spec.toDOM){let t=e.type.spec.toDOM(e);Array.isArray(t)&&t.length>0&&(o=t[0])}if(a.selfClose){let s;if(typeof a.selfClose==`string`){let e=new Token(a.selfClose,o,0);e.level=r,e.map=[t],this.tokens.push(e),s=e}else{let o=await a.selfClose(e,t,n);o.level=r,o.map=[t],this.tokens.push(o),s=o}[`before`,`both`].includes(a.margin||``)&&s.attrSet(`margin_before`,`1`),[`after`,`both`].includes(a.margin||``)&&s.attrSet(`margin_after`,`1`);return}let s;if(a.open){if(typeof a.open==`string`){let e=new Token(a.open,o,1);e.level=r,e.meta=`nodeSpec.open`,e.map=[t],this.tokens.push(e),s=e}else{let o=await a.open(e,t,n);o.level=r,o.meta=`nodeSpec.open()`,o.map=[t],this.tokens.push(o),s=o}[`before`,`both`].includes(a.margin||``)&&s.attrSet(`margin_before`,`1`)}if(e.inlineContent){let n=new Token(`inline`,``,0);n.level=r+1,n.map=[t],this.tokens.push(n),n.children=await this.inlineTokenizer.renderInline(e,t+1,r+1)}else if(e.childCount>0){let n=0;for(let a=0;a<e.childCount;a++){let o=e.child(a);await this.iterateNode(o,t+n+1,a,r+1),n+=o.nodeSize}}if(a.close){if(!s)throw Error(`No openToken`);let c;if(typeof a.close==`string`){let e=new Token(a.close,o,-1);e.meta=`nodeSpec.close`,e.level=r,this.tokens.push(e),c=e}else{let o=await a.close(e,t,n,s);o.meta=`nodeSpec.close()`,o.level=r,this.tokens.push(o),c=o}[`after`,`both`].includes(a.margin||``)&&c.attrSet(`margin_after`,`1`)}}async serialize(e,t={}){return await this.iterateNode(e,-1,0),this.tokens}},MdStashContext=class{ctxStash=[];currentCtx;constructor(){this.currentCtx={meta:{}},this.stash()}stash(){return this.ctxStash.push(this.currentCtx),this.currentCtx={...structuredClone({...this.currentCtx})},this.ctxStash.length-1}unstash(){let e=this.ctxStash.pop();if(!e)throw Error(`Unstash failed`);this.currentCtx=e}get current(){return this.currentCtx}};async function pmToMdConverter(e,t,n,r){let a=await extPmToMdConverter(e,t,n,r);return new TextEncoder().encode(a.content)}async function extPmToMdConverter(e,t,n,r){let a=new MdStashContext,o,s=new DocumentMarkdownTokenizer({doc(e){return{open:async(e,n,r)=>{let a=new Token(`frontmatter`,`frontmatter`,0);return e.attrs.meta&&(t.yaml?a.content=`---\n${t.yaml.stringify(e.attrs.meta)}\n---\n`:a.content=`---
101
- # No yaml service
106
+ `,this.ctx.current,e)}let a=this.ctx.current.handlers[e.type]||this.ctx.current.handlers.default;if(e.type===`inline`){if(e.children){this.ctx.stash(`serializeInlineTokens()`),this.ctx.current.log=(e,t)=>{writeIndented(this.ctx.output,e,this.ctx.current,t)};try{serializeInlineTokens(this.ctx,n,e.children),this.ctx.unstash(`serializeInlineTokens()`)}catch(e){if(this.ctx.current.debug(e.message),e.message===`Rewinded before inline tokens`)return;throw e}}}else if(a){for(let t of a)if(t(e,this.ctx,n))break}else throw this.ctx.current.debug(`current.handlers`,Object.keys(this.ctx.current.handlers).sort()),Error(`Unknown token: ${e.type} `+JSON.stringify(e));t[e.level]=e,e.nesting===-1&&(t[e.level+1]=new Token(``,``,e.nesting))}),this.ctx.output}},blankMark={open:``,close:``,mixable:!0},blankNode$1={open:``,close:``};function generateInlineTokens(e){let t=[],n=-1,r=``;for(let[a,o]of e){if(r.length>0){let e=new Token(`text`,``,0);e.meta=`generateInline1`,e.map=[n],e.content=r,t.push(e)}r=``,n=o,r+=a}if(r.length>0){let e=new Token(`text`,``,0);e.meta=`generateInline2`,e.map=[n],e.content=r,t.push(e)}return t}var nullNode={isText:!1,attrs:{},text:``,marks:[]},DocumentMarkdownInlineTokenizer=class{nodes;marks;options;schema;constructor(e,t,n,r){this.nodes=e,this.marks=t,this.options=n,this.schema=r}getMark(e){return this.marks[e]||blankMark}async renderInline(e,t,n){let r=[],a=[],o=[],s=async(s,c,l)=>{let u=t+c,d=s?s.marks:[];`type`in s&&s.type.name===this.options.hardBreakNodeName&&(d=d.filter(t=>{if(l+1==e.childCount)return!1;let n=e.child(l+1);return t.isInSet(n.marks)&&(!n.isText||/\S/.test(n.text))}));let f=a.splice(0,a.length);if(s?.isText&&d.some(e=>{let t=this.getMark(e.type.name);return t&&t.expelEnclosingWhitespace&&!e.isInSet(r)})){let[e,t,n]=/^(\s*)(.*)$/m.exec(s.text);t&&(f.push([t,u]),s=n?this.schema.text(n,s.marks):nullNode,s||(d=r))}if(s&&s.isText&&d.some(t=>{let n=this.getMark(t.type.name);return n&&n.expelEnclosingWhitespace&&(l==e.childCount-1||!t.isInSet(e.child(l+1).marks))})){let[e,t,n]=/^(.*?)(\s*)$/m.exec(s.text);n&&(a.push([n,u]),s=t?this.schema.text(t,s.marks):nullNode,s||(d=r))}let p=d.length?d[d.length-1]:null,m=p&&this.getMark(p.type.name).escape===!1,h=d.length-+!!m;outer:for(let e=0;e<h;e++){let t=d[e];if(!this.getMark(t.type.name).mixable)break;for(let n=0;n<r.length;n++){let a=r[n];if(!this.getMark(a.type.name).mixable)break;if(t.eq(a)){e>n?d=d.slice(0,n).concat(t).concat(d.slice(n,e)).concat(d.slice(e+1,h)):n>e&&(d=d.slice(0,e).concat(d.slice(e+1,n)).concat(t).concat(d.slice(n,h)));continue outer}}}let g=0;for(;g<Math.min(r.length,h)&&d[g].eq(r[g]);)++g;for(;g<r.length;){let e=r.pop();await this.markString(e,!1,o)}for(o.push(...generateInlineTokens(f.splice(0,f.length)));r.length<h;){let e=d[r.length];r.push(e),await this.markString(e,!0,o)}if(m&&s.isText){if(await this.markString(p,!0,o),s.text){let e=new Token(`text`,``,0);e.meta=`noEscText`,e.map=[u],e.content=s.text,o.push(e)}await this.markString(p,!1,o)}else{let e=`type`in s&&this.nodes[s.type.name]?this.nodes[s.type.name](s,t):blankNode$1,r=``;if(`type`in s&&s.type.spec.toDOM){let e=s.type.spec.toDOM(s);Array.isArray(e)&&e.length>0&&(r=e[0])}if(e.selfClose){if(typeof e.selfClose==`string`){let t=new Token(e.selfClose,r,0);t.meta=`nodeSpec.selfClose`,t.level=n,t.map=[u],o.push(t)}else if(`type`in s){let t=await e.selfClose(s,u,l);t.meta=`!nodeSpec.selfClose`,t.level=n,t.map=[u],o.push(t)}}}},c=0;for(let t=0;t<e.childCount;t++){let n=e.child(t);await s(n,c,t),c+=n.nodeSize}for(;r.length>0;){let e=r.pop();await this.markString(e,!1,o)}return o.push(...generateInlineTokens(a.splice(0,a.length))),o}async markString(e,t,n){let r=this.getMark(e.type.name),a=t?r.open:r.close;if(!a){if([`highlight`,`textColor`].includes(e.type.name))return;console.warn(`Unsupported mark type for markdown: `+e.type.name+`, available types: `+Object.keys(this.marks).join(`, `)+`. Mark will be ignored.`);return}typeof a==`string`||a(e);let o=``;if(e.type.spec.toDOM){let t=e.type.spec.toDOM(e,!0);Array.isArray(t)&&t.length>0&&(o=t[0])}if(typeof a==`string`){let e=new Token(a,o,t?1:-1);e.meta=`markString`,n.push(e)}else{let t=await a(e);t&&(t.meta=t.meta||`markString()`,n.push(t))}}},blankNode={open:``,close:``},DocumentMarkdownTokenizer=class{nodes;marks;schema;options;tokens=[];inlineTokenizer;constructor(e,t,n,r={hardBreakNodeName:`hard_break`}){this.nodes=e,this.marks=t,this.schema=n,this.options=r,this.inlineTokenizer=new DocumentMarkdownInlineTokenizer(e,t,r,n)}async iterateNode(e,t,n=0,r=-1){let a=this.nodes[e.type.name]?this.nodes[e.type.name](e,t):blankNode,o=``;if(e.type.spec.toDOM){let t=e.type.spec.toDOM(e);Array.isArray(t)&&t.length>0&&(o=t[0])}if(a.selfClose){let s;if(typeof a.selfClose==`string`){let e=new Token(a.selfClose,o,0);e.level=r,e.map=[t],this.tokens.push(e),s=e}else{let o=await a.selfClose(e,t,n);o.level=r,o.map=[t],this.tokens.push(o),s=o}[`before`,`both`].includes(a.margin||``)&&s.attrSet(`margin_before`,`1`),[`after`,`both`].includes(a.margin||``)&&s.attrSet(`margin_after`,`1`);return}let s;if(a.open){if(typeof a.open==`string`){let e=new Token(a.open,o,1);e.level=r,e.meta=`nodeSpec.open`,e.map=[t],this.tokens.push(e),s=e}else{let o=await a.open(e,t,n);o.level=r,o.meta=`nodeSpec.open()`,o.map=[t],this.tokens.push(o),s=o}[`before`,`both`].includes(a.margin||``)&&s.attrSet(`margin_before`,`1`)}if(e.inlineContent){let n=new Token(`inline`,``,0);n.level=r+1,n.map=[t],this.tokens.push(n),n.children=await this.inlineTokenizer.renderInline(e,t+1,r+1)}else if(e.childCount>0){let n=0;for(let a=0;a<e.childCount;a++){let o=e.child(a);await this.iterateNode(o,t+n+1,a,r+1),n+=o.nodeSize}}if(a.close){if(!s)throw Error(`No openToken`);let c;if(typeof a.close==`string`){let e=new Token(a.close,o,-1);e.meta=`nodeSpec.close`,e.level=r,this.tokens.push(e),c=e}else{let o=await a.close(e,t,n,s);o.meta=`nodeSpec.close()`,o.level=r,this.tokens.push(o),c=o}[`after`,`both`].includes(a.margin||``)&&c.attrSet(`margin_after`,`1`)}}async serialize(e,t={}){return await this.iterateNode(e,-1,0),this.tokens}},MdStashContext=class{ctxStash=[];currentCtx;constructor(){this.currentCtx={meta:{}},this.stash()}stash(){return this.ctxStash.push(this.currentCtx),this.currentCtx={...structuredClone({...this.currentCtx})},this.ctxStash.length-1}unstash(){let e=this.ctxStash.pop();if(!e)throw Error(`Unstash failed`);this.currentCtx=e}get current(){return this.currentCtx}};async function pmToMdConverter(e,t,n,r){let a=await extPmToMdConverter(e,t,n,r);return new TextEncoder().encode(a.content)}async function extPmToMdConverter(e,t,n,r){let a=new MdStashContext,o,s=new DocumentMarkdownTokenizer({doc(e){return{open:async(e,n,r)=>{let a=new Token(`frontmatter`,`frontmatter`,0);return e.attrs.meta&&(t.frontmatter?a.content=t.frontmatter.stringify(e.attrs.meta):a.content=`---
107
+ # No frontmatter service
102
108
  ---
103
- `),a}}},paragraph(e){return{open:async(e,t,n)=>{let r=new Token(`paragraph_open`,`p`,1);return o.resolve(t).parent?.type.name===`table_cell`&&n>0&&r.attrSet(`not_first_para`,`1`),r},close:async(e,t,n,r)=>{let a=new Token(`paragraph_close`,`p`,-1),o;return e.children.length===1&&e.children[0].type.name===`shortcode_inline`&&(o=e.children[0]),o?(o.attrs.nesting!==-1&&r.attrSet(`margin_before`,`1`),o.attrs.nesting!==1&&a.attrSet(`margin_after`,`1`)):(r.attrSet(`margin_before`,`1`),a.attrSet(`margin_after`,`1`)),a}}},hr(e){return{selfClose:`hr`,margin:`both`}},heading(e){return{open:async e=>{if(!e.attrs.level)throw Error(`No heading level`);return new Token(`heading_open`,`h`+e.attrs.level,1)},close:`heading_close`,margin:`both`}},blockquote(e){return{open:`blockquote_open`,close:`blockquote_close`}},math(){return{selfClose:async e=>{let t=new Token(`math`,`math`,0);return t.content=e.attrs.content,t.attrSet(`lang`,e.attrs.lang),t.meta=`noEscText`,t}}},task_list(e){return{open:async e=>{a.stash(),a.current.meta.list_type=`tl`,a.current.meta.list_type_symbol=``;let t=new Token(`task_list_open`,`ul`,1);return t.attrSet(`symbol`,`*`),t},close:async e=>(a.unstash(),new Token(`task_list_close`,`ul`,-1)),margin:`both`}},bullet_list(e){return{open:async(e,t,n)=>{a.stash(),a.current.meta.list_type=`ul`,a.current.meta.list_type_symbol=`*`;let r=new Token(`bullet_list_open`,`ul`,1);r.attrSet(`symbol`,`*`);let s=o.nodeAt(t+1);s?.type.name===`list_item`&&r.attrSet(`first_level_type`,s.attrs.type);let c=o.resolve(t),l=c.parent;return c.node(c.depth-1),l?.type.name===`table_cell`&&n>0&&r.attrSet(`not_first_para`,`1`),r},close:async(e,t)=>{a.unstash();let n=new Token(`bullet_list_close`,`ul`,-1),r=o.nodeAt(t+1);return r?.type.name===`list_item`&&n.attrSet(`first_level_type`,r.attrs.type),n},margin:`both`}},ordered_list(e){return{open:async(e,t,n)=>{a.stash(),a.current.meta.list_type=`ol`,a.current.meta.list_type_symbol=e.attrs.type||`1`;let r=new Token(`ordered_list_open`,`ol`,1);r.attrSet(`symbol`,e.attrs.type||`1`),r.attrSet(`start`,e.attrs.start);let s=o.nodeAt(t+1);return s?.type.name===`list_item`&&r.attrSet(`first_level_type`,s.attrs.type),o.resolve(t).parent?.type.name===`table_cell`&&n>0&&r.attrSet(`not_first_para`,`1`),r},close:async(e,t)=>{a.unstash();let n=new Token(`ordered_list_close`,`ol`,-1),r=o.nodeAt(t+1);return r?.type.name===`list_item`&&n.attrSet(`first_level_type`,r.attrs.type),n},margin:`both`}},list_item(e){return{open:async e=>{let t=new Token(`list_item_open`,`li`,1);return e.attrs.value&&t.attrSet(`value`,e.attrs.value),e.attrs.type&&t.attrSet(`type`,e.attrs.type),a.current.meta.list_type===`ul`&&(t.markup=a.current.meta.list_type_symbol||`-`),t},close:`list_item_close`}},task_item(e){return{open:async e=>{let t=new Token(`task_item_open`,`li`,1);return t.attrSet(`checked`,e.attrs.checked?`checked`:``),t},close:`task_item_close`}},table(e){return{open:`table_open`,close:`table_close`,margin:`both`}},table_row(e){return{open:`tr_open`,close:`tr_close`}},table_cell(e){return{open:`td_open`,close:`td_close`}},table_header(e){return{open:`th_open`,close:`th_close`}},br(e){return{selfClose:`hardbreak`}},softbreak(e){return{selfClose:`softbreak`}},text(e){return{selfClose:e=>{let t=new Token(`text`,``,0);return t.content=e.text||``,Promise.resolve(t)}}},code_block(e){return{selfClose:e=>{let t=new Token(`code_block`,`code`,0);return t.meta=`noEscText`,t.attrSet(`lang`,e.attrs.lang),t.content=e.textContent,Promise.resolve(t)},margin:`both`}},image(e){return{selfClose:e=>{let t=e.attrs.src,n=e.attrs.alt,r=new Token(`image`,`img`,0);return r.attrSet(`src`,t),r.attrSet(`alt`,n),r.attrSet(`origUrl`,e.attrs.origUrl),e.attrs.title&&r.attrSet(`title`,e.attrs.title),r.attrSet(`mdTemplate`,e.attrs.mdTemplate),Promise.resolve(r)}}},shortcode_inline(e){return{selfClose:e=>{let t=new Token(`shortcode_inline`,`shortcode_inline`,0);return t.content=e.attrs.content,Promise.resolve(t)}}},node_bookmark(e){return{selfClose:e=>{let t=new Token(`bookmark`,`bookmark`,0);return t.content=e.attrs.content,t.attrSet(`id`,e.attrs.id),Promise.resolve(t)}}}},{em:{open:`em_open`,close:`em_close`,mixable:!0,expelEnclosingWhitespace:!0},underline:{open:`underline_open`,close:`underline_close`,mixable:!0,expelEnclosingWhitespace:!0},strong:{open:`strong_open`,close:`strong_close`,mixable:!0,expelEnclosingWhitespace:!0},strike:{open:`strike_open`,close:`strike_close`,mixable:!0,expelEnclosingWhitespace:!0},math:{open:`math_inline_open`,close:`math_inline_close`},link:{open:async e=>{let t=new Token(`link_open`,`a`,1);return t.attrSet(`href`,e.attrs.href),t.attrSet(`origUrl`,e.attrs.origUrl),t.attrSet(`mdTemplate`,e.attrs.mdTemplate),t},close:`link_close`,mixable:!0},code:{open:`code_open`,close:`code_close`,escape:!1}},n),c=[...t.hooks||[]],l=EditorState.create({doc:e}),u=e=>{l=l.apply(e)};if(c.length>0)for(let e of c)await e(l,e=>u(e));o=l.doc;let d=await s.serialize(o);if(t.debugTokens){let e=new CustomEvent(`md:tokens`,{detail:{tokens:d}});r.dispatchEvent(e)}let f=await new MarkdownSerializer({debug:t.serializerDebug}).serialize(d),p=new CustomEvent(`md:output`,{detail:{output:f}});r.dispatchEvent(p);let m={},h=[],g;if(t.sourceMap){let t=new SmartOutput;nodeToTreeStringOutput(t,e),t.getSourceMap((e,t,n,r)=>{r&&(m[r.pos]={targetRow:e,targetCol:t})}),g=f.getSourceMap((e,t,n,r)=>{if(r?.map){let a=r.map[0],o=r.map[2];if(h.push({nodeIdx:a,targetPos:n,targetRow:e,targetCol:t,sourceCol:o}),m[a])return{sourceNo:0,sourceRowPos:m[a].targetRow,sourceColPos:m[a].targetCol}}}),g.file=`target.md`,g.sources=[`debug.txt`],g.sourcesContent=[t.toString()]}if(t.dispatchSourceMap){let e=new CustomEvent(`md:sourcemap`,{detail:{sourceMap:g,debugMap:m,rawTextMap:h}});r.dispatchEvent(e)}return{content:f.toString(),sourceMap:g,debugMap:m,rawTextMap:h}}var removeWhitespaces=e=>{let t=e.childNodes;for(let n=t.length-1;n>=0;--n){let r=t[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?e.removeChild(r):r.nodeType===1&&removeWhitespaces(r)}return e};function elementFromString(e){let t=`<html lang="en"><body>${e}</body></html>`,n=new globalThis.DOMParser().parseFromString(t,`text/html`).body;return removeWhitespaces(n)}function maybeMerge(e,t){if(e.isText&&t.isText&&Mark$1.sameSet(e.marks,t.marks))return e.withText(e.text+t.text)}var MarkdownParseState=class{schema;tokenHandlers;stack;constructor(e,t){this.schema=e,this.tokenHandlers=t,this.stack=[{type:e.topNodeType,attrs:null,content:[],marks:Mark$1.none}]}top(){return this.stack[this.stack.length-1]}push(e){this.stack.length&&this.top().content.push(e)}addText(e){if(!e)return;let t=this.top(),n=t.content,r=n[n.length-1],a=this.schema.text(e,t.marks),o;r&&(o=maybeMerge(r,a))?n[n.length-1]=o:n.push(a)}openMark(e){let t=this.top();t.marks=e.addToSet(t.marks)}closeMark(e){let t=this.top();t.marks=e.removeFromSet(t.marks)}parseTokens(e){for(let t=0;t<e.length;t++){let n=e[t],r=this.tokenHandlers[n.type];if(!r)throw console.log(Object.keys(this.tokenHandlers)),Error("Token type `"+n.type+"` not supported by Markdown parser");r(this,n,e,t)}}addNode(e,t,n){let r=this.top(),a=e.createAndFill(t,n,r?r.marks:[]);return a?(this.push(a),a):null}openNode(e,t){this.stack.push({type:e,attrs:t,content:[],marks:Mark$1.none})}closeNode(){let e=this.stack.pop();return this.addNode(e.type,e.attrs,e.content)}importNodes(e){for(let t of e)this.push(t)}};function attrs(e,t,n,r){return e.getAttrs?e.getAttrs(t,n,r):e.attrs instanceof Function?e.attrs(t):e.attrs}function noCloseToken(e,t){return e.noCloseToken||t==`code_block`||t==`fence`}function withoutTrailingNewline(e){return e[e.length-1]==`
109
+ `),a}}},paragraph(e){return{open:async(e,t,n)=>{let r=new Token(`paragraph_open`,`p`,1);return o.resolve(t).parent?.type.name===`table_cell`&&n>0&&r.attrSet(`not_first_para`,`1`),r},close:async(e,t,n,r)=>{let a=new Token(`paragraph_close`,`p`,-1),o;return e.children.length===1&&e.children[0].type.name===`shortcode_inline`&&(o=e.children[0]),o?(o.attrs.nesting!==-1&&r.attrSet(`margin_before`,`1`),o.attrs.nesting!==1&&a.attrSet(`margin_after`,`1`)):(r.attrSet(`margin_before`,`1`),a.attrSet(`margin_after`,`1`)),a}}},hr(e){return{selfClose:`hr`,margin:`both`}},heading(e){return{open:async e=>{if(!e.attrs.level)throw Error(`No heading level`);return new Token(`heading_open`,`h`+e.attrs.level,1)},close:`heading_close`,margin:`both`}},blockquote(e){return{open:`blockquote_open`,close:`blockquote_close`}},math(){return{selfClose:async e=>{let t=new Token(`math`,`math`,0);return t.content=e.attrs.content,t.attrSet(`lang`,e.attrs.lang),t.meta=`noEscText`,t}}},task_list(e){return{open:async e=>{a.stash(),a.current.meta.list_type=`tl`,a.current.meta.list_type_symbol=``;let t=new Token(`task_list_open`,`ul`,1);return t.attrSet(`symbol`,`*`),t},close:async e=>(a.unstash(),new Token(`task_list_close`,`ul`,-1)),margin:`both`}},bullet_list(e){return{open:async(e,t,n)=>{a.stash(),a.current.meta.list_type=`ul`,a.current.meta.list_type_symbol=`*`;let r=new Token(`bullet_list_open`,`ul`,1);r.attrSet(`symbol`,`*`);let s=o.nodeAt(t+1);s?.type.name===`list_item`&&r.attrSet(`first_level_type`,s.attrs.type);let c=o.resolve(t),l=c.parent;return c.node(c.depth-1),l?.type.name===`table_cell`&&n>0&&r.attrSet(`not_first_para`,`1`),r},close:async(e,t)=>{a.unstash();let n=new Token(`bullet_list_close`,`ul`,-1),r=o.nodeAt(t+1);return r?.type.name===`list_item`&&n.attrSet(`first_level_type`,r.attrs.type),n},margin:`both`}},ordered_list(e){return{open:async(e,t,n)=>{a.stash(),a.current.meta.list_type=`ol`,a.current.meta.list_type_symbol=e.attrs.type||`1`;let r=new Token(`ordered_list_open`,`ol`,1);r.attrSet(`symbol`,e.attrs.type||`1`),r.attrSet(`start`,e.attrs.start);let s=o.nodeAt(t+1);return s?.type.name===`list_item`&&r.attrSet(`first_level_type`,s.attrs.type),o.resolve(t).parent?.type.name===`table_cell`&&n>0&&r.attrSet(`not_first_para`,`1`),r},close:async(e,t)=>{a.unstash();let n=new Token(`ordered_list_close`,`ol`,-1),r=o.nodeAt(t+1);return r?.type.name===`list_item`&&n.attrSet(`first_level_type`,r.attrs.type),n},margin:`both`}},list_item(e){return{open:async e=>{let t=new Token(`list_item_open`,`li`,1);return e.attrs.value&&t.attrSet(`value`,e.attrs.value),e.attrs.type&&t.attrSet(`type`,e.attrs.type),a.current.meta.list_type===`ul`&&(t.markup=a.current.meta.list_type_symbol||`-`),t},close:`list_item_close`}},task_item(e){return{open:async e=>{let t=new Token(`task_item_open`,`li`,1);return t.attrSet(`checked`,e.attrs.checked?`checked`:``),t},close:`task_item_close`}},table(e){return{open:`table_open`,close:`table_close`,margin:`both`}},table_row(e){return{open:`tr_open`,close:`tr_close`}},table_cell(e){return{open:`td_open`,close:`td_close`}},table_header(e){return{open:`th_open`,close:`th_close`}},br(e){return{selfClose:`hardbreak`}},softbreak(e){return{selfClose:`softbreak`}},text(e){return{selfClose:e=>{let t=new Token(`text`,``,0);return t.content=e.text||``,Promise.resolve(t)}}},code_block(e){return{selfClose:e=>{let t=new Token(`code_block`,`code`,0);return t.meta=`noEscText`,t.attrSet(`lang`,e.attrs.lang),t.content=e.textContent,Promise.resolve(t)},margin:`both`}},image(e){return{selfClose:e=>{let t=e.attrs.src,n=e.attrs.alt,r=new Token(`image`,`img`,0);return r.attrSet(`src`,t),r.attrSet(`alt`,n),r.attrSet(`origUrl`,e.attrs.origUrl),e.attrs.title&&r.attrSet(`title`,e.attrs.title),r.attrSet(`mdTemplate`,e.attrs.mdTemplate),Promise.resolve(r)}}},shortcode_inline(e){return{selfClose:e=>{let t=new Token(`shortcode_inline`,`shortcode_inline`,0);return t.content=e.attrs.content,Promise.resolve(t)}}},node_bookmark(e){return{selfClose:e=>{let t=new Token(`bookmark`,`bookmark`,0);return t.content=e.attrs.content,t.attrSet(`id`,e.attrs.id),Promise.resolve(t)}}}},{em:{open:`em_open`,close:`em_close`,mixable:!0,expelEnclosingWhitespace:!0},underline:{open:`underline_open`,close:`underline_close`,mixable:!0,expelEnclosingWhitespace:!0},strong:{open:`strong_open`,close:`strong_close`,mixable:!0,expelEnclosingWhitespace:!0},strike:{open:`strike_open`,close:`strike_close`,mixable:!0,expelEnclosingWhitespace:!0},math:{open:`math_inline_open`,close:`math_inline_close`},link:{open:async e=>{let t=new Token(`link_open`,`a`,1);return t.attrSet(`href`,e.attrs.href),t.attrSet(`origUrl`,e.attrs.origUrl),t.attrSet(`mdTemplate`,e.attrs.mdTemplate),t},close:`link_close`,mixable:!0},code:{open:`code_open`,close:`code_close`,escape:!1}},n),c=[...t.hooks||[]],l=EditorState.create({doc:e}),u=e=>{l=l.apply(e)};if(c.length>0)for(let e of c)await e(l,e=>u(e));o=l.doc;let d=await s.serialize(o);if(t.debugTokens){let e=new CustomEvent(`md:tokens`,{detail:{tokens:d}});r.dispatchEvent(e)}let f=await new MarkdownSerializer({debug:t.serializerDebug}).serialize(d),p=new CustomEvent(`md:output`,{detail:{output:f}});r.dispatchEvent(p);let m={},h=[],g;if(t.sourceMap){let t=new SmartOutput;nodeToTreeStringOutput(t,e),t.getSourceMap((e,t,n,r)=>{r&&(m[r.pos]={targetRow:e,targetCol:t})}),g=f.getSourceMap((e,t,n,r)=>{if(r?.map){let a=r.map[0],o=r.map[2];if(h.push({nodeIdx:a,targetPos:n,targetRow:e,targetCol:t,sourceCol:o}),m[a])return{sourceNo:0,sourceRowPos:m[a].targetRow,sourceColPos:m[a].targetCol}}}),g.file=`target.md`,g.sources=[`debug.txt`],g.sourcesContent=[t.toString()]}if(t.dispatchSourceMap){let e=new CustomEvent(`md:sourcemap`,{detail:{sourceMap:g,debugMap:m,rawTextMap:h}});r.dispatchEvent(e)}return{content:f.toString(),sourceMap:g,debugMap:m,rawTextMap:h}}var removeWhitespaces=e=>{let t=e.childNodes;for(let n=t.length-1;n>=0;--n){let r=t[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?e.removeChild(r):r.nodeType===1&&removeWhitespaces(r)}return e};function elementFromString(e){let t=`<html lang="en"><body>${e}</body></html>`,n=new globalThis.DOMParser().parseFromString(t,`text/html`).body;return removeWhitespaces(n)}function decodeEntity(e){let t=`<html lang="en"><body>${e}</body></html>`;return new globalThis.DOMParser().parseFromString(t,`text/html`).body.innerText}function maybeMerge(e,t){if(e.isText&&t.isText&&Mark$1.sameSet(e.marks,t.marks))return e.withText(e.text+t.text)}var MarkdownParseState=class{schema;tokenHandlers;stack;constructor(e,t){this.schema=e,this.tokenHandlers=t,this.stack=[{type:e.topNodeType,attrs:null,content:[],marks:Mark$1.none}]}top(){return this.stack[this.stack.length-1]}push(e){this.stack.length&&this.top().content.push(e)}addText(e){if(!e)return;let t=this.top(),n=t.content,r=n[n.length-1],a=this.schema.text(e,t.marks),o;r&&(o=maybeMerge(r,a))?n[n.length-1]=o:n.push(a)}openMark(e){let t=this.top();t.marks=e.addToSet(t.marks)}closeMark(e){let t=this.top();t.marks=e.removeFromSet(t.marks)}parseTokens(e){for(let t=0;t<e.length;t++){let n=e[t],r=this.tokenHandlers[n.type];if(!r)throw console.log(Object.keys(this.tokenHandlers)),Error("Token type `"+n.type+"` not supported by Markdown parser");r(this,n,e,t)}}addNode(e,t,n){let r=this.top(),a=e.createAndFill(t,n,r?r.marks:[]);return a?(this.push(a),a):null}openNode(e,t){this.stack.push({type:e,attrs:t,content:[],marks:Mark$1.none})}closeNode(){let e=this.stack.pop();return this.addNode(e.type,e.attrs,e.content)}importNodes(e){for(let t of e)this.push(t)}};function attrs(e,t,n,r){return e.getAttrs?e.getAttrs(t,n,r):e.attrs instanceof Function?e.attrs(t):e.attrs}function noCloseToken(e,t){return e.noCloseToken||t==`code_block`||t==`fence`}function withoutTrailingNewline(e){return e[e.length-1]==`
104
110
  `?e.slice(0,e.length-1):e}function noOp(){}function tokenHandlers(e,t){let n=Object.create(null);for(let r in t){let a=t[r];if(a.block){let t=e.nodes[a.block];noCloseToken(a,r)?n[r]=(e,n,r,o)=>{e.openNode(t,attrs(a,n,r,o)),e.addText(withoutTrailingNewline(n.content)),e.closeNode()}:(n[r+`_open`]=(e,n,r,o)=>e.openNode(t,attrs(a,n,r,o)),n[r+`_close`]=e=>e.closeNode())}else if(a.node){let t=e.nodes[a.node];n[r]=(e,n,r,o)=>e.addNode(t,attrs(a,n,r,o))}else if(a.mark){let t=e.marks[a.mark];noCloseToken(a,r)?n[r]=(e,n,r,o)=>{e.openMark(t.create(attrs(a,n,r,o))),e.addText(withoutTrailingNewline(n.content)),e.closeMark(t)}:(n[r+`_open`]=(e,n,r,o)=>e.openMark(t.create(attrs(a,n,r,o))),n[r+`_close`]=e=>e.closeMark(t))}else if(a.custom){let e=a.custom;n[r]=(t,n,r,a)=>{e(t,n,r,a)}}else if(a.ignore)noCloseToken(a,r)?n[r]=noOp:(n[r+`_open`]=noOp,n[r+`_close`]=noOp);else throw RangeError(`Unrecognized parsing spec `+JSON.stringify(a))}return n.text=(e,t)=>e.addText(t.content),n.inline=(e,t)=>e.parseTokens(t.children),n.softbreak=n.softbreak||(e=>e.addText(` `)),n}var MarkdownParser=class{schema;tokenizer;tokens;tokenHandlers;constructor(e,t,n){this.schema=e,this.tokenizer=t,this.tokens=n,this.tokenHandlers=tokenHandlers(e,n)}parse(e,t={}){let n=new MarkdownParseState(this.schema,this.tokenHandlers),r=this.tokenizer.parse(e,t);n.parseTokens(r);let a;do a=n.closeNode();while(n.stack.length);return a||this.schema.topNodeType.createAndFill()}},__defProp=Object.defineProperty,__name=(e,t)=>__defProp(e,`name`,{value:t,configurable:!0}),Edit=class{static{__name(this,`Edit`)}startPosition;oldEndPosition;newEndPosition;startIndex;oldEndIndex;newEndIndex;constructor({startIndex:e,oldEndIndex:t,newEndIndex:n,startPosition:r,oldEndPosition:a,newEndPosition:o}){this.startIndex=e>>>0,this.oldEndIndex=t>>>0,this.newEndIndex=n>>>0,this.startPosition=r,this.oldEndPosition=a,this.newEndPosition=o}editPoint(e,t){let n=t,r={...e};if(t>=this.oldEndIndex){n=this.newEndIndex+(t-this.oldEndIndex);let a=e.row;r.row=this.newEndPosition.row+(e.row-this.oldEndPosition.row),r.column=a===this.oldEndPosition.row?this.newEndPosition.column+(e.column-this.oldEndPosition.column):e.column}else t>this.startIndex&&(n=this.newEndIndex,r.row=this.newEndPosition.row,r.column=this.newEndPosition.column);return{point:r,index:n}}editRange(e){let t={startIndex:e.startIndex,startPosition:{...e.startPosition},endIndex:e.endIndex,endPosition:{...e.endPosition}};return e.endIndex>=this.oldEndIndex?e.endIndex!==2**53-1&&(t.endIndex=this.newEndIndex+(e.endIndex-this.oldEndIndex),t.endPosition={row:this.newEndPosition.row+(e.endPosition.row-this.oldEndPosition.row),column:e.endPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.endPosition.column-this.oldEndPosition.column):e.endPosition.column},t.endIndex<this.newEndIndex&&(t.endIndex=2**53-1,t.endPosition={row:2**53-1,column:2**53-1})):e.endIndex>this.startIndex&&(t.endIndex=this.startIndex,t.endPosition={...this.startPosition}),e.startIndex>=this.oldEndIndex?(t.startIndex=this.newEndIndex+(e.startIndex-this.oldEndIndex),t.startPosition={row:this.newEndPosition.row+(e.startPosition.row-this.oldEndPosition.row),column:e.startPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.startPosition.column-this.oldEndPosition.column):e.startPosition.column},t.startIndex<this.newEndIndex&&(t.startIndex=2**53-1,t.startPosition={row:2**53-1,column:2**53-1})):e.startIndex>this.startIndex&&(t.startIndex=this.startIndex,t.startPosition={...this.startPosition}),t}},SIZE_OF_SHORT=2,SIZE_OF_INT=4,SIZE_OF_CURSOR=4*SIZE_OF_INT,SIZE_OF_NODE=5*SIZE_OF_INT,SIZE_OF_POINT=2*SIZE_OF_INT,SIZE_OF_RANGE=2*SIZE_OF_INT+2*SIZE_OF_POINT,ZERO_POINT={row:0,column:0},INTERNAL=Symbol(`INTERNAL`);function assertInternal(e){if(e!==INTERNAL)throw Error(`Illegal constructor`)}__name(assertInternal,`assertInternal`);function isPoint(e){return!!e&&typeof e.row==`number`&&typeof e.column==`number`}__name(isPoint,`isPoint`);function setModule(e){C=e}__name(setModule,`setModule`);var C,LookaheadIterator=class{static{__name(this,`LookaheadIterator`)}0=0;language;constructor(e,t,n){assertInternal(e),this[0]=t,this.language=n}get currentTypeId(){return C._ts_lookahead_iterator_current_symbol(this[0])}get currentType(){return this.language.types[this.currentTypeId]||`ERROR`}delete(){C._ts_lookahead_iterator_delete(this[0]),this[0]=0}reset(e,t){return C._ts_lookahead_iterator_reset(this[0],e[0],t)?(this.language=e,!0):!1}resetState(e){return!!C._ts_lookahead_iterator_reset_state(this[0],e)}[Symbol.iterator](){return{next:__name(()=>C._ts_lookahead_iterator_next(this[0])?{done:!1,value:this.currentType}:{done:!0,value:``},`next`)}}};function getText(e,t,n,r){let a=n-t,o=e.textCallback(t,r);if(o){for(t+=o.length;t<n;){let n=e.textCallback(t,r);if(n&&n.length>0)t+=n.length,o+=n;else break}t>n&&(o=o.slice(0,a))}return o??``}__name(getText,`getText`);var Tree=class e{static{__name(this,`Tree`)}0=0;textCallback;language;constructor(e,t,n,r){assertInternal(e),this[0]=t,this.language=n,this.textCallback=r}copy(){return new e(INTERNAL,C._ts_tree_copy(this[0]),this.language,this.textCallback)}delete(){C._ts_tree_delete(this[0]),this[0]=0}get rootNode(){return C._ts_tree_root_node_wasm(this[0]),unmarshalNode(this)}rootNodeWithOffset(e,t){let n=TRANSFER_BUFFER+SIZE_OF_NODE;return C.setValue(n,e,`i32`),marshalPoint(n+SIZE_OF_INT,t),C._ts_tree_root_node_with_offset_wasm(this[0]),unmarshalNode(this)}edit(e){marshalEdit(e),C._ts_tree_edit_wasm(this[0])}walk(){return this.rootNode.walk()}getChangedRanges(t){if(!(t instanceof e))throw TypeError(`Argument must be a Tree`);C._ts_tree_get_changed_ranges_wasm(this[0],t[0]);let n=C.getValue(TRANSFER_BUFFER,`i32`),r=C.getValue(TRANSFER_BUFFER+SIZE_OF_INT,`i32`),a=Array(n);if(n>0){let e=r;for(let t=0;t<n;t++)a[t]=unmarshalRange(e),e+=SIZE_OF_RANGE;C._free(r)}return a}getIncludedRanges(){C._ts_tree_included_ranges_wasm(this[0]);let e=C.getValue(TRANSFER_BUFFER,`i32`),t=C.getValue(TRANSFER_BUFFER+SIZE_OF_INT,`i32`),n=Array(e);if(e>0){let r=t;for(let t=0;t<e;t++)n[t]=unmarshalRange(r),r+=SIZE_OF_RANGE;C._free(t)}return n}},TreeCursor=class e{static{__name(this,`TreeCursor`)}0=0;1=0;2=0;3=0;tree;constructor(e,t){assertInternal(e),this.tree=t,unmarshalTreeCursor(this)}copy(){let t=new e(INTERNAL,this.tree);return C._ts_tree_cursor_copy_wasm(this.tree[0]),unmarshalTreeCursor(t),t}delete(){marshalTreeCursor(this),C._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}get currentNode(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_wasm(this.tree[0]),unmarshalNode(this.tree)}get currentFieldId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return marshalTreeCursor(this),C._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_current_descendant_index_wasm(this.tree[0])}get nodeType(){return this.tree.language.types[this.nodeTypeId]||`ERROR`}get nodeTypeId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){marshalTreeCursor(this);let e=C._ts_tree_cursor_start_index_wasm(this.tree[0]),t=C._ts_tree_cursor_end_index_wasm(this.tree[0]);C._ts_tree_cursor_start_position_wasm(this.tree[0]);let n=unmarshalPoint(TRANSFER_BUFFER);return getText(this.tree,e,t,n)}get startPosition(){return marshalTreeCursor(this),C._ts_tree_cursor_start_position_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get endPosition(){return marshalTreeCursor(this),C._ts_tree_cursor_end_position_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get startIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_end_index_wasm(this.tree[0])}gotoFirstChild(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoLastChild(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoParent(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoNextSibling(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoPreviousSibling(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoDescendant(e){marshalTreeCursor(this),C._ts_tree_cursor_goto_descendant_wasm(this.tree[0],e),unmarshalTreeCursor(this)}gotoFirstChildForIndex(e){marshalTreeCursor(this),C.setValue(TRANSFER_BUFFER+SIZE_OF_CURSOR,e,`i32`);let t=C._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return unmarshalTreeCursor(this),t===1}gotoFirstChildForPosition(e){marshalTreeCursor(this),marshalPoint(TRANSFER_BUFFER+SIZE_OF_CURSOR,e);let t=C._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return unmarshalTreeCursor(this),t===1}reset(e){marshalNode(e),marshalTreeCursor(this,TRANSFER_BUFFER+SIZE_OF_NODE),C._ts_tree_cursor_reset_wasm(this.tree[0]),unmarshalTreeCursor(this)}resetTo(e){marshalTreeCursor(this,TRANSFER_BUFFER),marshalTreeCursor(e,TRANSFER_BUFFER+SIZE_OF_CURSOR),C._ts_tree_cursor_reset_to_wasm(this.tree[0],e.tree[0]),unmarshalTreeCursor(this)}},Node$1=class{static{__name(this,`Node`)}0=0;_children;_namedChildren;constructor(e,{id:t,tree:n,startIndex:r,startPosition:a,other:o}){assertInternal(e),this[0]=o,this.id=t,this.tree=n,this.startIndex=r,this.startPosition=a}id;startIndex;startPosition;tree;get typeId(){return marshalNode(this),C._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return marshalNode(this),C._ts_node_grammar_symbol_wasm(this.tree[0])}get type(){return this.tree.language.types[this.typeId]||`ERROR`}get grammarType(){return this.tree.language.types[this.grammarId]||`ERROR`}get isNamed(){return marshalNode(this),C._ts_node_is_named_wasm(this.tree[0])===1}get isExtra(){return marshalNode(this),C._ts_node_is_extra_wasm(this.tree[0])===1}get isError(){return marshalNode(this),C._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return marshalNode(this),C._ts_node_is_missing_wasm(this.tree[0])===1}get hasChanges(){return marshalNode(this),C._ts_node_has_changes_wasm(this.tree[0])===1}get hasError(){return marshalNode(this),C._ts_node_has_error_wasm(this.tree[0])===1}get endIndex(){return marshalNode(this),C._ts_node_end_index_wasm(this.tree[0])}get endPosition(){return marshalNode(this),C._ts_node_end_point_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get text(){return getText(this.tree,this.startIndex,this.endIndex,this.startPosition)}get parseState(){return marshalNode(this),C._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return marshalNode(this),C._ts_node_next_parse_state_wasm(this.tree[0])}equals(e){return this.tree===e.tree&&this.id===e.id}child(e){return marshalNode(this),C._ts_node_child_wasm(this.tree[0],e),unmarshalNode(this.tree)}namedChild(e){return marshalNode(this),C._ts_node_named_child_wasm(this.tree[0],e),unmarshalNode(this.tree)}childForFieldId(e){return marshalNode(this),C._ts_node_child_by_field_id_wasm(this.tree[0],e),unmarshalNode(this.tree)}childForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t===-1?null:this.childForFieldId(t)}fieldNameForChild(e){marshalNode(this);let t=C._ts_node_field_name_for_child_wasm(this.tree[0],e);return t?C.AsciiToString(t):null}fieldNameForNamedChild(e){marshalNode(this);let t=C._ts_node_field_name_for_named_child_wasm(this.tree[0],e);return t?C.AsciiToString(t):null}childrenForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1&&t!==0?this.childrenForFieldId(t):[]}childrenForFieldId(e){marshalNode(this),C._ts_node_children_by_field_id_wasm(this.tree[0],e);let t=C.getValue(TRANSFER_BUFFER,`i32`),n=C.getValue(TRANSFER_BUFFER+SIZE_OF_INT,`i32`),r=Array(t);if(t>0){let e=n;for(let n=0;n<t;n++)r[n]=unmarshalNode(this.tree,e),e+=SIZE_OF_NODE;C._free(n)}return r}firstChildForIndex(e){marshalNode(this);let t=TRANSFER_BUFFER+SIZE_OF_NODE;return C.setValue(t,e,`i32`),C._ts_node_first_child_for_byte_wasm(this.tree[0]),unmarshalNode(this.tree)}firstNamedChildForIndex(e){marshalNode(this);let t=TRANSFER_BUFFER+SIZE_OF_NODE;return C.setValue(t,e,`i32`),C._ts_node_first_named_child_for_byte_wasm(this.tree[0]),unmarshalNode(this.tree)}get childCount(){return marshalNode(this),C._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return marshalNode(this),C._ts_node_named_child_count_wasm(this.tree[0])}get firstChild(){return this.child(0)}get firstNamedChild(){return this.namedChild(0)}get lastChild(){return this.child(this.childCount-1)}get lastNamedChild(){return this.namedChild(this.namedChildCount-1)}get children(){if(!this._children){marshalNode(this),C._ts_node_children_wasm(this.tree[0]);let e=C.getValue(TRANSFER_BUFFER,`i32`),t=C.getValue(TRANSFER_BUFFER+SIZE_OF_INT,`i32`);if(this._children=Array(e),e>0){let n=t;for(let t=0;t<e;t++)this._children[t]=unmarshalNode(this.tree,n),n+=SIZE_OF_NODE;C._free(t)}}return this._children}get namedChildren(){if(!this._namedChildren){marshalNode(this),C._ts_node_named_children_wasm(this.tree[0]);let e=C.getValue(TRANSFER_BUFFER,`i32`),t=C.getValue(TRANSFER_BUFFER+SIZE_OF_INT,`i32`);if(this._namedChildren=Array(e),e>0){let n=t;for(let t=0;t<e;t++)this._namedChildren[t]=unmarshalNode(this.tree,n),n+=SIZE_OF_NODE;C._free(t)}}return this._namedChildren}descendantsOfType(e,t=ZERO_POINT,n=ZERO_POINT){Array.isArray(e)||(e=[e]);let r=[],a=this.tree.language.types;for(let t of e)t==`ERROR`&&r.push(65535);for(let t=0,n=a.length;t<n;t++)e.includes(a[t])&&r.push(t);let o=C._malloc(SIZE_OF_INT*r.length);for(let e=0,t=r.length;e<t;e++)C.setValue(o+e*SIZE_OF_INT,r[e],`i32`);marshalNode(this),C._ts_node_descendants_of_type_wasm(this.tree[0],o,r.length,t.row,t.column,n.row,n.column);let s=C.getValue(TRANSFER_BUFFER,`i32`),c=C.getValue(TRANSFER_BUFFER+SIZE_OF_INT,`i32`),l=Array(s);if(s>0){let e=c;for(let t=0;t<s;t++)l[t]=unmarshalNode(this.tree,e),e+=SIZE_OF_NODE}return C._free(c),C._free(o),l}get nextSibling(){return marshalNode(this),C._ts_node_next_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get previousSibling(){return marshalNode(this),C._ts_node_prev_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get nextNamedSibling(){return marshalNode(this),C._ts_node_next_named_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get previousNamedSibling(){return marshalNode(this),C._ts_node_prev_named_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get descendantCount(){return marshalNode(this),C._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return marshalNode(this),C._ts_node_parent_wasm(this.tree[0]),unmarshalNode(this.tree)}childWithDescendant(e){return marshalNode(this),marshalNode(e,1),C._ts_node_child_with_descendant_wasm(this.tree[0]),unmarshalNode(this.tree)}descendantForIndex(e,t=e){if(typeof e!=`number`||typeof t!=`number`)throw Error(`Arguments must be numbers`);marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return C.setValue(n,e,`i32`),C.setValue(n+SIZE_OF_INT,t,`i32`),C._ts_node_descendant_for_index_wasm(this.tree[0]),unmarshalNode(this.tree)}namedDescendantForIndex(e,t=e){if(typeof e!=`number`||typeof t!=`number`)throw Error(`Arguments must be numbers`);marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return C.setValue(n,e,`i32`),C.setValue(n+SIZE_OF_INT,t,`i32`),C._ts_node_named_descendant_for_index_wasm(this.tree[0]),unmarshalNode(this.tree)}descendantForPosition(e,t=e){if(!isPoint(e)||!isPoint(t))throw Error(`Arguments must be {row, column} objects`);marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return marshalPoint(n,e),marshalPoint(n+SIZE_OF_POINT,t),C._ts_node_descendant_for_position_wasm(this.tree[0]),unmarshalNode(this.tree)}namedDescendantForPosition(e,t=e){if(!isPoint(e)||!isPoint(t))throw Error(`Arguments must be {row, column} objects`);marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return marshalPoint(n,e),marshalPoint(n+SIZE_OF_POINT,t),C._ts_node_named_descendant_for_position_wasm(this.tree[0]),unmarshalNode(this.tree)}walk(){return marshalNode(this),C._ts_tree_cursor_new_wasm(this.tree[0]),new TreeCursor(INTERNAL,this.tree)}edit(e){if(this.startIndex>=e.oldEndIndex){this.startIndex=e.newEndIndex+(this.startIndex-e.oldEndIndex);let t,n;this.startPosition.row>e.oldEndPosition.row?(t=this.startPosition.row-e.oldEndPosition.row,n=this.startPosition.column):(t=0,n=this.startPosition.column,this.startPosition.column>=e.oldEndPosition.column&&(n=this.startPosition.column-e.oldEndPosition.column)),t>0?(this.startPosition.row+=t,this.startPosition.column=n):this.startPosition.column+=n}else this.startIndex>e.startIndex&&(this.startIndex=e.newEndIndex,this.startPosition.row=e.newEndPosition.row,this.startPosition.column=e.newEndPosition.column)}toString(){marshalNode(this);let e=C._ts_node_to_string_wasm(this.tree[0]),t=C.AsciiToString(e);return C._free(e),t}};function unmarshalCaptures(e,t,n,r,a){for(let o=0,s=a.length;o<s;o++){let s=C.getValue(n,`i32`);n+=SIZE_OF_INT;let c=unmarshalNode(t,n);n+=SIZE_OF_NODE,a[o]={patternIndex:r,name:e.captureNames[s],node:c}}return n}__name(unmarshalCaptures,`unmarshalCaptures`);function marshalNode(e,t=0){let n=TRANSFER_BUFFER+t*SIZE_OF_NODE;C.setValue(n,e.id,`i32`),n+=SIZE_OF_INT,C.setValue(n,e.startIndex,`i32`),n+=SIZE_OF_INT,C.setValue(n,e.startPosition.row,`i32`),n+=SIZE_OF_INT,C.setValue(n,e.startPosition.column,`i32`),n+=SIZE_OF_INT,C.setValue(n,e[0],`i32`)}__name(marshalNode,`marshalNode`);function unmarshalNode(e,t=TRANSFER_BUFFER){let n=C.getValue(t,`i32`);if(t+=SIZE_OF_INT,n===0)return null;let r=C.getValue(t,`i32`);t+=SIZE_OF_INT;let a=C.getValue(t,`i32`);t+=SIZE_OF_INT;let o=C.getValue(t,`i32`);t+=SIZE_OF_INT;let s=C.getValue(t,`i32`);return new Node$1(INTERNAL,{id:n,tree:e,startIndex:r,startPosition:{row:a,column:o},other:s})}__name(unmarshalNode,`unmarshalNode`);function marshalTreeCursor(e,t=TRANSFER_BUFFER){C.setValue(t+0*SIZE_OF_INT,e[0],`i32`),C.setValue(t+1*SIZE_OF_INT,e[1],`i32`),C.setValue(t+2*SIZE_OF_INT,e[2],`i32`),C.setValue(t+3*SIZE_OF_INT,e[3],`i32`)}__name(marshalTreeCursor,`marshalTreeCursor`);function unmarshalTreeCursor(e){e[0]=C.getValue(TRANSFER_BUFFER+0*SIZE_OF_INT,`i32`),e[1]=C.getValue(TRANSFER_BUFFER+1*SIZE_OF_INT,`i32`),e[2]=C.getValue(TRANSFER_BUFFER+2*SIZE_OF_INT,`i32`),e[3]=C.getValue(TRANSFER_BUFFER+3*SIZE_OF_INT,`i32`)}__name(unmarshalTreeCursor,`unmarshalTreeCursor`);function marshalPoint(e,t){C.setValue(e,t.row,`i32`),C.setValue(e+SIZE_OF_INT,t.column,`i32`)}__name(marshalPoint,`marshalPoint`);function unmarshalPoint(e){return{row:C.getValue(e,`i32`)>>>0,column:C.getValue(e+SIZE_OF_INT,`i32`)>>>0}}__name(unmarshalPoint,`unmarshalPoint`);function marshalRange(e,t){marshalPoint(e,t.startPosition),e+=SIZE_OF_POINT,marshalPoint(e,t.endPosition),e+=SIZE_OF_POINT,C.setValue(e,t.startIndex,`i32`),e+=SIZE_OF_INT,C.setValue(e,t.endIndex,`i32`),e+=SIZE_OF_INT}__name(marshalRange,`marshalRange`);function unmarshalRange(e){let t={};return t.startPosition=unmarshalPoint(e),e+=SIZE_OF_POINT,t.endPosition=unmarshalPoint(e),e+=SIZE_OF_POINT,t.startIndex=C.getValue(e,`i32`)>>>0,e+=SIZE_OF_INT,t.endIndex=C.getValue(e,`i32`)>>>0,t}__name(unmarshalRange,`unmarshalRange`);function marshalEdit(e,t=TRANSFER_BUFFER){marshalPoint(t,e.startPosition),t+=SIZE_OF_POINT,marshalPoint(t,e.oldEndPosition),t+=SIZE_OF_POINT,marshalPoint(t,e.newEndPosition),t+=SIZE_OF_POINT,C.setValue(t,e.startIndex,`i32`),t+=SIZE_OF_INT,C.setValue(t,e.oldEndIndex,`i32`),t+=SIZE_OF_INT,C.setValue(t,e.newEndIndex,`i32`),t+=SIZE_OF_INT}__name(marshalEdit,`marshalEdit`);function unmarshalLanguageMetadata(e){return{major_version:C.getValue(e,`i32`),minor_version:C.getValue(e+=SIZE_OF_INT,`i32`),patch_version:C.getValue(e+=SIZE_OF_INT,`i32`)}}__name(unmarshalLanguageMetadata,`unmarshalLanguageMetadata`);var LANGUAGE_FUNCTION_REGEX=/^tree_sitter_\w+$/,Language=class e{static{__name(this,`Language`)}0=0;types;fields;constructor(e,t){assertInternal(e),this[0]=t,this.types=Array(C._ts_language_symbol_count(this[0]));for(let e=0,t=this.types.length;e<t;e++)C._ts_language_symbol_type(this[0],e)<2&&(this.types[e]=C.UTF8ToString(C._ts_language_symbol_name(this[0],e)));this.fields=Array(C._ts_language_field_count(this[0])+1);for(let e=0,t=this.fields.length;e<t;e++){let t=C._ts_language_field_name_for_id(this[0],e);t===0?this.fields[e]=null:this.fields[e]=C.UTF8ToString(t)}}get name(){let e=C._ts_language_name(this[0]);return e===0?null:C.UTF8ToString(e)}get abiVersion(){return C._ts_language_abi_version(this[0])}get metadata(){return C._ts_language_metadata_wasm(this[0]),C.getValue(TRANSFER_BUFFER,`i32`)===0?null:unmarshalLanguageMetadata(TRANSFER_BUFFER+SIZE_OF_INT)}get fieldCount(){return this.fields.length-1}get stateCount(){return C._ts_language_state_count(this[0])}fieldIdForName(e){let t=this.fields.indexOf(e);return t===-1?null:t}fieldNameForId(e){return this.fields[e]??null}idForNodeType(e,t){let n=C.lengthBytesUTF8(e),r=C._malloc(n+1);C.stringToUTF8(e,r,n+1);let a=C._ts_language_symbol_for_name(this[0],r,n,+!!t);return C._free(r),a||null}get nodeTypeCount(){return C._ts_language_symbol_count(this[0])}nodeTypeForId(e){let t=C._ts_language_symbol_name(this[0],e);return t?C.UTF8ToString(t):null}nodeTypeIsNamed(e){return!!C._ts_language_type_is_named_wasm(this[0],e)}nodeTypeIsVisible(e){return!!C._ts_language_type_is_visible_wasm(this[0],e)}get supertypes(){C._ts_language_supertypes_wasm(this[0]);let e=C.getValue(TRANSFER_BUFFER,`i32`),t=C.getValue(TRANSFER_BUFFER+SIZE_OF_INT,`i32`),n=Array(e);if(e>0){let r=t;for(let t=0;t<e;t++)n[t]=C.getValue(r,`i16`),r+=SIZE_OF_SHORT}return n}subtypes(e){C._ts_language_subtypes_wasm(this[0],e);let t=C.getValue(TRANSFER_BUFFER,`i32`),n=C.getValue(TRANSFER_BUFFER+SIZE_OF_INT,`i32`),r=Array(t);if(t>0){let e=n;for(let n=0;n<t;n++)r[n]=C.getValue(e,`i16`),e+=SIZE_OF_SHORT}return r}nextState(e,t){return C._ts_language_next_state(this[0],e,t)}lookaheadIterator(e){let t=C._ts_lookahead_iterator_new(this[0],e);return t?new LookaheadIterator(INTERNAL,t,this):null}static async load(t){let n;if(t instanceof Uint8Array)n=t;else if(globalThis.process?.versions.node)n=await(await Promise.resolve().then(()=>require_rolldown_runtime.r(require("./__vite-browser-external-Dghh9khe.cjs").default,1))).readFile(t);else{let e=await fetch(t);if(!e.ok){let t=await e.text();throw Error(`Language.load failed with status ${e.status}.
105
111
 
106
112
  ${t}`)}let r=e.clone();try{n=await WebAssembly.compileStreaming(e)}catch(e){console.error(`wasm streaming compile failed:`,e),console.error(`falling back to ArrayBuffer instantiation`),n=new Uint8Array(await r.arrayBuffer())}}let r=await C.loadWebAssemblyModule(n,{loadAsync:!0}),a=Object.keys(r),o=a.find(e=>LANGUAGE_FUNCTION_REGEX.test(e)&&!e.includes(`external_scanner_`));if(!o)throw console.log(`Couldn't find language function in Wasm file. Symbols:
@@ -108,15 +114,12 @@ ${JSON.stringify(a,null,2)}`),Error(`Language.load failed: no language function
108
114
  `)[0],s=o.match(QUERY_WORD_REGEX)?.[0]??``;switch(C._free(r),e){case QueryErrorKind.Syntax:throw new QueryError(QueryErrorKind.Syntax,{suffix:`${a}: '${o}'...`},a,0);case QueryErrorKind.NodeName:throw new QueryError(e,{word:s},a,s.length);case QueryErrorKind.FieldName:throw new QueryError(e,{word:s},a,s.length);case QueryErrorKind.CaptureName:throw new QueryError(e,{word:s},a,s.length);case QueryErrorKind.PatternStructure:throw new QueryError(e,{suffix:`${a}: '${o}'...`},a,0)}}let o=C._ts_query_string_count(a),s=C._ts_query_capture_count(a),c=C._ts_query_pattern_count(a),l=Array(s),u=Array(c),d=Array(o);for(let e=0;e<s;e++){let t=C._ts_query_capture_name_for_id(a,e,TRANSFER_BUFFER),n=C.getValue(TRANSFER_BUFFER,`i32`);l[e]=C.UTF8ToString(t,n)}for(let e=0;e<c;e++){let t=Array(s);for(let n=0;n<s;n++)t[n]=C._ts_query_capture_quantifier_for_id(a,e,n);u[e]=t}for(let e=0;e<o;e++){let t=C._ts_query_string_value_for_id(a,e,TRANSFER_BUFFER),n=C.getValue(TRANSFER_BUFFER,`i32`);d[e]=C.UTF8ToString(t,n)}let f=Array(c),p=Array(c),m=Array(c),h=Array(c),g=Array(c);for(let e=0;e<c;e++){let t=C._ts_query_predicates_for_pattern(a,e,TRANSFER_BUFFER),n=C.getValue(TRANSFER_BUFFER,`i32`);h[e]=[],g[e]=[];let r=[],o=t;for(let t=0;t<n;t++){let t=C.getValue(o,`i32`);o+=SIZE_OF_INT;let n=C.getValue(o,`i32`);o+=SIZE_OF_INT,parsePattern(e,t,n,l,d,r,g,h,f,p,m)}Object.freeze(g[e]),Object.freeze(h[e]),Object.freeze(f[e]),Object.freeze(p[e]),Object.freeze(m[e])}C._free(r),this[0]=a,this.captureNames=l,this.captureQuantifiers=u,this.textPredicates=g,this.predicates=h,this.setProperties=f,this.assertedProperties=p,this.refutedProperties=m,this.exceededMatchLimit=!1}delete(){C._ts_query_delete(this[0]),this[0]=0}matches(e,t={}){let n=t.startPosition??ZERO_POINT,r=t.endPosition??ZERO_POINT,a=t.startIndex??0,o=t.endIndex??0,s=t.startContainingPosition??ZERO_POINT,c=t.endContainingPosition??ZERO_POINT,l=t.startContainingIndex??0,u=t.endContainingIndex??0,d=t.matchLimit??4294967295,f=t.maxStartDepth??4294967295,p=t.progressCallback;if(typeof d!=`number`)throw Error(`Arguments must be numbers`);if(this.matchLimit=d,o!==0&&a>o)throw Error("`startIndex` cannot be greater than `endIndex`");if(r!==ZERO_POINT&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw Error("`startPosition` cannot be greater than `endPosition`");if(u!==0&&l>u)throw Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(c!==ZERO_POINT&&(s.row>c.row||s.row===c.row&&s.column>c.column))throw Error("`startContainingPosition` cannot be greater than `endContainingPosition`");p&&(C.currentQueryProgressCallback=p),marshalNode(e),C._ts_query_matches_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,a,o,s.row,s.column,c.row,c.column,l,u,d,f);let m=C.getValue(TRANSFER_BUFFER,`i32`),h=C.getValue(TRANSFER_BUFFER+SIZE_OF_INT,`i32`),g=C.getValue(TRANSFER_BUFFER+2*SIZE_OF_INT,`i32`),_=Array(m);this.exceededMatchLimit=!!g;let v=0,y=h;for(let t=0;t<m;t++){let t=C.getValue(y,`i32`);y+=SIZE_OF_INT;let n=C.getValue(y,`i32`);y+=SIZE_OF_INT;let r=Array(n);if(y=unmarshalCaptures(this,e.tree,y,t,r),this.textPredicates[t].every(e=>e(r))){_[v]={patternIndex:t,captures:r};let e=this.setProperties[t];_[v].setProperties=e;let n=this.assertedProperties[t];_[v].assertedProperties=n;let a=this.refutedProperties[t];_[v].refutedProperties=a,v++}}return _.length=v,C._free(h),C.currentQueryProgressCallback=null,_}captures(e,t={}){let n=t.startPosition??ZERO_POINT,r=t.endPosition??ZERO_POINT,a=t.startIndex??0,o=t.endIndex??0,s=t.startContainingPosition??ZERO_POINT,c=t.endContainingPosition??ZERO_POINT,l=t.startContainingIndex??0,u=t.endContainingIndex??0,d=t.matchLimit??4294967295,f=t.maxStartDepth??4294967295,p=t.progressCallback;if(typeof d!=`number`)throw Error(`Arguments must be numbers`);if(this.matchLimit=d,o!==0&&a>o)throw Error("`startIndex` cannot be greater than `endIndex`");if(r!==ZERO_POINT&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw Error("`startPosition` cannot be greater than `endPosition`");if(u!==0&&l>u)throw Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(c!==ZERO_POINT&&(s.row>c.row||s.row===c.row&&s.column>c.column))throw Error("`startContainingPosition` cannot be greater than `endContainingPosition`");p&&(C.currentQueryProgressCallback=p),marshalNode(e),C._ts_query_captures_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,a,o,s.row,s.column,c.row,c.column,l,u,d,f);let m=C.getValue(TRANSFER_BUFFER,`i32`),h=C.getValue(TRANSFER_BUFFER+SIZE_OF_INT,`i32`),g=C.getValue(TRANSFER_BUFFER+2*SIZE_OF_INT,`i32`),_=[];this.exceededMatchLimit=!!g;let v=[],y=h;for(let t=0;t<m;t++){let t=C.getValue(y,`i32`);y+=SIZE_OF_INT;let n=C.getValue(y,`i32`);y+=SIZE_OF_INT;let r=C.getValue(y,`i32`);if(y+=SIZE_OF_INT,v.length=n,y=unmarshalCaptures(this,e.tree,y,t,v),this.textPredicates[t].every(e=>e(v))){let e=v[r];e.setProperties=this.setProperties[t],e.assertedProperties=this.assertedProperties[t],e.refutedProperties=this.refutedProperties[t],_.push(e)}}return C._free(h),C.currentQueryProgressCallback=null,_}predicatesForPattern(e){return this.predicates[e]}disableCapture(e){let t=C.lengthBytesUTF8(e),n=C._malloc(t+1);C.stringToUTF8(e,n,t+1),C._ts_query_disable_capture(this[0],n,t),C._free(n)}disablePattern(e){if(e>=this.predicates.length)throw Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);C._ts_query_disable_pattern(this[0],e)}didExceedMatchLimit(){return this.exceededMatchLimit}startIndexForPattern(e){if(e>=this.predicates.length)throw Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return C._ts_query_start_byte_for_pattern(this[0],e)}endIndexForPattern(e){if(e>=this.predicates.length)throw Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return C._ts_query_end_byte_for_pattern(this[0],e)}patternCount(){return C._ts_query_pattern_count(this[0])}captureIndexForName(e){return this.captureNames.indexOf(e)}isPatternRooted(e){return C._ts_query_is_pattern_rooted(this[0],e)===1}isPatternNonLocal(e){return C._ts_query_is_pattern_non_local(this[0],e)===1}isPatternGuaranteedAtStep(e){return C._ts_query_is_pattern_guaranteed_at_step(this[0],e)===1}},SoftNode=class{_startIndexOffset;_startRowOffset;_startColOffset;_endIndexOffset;_endRowOffset;_endColOffset;getReferencePoint;tree;treeText;constructor(e){this.tree=e.tree,this.treeText=e.treeText,this.getReferencePoint=e.getReferencePoint,this._startIndexOffset=e._startIndexOffset,this._startRowOffset=e._startRowOffset,this._startColOffset=e._startColOffset,this._endIndexOffset=e._endIndexOffset,this._endRowOffset=e._endRowOffset,this._endColOffset=e._endColOffset}get startIndex(){return this._startIndexOffset+this.getReferencePoint().index}get startPosition(){return{row:this._startRowOffset+this.getReferencePoint().position.row,column:this._startColOffset+this.getReferencePoint().position.column}}get endIndex(){return this._endIndexOffset+this.getReferencePoint().index}get endPosition(){return{row:this._endRowOffset+this.getReferencePoint().position.row,column:this._endColOffset+this.getReferencePoint().position.column}}},WhitespaceNode=class extends SoftNode{type=`whitespace`;typeId=-1;parent;text;children=[];constructor(e){super(e),this.parent=e.parent,this.text=e.text}toJSON(){return{type:this.type,typeId:this.typeId,text:this.text}}},SoftTextNode=class extends SoftNode{type=`text`;typeId=-2;parent;text;children=[];constructor(e){super(e),this.parent=e.parent,this.text=e.text}toJSON(){return{type:this.type,typeId:this.typeId,text:this.text}}},ExtendedNode=class{node;treeText;xxx=1;tree;type;typeId;text;_children;parent;constructor(e,t){this.node=e,this.treeText=t,this.tree=e.tree,this.treeText=t,this.type=e.type,this.typeId=e.typeId,this.text=e.text,this.parent=e.parent,this._children=e.children}get startIndex(){return this.node.startIndex}get endIndex(){return this.node.endIndex}get startPosition(){return this.node.startPosition}get endPosition(){return this.node.endPosition}get children(){return childrenWithSoftNodes(this,this._children,this.treeText)}toJSON(){return{typeId:this.typeId,type:this.type,text:this.text,startIndex:this.startIndex,endIndex:this.endIndex,children:this.children.map(e=>e.toJSON())}}},childrenWithSoftNodes=(e,t,n)=>{if(t?.length>0){let r=[],a=[...t],o=a.shift(),s=(t,a,o)=>{let{index:s,position:c}=a(),l=s,u=c,d=t.split(/(?<!\s)(?=\s+)/g),f=u.column,p=u.row;for(let t of d){if(t.length==0)continue;let u=l+t.length;if(t.match(/^\s/)){let d=p,m=f;p+=(t.match(/\n/g)||[]).length,d==p?f+=t.length:f=t.split(`
109
115
  `).slice(-1)[0].length,r.push(new WhitespaceNode({tree:e.tree,treeText:n,parent:o,getReferencePoint:a,text:t,_startIndexOffset:l-s,_startRowOffset:d-c.row,_startColOffset:m-c.column,_endIndexOffset:u-s,_endRowOffset:p-c.row,_endColOffset:f-c.column}))}else{let d=f;f+=t.length,r.push(new SoftTextNode({tree:e.tree,treeText:n,parent:o,getReferencePoint:a,text:t,_startIndexOffset:l-s,_startRowOffset:p-c.row,_startColOffset:d-c.column,_endIndexOffset:u-s,_endRowOffset:p-c.row,_endColOffset:f-c.column}))}l=u}};if(e.startIndex!=o.startIndex){let t=e;s(n.slice(e.startIndex,o.startIndex),()=>({index:t.startIndex,position:t.startPosition}),e)}r.push(o);let c=o;for(let t of a){if(c.endIndex!=t.startIndex){let r=c;s(n.slice(c.endIndex,t.startIndex),()=>({index:r.endIndex,position:r.endPosition}),e)}r.push(t),c=t}if(c.endIndex!=e.endIndex){let t=n.slice(c.endIndex,e.endIndex),r=c;s(t,()=>({index:r.endIndex,position:r.endPosition}),e,`L ${c.endIndex} ${e.endIndex} `)}return r.map(e=>new ExtendedNode(e,n))}return[]},hasBeenLoaded=!1;async function createParser(e,{assetLoad:t}){if(!hasBeenLoaded){hasBeenLoaded=!0;let e={wasmBinary:await t(`tree-sitter/web-tree-sitter.wasm`)};await Parser.init(e)}let n=new Parser,r=await Language.load(e);return n.setLanguage(r),n}var wasm_default=[{repo:`tree-sitter/tree-sitter`,version:`latest`,files:[`web-tree-sitter.tar.gz/web-tree-sitter.wasm`,`web-tree-sitter.tar.gz/web-tree-sitter.js`]},{repo:`ggodlewski/tree-sitter-mermaid`,version:`latest`,files:[`tree-sitter-mermaid.wasm`],queries:{"highlights.scm":`master/queries/highlights.scm`}},{repo:`tree-sitter-grammars/tree-sitter-markdown`,version:`latest`,files:[`tree-sitter-markdown.wasm`,`tree-sitter-markdown_inline.wasm`],queries:{"highlights.scm":`split_parser/tree-sitter-markdown/queries/highlights.scm`,"injections.scm":`split_parser/tree-sitter-markdown/queries/injections.scm`,"highlights-inline.scm":`split_parser/tree-sitter-markdown-inline/queries/highlights.scm`,"injections-inline.scm":`split_parser/tree-sitter-markdown-inline/queries/injections.scm`}},{repo:`tree-sitter-grammars/tree-sitter-diff`,version:`latest`,files:[`tree-sitter-diff.wasm`],queries:{"highlights.scm":`main/queries/highlights.scm`}},{repo:`tree-sitter-grammars/tree-sitter-xml`,version:`latest`,files:[`tree-sitter-xml.wasm`,`tree-sitter-dtd.wasm`],queries:{"highlights.scm":`master/queries/xml/highlights.scm`,"highlights-dtd.scm":`master/queries/dtd/highlights.scm`}},{repo:`tree-sitter/tree-sitter-html`,version:`latest`,files:[`tree-sitter-html.wasm`],queries:{"highlights.scm":`master/queries/highlights.scm`,"injections.scm":`master/queries/injections.scm`}},{repo:`tree-sitter/tree-sitter-css`,version:`latest`,files:[`tree-sitter-css.wasm`],queries:{"highlights.scm":`master/queries/highlights.scm`}},{repo:`tree-sitter-grammars/tree-sitter-toml`,version:`latest`,files:[`tree-sitter-toml.wasm`],queries:{"highlights.scm":`master/queries/highlights.scm`}},{repo:`tree-sitter/tree-sitter-json`,version:`latest`,files:[`tree-sitter-json.wasm`],queries:{"highlights.scm":`master/queries/highlights.scm`}},{repo:`tree-sitter/tree-sitter-regex`,version:`latest`,files:[`tree-sitter-regex.wasm`],queries:{"highlights.scm":`master/queries/highlights.scm`}},{repo:`tree-sitter/tree-sitter-rust`,version:`latest`,files:[`tree-sitter-rust.wasm`],queries:{"highlights.scm":`master/queries/highlights.scm`,"injections.scm":`master/queries/injections.scm`,"tags.scm":`master/queries/tags.scm`}},{repo:`tree-sitter/tree-sitter-typescript`,version:`latest`,files:[`tree-sitter-typescript.wasm`,`tree-sitter-tsx.wasm`],queries:{"highlights.scm":`master/queries/highlights.scm`,"locals.scm":`master/queries/locals.scm`,"tags.scm":`master/queries/tags.scm`}},{repo:`tree-sitter/tree-sitter-java`,version:`latest`,files:[`tree-sitter-java.wasm`],queries:{"highlights.scm":`master/queries/highlights.scm`,"tags.scm":`master/queries/tags.scm`}},{repo:`tree-sitter/tree-sitter-javascript`,version:`latest`,files:[`tree-sitter-javascript.wasm`],queries:{"highlights.scm":`master/queries/highlights.scm`,"highlights-jsx.scm":`master/queries/highlights-jsx.scm`,"highlights-params.scm":`master/queries/highlights-params.scm`,"injections.scm":`master/queries/injections.scm`,"locals.scm":`master/queries/locals.scm`,"tags.scm":`master/queries/tags.scm`}},{repo:`tree-sitter-grammars/tree-sitter-yaml`,files:[`tree-sitter-yaml.wasm`],queries:{"highlights.scm":`master/queries/highlights.scm`}}];function getLangsList(){return wasm_default.map(e=>e.repo.split(`-`).pop()).filter(e=>typeof e==`string`)}function getLangTreeSitter(e){let t=wasm_default.find(t=>t.repo.endsWith(`-`+e));if(!t)throw Error(`No grammar for: `+e);return{lang:e,dir:t.repo.split(`/`)[1],repo:t.repo,files:t.files,queries:t.queries}}function treeToTokens(e,t,n){let r=[],a=0,o=e=>{if(e)return n.substring(e.startIndex,e.endIndex)},s=(e,t)=>{let n=r[r.length-1];if(n?.type===`inline`){n.children||=[],n.children.push(e),n.content=e.content;return}let o=new Token(`inline`,``,0);o.info=t,o.level=a,o.children=[e],o.content=o.children.map(e=>e.content||``).join(``),r.push(o)},c=(e,t,n={row:0,column:0})=>{let o=e=>{if(e)return t.substring(e.startIndex,e.endIndex)},l=(e,t)=>{let r=e.split(`
110
116
  `),a=0;for(let e of r){if(a>0){let e=[n.row+t.startPosition?.row+a,n.row+t.endPosition?.row+a,0,0],r=new Token(`softbreak`,`wbr`,0);r.map=e,r.content=`
111
- `,s(r,`softbreak between text rows`)}let o=[n.row+t.startPosition?.row+a,n.row+t.endPosition?.row+a,n.column+t.startPosition?.column,(+t.endPosition.row==+t.startPosition.row?n.column:0)+t.endPosition?.column],c=new Token(`text`,``,0);c.map=o,c.meta=`noEscText`,c.content=r.length>1?e.replace(/^\s+/,``):e,s(c,`text`),a++}};for(let u of e){let e=[n.row+u.startPosition?.row,n.row+u.endPosition?.row,n.column+u.startPosition?.column,(+u.endPosition.row==+u.startPosition.row?n.column:0)+u.endPosition?.column];if(u.type.length===1){let t=new Token(`text`,``,0);t.map=e,t.meta=`noEscText`,t.content=o(u)||``,s(t,`walkInline`);continue}switch(u.type){case`block_continuation`:case`emphasis_delimiter`:case`code_span_delimiter`:break;case`inline`:case`text`:l(o(u)??``,u);break;case`latex_block`:{let t=u.children.find(e=>e?.type===`latex_span_delimiter`),n=u.children.filter(e=>e?.type!==`latex_span_delimiter`).map(e=>o(e)).join(``);if(o(t)===`$$`){let e=new Token(`fence`,`pre`,0);e.level=a,e.markup=`$$`,e.meta=`noEscText`,e.attrSet(`lang`,`latex`),e.content=n.trim(),r.push(e)}else{let t=new Token(`math`,``,0);t.attrSet(`lang`,`latex`),t.map=e,t.meta=`noEscText`,t.content=n,s(t,`latex_block`)}}break;case`whitespace`:{let t=o(u)||``;if(t===`
117
+ `,s(r,`softbreak between text rows`)}let o=[n.row+t.startPosition?.row+a,n.row+t.endPosition?.row+a,n.column+t.startPosition?.column,(+t.endPosition.row==+t.startPosition.row?n.column:0)+t.endPosition?.column],c=new Token(`text`,``,0);c.map=o,c.meta=`noEscText`,c.content=r.length>1?e.replace(/^\s+/,``):e,s(c,`text`),a++}};for(let u of e){let e=[n.row+u.startPosition?.row,n.row+u.endPosition?.row,n.column+u.startPosition?.column,(+u.endPosition.row==+u.startPosition.row?n.column:0)+u.endPosition?.column];if(u.type.length===1){let t=new Token(`text`,``,0);t.map=e,t.meta=`noEscText`,t.content=o(u)||``,s(t,`walkInline`);continue}switch(u.type){case`block_continuation`:case`emphasis_delimiter`:case`code_span_delimiter`:break;case`inline`:case`text`:l(o(u)??``,u);break;case`entity_reference`:{let e=o(u)??``,t=[n.row+u.startPosition?.row,n.row+u.endPosition?.row,0,0],r=new Token(`entity`,`entity`,0);r.map=t,r.content=e,s(r,`entity`)}break;case`latex_block`:{let t=u.children.find(e=>e?.type===`latex_span_delimiter`),n=u.children.filter(e=>e?.type!==`latex_span_delimiter`).map(e=>o(e)).join(``);if(o(t)===`$$`){let e=new Token(`fence`,`pre`,0);e.level=a,e.markup=`$$`,e.meta=`noEscText`,e.attrSet(`lang`,`latex`),e.content=n.trim(),r.push(e)}else{let t=new Token(`math`,``,0);t.attrSet(`lang`,`latex`),t.map=e,t.meta=`noEscText`,t.content=n,s(t,`latex_block`)}}break;case`whitespace`:{let t=o(u)||``;if(t===`
112
118
  `){let n=new Token(`softbreak`,`wbr`,0);n.map=e,n.content=t??``,s(n,`whitespace
113
119
  `);break}if(t&&t.match(/^\s+$/)){if(t.endsWith(`
114
- `)){let n=new Token(`hardbreak`,`wbr`,0);n.map=e,n.meta=`noEscText`,n.content=t??``,s(n,`whitespace hardbreak`)}else{let n=new Token(`text`,`br`,0);n.map=e,n.meta=`noEscText`,n.content=t??``,s(n,`whitespace space`)}break}if(t?.trim().length>0){l(t,u);break}}break;case`shortcut_link`:{let t=`a`,n=new Token(`link_open`,`a`,1),r=u.children.find(e=>e?.type===`link_destination`);n.attrSet(`href`,o(r)||``);let a=u.children.find(e=>e?.type===`link_title`);a&&n.attrSet(`title`,o(a)||``),s(n,`shortcut_link`),u.children.filter(e=>e.type===`link_text`).forEach(t=>{let n=new Token(`text`,``,0);n.map=e,n.meta=`noEscText`,n.content=o(t)??``,s(n,`link_text`)}),s(new Token(`link_close`,`a`,-1),`/shortcut_link`)}break;case`inline_link`:{let t=`a`,n=new Token(`link_open`,`a`,1),r=u.children.find(e=>e.type===`link_destination`);n.attrSet(`href`,r?.text||``);let a=u.children.find(e=>e.type===`link_title`);a&&n.attrSet(`title`,a.text||``),s(n,`inline_link`),u.children.filter(e=>e.type===`link_text`).forEach(t=>{let n=new Token(`text`,``,0);n.map=e,n.meta=`noEscText`,n.content=o(t)??``,s(n,`inline_link_txt`)}),s(new Token(`link_close`,`a`,-1),`/inline_link`)}break;case`image`:{let e=new Token(`image`,`img`,0),t=u.children.find(e=>e.type===`image_description`);e.attrSet(`alt`,t?.text||``);let n=u.children.find(e=>e.type===`link_destination`);e.attrSet(`src`,n?.text||``);let r=u.children.find(e=>e.type===`link_title`);r&&e.attrSet(`title`,r.text||``),s(e,`image`)}break;case`strong_emphasis`:{let e=u.children.find(e=>e.type===`emphasis_delimiter`),n=e?.text===`_`?`underline`:`strong`,r=e?.text===`_`?`u`:`strong`,a=new Token(n+`_open`,r,1);e?.text===`_`&&(a.markup=`__`),s(a,`strongem`),c(u.children,t);let l=new Token(n+`_close`,r,-1);o(e)===`_`&&(l.markup=`__`),s(l,`/strongem`)}break;case`emphasis`:{let e=u.children.find(e=>e.type===`emphasis_delimiter`),n=u.children.filter(e=>e.type!==`emphasis_delimiter`),r=e?.text===`_`?`underline`:`em`,a=e?.text===`_`?`u`:`em`;s(new Token(r+`_open`,a,1),`em`),c(n.filter(e=>!!e),t),s(new Token(r+`_close`,a,-1),`/em`)}break;case`strikethrough`:{let e=`strike`;s(new Token(`strike_open`,e,1),`s`),c(u.children.filter(e=>!!e),t),s(new Token(`strike_close`,e,-1),`/s`)}break;case`code_span`:{let e=`code`;s(new Token(`code_open`,e,1),`code`),c(u.children.filter(e=>!!e),t),s(new Token(`code_close`,e,-1),`/code`)}break;case`html_tag`:{let e=new Token(`html_block`,``,0);e.content=o(u)||``,s(e,`html_block`)}break;case`hard_line_break`:{let t=new Token(`hardbreak`,`br`,0);t.map=e,t.meta=`noEscText`,t.content=o(u)??``,s(t,`hard_line_break`)}break;case`backslash_escape`:{let t=new Token(`text`,``,0);t.map=e,t.meta=`noEscText`,t.content=o(u)??``,s(t,`backslash_escape`)}break;default:throw console.debug(`inline_node`,u),Error(`Unhandled inline node type: ${u.type}`)}}},l=(e,n={tableRowType:`tbody`,cellNo:0,cellAlign:[]})=>{if(e){if(e.type===`inline`){let n=o(e);if(!n)throw Error(`!inlineText`);let r=t.parse(n);if(!r)throw Error(`!inlineTree`);let a=new ExtendedNode(r.rootNode,n);c(a.children.length>0?a.children:[a],n,e.startPosition);return}if(!e.children||e.children.length===0){if(e.type===`text`||e.type.length===1){let t=new Token(`text`,``,0);t.map=[+e.startPosition?.row,+e.endPosition?.row,+e.startPosition?.column,+e.endPosition?.column],t.meta=`noEscText`,t.content=o(e)??``,s(t,`txt2`);return}if(e.type===`whitespace`){if(a===0||(o(e)||``).match(/^\n+$/))return;let t=o(e)||``;if(t&&t.match(/^\s+$/)){let t=new Token(`text`,`br`,0);t.map=[+e.startPosition?.row,+e.endPosition?.row,+e.startPosition?.column,+e.endPosition?.column],t.meta=`noEscText`,t.content=o(e)??``,s(t,`txt3`);return}if(t.trim().length>0){let n=new Token(`text`,``,0);n.map=[+e.startPosition?.row,+e.endPosition?.row,+e.startPosition?.column,+e.endPosition?.column],n.meta=`noEscText`,n.content=t??``,s(n,`txt4`);return}}}switch(e.type){case`block_continuation`:break;case`document`:case`section`:e.children.filter(e=>!!e).forEach(e=>l(e,n));break;case`thematic_break`:{let t=new Token(`hr`,`hr`,0);t.level=a,t.map=[+e.startPosition?.row,+e.endPosition?.row,+e.startPosition?.column,+e.endPosition?.column],t.markup=o(e)||``,t.attrSet(`margin_before`,`1`),t.attrSet(`margin_after`,`1`),r.push(t)}break;case`setext_heading`:{let t=e.children.filter(e=>!!e).find(e=>e.type.startsWith(`setext_`)&&e.type.endsWith(`_underline`)),s=t?.type.substring(7,9)||`h1`,c=new Token(`heading_open`,s,1);c.level=a,c.markup=o(t)||`#`,c.attrSet(`margin_before`,`1`),r.push(c);let u=e.children.filter(e=>!!e).filter(e=>!e.type.startsWith(`setext_`));a++,u.forEach(e=>l(e,n)),a--;let d=new Token(`heading_close`,s,-1);d.level=a,d.markup=o(t)||``,d.attrSet(`margin_after`,`1`),r.push(d)}break;case`atx_heading`:{let t=e.children.filter(e=>!!e).find(e=>e.type.startsWith(`atx_`)&&e.type.endsWith(`_marker`)),s=t?.type.substring(4,6)||`h1`,c=new Token(`heading_open`,s,1);c.level=a,c.markup=o(t)||`#`,c.attrSet(`margin_before`,`1`),r.push(c);let u=[...e.children.filter(e=>!!e)];u.length>0&&u[0].type.endsWith(`_marker`)&&u.splice(0,1),u.length>0&&u[0].type===`whitespace`&&u.splice(0,1),u.length>0&&u[u.length-1].type===`whitespace`&&u.splice(u.length-1,1),a++,u.forEach(e=>l(e,n)),a--;let d=new Token(`heading_close`,s,-1);d.level=a,d.attrSet(`margin_after`,`1`),r.push(d)}break;case`minus_metadata`:{let t=new Token(`frontmatter`,`frontmatter`,0);t.level=a,t.content=o(e)||``,r.push(t)}break;case`fenced_code_block`:{let t=`fence`,n=`pre`,s=e.children.filter(e=>!!e).find(e=>e.type===`info_string`),c=new Token(`fence`,`pre`,0);c.meta=`noEscText`,c.level=a,c.markup="```",s&&c.attrSet(`lang`,o(s)||``),c.content=[...e.children.filter(e=>!!e).filter(e=>e?.type===`code_fence_content`)].map(e=>o(e)||``).join(``),c.attrSet(`margin_before`,`1`),c.attrSet(`margin_after`,`1`),r.push(c)}break;case`block_quote`:{let t=`blockquote`,o=new Token(`blockquote_open`,t,1);o.level=a,o.attrSet(`margin_before`,`1`),r.push(o),a++,e.children?.filter(e=>![`block_quote_marker`].includes(e.type)).forEach(e=>l(e,n)),a--;let s=new Token(`blockquote_close`,t,-1);s.level=a,s.attrSet(`margin_after`,`1`),r.push(s)}break;case`indented_code_block`:{let t=new Token(`code_block`,`code_block`,0);t.level=a;let n=80;`indent`in e&&(n=e.indent.length);let o=e.text.split(`
120
+ `)){let n=new Token(`hardbreak`,`wbr`,0);n.map=e,n.meta=`noEscText`,n.content=t??``,s(n,`whitespace hardbreak`)}else{let n=new Token(`text`,`br`,0);n.map=e,n.meta=`noEscText`,n.content=t??``,s(n,`whitespace space`)}break}if(t?.trim().length>0){l(t,u);break}}break;case`shortcut_link`:{let t=`a`,n=new Token(`link_open`,`a`,1),r=u.children.find(e=>e?.type===`link_destination`);n.attrSet(`href`,o(r)||``);let a=u.children.find(e=>e?.type===`link_title`);a&&n.attrSet(`title`,o(a)||``),s(n,`shortcut_link`),u.children.filter(e=>e.type===`link_text`).forEach(t=>{let n=new Token(`text`,``,0);n.map=e,n.meta=`noEscText`,n.content=o(t)??``,s(n,`link_text`)}),s(new Token(`link_close`,`a`,-1),`/shortcut_link`)}break;case`inline_link`:{let t=`a`,n=new Token(`link_open`,`a`,1),r=u.children.find(e=>e.type===`link_destination`);n.attrSet(`href`,r?.text||``);let a=u.children.find(e=>e.type===`link_title`);a&&n.attrSet(`title`,a.text||``),s(n,`inline_link`),u.children.filter(e=>e.type===`link_text`).forEach(t=>{let n=new Token(`text`,``,0);n.map=e,n.meta=`noEscText`,n.content=o(t)??``,s(n,`inline_link_txt`)}),s(new Token(`link_close`,`a`,-1),`/inline_link`)}break;case`image`:{let e=new Token(`image`,`img`,0),t=u.children.find(e=>e.type===`image_description`);e.attrSet(`alt`,t?.text||``);let n=u.children.find(e=>e.type===`link_destination`);e.attrSet(`src`,n?.text||``);let r=u.children.find(e=>e.type===`link_title`);r&&e.attrSet(`title`,r.text||``),s(e,`image`)}break;case`strong_emphasis`:{let e=u.children.find(e=>e.type===`emphasis_delimiter`),n=e?.text===`_`?`underline`:`strong`,r=e?.text===`_`?`u`:`strong`,a=new Token(n+`_open`,r,1);e?.text===`_`&&(a.markup=`__`),s(a,`strongem`),c(u.children,t);let l=new Token(n+`_close`,r,-1);o(e)===`_`&&(l.markup=`__`),s(l,`/strongem`)}break;case`emphasis`:{let e=u.children.find(e=>e.type===`emphasis_delimiter`),n=u.children.filter(e=>e.type!==`emphasis_delimiter`),r=e?.text===`_`?`underline`:`em`,a=e?.text===`_`?`u`:`em`;s(new Token(r+`_open`,a,1),`em`),c(n.filter(e=>!!e),t),s(new Token(r+`_close`,a,-1),`/em`)}break;case`strikethrough`:{let e=`strike`;s(new Token(`strike_open`,e,1),`s`),c(u.children.filter(e=>!!e),t),s(new Token(`strike_close`,e,-1),`/s`)}break;case`code_span`:{let e=`code`;s(new Token(`code_open`,e,1),`code`),c(u.children.filter(e=>!!e),t),s(new Token(`code_close`,e,-1),`/code`)}break;case`html_tag`:{let e=new Token(`html_block`,``,0);e.content=o(u)||``,s(e,`html_block`)}break;case`hard_line_break`:{let t=new Token(`hardbreak`,`br`,0);t.map=e,t.meta=`noEscText`,t.content=o(u)??``,s(t,`hard_line_break`)}break;case`backslash_escape`:{let t=new Token(`text`,``,0);t.map=e,t.meta=`noEscText`,t.content=o(u)??``,s(t,`backslash_escape`)}break;default:{console.debug(`Unhandled inline node type: ${u.type}`,u);let t=new Token(`text`,``,0);t.map=e,t.meta=`noEscText`,t.content=`Error: Unhandled inline node type: ${u.type} ${JSON.stringify(u)}`,s(t,`backslash_escape`)}break}}},l=(e,n={tableRowType:`tbody`,cellNo:0,cellAlign:[]})=>{if(e){if(e.type===`inline`){let n=o(e);if(!n)throw Error(`!inlineText`);let r=t.parse(n);if(!r)throw Error(`!inlineTree`);let a=new ExtendedNode(r.rootNode,n);c(a.children.length>0?a.children:[a],n,e.startPosition);return}if(!e.children||e.children.length===0){if(e.type===`text`||e.type.length===1){let t=new Token(`text`,``,0);t.map=[+e.startPosition?.row,+e.endPosition?.row,+e.startPosition?.column,+e.endPosition?.column],t.meta=`noEscText`,t.content=o(e)??``,s(t,`txt2`);return}if(e.type===`whitespace`){if(a===0||(o(e)||``).match(/^\n+$/))return;let t=o(e)||``;if(t&&t.match(/^\s+$/)){let t=new Token(`text`,`br`,0);t.map=[+e.startPosition?.row,+e.endPosition?.row,+e.startPosition?.column,+e.endPosition?.column],t.meta=`noEscText`,t.content=o(e)??``,s(t,`txt3`);return}if(t.trim().length>0){let n=new Token(`text`,``,0);n.map=[+e.startPosition?.row,+e.endPosition?.row,+e.startPosition?.column,+e.endPosition?.column],n.meta=`noEscText`,n.content=t??``,s(n,`txt4`);return}}}switch(e.type){case`block_continuation`:break;case`document`:case`section`:e.children.filter(e=>!!e).forEach(e=>l(e,n));break;case`thematic_break`:{let t=new Token(`hr`,`hr`,0);t.level=a,t.map=[+e.startPosition?.row,+e.endPosition?.row,+e.startPosition?.column,+e.endPosition?.column],t.markup=o(e)||``,t.attrSet(`margin_before`,`1`),t.attrSet(`margin_after`,`1`),r.push(t)}break;case`setext_heading`:{let t=e.children.filter(e=>!!e).find(e=>e.type.startsWith(`setext_`)&&e.type.endsWith(`_underline`)),s=t?.type.substring(7,9)||`h1`,c=new Token(`heading_open`,s,1);c.level=a,c.markup=o(t)||`#`,c.attrSet(`margin_before`,`1`),r.push(c);let u=e.children.filter(e=>!!e).filter(e=>!e.type.startsWith(`setext_`));a++,u.forEach(e=>l(e,n)),a--;let d=new Token(`heading_close`,s,-1);d.level=a,d.markup=o(t)||``,d.attrSet(`margin_after`,`1`),r.push(d)}break;case`atx_heading`:{let t=e.children.filter(e=>!!e).find(e=>e.type.startsWith(`atx_`)&&e.type.endsWith(`_marker`)),s=t?.type.substring(4,6)||`h1`,c=new Token(`heading_open`,s,1);c.level=a,c.markup=o(t)||`#`,c.attrSet(`margin_before`,`1`),r.push(c);let u=[...e.children.filter(e=>!!e)];u.length>0&&u[0].type.endsWith(`_marker`)&&u.splice(0,1),u.length>0&&u[0].type===`whitespace`&&u.splice(0,1),u.length>0&&u[u.length-1].type===`whitespace`&&u.splice(u.length-1,1),a++,u.forEach(e=>l(e,n)),a--;let d=new Token(`heading_close`,s,-1);d.level=a,d.attrSet(`margin_after`,`1`),r.push(d)}break;case`minus_metadata`:{let t=new Token(`frontmatter`,`frontmatter`,0);t.level=a,t.content=o(e)||``,r.push(t)}break;case`fenced_code_block`:{let t=`fence`,n=`pre`,s=e.children.filter(e=>!!e).find(e=>e.type===`info_string`),c=new Token(`fence`,`pre`,0);c.meta=`noEscText`,c.level=a,c.markup="```",s&&c.attrSet(`lang`,o(s)||``),c.content=[...e.children.filter(e=>!!e).filter(e=>e?.type===`code_fence_content`)].map(e=>o(e)||``).join(``),c.attrSet(`margin_before`,`1`),c.attrSet(`margin_after`,`1`),r.push(c)}break;case`block_quote`:{let t=`blockquote`,o=new Token(`blockquote_open`,t,1);o.level=a,o.attrSet(`margin_before`,`1`),r.push(o),a++,e.children?.filter(e=>![`block_quote_marker`].includes(e.type)).forEach(e=>l(e,n)),a--;let s=new Token(`blockquote_close`,t,-1);s.level=a,s.attrSet(`margin_after`,`1`),r.push(s)}break;case`indented_code_block`:{let t=new Token(`code_block`,`code_block`,0);t.level=a;let n=80;`indent`in e&&(n=e.indent.length);let o=e.text.split(`
115
121
  `);for(let e of o){if(e.trim().length===0)continue;let t=e.match(/^ +/);t?n>t[0].length&&(n=t[0].length):n=0}let s=o.map(e=>e.substring(n)).join(`
116
- `);t.attrSet(`indent`,``+n),t.content=s,t.attrSet(`margin_before`,`1`),t.attrSet(`margin_after`,`1`),r.push(t)}break;case`paragraph`:{let t=`p`,o=new Token(`paragraph_open`,`p`,1);o.level=a,o.attrSet(`margin_before`,`1`),r.push(o),a++,e.children?.forEach(e=>l(e,n)),a--;let s=new Token(`paragraph_close`,`p`,-1);s.level=a,s.attrSet(`margin_after`,`1`),r.push(s)}break;case`pipe_table_cell`:{let t=n.tableRowType===`thead`?`th`:`td`,o=n.tableRowType===`thead`?`th`:`td`,c=new Token(t+`_open`,o,1);c.attrSet(`align`,n.cellAlign[n.cellNo]||`left`),c.level=a,r.push(c),a++;{let t=`p`,o=new Token(`paragraph_open`,`p`,1);o.level=a,r.push(o);let c=[...e.children];for(;c.length>0&&c[c.length-1].type===`whitespace`;)c.splice(c.length-1,1);if(c.length>0)c.forEach(e=>l(e,n));else{let t=[e.startPosition?.row,e.endPosition?.row,e.startPosition?.column,e.endPosition?.column],n=new Token(`text`,``,0);n.map=t,n.meta=`noEscText`,n.content=e.text?.replace(/\s+$/,``)??``,s(n,`txt5`)}let u=new Token(`paragraph_close`,`p`,-1);u.level=a,r.push(u)}a--;let u=new Token(t+`_close`,o,-1);u.level=a,r.push(u),n.cellNo++}break;case`pipe_table_header`:case`pipe_table_row`:{let t=`tr`,o=new Token(`tr_open`,`tr`,1);o.level=a,r.push(o),a++,e.children.filter(e=>!!e).filter(e=>e.type===`pipe_table_cell`).forEach(e=>l(e,n)),a--;let s=new Token(`tr_close`,`tr`,-1);s.level=a,r.push(s)}break;case`pipe_table`:{let t=`table`,o=new Token(`table_open`,t,1);o.level=a,o.attrSet(`margin_before`,`1`),r.push(o),a++;let s=e.children.filter(e=>!!e).filter(e=>e.type===`pipe_table_delimiter_row`),c=[];if(s.length>0){let e=s[0].children.filter(e=>!!e).filter(e=>e.type===`pipe_table_delimiter_cell`);for(let t=0;t<e.length;t++)e[t].children.filter(e=>!!e).find(e=>e.type===`pipe_table_align_right`)?c.push(`right`):c.push(`left`)}let u=e.children.filter(e=>!!e).filter(e=>e.type===`pipe_table_header`);if(u.length>0){let e=`thead`,t=new Token(`thead_open`,e,1);t.level=a,r.push(t),a++,u.forEach(e=>l(e,{...n,tableRowType:`thead`,cellNo:0,cellAlign:c})),a--;let o=new Token(`thead_close`,e,-1);o.level=a,r.push(o)}let d=e.children?.filter(e=>e?.type===`pipe_table_row`);d.length>0&&(a++,d.filter(e=>!!e).forEach(e=>l(e,{...n,tableRowType:`tbody`,cellAlign:c})),a--),a--;let f=new Token(`table_close`,t,-1);f.level=a,f.attrSet(`margin_after`,`1`),r.push(f)}break;case`list`:{let t=`bullet_list`,s=`ul`,c=``,u=e.children.filter(e=>!!e).find(e=>e.type===`list_item`);if(u){let e=u.children.filter(e=>!!e).find(e=>e.type.startsWith(`task_list_marker`)),n=u.children.filter(e=>!!e).find(e=>e.type.startsWith(`list_marker_dot`));e?(t=`task_list`,s=`ul`):n&&(t=`ordered_list`,s=`ol`,c=(o(n)||``).trim().replace(`.`,``))}let d=new Token(t+`_open`,s,1);d.level=a,d.markup=s===`ol`?`.`:`*`,d.attrSet(`symbol`,s===`ol`?`1`:`*`),c&&d.attrSet(`start`,c),d.attrSet(`margin_before`,`1`),r.push(d),a++,e.children.filter(e=>!!e).forEach(e=>l(e,n)),a--;let f=new Token(t+`_close`,s,-1);f.level=a,f.attrSet(`margin_after`,`1`),r.push(f)}break;case`list_item`:{let t=e.children.filter(e=>!!e).find(e=>e.type.startsWith(`task_list_marker_`)),s=e.children.filter(e=>!!e).find(e=>e.type.startsWith(`list_marker_`));if(!s)break;let c=t?`task_item`:`list_item`,u=`li`,d=new Token(c+`_open`,`li`,1);d.level=a,d.markup=(o(s)||``).trim(),s.type===`list_marker_dot`&&(d.info=``,d.markup=``),t&&(t.type,d.attrSet(`checked`,t.type===`task_list_marker_checked`?`checked`:``)),r.push(d),a++,l(e.children.filter(e=>!!e).find(e=>e.type===`paragraph`),n);let f=e.children.filter(e=>!!e).filter(e=>e.type===`list`);for(let e of f)l(e,n);a--;let p=new Token(c+`_close`,`li`,-1);p.level=a,r.push(p)}break;case`html_block`:{let t=new Token(`html_block`,``,0);t.level=a,t.content=o(e)??``,t.attrSet(`margin_before`,`1`),t.attrSet(`margin_after`,`1`),r.push(t)}break;case`text`:{let t=new Token(`text`,``,0);t.level=a,t.content=o(e)??``,r.push(t)}break;default:throw console.warn(`Unhandled node type: ${e.type}, children: ${e.children.map(e=>e.type).join(`, `)}`,{...e,children:void 0,_children:void 0,tree:void 0}),Error(`Unhandled node type: ${e.type}`)}}};return l(e),r}async function sitterTokenizer(e){let t=getLangTreeSitter(`markdown`),n=t.files.find(e=>e.indexOf(`_inline`)===-1),r=t.files.find(e=>e.indexOf(`_inline`)>-1),a=await e(t.dir+`/`+n),o=await e(t.dir+`/`+r),s=await createParser(a,{assetLoad:e}),c=await createParser(o,{assetLoad:e});return{parse:e=>{let t=s.parse(e);if(!t)throw Error(`Tree is null`);return treeToTokens(new ExtendedNode(t.rootNode,e),c,e)}}}function listIsTight(e,t){for(;++t<e.length;)if(e[t].type!=`list_item_open`)return e[t].hidden;return!1}async function mdToPmConverter(e,t,n){return mdToPmConverterText(new TextDecoder().decode(e),t,n)}async function mdToPmConverterText(e,t,n){if(!t.assetLoad)throw Error(`No config.assetLoad`);let r=new MarkdownParser(n,await sitterTokenizer(t.assetLoad),{frontmatter:{custom:(e,n)=>{let r=e.stack[0];if(r?.type.name===`doc`){let e=n.content,a=e.indexOf(`
117
- ---
118
- `,4);if(e.startsWith(`---
119
- `)&&a>-1){let n=t.yaml?.parse(e.substring(4,a))||void 0;r.attrs={...r.attrs,meta:n}}}}},blockquote:{block:`blockquote`},paragraph:{block:`paragraph`},task_item:{block:`task_item`},task_list:{block:`task_list`},list_item:{block:`list_item`},bullet_list:{block:`bullet_list`,getAttrs:(e,t,n)=>({tight:listIsTight(t,n)})},ordered_list:{block:`ordered_list`,getAttrs:(e,t,n)=>({start:+e.attrGet(`start`)||1,tight:listIsTight(t,n)})},dl:{block:`dl`},dt:{block:`dt`},dd:{block:`dd`},heading:{block:`heading`,getAttrs:e=>({level:+e.tag.slice(1)})},code_block:{block:`code_block`,getAttrs:e=>({lang:e.attrGet(`lang`)||void 0}),noCloseToken:!0},fence:{block:`code_block`,getAttrs:e=>({lang:e.attrGet(`lang`)||void 0}),noCloseToken:!0},hr:{custom:(e,t,r,a)=>{e.openNode(n.nodes.paragraph,{}),e.addNode(n.nodes.hr,{}),e.closeNode()}},image:{node:`image`,getAttrs:e=>{let t=e.children?e.children[0]:void 0;return{src:e.attrGet(`src`),title:e.attrGet(`title`)||null,alt:t?.content||null}}},hardbreak:{node:`br`},em:{mark:`em`},underline:{mark:`underline`},strong:{mark:`strong`},strike:{mark:`strike`},link:{mark:`link`,getAttrs:e=>({href:e.attrGet(`href`),title:e.attrGet(`title`)||null})},code:{mark:`code`},html_block:{custom:(e,t,r,a)=>{let o=DOMParser$1.fromSchema(n).parse(elementFromString(t.content));e.importNodes(o.children)}},footnote_ref:{block:`code_block`},table:{block:`table`},tr:{block:`table_row`},td:{block:`table_cell`},th:{block:`table_header`},thead:{ignore:!0}}).parse(e),a=[...t.hooks||[]],o=EditorState.create({doc:r}),s=e=>{o=o.apply(e)};if(a.length>0)for(let e of a)await e(o,e=>s(e));return o.doc}var addEmptyLines=(e,t)=>{let n=e.doc,r=e.tr,a=e.schema.nodes.br,o=e.schema.nodes.softbreak;function s(e,t,n=0,c=0){let l=0,u=!1;for(let t=0;t<e.length;t++){let d=e[t];if([`image`,`node_bookmark`].includes(d.type.name)&&t>0){let s=e[t-1];if(s.type!==o)if(s.type===a)r.setNodeMarkup(r.mapping.map(n+l-s.nodeSize),o);else{let e=o.createAndFill();e&&r.insert(r.mapping.map(n+l),e)}}if(d.type.name===`softbreak`){let a=e[t-1];e[t+1],a?.type.name===`softbreak`&&r.delete(r.mapping.map(n+l),r.mapping.map(n+l+d.nodeSize)),a?.textContent?.endsWith(` `)&&r.delete(r.mapping.map(n+l),r.mapping.map(n+l+d.nodeSize)),u||r.delete(r.mapping.map(n+l),r.mapping.map(n+l+d.nodeSize))}else u=!0;s(d.children,d,n+l+1,c+1),l+=d.nodeSize}}return s(n.children,n),t&&t(r),r.docChanged},fixIdLinks=(e,t)=>{let n=e.tr,r=e.schema.marks.link;return e.doc.descendants((e,t)=>{e.marks.forEach(a=>{if(a.type===r&&a.attrs.href.startsWith(`#`)){let o=(e.text||e.textBetween(0,e.content.size)).toLowerCase().replace(/[^\w]+/g,` `).trim().replaceAll(` `,`-`);o&&(n=n.removeMark(t,t+e.nodeSize,r).addMark(t,t+e.nodeSize,r.create({...a.attrs,href:`#`+o})))}})}),t&&t(n),n.docChanged},fixShortCodes=(e,t)=>{let n=e.doc,r=e.tr,a=e.schema.nodes.br,o=e.schema.nodes.softbreak;if(!a)throw Error(`No hardbreak type in schema`);if(!o)throw Error(`No softbreak type in schema`);function s(e,t=0,n=0){e.forEach((c,l,u)=>{if(c.type.name===`shortcode_inline`){if(u>1){let n=e.child(u-1);n.type===a&&(r=r.setNodeMarkup(t+l-n.nodeSize,o))}u<e.childCount-1&&e.child(u+1).type===a&&(r=r.setNodeMarkup(t+l+c.nodeSize,o))}s(c,t+l+1,n+1)})}return s(n),t&&t(r),r.steps.length>0},removeEmptyTags=(e,t)=>{let n=e.schema.nodes.paragraph,r=e.tr;return e.doc.descendants((e,t)=>{if([`paragraph`].includes(e.type.name)){let n=e.children.every(e=>e.isText&&e.textContent===``);(e.childCount===0||n)&&r.deleteRange(r.mapping.map(t),r.mapping.map(t+e.nodeSize))}else if([`heading`].includes(e.type.name)){let a=e.children.find(e=>e.type.name===`node_bookmark`),o=e.children.every(e=>e.isText&&e.textContent===``||e.type.name===`node_bookmark`);a&&o?r.setNodeMarkup(r.mapping.map(t),n):(e.childCount===0||o)&&r.deleteRange(r.mapping.map(t),r.mapping.map(t+e.nodeSize))}}),t&&t(r),r.docChanged},removeSuggest=(e,t)=>{let n={},r=e.tr,a=e.doc,o=`comment`;a.descendants((e,t)=>{if(e.type.name===`comment`&&e.attrs.id){let r=e.attrs.id;n[r]||(n[r]=[]),e.attrs.nesting===1&&(n[r][0]={node:e,pos:t}),e.attrs.nesting===-1&&(n[r][1]={node:e,pos:t})}});for(let e in n){let t=n[e][0],a=n[e][1];if(t&&a){let e=t.pos,n=a.pos+a.node.nodeSize;r.replace(r.mapping.map(e),r.mapping.map(n))}}return t&&t(r),r.docChanged},rewriteUrls=e=>async(t,n)=>{let r=e?.();if(!r)return!1;let a=t.tr,o=t.schema.marks.link,s=t.schema.nodes.image,c=[],l=[];t.doc.descendants((e,t)=>{e.marks.forEach(n=>{n.type===o&&c.push([n,t,t+e.nodeSize])}),e.type===s&&l.push([e,t])});for(let[e,n,o]of c){let s=e.attrs.href,c={},l=await r(s,{type:`A`,dest:`md`,setMeta:(e,t)=>{c[e]=t}});if(l!==s||c.mdTemplate){let r=c.mdTemplate;a.removeMark(a.mapping.map(n),a.mapping.map(o),e);let u=t.schema.mark(`link`,{...e.attrs,href:l,origUrl:s,mdTemplate:r});a.addMark(a.mapping.map(n),a.mapping.map(o),u)}}for(let[e,t]of l){let n=e.attrs.src,o={},s=await r(n,{type:`IMG`,dest:`md`,setMeta:(e,t)=>{o[e]=t}});if(s!==n||o.mdTemplate){let r=o.mdTemplate;a.setNodeMarkup(a.mapping.map(t),null,{...e.attrs,src:s,origUrl:n,mdTemplate:r})}}return n&&n(a),a.docChanged},trimLines=(e,t)=>{let n=e.doc,r=e.schema,a=e.tr,o=e.schema.nodes.br,s=e.schema.nodes.softbreak,c=e.schema.nodes.paragraph;function l(e,t,n=0,u=0){let d=0;if(t.type.name===`code_block`&&t.textContent.trim())return;function f(t,o){let s=n+o;for(let n=t-1;n>=0;n--){let t=e[n];if(t?.type.name!==`text`)break;let o=t.text||``,c=o.replace(/[ \t\u00A0]+$/,``);if(c!==o){let e=s-t.nodeSize;c.length>0?a.replaceRangeWith(a.mapping.map(e),a.mapping.map(s),r.text(c)):a.replace(a.mapping.map(e),a.mapping.map(s))}else break;s-=t.nodeSize;break}}let p=!1;for(let m=0;m<e.length;m++){let h=e[m];if(h.isText){let e=h.text||``;if(e.match(/^([ \t\u00A0]+)/)&&!p&&c!==t.type){e=e.replace(/^[ \t\u00A0]+/,``);let t=n+d,o=t+h.nodeSize;e?a.replaceRangeWith(a.mapping.map(t),a.mapping.map(o),r.text(e)):a.replace(a.mapping.map(t),a.mapping.map(o))}e&&(p=!0)}o===h.type&&(f(m,d),m+1<e.length&&(e[m+1].type===o||e[m+1].type===s)&&a.setNodeMarkup(a.mapping.map(n+d),s)),l(h.children,h,n+d+1,u+1),d+=h.nodeSize}f(e.length,d)}return l(n.children,n),t&&t(a),a.docChanged},insertToc=(e,t)=>{let n=e.doc,r=e.tr,a=e.schema.nodes.br,o=e.schema.nodes.softbreak;if(!a)throw Error(`No hardbreak type in schema`);if(!o)throw Error(`No softbreak type in schema`);return n.forEach((e,t,n)=>{if(e.type.name===`bullet_list`&&e.attrs.toc){let t=e.copy(Fragment.from(e.content));r.insert(0,t)}}),t&&t(r),r.steps.length>0},addEnterAfterImage=(e,t)=>{let n=e.tr,r=e.schema.nodes.image,a=e.schema.nodes.br,o=e.schema.nodes.softbreak;function s(t,c=0,l=0){t.forEach((u,d,f)=>{if(u.type!==r)return;let p=t.nodeAt(f+1);if(p?.type===a&&p?.type===o)return;let m=c+d+u.nodeSize;n.insert(n.mapping.map(m),Fragment.from([e.schema.node(`softbreak`),e.schema.node(`softbreak`)])),s(u,c+d+1,l+1)})}return s(e.doc),t&&t(n),n.docChanged},fixParaEnding=(e,t)=>{let n=e.doc,r=e.tr,a=e.schema.nodes.br,o=e.schema.nodes.paragraph;function s(e,t,n=0,c=0){if(t.type===o){let o=t.content.size;for(let t=e.length-1;t>=0;t--){let s=e[t];if(s.type!==a)break;o-=s.nodeSize;let c=n+o,l=c+s.nodeSize;r.replace(r.mapping.map(c),r.mapping.map(l))}return}let l=0;for(let t=0;t<e.length;t++){let r=e[t];s(r.children,r,n+l+1,c+1),l+=r.nodeSize}}return s(n.children,n),t&&t(r),r.docChanged};function getDefaultsPreProcessFilters(e){return[insertToc,fixShortCodes,removeSuggest,removeEmptyTags,fixIdLinks,fixParaEnding,trimLines,addEnterAfterImage,addEmptyLines,rewriteUrls(e.getUrlRewriter)]}var MarkdownContentMapper=class e{result;rawTextArr;constructor(e,t){this.result=t,this.rawTextArr=[];for(let e of t.rawTextMap)e.nodeIdx>=0&&this.rawTextArr.push({nodeIdx:e.nodeIdx,maxNodeIdx:e.nodeIdx,targetPos:e.targetPos,targetRow:e.targetRow,targetCol:e.targetCol});this.rawTextArr.sort((e,t)=>e.nodeIdx-t.nodeIdx);for(let t=0;t<this.rawTextArr.length;t++){let n=t+1;n<this.rawTextArr.length?this.rawTextArr[t].maxNodeIdx=this.rawTextArr[n].nodeIdx-1:this.rawTextArr[t].maxNodeIdx=e}}getTextContent(){return this.result.content}toRawTextPos(e){for(let t=0;t<this.rawTextArr.length;t++){let n=this.rawTextArr[t];if(e>=n.nodeIdx&&e<=n.maxNodeIdx)return n.targetPos+e-n.nodeIdx}return-1}toRawTextLineCol(e){for(let t=0;t<this.rawTextArr.length;t++){let n=this.rawTextArr[t];if(e>=n.nodeIdx&&e<=n.maxNodeIdx)return[n.targetRow,n.targetCol+e-n.nodeIdx]}return[0,0]}fromLineChar(e,t){for(let n=0;n<this.rawTextArr.length;n++){let r=this.rawTextArr[n],a=r.maxNodeIdx-r.nodeIdx+1;if(r.targetRow===e){if(t>=r.targetCol&&t<r.targetCol+a){let e=t-r.targetCol;return r.nodeIdx+e}let e=this.rawTextArr[n+1];if((!e||e.targetRow>r.targetRow)&&t>=r.targetCol+a)return r.maxNodeIdx}}return-1}static async create(t,n){let r=await extPmToMdConverter(t.doc,n,t.schema,new EventTarget);return new e(t.doc.nodeSize,r)}},MarkdownPluginState=class{editor;extensionMarkdown;capturing=!1;workspace;constructor(e,t){this.editor=e,this.extensionMarkdown=t,this.workspace=e.ci.resolve(`workspace`),this.performSnapshot=debounce(this.performSnapshot.bind(this),800)}async performSnapshot(){let e=this.editor.version,t=this.editor.config.uri;if(!t)return;let n={version:e,state:this.editor.state,materialized:void 0},r=async()=>(n.materialized||=await MarkdownContentMapper.create(n.state,this.extensionMarkdown.config),n.materialized);this.workspace.getFile(t)?this.workspace.modifyFile({uri:t,lang:`markdown`,version:e,getContentMapper:r}):this.workspace.openFile({uri:t,lang:`markdown`,version:e,getContentMapper:r})}};function createMarkdownPlugin(e,t){return new Plugin({state:{init(){return new MarkdownPluginState(t,e)},apply(e,t,n,r){return e.docChanged&&t.capturing&&t.performSnapshot(),t}},view(){return{destroy(){let e=t.config.uri;e&&t.ci.resolve(`workspace`).closeFile(e)}}}})}var ExtensionMarkdown=class extends Extension{config;name=`markdown`;hooks={};urlFromRewriter;urlToRewriter;constructor(e={}){super(e),this.config=e}getConverters(e,t){let n={"text/x-markdown":{fromDoc:n=>pmToMdConverter(n,{assetLoad:this.editor.config.assetLoad,...this.config,urlRewriter:this.urlToRewriter,hooks:this.hooks[`pm2md.pre`],yaml:e.ci.resolve(`yaml`)},t,e),toDoc:n=>mdToPmConverter(n,{assetLoad:this.editor.config.assetLoad,...this.config,urlRewriter:this.urlFromRewriter,hooks:this.hooks[`md2pm.post`],yaml:e.ci.resolve(`yaml`)},t)}};return n[`text/markdown`]=n[`text/x-markdown`],n}toMarkdown(e){return extPmToMdConverter(e,{sourceMap:!0,yaml:this.editor.ci.resolve(`yaml`)},this.editor.schema,this.editor)}async fromMarkdown(e){let t=(await mdToPmConverterText(e,{assetLoad:this.editor.config.assetLoad,...this.config},this.editor.schema)).content;if(t.content.length===1){let e=t.content[0];if(e.type.name===`paragraph`)return new Slice(e.content,0,0)}return new Slice(t,0,0)}created(){this.editor.schema.topNodeType.name===`doc`?this.hooks[`pm2md.pre`]=getDefaultsPreProcessFilters({getUrlRewriter:()=>this.urlToRewriter}):this.hooks[`pm2md.pre`]=[],this.hooks[`md2pm.post`]=[rewriteUrls(()=>this.urlFromRewriter)]}getCommandFactories(){return{getMarkdownHooks:(e,t)=>()=>(t(this.hooks[e]),!0),setMarkdownHooks:(e,t)=>()=>(this.hooks[e]=t,!0),setFromMarkdownUrlRewriter:e=>()=>(this.urlFromRewriter=e,!0),setToMarkdownUrlRewriter:e=>()=>(this.urlToRewriter=e,!0)}}getProseMirrorPlugins(){return[createMarkdownPlugin(this,this.editor)]}};async function init$1(e){let t=await Promise.resolve().then(()=>require("./odt_parser.internal-DGJtzBJe.cjs")),n=await WebAssembly.instantiate(e,{"./odt_parser.internal.js":t});return t.__wbg_set_wasm(n.instance.exports),n.instance.exports.__wbindgen_start(),t.init_debug(),n.instance,t}function inchesToMm(e){return e?e.endsWith(`pt`)?parseFloat(e.substring(0,e.length-2))*.3528:e.endsWith(`in`)?parseFloat(e.substring(0,e.length-2))*25.4:e.endsWith(`em`)?parseFloat(e.substring(0,e.length-2))/.125*25.4:0:0}function getInlineNodesHandlers(){return{$text:(e,t)=>{if(e.current.marks.length>0){let n=t.match(/^([ \t\u00A0]*)(.*)([ \t\u00A0]*)$/);n[1]&&e.current.content.push(e.schema.text(n[1]));let r=e.createText(n[2]);r&&e.current.content.push(r),n[3]&&e.current.content.push(e.schema.text(n[3]));return}let n=e.createText(t);n&&e.current.content.push(n)},s:(e,t)=>{let n=t[`@c`]||1,r=` `.repeat(n),a=e.createText(r);a&&e.current.content.push(a)},tab:(e,t)=>{let n=e.createText(` `);n&&e.current.content.push(n)},rect:(e,t)=>{t[`@rel-width`]===`100%`&&(e.openNode(),e.closeNode(`hr`))},"line-break":(e,t)=>{e.openNode(),e.closeNode(`br`)},"soft-page-break":(e,t)=>{e.openNode(),e.closeNode(`softbreak`)},bookmark:(e,t)=>{e.openNode(),e.closeNode(`node_bookmark`,{id:t[`@name`]})},"bookmark-start":(e,t)=>{},"bookmark-end":(e,t)=>{},"change-start":(e,t)=>{e.openNode(),e.closeNode(`comment`,{id:t[`@change-id`],nesting:1})},"change-end":(e,t)=>{e.openNode(),e.closeNode(`comment`,{id:t[`@change-id`],nesting:-1})}}}function getBasicNodesHandlers(){return{body:(e,t)=>{e.handle(`text`,t.text)},text:(e,t)=>{iterateChildren(t.$value,t=>e.handle(t.tag,t.value))},p:(e,t)=>{let n={},r=e.getElementStyle(t),a=r.styles.find(e=>e.startsWith(`Heading_20_`));a&&(n.level=parseInt(a.substring(11)));let o=`paragraph`;r.styles.find(e=>e.startsWith(`Heading_20_`))&&(o=`heading`),e.openNode();let s=e.styleToMarks(r);s.length>0&&(e.current.marks=[...e.current.marks,...s]),iterateChildren(t.$value,t=>{e.handle(t.tag,t.value)}),e.closeNode(o,n)},"table-of-content":(e,t)=>{let n=[],r=-1;for(let a of t[`index-body`].p){let t=e.getElementStyle(a),o=0;if(`paragraph-properties`in t&&(o=inchesToMm(t[`paragraph-properties`][`@margin-left`])),r<o)n.length>0&&e.openNode(),e.openNode(),n.push(o);else for(let t=n.length-1;t>=0&&n[t]>o;t--)e.closeNode(`bullet_list`,{odtMarginLeft:o}),t>0&&e.closeNode(`list_item`),n.pop();e.openNode(),e.handle(`p`,a),e.closeNode(`list_item`),r=o}for(let t=n.length-1;t>=0;t--){let r=n.pop();t>0?(e.closeNode(`bullet_list`,{odtMarginLeft:r}),e.closeNode(`list_item`)):e.closeNode(`bullet_list`,{odtMarginLeft:r,toc:!0})}},span:(e,t)=>{let n=e.getElementStyle(t),r=e.styleToMarks(n);r.length>0&&(e.stash(),e.current.marks=[...e.current.marks,...r]),iterateChildren(t.$value,t=>{e.handle(t.tag,t.value)}),r.length>0&&e.unstash()},a:(e,t)=>{let n={href:t[`@href`]},r=[e.schema.mark(`link`,n)];r.length>0&&(e.stash(),e.current.marks=[...e.current.marks,...r]),iterateChildren(t.$value,t=>{e.handle(t.tag,t.value)}),r.length>0&&e.unstash()}}}function processListStyle(e,t){let n=e.listTracker,r={},a=resolveListStyle(e.stylesTree,e.automaticStyles,``);for(let t=n.listStack.length-1;t>=0;t--){let r=n.listStack[t];a[`@name`]||(a=resolveListStyle(e.stylesTree,e.automaticStyles,r.styleName))}let o=`bullet_list`;if(a){let e=a[`list-level-style-number`].find(e=>parseInt(String(e[`@level`]))===t);if(e){r.type=e[`@num-format`]||`1`,e[`@start-value`]&&(r.start=String(e[`@start-value`])),o=`ordered_list`;let t=e[`list-level-properties`][`list-level-label-alignment`][`@margin-left`];t&&(r.odtMarginLeft=inchesToMm(t))}let n=a[`list-level-style-bullet`].find(e=>parseInt(String(e[`@level`]))===t);if(n){let e=n[`list-level-properties`][`list-level-label-alignment`][`@margin-left`];e&&(r.odtMarginLeft=inchesToMm(e))}}return{attrs:r,nodeTypeName:o}}function getListNodesHandlers(){return{list:(e,t)=>{let n=e.listTracker;n.pushList(t[`@xml:id`],t[`@style-name`]);let{nodeTypeName:r,attrs:a}=processListStyle(e,n.getCurrentList().level);e.current.meta.list_type=r,t[`@xml:id`]&&(a.id=t[`@xml:id`]),t[`@continue-list`]&&(a.continue=t[`@continue-list`]),t[`@continue-numbering`]&&(a.continue=`_last`),e.openNode(),iterateChildren(t[`list-item`].map(e=>({"list-item":e})),t=>{e.handle(t.tag,t.value)}),e.current.content.length===0?e.dropNode():e.closeNode(r,a),n.listStack.pop()},"list-item":(e,t)=>{e.openNode(),iterateChildren(t.$value,t=>e.handle(t.tag,t.value));let n={};n.markup=`* `,e.closeNode(`list_item`,n)}}}function getTableNodesHandlers(){return{table:(e,t)=>{e.openNode();for(let n of t[`table-row`])e.handle(`table-row`,n);e.closeNode(`table`)},"table-row":(e,t)=>{e.openNode();for(let n of t[`table-cell`])e.handle(`table-cell`,n);e.closeNode(`table_row`)},"table-cell":(e,t)=>{e.openNode(),iterateChildren(t.$value,t=>e.handle(t.tag,t.value)),e.closeNode(`table_cell`)}}}var ListNumbering=class e{id;levels={};forceStart={};constructor(e){this.id=e;for(let e=0;e<20;e++)this.levels[e]=1}clearAbove(e){for(let t=e+1;t<20;t++)this.levels[t]=1}clone(t){let n=new e(t);return n.levels=structuredClone(n.levels),n.forceStart=structuredClone(n.forceStart),n}},ListTracker=class{listStack=[];pushList(e,t=``){let n={id:e,styleName:t,level:this.listStack.length+1};return this.listStack.push(n),n}getCurrentList(){return this.listStack[this.listStack.length-1]}},COURIER_FONTS=[`Courier New`,`Courier`,`Roboto Mono`];function resolveListStyle(e,t,n){let r;return r=e.styles[`list-style`].find(e=>e[`@name`]===n),r||={"@name":n,"list-level-style-number":[],"list-level-style-bullet":[]},r}function resolveStyle(e,t,n){let r;if(r||=e.styles.style.find(e=>e[`@name`]===n),r||=t.style.find(e=>e[`@name`]===n),r||={"@name":n,styles:[]},r.styles=[n],r[`@parent-style-name`]){let n=resolveStyle(e,t,r[`@parent-style-name`]);if(n){let e=[...r.styles,...n.styles];for(let e of Object.keys(r))r[e]===void 0&&delete r[e];r={...n,...r,styles:e}}}return r}function tagEnum(e){if(typeof e==`string`)return{tag:e,value:e};if(typeof e==`object`){let t=Object.entries(e);if(t.length===1)return{tag:t[0][0],value:t[0][1]}}throw Error(`Incorrect enum: `+JSON.stringify(e))}function iterateChildren(e,t){for(let n of e)n!==`Unknown`&&t(tagEnum(n))}var OdtStashContext=class{schema;stylesTree;automaticStyles;ctxStash=[];currentCtx;listTracker=new ListTracker;constructor(e,t,n,r){this.schema=e,this.stylesTree=n,this.automaticStyles=r,this.currentCtx={handlers:t,content:[],marks:[],meta:{}},this.stash()}stash(){this.ctxStash.push(this.currentCtx);let e={},t={...this.currentCtx.handlers},n=this.currentCtx.content,r=this.currentCtx.marks;return this.currentCtx={...structuredClone({...this.currentCtx,content:void 0,marks:void 0,handlers:void 0}),...e,content:n,marks:r,handlers:t},this.ctxStash.length-1}unstash(){let e=this.ctxStash.pop();if(!e)throw Error(`Unstash failed`);this.currentCtx=e}openNode(){this.stash(),this.current.content=[]}dropNode(){this.unstash()}closeNode(e,t={},n=Mark$1.none){let r=this.createNode(e,t,n);return this.unstash(),r&&this.current.content.push(r),r}createNode(e,t={},n=Mark$1.none){let r=this.schema.nodes[e];if(!r)throw Error(`Invalid node type: `+e);let a=r.createAndFill(t,this.current.content,n);if(!a)throw Error(`Error creating node: `+e);return a}createText(e){if(!e)return;let t=uniqMarks(this.current.marks);return this.schema.text(e,t)}styleToMarks(e){let t=[],n=e&&e[`text-properties`]||{};if(COURIER_FONTS.indexOf(n[`@font-name`]||``)>-1){let e=this.schema.mark(`code`);t.push(e)}if(n[`@font-style`]===`italic`){let e=this.schema.mark(`em`);t.push(e)}if(n[`@font-weight`]===`bold`){let e=this.schema.mark(`strong`);t.push(e)}return t}handle(e,t){if(!this.current.handlers[e])throw Error(`No handler for node: `+e);if(typeof this.current.handlers[e]!=`function`)throw Error(`Invalid handler for node: `+e);this.current.handlers[e](this,t)}getElementStyle(e){return typeof e==`object`&&e[`@style-name`]?resolveStyle(this.stylesTree,this.automaticStyles,e[`@style-name`]):{styles:[]}}get current(){return this.currentCtx}},OdtParser=class{schema;config;constructor(e,t={}){this.schema=e,this.config=t}filesMap;parse(e){let t=e.contentTree,n=e.stylesTree,r={...getInlineNodesHandlers(),...getBasicNodesHandlers(),...getListNodesHandlers(),...getTableNodesHandlers(),g:()=>{let e=a.createText(`INSTEAD OF EMBEDDED DIAGRAM ABOVE USE EMBEDDED DIAGRAM FROM DRIVE AND PUT LINK TO IT IN THE DESCRIPTION. See: https://github.com/mieweb/wikiGDrive/issues/353`);e&&a.current.content.push(e)},frame:(t,n)=>{if(n.object&&n.object[`@href`]){let r=n.object[`@href`].replace(/^\.\//,``)+`/content.xml`;if(e[r]){let n=new TextDecoder().decode(e[r]);t.openNode(),t.closeNode(`math`,{lang:`mathml`,content:n});return}}if(n.image&&n.image[`@href`]){let e=n.desc?.$value||``,r=n.image[`@href`];t.openNode(),t.closeNode(`image`,{src:r,alt:e})}},annotation:()=>{},note:(e,t)=>{let n=t[`note-citation`],r=t[`note-body`];if(!(!n||!r)){e.handle(`text`,{$value:[{$text:n.$value}]});for(let t of r.p)iterateChildren(t.$value,t=>e.handle(t.tag,t.value)),e.closeNode(`paragraph`),e.openNode()}}},a=new OdtStashContext(this.schema,r,n,t[`automatic-styles`]);return a.openNode(),a.handle(`body`,t.body),a.closeNode(`doc`)}};function uniqMarks(e){let t=[];for(let n of e)[`strong`,`italic`,`underline`,`subscript`,`superscript`,`code`].includes(n.type.name)&&t.find(e=>e.type===n.type)||t.push(n);return t}var convertCodeParagraphsToCodeBlocks=(e,t)=>{let n=e.doc,r=e.schema,a=e.tr,o=r.marks.code;return n.descendants((e,t)=>{if(e.type.name===`paragraph`){let n=``,s=0,c=[];for(let t=0;t<e.childCount;t++){let r=e.child(t),a=r.marks.some(e=>e.type===o),l=r.textContent.match(/^[ \t\u00A0]+$/);if(r.type.name===`node_bookmark`){c.push(r),s+=r.nodeSize;continue}if(r.type.name===`br`){n+=`
122
+ `);t.attrSet(`indent`,``+n),t.content=s,t.attrSet(`margin_before`,`1`),t.attrSet(`margin_after`,`1`),r.push(t)}break;case`paragraph`:{let t=`p`,o=new Token(`paragraph_open`,`p`,1);o.level=a,o.attrSet(`margin_before`,`1`),r.push(o),a++,e.children?.forEach(e=>l(e,n)),a--;let s=new Token(`paragraph_close`,`p`,-1);s.level=a,s.attrSet(`margin_after`,`1`),r.push(s)}break;case`pipe_table_cell`:{let t=n.tableRowType===`thead`?`th`:`td`,o=n.tableRowType===`thead`?`th`:`td`,c=new Token(t+`_open`,o,1);c.attrSet(`align`,n.cellAlign[n.cellNo]||`left`),c.level=a,r.push(c),a++;{let t=`p`,o=new Token(`paragraph_open`,`p`,1);o.level=a,r.push(o);let c=[...e.children];for(;c.length>0&&c[c.length-1].type===`whitespace`;)c.splice(c.length-1,1);if(c.length>0)c.forEach(e=>l(e,n));else{let t=[e.startPosition?.row,e.endPosition?.row,e.startPosition?.column,e.endPosition?.column],n=new Token(`text`,``,0);n.map=t,n.meta=`noEscText`,n.content=e.text?.replace(/\s+$/,``)??``,s(n,`txt5`)}let u=new Token(`paragraph_close`,`p`,-1);u.level=a,r.push(u)}a--;let u=new Token(t+`_close`,o,-1);u.level=a,r.push(u),n.cellNo++}break;case`pipe_table_header`:case`pipe_table_row`:{let t=`tr`,o=new Token(`tr_open`,`tr`,1);o.level=a,r.push(o),a++,e.children.filter(e=>!!e).filter(e=>e.type===`pipe_table_cell`).forEach(e=>l(e,n)),a--;let s=new Token(`tr_close`,`tr`,-1);s.level=a,r.push(s)}break;case`pipe_table`:{let t=`table`,o=new Token(`table_open`,t,1);o.level=a,o.attrSet(`margin_before`,`1`),r.push(o),a++;let s=e.children.filter(e=>!!e).filter(e=>e.type===`pipe_table_delimiter_row`),c=[];if(s.length>0){let e=s[0].children.filter(e=>!!e).filter(e=>e.type===`pipe_table_delimiter_cell`);for(let t=0;t<e.length;t++)e[t].children.filter(e=>!!e).find(e=>e.type===`pipe_table_align_right`)?c.push(`right`):c.push(`left`)}let u=e.children.filter(e=>!!e).filter(e=>e.type===`pipe_table_header`);if(u.length>0){let e=`thead`,t=new Token(`thead_open`,e,1);t.level=a,r.push(t),a++,u.forEach(e=>l(e,{...n,tableRowType:`thead`,cellNo:0,cellAlign:c})),a--;let o=new Token(`thead_close`,e,-1);o.level=a,r.push(o)}let d=e.children?.filter(e=>e?.type===`pipe_table_row`);d.length>0&&(a++,d.filter(e=>!!e).forEach(e=>l(e,{...n,tableRowType:`tbody`,cellAlign:c})),a--),a--;let f=new Token(`table_close`,t,-1);f.level=a,f.attrSet(`margin_after`,`1`),r.push(f)}break;case`list`:{let t=`bullet_list`,s=`ul`,c=``,u=e.children.filter(e=>!!e).find(e=>e.type===`list_item`);if(u){let e=u.children.filter(e=>!!e).find(e=>e.type.startsWith(`task_list_marker`)),n=u.children.filter(e=>!!e).find(e=>e.type.startsWith(`list_marker_dot`));e?(t=`task_list`,s=`ul`):n&&(t=`ordered_list`,s=`ol`,c=(o(n)||``).trim().replace(`.`,``))}let d=new Token(t+`_open`,s,1);d.level=a,d.markup=s===`ol`?`.`:`*`,d.attrSet(`symbol`,s===`ol`?`1`:`*`),c&&d.attrSet(`start`,c),d.attrSet(`margin_before`,`1`),r.push(d),a++,e.children.filter(e=>!!e).forEach(e=>l(e,n)),a--;let f=new Token(t+`_close`,s,-1);f.level=a,f.attrSet(`margin_after`,`1`),r.push(f)}break;case`list_item`:{let t=e.children.filter(e=>!!e).find(e=>e.type.startsWith(`task_list_marker_`)),s=e.children.filter(e=>!!e).find(e=>e.type.startsWith(`list_marker_`));if(!s)break;let c=t?`task_item`:`list_item`,u=`li`,d=new Token(c+`_open`,`li`,1);d.level=a,d.markup=(o(s)||``).trim(),s.type===`list_marker_dot`&&(d.info=``,d.markup=``),t&&(t.type,d.attrSet(`checked`,t.type===`task_list_marker_checked`?`checked`:``)),r.push(d),a++,l(e.children.filter(e=>!!e).find(e=>e.type===`paragraph`),n);let f=e.children.filter(e=>!!e).filter(e=>e.type===`list`);for(let e of f)l(e,n);a--;let p=new Token(c+`_close`,`li`,-1);p.level=a,r.push(p)}break;case`html_block`:{let t=new Token(`html_block`,``,0);t.level=a,t.content=o(e)??``,t.attrSet(`margin_before`,`1`),t.attrSet(`margin_after`,`1`),r.push(t)}break;case`text`:{let t=new Token(`text`,``,0);t.level=a,t.content=o(e)??``,r.push(t)}break;default:throw console.warn(`Unhandled node type: ${e.type}, children: ${e.children.map(e=>e.type).join(`, `)}`,{...e,children:void 0,_children:void 0,tree:void 0}),Error(`Unhandled node type: ${e.type}`)}}};return l(e),r}async function sitterTokenizer(e){let t=getLangTreeSitter(`markdown`),n=t.files.find(e=>e.indexOf(`_inline`)===-1),r=t.files.find(e=>e.indexOf(`_inline`)>-1),a=await e(t.dir+`/`+n),o=await e(t.dir+`/`+r),s=await createParser(a,{assetLoad:e}),c=await createParser(o,{assetLoad:e});return{parse:e=>{let t=s.parse(e);if(!t)throw Error(`Tree is null`);return treeToTokens(new ExtendedNode(t.rootNode,e),c,e)}}}function listIsTight(e,t){for(;++t<e.length;)if(e[t].type!=`list_item_open`)return e[t].hidden;return!1}async function mdToPmConverter(e,t,n){return mdToPmConverterText(new TextDecoder().decode(e),t,n)}async function mdToPmConverterText(e,t,n){if(!t.assetLoad)throw Error(`No config.assetLoad`);let r=new MarkdownParser(n,await sitterTokenizer(t.assetLoad),{frontmatter:{custom:(e,n)=>{let r=e.stack[0];if(r?.type.name===`doc`&&t.frontmatter){let e=t.frontmatter.parse(n.content)||void 0;r.attrs={...r.attrs,meta:e}}}},blockquote:{block:`blockquote`},paragraph:{block:`paragraph`},task_item:{block:`task_item`},task_list:{block:`task_list`},list_item:{block:`list_item`},bullet_list:{block:`bullet_list`,getAttrs:(e,t,n)=>({tight:listIsTight(t,n)})},ordered_list:{block:`ordered_list`,getAttrs:(e,t,n)=>({start:+e.attrGet(`start`)||1,tight:listIsTight(t,n)})},dl:{block:`dl`},dt:{block:`dt`},dd:{block:`dd`},heading:{block:`heading`,getAttrs:e=>({level:+e.tag.slice(1)})},code_block:{block:`code_block`,getAttrs:e=>({lang:e.attrGet(`lang`)||void 0}),noCloseToken:!0},fence:{block:`code_block`,getAttrs:e=>({lang:e.attrGet(`lang`)||void 0}),noCloseToken:!0},hr:{custom:(e,t,r,a)=>{e.openNode(n.nodes.paragraph,{}),e.addNode(n.nodes.hr,{}),e.closeNode()}},image:{node:`image`,getAttrs:e=>{let t=e.children?e.children[0]:void 0;return{src:e.attrGet(`src`),title:e.attrGet(`title`)||null,alt:t?.content||null}}},entity:{custom:(e,t,n,r)=>{e.addText(decodeEntity(t.content))}},hardbreak:{node:`br`},em:{mark:`em`},underline:{mark:`underline`},strong:{mark:`strong`},strike:{mark:`strike`},link:{mark:`link`,getAttrs:e=>({href:e.attrGet(`href`),title:e.attrGet(`title`)||null})},code:{mark:`code`},html_block:{custom:(e,t,r,a)=>{let o=DOMParser$1.fromSchema(n).parse(elementFromString(t.content));e.importNodes(o.children)}},footnote_ref:{block:`code_block`},table:{block:`table`},tr:{block:`table_row`},td:{block:`table_cell`},th:{block:`table_header`},thead:{ignore:!0}}).parse(e),a=[...t.hooks||[]],o=EditorState.create({doc:r}),s=e=>{o=o.apply(e)};if(a.length>0)for(let e of a)await e(o,e=>s(e));return o.doc}var addEmptyLines=(e,t)=>{let n=e.doc,r=e.tr,a=e.schema.nodes.br,o=e.schema.nodes.softbreak;function s(e,t,n=0,c=0){let l=0,u=!1;for(let t=0;t<e.length;t++){let d=e[t];if([`image`,`node_bookmark`].includes(d.type.name)&&t>0){let s=e[t-1];if(s.type!==o)if(s.type===a)r.setNodeMarkup(r.mapping.map(n+l-s.nodeSize),o);else{let e=o.createAndFill();e&&r.insert(r.mapping.map(n+l),e)}}if(d.type.name===`softbreak`){let a=e[t-1];e[t+1],a?.type.name===`softbreak`&&r.delete(r.mapping.map(n+l),r.mapping.map(n+l+d.nodeSize)),a?.textContent?.endsWith(` `)&&r.delete(r.mapping.map(n+l),r.mapping.map(n+l+d.nodeSize)),u||r.delete(r.mapping.map(n+l),r.mapping.map(n+l+d.nodeSize))}else u=!0;s(d.children,d,n+l+1,c+1),l+=d.nodeSize}}return s(n.children,n),t&&t(r),r.docChanged},fixIdLinks=(e,t)=>{let n=e.tr,r=e.schema.marks.link;return e.doc.descendants((e,t)=>{e.marks.forEach(a=>{if(a.type===r&&a.attrs.href.startsWith(`#`)){let o=(e.text||e.textBetween(0,e.content.size)).toLowerCase().replace(/[^\w]+/g,` `).trim().replaceAll(` `,`-`);o&&(n=n.removeMark(t,t+e.nodeSize,r).addMark(t,t+e.nodeSize,r.create({...a.attrs,href:`#`+o})))}})}),t&&t(n),n.docChanged},fixShortCodes=(e,t)=>{let n=e.doc,r=e.tr,a=e.schema.nodes.br,o=e.schema.nodes.softbreak;if(!a)throw Error(`No hardbreak type in schema`);if(!o)throw Error(`No softbreak type in schema`);function s(e,t=0,n=0){e.forEach((c,l,u)=>{if(c.type.name===`shortcode_inline`){if(u>1){let n=e.child(u-1);n.type===a&&(r=r.setNodeMarkup(t+l-n.nodeSize,o))}u<e.childCount-1&&e.child(u+1).type===a&&(r=r.setNodeMarkup(t+l+c.nodeSize,o))}s(c,t+l+1,n+1)})}return s(n),t&&t(r),r.steps.length>0},removeEmptyTags=(e,t)=>{let n=e.schema.nodes.paragraph,r=e.tr;return e.doc.descendants((e,t)=>{if([`paragraph`].includes(e.type.name)){let n=e.children.every(e=>e.isText&&e.textContent===``);(e.childCount===0||n)&&r.deleteRange(r.mapping.map(t),r.mapping.map(t+e.nodeSize))}else if([`heading`].includes(e.type.name)){let a=e.children.find(e=>e.type.name===`node_bookmark`),o=e.children.every(e=>e.isText&&e.textContent===``||e.type.name===`node_bookmark`);a&&o?r.setNodeMarkup(r.mapping.map(t),n):(e.childCount===0||o)&&r.deleteRange(r.mapping.map(t),r.mapping.map(t+e.nodeSize))}}),t&&t(r),r.docChanged},removeSuggest=(e,t)=>{let n={},r=e.tr,a=e.doc,o=`comment`;a.descendants((e,t)=>{if(e.type.name===`comment`&&e.attrs.id){let r=e.attrs.id;n[r]||(n[r]=[]),e.attrs.nesting===1&&(n[r][0]={node:e,pos:t}),e.attrs.nesting===-1&&(n[r][1]={node:e,pos:t})}});for(let e in n){let t=n[e][0],a=n[e][1];if(t&&a){let e=t.pos,n=a.pos+a.node.nodeSize;r.replace(r.mapping.map(e),r.mapping.map(n))}}return t&&t(r),r.docChanged},rewriteUrls=e=>async(t,n)=>{let r=e?.();if(!r)return!1;let a=t.tr,o=t.schema.marks.link,s=t.schema.nodes.image,c=[],l=[];t.doc.descendants((e,t)=>{e.marks.forEach(n=>{n.type===o&&c.push([n,t,t+e.nodeSize])}),e.type===s&&l.push([e,t])});for(let[e,n,o]of c){let s=e.attrs.href,c={},l=await r(s,{type:`A`,dest:`md`,setMeta:(e,t)=>{c[e]=t}});if(l!==s||c.mdTemplate){let r=c.mdTemplate;a.removeMark(a.mapping.map(n),a.mapping.map(o),e);let u=t.schema.mark(`link`,{...e.attrs,href:l,origUrl:s,mdTemplate:r});a.addMark(a.mapping.map(n),a.mapping.map(o),u)}}for(let[e,t]of l){let n=e.attrs.src,o={},s=await r(n,{type:`IMG`,dest:`md`,setMeta:(e,t)=>{o[e]=t}});if(s!==n||o.mdTemplate){let r=o.mdTemplate;a.setNodeMarkup(a.mapping.map(t),null,{...e.attrs,src:s,origUrl:n,mdTemplate:r})}}return n&&n(a),a.docChanged},trimLines=(e,t)=>{let n=e.doc,r=e.schema,a=e.tr,o=e.schema.nodes.br,s=e.schema.nodes.softbreak,c=e.schema.nodes.paragraph;function l(e,t,n=0,u=0){let d=0;if(t.type.name===`code_block`&&t.textContent.trim())return;function f(t,o){let s=n+o;for(let n=t-1;n>=0;n--){let t=e[n];if(t?.type.name!==`text`)break;let o=t.text||``,c=o.replace(/[ \t\u00A0]+$/,``);if(c!==o){let e=s-t.nodeSize;c.length>0?a.replaceRangeWith(a.mapping.map(e),a.mapping.map(s),r.text(c)):a.replace(a.mapping.map(e),a.mapping.map(s))}else break;s-=t.nodeSize;break}}let p=!1;for(let m=0;m<e.length;m++){let h=e[m];if(h.isText){let e=h.text||``;if(e.match(/^([ \t\u00A0]+)/)&&!p&&c!==t.type){e=e.replace(/^[ \t\u00A0]+/,``);let t=n+d,o=t+h.nodeSize;e?a.replaceRangeWith(a.mapping.map(t),a.mapping.map(o),r.text(e)):a.replace(a.mapping.map(t),a.mapping.map(o))}e&&(p=!0)}o===h.type&&(f(m,d),m+1<e.length&&(e[m+1].type===o||e[m+1].type===s)&&a.setNodeMarkup(a.mapping.map(n+d),s)),l(h.children,h,n+d+1,u+1),d+=h.nodeSize}f(e.length,d)}return l(n.children,n),t&&t(a),a.docChanged},insertToc=(e,t)=>{let n=e.doc,r=e.tr,a=e.schema.nodes.br,o=e.schema.nodes.softbreak;if(!a)throw Error(`No hardbreak type in schema`);if(!o)throw Error(`No softbreak type in schema`);return n.forEach((e,t,n)=>{if(e.type.name===`bullet_list`&&e.attrs.toc){let t=e.copy(Fragment.from(e.content));r.insert(0,t)}}),t&&t(r),r.steps.length>0},addEnterAfterImage=(e,t)=>{let n=e.tr,r=e.schema.nodes.image,a=e.schema.nodes.br,o=e.schema.nodes.softbreak;function s(t,c=0,l=0){t.forEach((u,d,f)=>{if(u.type!==r)return;let p=t.nodeAt(f+1);if(p?.type===a&&p?.type===o)return;let m=c+d+u.nodeSize;n.insert(n.mapping.map(m),Fragment.from([e.schema.node(`softbreak`),e.schema.node(`softbreak`)])),s(u,c+d+1,l+1)})}return s(e.doc),t&&t(n),n.docChanged},fixParaEnding=(e,t)=>{let n=e.doc,r=e.tr,a=e.schema.nodes.br,o=e.schema.nodes.paragraph;function s(e,t,n=0,c=0){if(t.type===o){let o=t.content.size;for(let t=e.length-1;t>=0;t--){let s=e[t];if(s.type!==a)break;o-=s.nodeSize;let c=n+o,l=c+s.nodeSize;r.replace(r.mapping.map(c),r.mapping.map(l))}return}let l=0;for(let t=0;t<e.length;t++){let r=e[t];s(r.children,r,n+l+1,c+1),l+=r.nodeSize}}return s(n.children,n),t&&t(r),r.docChanged};function getDefaultsPreProcessFilters(e){return[insertToc,fixShortCodes,removeSuggest,removeEmptyTags,fixIdLinks,fixParaEnding,trimLines,addEnterAfterImage,addEmptyLines,rewriteUrls(e.getUrlRewriter)]}var MarkdownContentMapper=class e{result;rawTextArr;constructor(e,t){this.result=t,this.rawTextArr=[];for(let e of t.rawTextMap)e.nodeIdx>=0&&this.rawTextArr.push({nodeIdx:e.nodeIdx,maxNodeIdx:e.nodeIdx,targetPos:e.targetPos,targetRow:e.targetRow,targetCol:e.targetCol});this.rawTextArr.sort((e,t)=>e.nodeIdx-t.nodeIdx);for(let t=0;t<this.rawTextArr.length;t++){let n=t+1;n<this.rawTextArr.length?this.rawTextArr[t].maxNodeIdx=this.rawTextArr[n].nodeIdx-1:this.rawTextArr[t].maxNodeIdx=e}}getTextContent(){return this.result.content}toRawTextPos(e){for(let t=0;t<this.rawTextArr.length;t++){let n=this.rawTextArr[t];if(e>=n.nodeIdx&&e<=n.maxNodeIdx)return n.targetPos+e-n.nodeIdx}return-1}toRawTextLineCol(e){for(let t=0;t<this.rawTextArr.length;t++){let n=this.rawTextArr[t];if(e>=n.nodeIdx&&e<=n.maxNodeIdx)return[n.targetRow,n.targetCol+e-n.nodeIdx]}return[0,0]}fromLineChar(e,t){for(let n=0;n<this.rawTextArr.length;n++){let r=this.rawTextArr[n],a=r.maxNodeIdx-r.nodeIdx+1;if(r.targetRow===e){if(t>=r.targetCol&&t<r.targetCol+a){let e=t-r.targetCol;return r.nodeIdx+e}let e=this.rawTextArr[n+1];if((!e||e.targetRow>r.targetRow)&&t>=r.targetCol+a)return r.maxNodeIdx}}return-1}static async create(t,n){let r=await extPmToMdConverter(t.doc,n,t.schema,new EventTarget);return new e(t.doc.nodeSize,r)}},MarkdownPluginState=class{editor;extensionMarkdown;capturing=!0;workspace;constructor(e,t){this.editor=e,this.extensionMarkdown=t,this.workspace=e.ci.resolve(`workspace`),this.performSnapshot=debounce(this.performSnapshot.bind(this),800)}async performSnapshot(){let e=this.editor.version,t=this.editor.config.uri;if(!t)return;let n={version:e,state:this.editor.state,materialized:void 0},r=async()=>(n.materialized||=await MarkdownContentMapper.create(n.state,{...this.extensionMarkdown.config,sourceMap:!0}),n.materialized);this.workspace.getFile(t)?this.workspace.modifyFile({uri:t,lang:`markdown`,version:e,getContentMapper:r}):this.workspace.openFile({uri:t,lang:`markdown`,version:e,getContentMapper:r})}};function createMarkdownPlugin(e,t){return new Plugin({state:{init(){return new MarkdownPluginState(t,e)},apply(e,t,n,r){return e.docChanged&&t.capturing&&t.performSnapshot(),t}},view(){return{destroy(){let e=t.config.uri;e&&t.ci.resolve(`workspace`).closeFile(e)}}}})}var ExtensionMarkdown=class extends Extension{config;name=`markdown`;hooks={};urlFromRewriter;urlToRewriter;constructor(e={}){super(e),this.config=e}getConverters(e,t){let n={"text/x-markdown":{fromDoc:n=>pmToMdConverter(n,{assetLoad:this.editor.config.assetLoad,...this.config,urlRewriter:this.urlToRewriter,hooks:this.hooks[`pm2md.pre`],frontmatter:e.ci.resolve(`frontmatter`)},t,e),toDoc:n=>mdToPmConverter(n,{assetLoad:this.editor.config.assetLoad,...this.config,urlRewriter:this.urlFromRewriter,hooks:this.hooks[`md2pm.post`],frontmatter:e.ci.resolve(`frontmatter`)},t)}};return n[`text/markdown`]=n[`text/x-markdown`],n}toMarkdown(e){return extPmToMdConverter(e,{sourceMap:!0,frontmatter:this.editor.ci.resolve(`frontmatter`)},this.editor.schema,this.editor)}async fromMarkdown(e){let t=(await mdToPmConverterText(e,{assetLoad:this.editor.config.assetLoad,...this.config},this.editor.schema)).content;if(t.content.length===1){let e=t.content[0];if(e.type.name===`paragraph`)return new Slice(e.content,0,0)}return new Slice(t,0,0)}created(){this.editor.schema.topNodeType.name===`doc`?this.hooks[`pm2md.pre`]=getDefaultsPreProcessFilters({getUrlRewriter:()=>this.urlToRewriter}):this.hooks[`pm2md.pre`]=[],this.hooks[`md2pm.post`]=[rewriteUrls(()=>this.urlFromRewriter)]}getCommandFactories(){return{getMarkdownHooks:(e,t)=>()=>(t(this.hooks[e]),!0),setMarkdownHooks:(e,t)=>()=>(this.hooks[e]=t,!0),setFromMarkdownUrlRewriter:e=>()=>(this.urlFromRewriter=e,!0),setToMarkdownUrlRewriter:e=>()=>(this.urlToRewriter=e,!0)}}getProseMirrorPlugins(){return[createMarkdownPlugin(this,this.editor)]}};async function init$1(e){let t=await Promise.resolve().then(()=>require("./odt_parser.internal-DGJtzBJe.cjs")),n=await WebAssembly.instantiate(e,{"./odt_parser.internal.js":t});return t.__wbg_set_wasm(n.instance.exports),n.instance.exports.__wbindgen_start(),t.init_debug(),n.instance,t}function inchesToMm(e){return e?e.endsWith(`pt`)?parseFloat(e.substring(0,e.length-2))*.3528:e.endsWith(`in`)?parseFloat(e.substring(0,e.length-2))*25.4:e.endsWith(`em`)?parseFloat(e.substring(0,e.length-2))/.125*25.4:0:0}function getInlineNodesHandlers(){return{$text:(e,t)=>{if(e.current.marks.length>0){let n=t.match(/^([ \t\u00A0]*)(.*)([ \t\u00A0]*)$/);n[1]&&e.current.content.push(e.schema.text(n[1]));let r=e.createText(n[2]);r&&e.current.content.push(r),n[3]&&e.current.content.push(e.schema.text(n[3]));return}let n=e.createText(t);n&&e.current.content.push(n)},s:(e,t)=>{let n=t[`@c`]||1,r=` `.repeat(n),a=e.createText(r);a&&e.current.content.push(a)},tab:(e,t)=>{let n=e.createText(` `);n&&e.current.content.push(n)},rect:(e,t)=>{t[`@rel-width`]===`100%`&&(e.openNode(),e.closeNode(`hr`))},"line-break":(e,t)=>{e.openNode(),e.closeNode(`br`)},"soft-page-break":(e,t)=>{e.openNode(),e.closeNode(`softbreak`)},bookmark:(e,t)=>{e.openNode(),e.closeNode(`node_bookmark`,{id:t[`@name`]})},"bookmark-start":(e,t)=>{},"bookmark-end":(e,t)=>{},"change-start":(e,t)=>{e.openNode(),e.closeNode(`comment`,{id:t[`@change-id`],nesting:1})},"change-end":(e,t)=>{e.openNode(),e.closeNode(`comment`,{id:t[`@change-id`],nesting:-1})}}}function getBasicNodesHandlers(){return{body:(e,t)=>{e.handle(`text`,t.text)},text:(e,t)=>{iterateChildren(t.$value,t=>e.handle(t.tag,t.value))},p:(e,t)=>{let n={},r=e.getElementStyle(t),a=r.styles.find(e=>e.startsWith(`Heading_20_`));a&&(n.level=parseInt(a.substring(11)));let o=`paragraph`;r.styles.find(e=>e.startsWith(`Heading_20_`))&&(o=`heading`),e.openNode();let s=e.styleToMarks(r);s.length>0&&(e.current.marks=[...e.current.marks,...s]),iterateChildren(t.$value,t=>{e.handle(t.tag,t.value)}),e.closeNode(o,n)},"table-of-content":(e,t)=>{let n=[],r=-1;for(let a of t[`index-body`].p){let t=e.getElementStyle(a),o=0;if(`paragraph-properties`in t&&(o=inchesToMm(t[`paragraph-properties`][`@margin-left`])),r<o)n.length>0&&e.openNode(),e.openNode(),n.push(o);else for(let t=n.length-1;t>=0&&n[t]>o;t--)e.closeNode(`bullet_list`,{odtMarginLeft:o}),t>0&&e.closeNode(`list_item`),n.pop();e.openNode(),e.handle(`p`,a),e.closeNode(`list_item`),r=o}for(let t=n.length-1;t>=0;t--){let r=n.pop();t>0?(e.closeNode(`bullet_list`,{odtMarginLeft:r}),e.closeNode(`list_item`)):e.closeNode(`bullet_list`,{odtMarginLeft:r,toc:!0})}},span:(e,t)=>{let n=e.getElementStyle(t),r=e.styleToMarks(n);r.length>0&&(e.stash(),e.current.marks=[...e.current.marks,...r]),iterateChildren(t.$value,t=>{e.handle(t.tag,t.value)}),r.length>0&&e.unstash()},a:(e,t)=>{let n={href:t[`@href`]},r=[e.schema.mark(`link`,n)];r.length>0&&(e.stash(),e.current.marks=[...e.current.marks,...r]),iterateChildren(t.$value,t=>{e.handle(t.tag,t.value)}),r.length>0&&e.unstash()}}}function processListStyle(e,t){let n=e.listTracker,r={},a=resolveListStyle(e.stylesTree,e.automaticStyles,``);for(let t=n.listStack.length-1;t>=0;t--){let r=n.listStack[t];a[`@name`]||(a=resolveListStyle(e.stylesTree,e.automaticStyles,r.styleName))}let o=`bullet_list`;if(a){let e=a[`list-level-style-number`].find(e=>parseInt(String(e[`@level`]))===t);if(e){r.type=e[`@num-format`]||`1`,e[`@start-value`]&&(r.start=String(e[`@start-value`])),o=`ordered_list`;let t=e[`list-level-properties`][`list-level-label-alignment`][`@margin-left`];t&&(r.odtMarginLeft=inchesToMm(t))}let n=a[`list-level-style-bullet`].find(e=>parseInt(String(e[`@level`]))===t);if(n){let e=n[`list-level-properties`][`list-level-label-alignment`][`@margin-left`];e&&(r.odtMarginLeft=inchesToMm(e))}}return{attrs:r,nodeTypeName:o}}function getListNodesHandlers(){return{list:(e,t)=>{let n=e.listTracker;n.pushList(t[`@xml:id`],t[`@style-name`]);let{nodeTypeName:r,attrs:a}=processListStyle(e,n.getCurrentList().level);e.current.meta.list_type=r,t[`@xml:id`]&&(a.id=t[`@xml:id`]),t[`@continue-list`]&&(a.continue=t[`@continue-list`]),t[`@continue-numbering`]&&(a.continue=`_last`),e.openNode(),iterateChildren(t[`list-item`].map(e=>({"list-item":e})),t=>{e.handle(t.tag,t.value)}),e.current.content.length===0?e.dropNode():e.closeNode(r,a),n.listStack.pop()},"list-item":(e,t)=>{e.openNode(),iterateChildren(t.$value,t=>e.handle(t.tag,t.value));let n={};n.markup=`* `,e.closeNode(`list_item`,n)}}}function getTableNodesHandlers(){return{table:(e,t)=>{e.openNode();for(let n of t[`table-row`])e.handle(`table-row`,n);e.closeNode(`table`)},"table-row":(e,t)=>{e.openNode();for(let n of t[`table-cell`])e.handle(`table-cell`,n);e.closeNode(`table_row`)},"table-cell":(e,t)=>{e.openNode(),iterateChildren(t.$value,t=>e.handle(t.tag,t.value)),e.closeNode(`table_cell`)}}}var ListNumbering=class e{id;levels={};forceStart={};constructor(e){this.id=e;for(let e=0;e<20;e++)this.levels[e]=1}clearAbove(e){for(let t=e+1;t<20;t++)this.levels[t]=1}clone(t){let n=new e(t);return n.levels=structuredClone(n.levels),n.forceStart=structuredClone(n.forceStart),n}},ListTracker=class{listStack=[];pushList(e,t=``){let n={id:e,styleName:t,level:this.listStack.length+1};return this.listStack.push(n),n}getCurrentList(){return this.listStack[this.listStack.length-1]}},COURIER_FONTS=[`Courier New`,`Courier`,`Roboto Mono`];function resolveListStyle(e,t,n){let r;return r=e.styles[`list-style`].find(e=>e[`@name`]===n),r||={"@name":n,"list-level-style-number":[],"list-level-style-bullet":[]},r}function resolveStyle(e,t,n){let r;if(r||=e.styles.style.find(e=>e[`@name`]===n),r||=t.style.find(e=>e[`@name`]===n),r||={"@name":n,styles:[]},r.styles=[n],r[`@parent-style-name`]){let n=resolveStyle(e,t,r[`@parent-style-name`]);if(n){let e=[...r.styles,...n.styles];for(let e of Object.keys(r))r[e]===void 0&&delete r[e];r={...n,...r,styles:e}}}return r}function tagEnum(e){if(typeof e==`string`)return{tag:e,value:e};if(typeof e==`object`){let t=Object.entries(e);if(t.length===1)return{tag:t[0][0],value:t[0][1]}}throw Error(`Incorrect enum: `+JSON.stringify(e))}function iterateChildren(e,t){for(let n of e)n!==`Unknown`&&t(tagEnum(n))}var OdtStashContext=class{schema;stylesTree;automaticStyles;ctxStash=[];currentCtx;listTracker=new ListTracker;constructor(e,t,n,r){this.schema=e,this.stylesTree=n,this.automaticStyles=r,this.currentCtx={handlers:t,content:[],marks:[],meta:{}},this.stash()}stash(){this.ctxStash.push(this.currentCtx);let e={},t={...this.currentCtx.handlers},n=this.currentCtx.content,r=this.currentCtx.marks;return this.currentCtx={...structuredClone({...this.currentCtx,content:void 0,marks:void 0,handlers:void 0}),...e,content:n,marks:r,handlers:t},this.ctxStash.length-1}unstash(){let e=this.ctxStash.pop();if(!e)throw Error(`Unstash failed`);this.currentCtx=e}openNode(){this.stash(),this.current.content=[]}dropNode(){this.unstash()}closeNode(e,t={},n=Mark$1.none){let r=this.createNode(e,t,n);return this.unstash(),r&&this.current.content.push(r),r}createNode(e,t={},n=Mark$1.none){let r=this.schema.nodes[e];if(!r)throw Error(`Invalid node type: `+e);let a=r.createAndFill(t,this.current.content,n);if(!a)throw Error(`Error creating node: `+e);return a}createText(e){if(!e)return;let t=uniqMarks(this.current.marks);return this.schema.text(e,t)}styleToMarks(e){let t=[],n=e&&e[`text-properties`]||{};if(COURIER_FONTS.indexOf(n[`@font-name`]||``)>-1){let e=this.schema.mark(`code`);t.push(e)}if(n[`@font-style`]===`italic`){let e=this.schema.mark(`em`);t.push(e)}if(n[`@font-weight`]===`bold`){let e=this.schema.mark(`strong`);t.push(e)}return t}handle(e,t){if(!this.current.handlers[e])throw Error(`No handler for node: `+e);if(typeof this.current.handlers[e]!=`function`)throw Error(`Invalid handler for node: `+e);this.current.handlers[e](this,t)}getElementStyle(e){return typeof e==`object`&&e[`@style-name`]?resolveStyle(this.stylesTree,this.automaticStyles,e[`@style-name`]):{styles:[]}}get current(){return this.currentCtx}},OdtParser=class{schema;config;constructor(e,t={}){this.schema=e,this.config=t}filesMap;parse(e){let t=e.contentTree,n=e.stylesTree,r={...getInlineNodesHandlers(),...getBasicNodesHandlers(),...getListNodesHandlers(),...getTableNodesHandlers(),g:()=>{let e=a.createText(`INSTEAD OF EMBEDDED DIAGRAM ABOVE USE EMBEDDED DIAGRAM FROM DRIVE AND PUT LINK TO IT IN THE DESCRIPTION. See: https://github.com/mieweb/wikiGDrive/issues/353`);e&&a.current.content.push(e)},frame:(t,n)=>{if(n.object&&n.object[`@href`]){let r=n.object[`@href`].replace(/^\.\//,``)+`/content.xml`;if(e[r]){let n=new TextDecoder().decode(e[r]);t.openNode(),t.closeNode(`math`,{lang:`mathml`,content:n});return}}if(n.image&&n.image[`@href`]){let e=n.desc?.$value||``,r=n.image[`@href`];t.openNode(),t.closeNode(`image`,{src:r,alt:e})}},annotation:()=>{},note:(e,t)=>{let n=t[`note-citation`],r=t[`note-body`];if(!(!n||!r)){e.handle(`text`,{$value:[{$text:n.$value}]});for(let t of r.p)iterateChildren(t.$value,t=>e.handle(t.tag,t.value)),e.closeNode(`paragraph`),e.openNode()}}},a=new OdtStashContext(this.schema,r,n,t[`automatic-styles`]);return a.openNode(),a.handle(`body`,t.body),a.closeNode(`doc`)}};function uniqMarks(e){let t=[];for(let n of e)[`strong`,`italic`,`underline`,`subscript`,`superscript`,`code`].includes(n.type.name)&&t.find(e=>e.type===n.type)||t.push(n);return t}var convertCodeParagraphsToCodeBlocks=(e,t)=>{let n=e.doc,r=e.schema,a=e.tr,o=r.marks.code;return n.descendants((e,t)=>{if(e.type.name===`paragraph`){let n=``,s=0,c=[];for(let t=0;t<e.childCount;t++){let r=e.child(t),a=r.marks.some(e=>e.type===o),l=r.textContent.match(/^[ \t\u00A0]+$/);if(r.type.name===`node_bookmark`){c.push(r),s+=r.nodeSize;continue}if(r.type.name===`br`){n+=`
120
123
  `,s+=r.nodeSize;continue}if(a||l){n+=r.text||r.textBetween(0,r.content.size),s+=r.nodeSize;continue}break}if(s>0){let e=a.mapping.map(t),o=a.mapping.map(t+1+s);if(n.trim()){let t=r.text(n),s=r.nodes.code_block.createAndFill(null,[t]);s&&a.replaceRangeWith(e,o,s)}else a.replace(e,o);for(let t of c)a.insert(e,t)}s>0&&(s+2,e.nodeSize)}}),t&&t(a),a.docChanged},ANY_LIST$1=[`ordered_list`,`bullet_list`],fixContinuedLists=(e,t)=>{let n=e.doc,r=e.tr,a=new Map,o=``;function s(e){let t=null;o&&a.has(o)&&(t=a.get(o));let n=e.attrs.continue;return n&&(t=a.get(n)),t||=new ListNumbering(o),a.set(o,t),{listNumbering:t}}let c=!0,l=0;function u(e,t=0,n=0){if(e.type.name===`list_item`){let n=a.get(`_current`),o=e.content.firstChild;o&&n&&(o.type.name===`paragraph`&&o.content.childCount>0?(n.forceStart[l]&&(delete n.forceStart[l],r=r.setNodeMarkup(r.mapping.map(t-1),e.type,{...e.attrs,value:n.levels[l]})),n.levels[l]++):(r=r.setNodeMarkup(r.mapping.map(t-1),e.type,{...e.attrs,type:`none`}),n.forceStart[l]=!0))}if(!ANY_LIST$1.includes(e.type.name))e.forEach((e,r)=>{u(e,t+r+1,n+1)});else{l++,l===1&&(o=e.attrs.id,c=!0);let{listNumbering:d}=s(e);a.set(`_current`,d),c||(d.levels[l]=1),e.attrs.start&&(d.levels[l]=e.attrs.start),e.type.name===`ordered_list`&&1<d.levels[l]&&(r=r.setNodeMarkup(r.mapping.map(t-1),e.type,{...e.attrs,start:d.levels[l],continue:void 0})),e.forEach((e,r)=>{u(e,t+r+1,n+1)}),l===1&&a.set(`_last`,d),l--,c=!1}}return u(n),t&&t(r),r.steps.length>0},convertMathMl=(e,t)=>{let n=e.doc,r=e.schema,a=r.nodes.math,o=r.nodes.code_block;if(!a||!o)return!1;let s=!1,c=e.tr;return n.forEach((e,t,n)=>{if(e.childCount!==1)return;let l=t,u=e.child(0);if(u.type!==a||u.attrs.content.length===0)return;let d=o.create({lang:u.attrs.lang},r.text(u.attrs.content));c.replaceWith(c.mapping.map(l),c.mapping.map(l+e.nodeSize),d),s=!0}),s?(t&&t(c),c.docChanged):!1},CODEBLOCK_START=``,CODEBLOCK_END=``,mergeCodeBlocks=(e,t)=>{let n=e.schema,r=e.tr,a=n.nodes.code_block,o=n.nodes.paragraph;e.doc.descendants((e,t)=>{[CODEBLOCK_START,CODEBLOCK_END].includes(e.textContent.trim())&&(r=r.deleteRange(r.mapping.map(t),r.mapping.map(t+e.nodeSize)))});let s=e.doc,c=0;for(let t=0;t<s.childCount;t++){let t=s.nodeAt(c);if(!t)continue;if(t.type!==a){c+=t.nodeSize;continue}let l=[],u=0;{u+=t.nodeSize;let e=t.text||t.textBetween(0,t.content.size);l.push(e.endsWith(`
121
124
  `)?e:e+`
122
125
  `)}let d=c+t.nodeSize;for(;;){let n=e.doc.nodeAt(d);if(!n)break;if(d+=n.nodeSize,n.type===o&&n.childCount===0){l.push(`