@ones-editor/editor 1.1.3-bate.10 → 1.1.3-bate.12

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/index.js CHANGED
@@ -24,7 +24,7 @@ Available method signatures are:
24
24
  `:""}const A5={boxType:"br",updateBoxContent:Z_,convertTo:tM},x5=I("editor-boxes");class b5{constructor(t){g(this,"boxes",new Map);this.editor=t}registerBoxClass(t){const e=t.boxType,r=this.boxes.get(e);p(x5,!r,`duplicated box type: ${e}`),this.boxes.set(e,t)}getBoxClass(t){const e=this.boxes.get(t);return p(x5,e,`unknown box type: ${t}`),e}createBox(t,e){const r=xv(e),i=vv(r);return this.getBoxClass(e.type).updateBoxContent(this.editor,r,i,e),r}forEach(t){this.boxes.forEach(t)}}function eM(n,t,e,r){const i=r,{width:o,height:s,src:l}=i,c=["editor-box-image"];i.link&&c.push("editor-box-image-link");const d=B("img",c,e);o&&(d.style.width=`${o}px`),s&&(d.style.height=`${s}px`),d.src=n.doc.buildResourceUrl(l)}const v5={boxType:"image",updateBoxContent:eM},nM="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIGZpbGw9InJnYigxNzgsIDE4OCwgMjA1KSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0ibTE3IDE1IDEuNTUgMS41NWMtLjk2IDEuNjktMy4zMyAzLjA0LTUuNTUgMy4zN1YxMWgzVjloLTNWNy44MkMxNC4xNiA3LjQgMTUgNi4zIDE1IDVjMC0xLjY1LTEuMzUtMy0zLTNTOSAzLjM1IDkgNWMwIDEuMy44NCAyLjQgMiAyLjgyVjlIOHYyaDN2OC45MmMtMi4yMi0uMzMtNC41OS0xLjY4LTUuNTUtMy4zN0w3IDE1bC00LTN2M2MwIDMuODggNC45MiA3IDkgN3M5LTMuMTIgOS03di0zbC00IDN6TTEyIDRjLjU1IDAgMSAuNDUgMSAxcy0uNDUgMS0xIDEtMS0uNDUtMS0xIC40NS0xIDEtMXoiPjwvcGF0aD4KPC9zdmc+Cg==";function rM(n,t,e){z(e,"editor-box-anchor"),Ag(nM,[],e)}const B5={boxType:"anchor",updateBoxContent:rM};function iM(n,t,e,r){B("span",[],e,r.text)}const T5={insertionType:"inputting",updateInsertionContent:iM},y5=I("editor-insertion");class R5{constructor(t){g(this,"insertions",new Map);this.editor=t}registerInsertionClass(t){const e=t.insertionType,r=this.insertions.get(e);p(y5,!r,`duplicated insertion type: ${e}`),this.insertions.set(e,t)}getInsertionClass(t){const e=this.insertions.get(t);return p(y5,e,`unknown insertion type: ${t}`),e}createInsertion(t,e){const r=Bv(e.type,e.id,e.attributes),i=yv(r);return this.getInsertionClass(e.type).updateInsertionContent(this.editor,r,i,e),r}}class oM{constructor(t){g(this,"cursors",new Map);g(this,"timer");this.editor=t,this.timer=this.startTimer()}add(t,e){this.cursors.set(t,e)}startTimer(){return setInterval(()=>{const t=Date.now();Array.from(this.cursors).forEach(([e,r])=>{if(t-r>3e3){const i=Tv(this.editor,e);i&&ot(i,"active"),this.cursors.delete(e)}})},1e3)}destroy(){clearInterval(this.timer)}}function sM(n,t,e,r){var l;const i=r;Date.now()-i.time<5*1e3&&(n.addCustom("active-cursors",d=>new oM(d)).add(i.id,i.time),z(t,"active")),B("span",[],e,"|").setAttribute("data-cursor-name",i.name),t.style.setProperty("--cursor-color",n.getColor((l=i.rainbowIndex)!=null?l:0))}const U1={insertionType:"remote-cursor",updateInsertionContent:sM};class k5{constructor(t){g(this,"decorators",[]);this.editor=t}registerDecorator(t){this.decorators.push(t)}decorateBlock(t,e){let r=e;return this.decorators.forEach(i=>{if(i.decorateBlock){const o=i.decorateBlock(this.editor,t,e);o&&(r=gt.default(o))}}),r}decorateText(t,e){let r=e;const i=new Map;return this.decorators.forEach(o=>{if(o.decorateText){const s=o.decorateText(this.editor,t,e);if(s){const{insertions:l,text:c}=s;l&&Array.from(l.entries()).forEach(([d,h])=>{const C=i.get(d);C?C.push(...h):i.set(d,h)}),c&&(r=gt.default(c))}}}),{insertions:i,text:r}}}const O1=I("editor-input");class lM{constructor(t,e){g(this,"editor");g(this,"composing",!1);g(this,"callbacks");g(this,"inputElement");g(this,"handleDocumentClick",t=>{const e=this.editor.rootContainer,r=t.target;if(r&&e.contains(r)&&!Hs(r)){this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus();return}this.editor.emit("blur",this.editor),this.callbacks.onBlur()});g(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var e;const t=(e=document.getSelection())==null?void 0:e.focusNode;t&&this.editor.contains(t)&&!Hs(t)||(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});g(this,"handleEditorSelectionChanged",()=>{const e=!this.editor.isWritable();this.inputElement.readOnly=e});g(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});g(this,"handleCompositionstart",t=>{!this.editor.isWritable()||(this.composing=!0,this.callbacks.onCompositionStart(t))});g(this,"handleCompositionend",t=>{Vc()?setTimeout(()=>{this.composing=!1},100):this.composing=!1,this.callbacks.onUpdateCompositionText(t,this.inputElement.value,!0),this.inputElement.value=""});g(this,"handleInput",t=>{if(t instanceof InputEvent&&!!t.data){if(this.editor.readonly||!this.editor.isWritable()){this.inputElement.value="";return}this.composing?this.callbacks.onUpdateCompositionText(t,t.data,!1):(this.callbacks.onInsertText(t,t.data),this.inputElement.value="")}});g(this,"handleKeyDown",t=>{if(!this.composing){if(this.callbacks.onKeyDown(t)){t.preventDefault(),t.stopPropagation();return}!this.editor.isWritable()||setTimeout(()=>{this.composing||(this.inputElement.value="")})}});g(this,"handleCopy",t=>{this.callbacks.onCopy(t)});g(this,"handleCut",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onCut(t),O1.debug("on cut")});g(this,"handlePaste",t=>{if(t.target instanceof HTMLInputElement&&this.inputElement===t.target){if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onPaste(t)}});g(this,"handlePasteText",(t,e)=>{this.callbacks.onPasteText(t,e)});this.editor=t,this.callbacks=e;const r=B("input",["editor-input"],t.contentElement);r.type="text",r.name="editor-input",r.onkeydown=this.handleKeyDown,r.oninput=this.handleInput,r.oncopy=this.handleCopy,document.addEventListener("paste",this.handlePaste),r.oncut=this.handleCut,r.addEventListener("compositionstart",this.handleCompositionstart),r.addEventListener("compositionend",this.handleCompositionend),this.inputElement=r,document.addEventListener("click",this.handleDocumentClick),document.addEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.addListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){this.callbacks.destroy(),document.removeEventListener("click",this.handleDocumentClick),document.removeEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.removeListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged);const t=this.inputElement;t.removeEventListener("compositionstart",this.handleCompositionstart),t.removeEventListener("compositionend",this.handleCompositionend),t.onkeydown=null,t.oninput=null,t.oncopy=null,document.removeEventListener("paste",this.handlePaste),t.oncut=null}getInput(){return this.inputElement}focus(){this.editor.selection.caret.visible()||this.editor.selection.caret.update(),he.isMobileSafari?(this.inputElement.focus(),z(this.editor.rootElement,"active")):setTimeout(()=>{this.inputElement.focus(),z(this.editor.rootElement,"active")})}handleChanged(t){this.callbacks.onChanged(t)}handleRemoteChanged(t){this.callbacks.onRemoteChanged(t)}addHandler(t){this.callbacks.addHandler(t)}removeHandler(t){this.callbacks.removeHandler(t)}defaultInsertText(t,e,r,i,o){p(O1,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,r,i,o)}defaultHandleKeydown(t,e){return p(O1,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}forEach(t){this.callbacks.forEach(t)}}function w5(n){const t=n.rootElement,e=t.getBoundingClientRect(),r=cr(t),i=window.innerWidth,o=window.innerHeight,s=e.left<0?0:e.left,l=e.top<0?0:e.top,c=e.right>i?i:e.right,d=e.bottom>o?o:e.bottom,h=(s+c)/2,C=(l+d)/2,E=0-e.left+h,x=0-e.top+C,v=n.input.inputElement;v.style.left=`${E/r}px`,v.style.top=`${x/r}px`}const N1=I("editor-caret");function aM(){const t=window.navigator.userAgent.match(/Firefox\/(\d+)\./);return t?Number.parseInt(t[1],10):null}class cM{constructor(t){g(this,"editor");g(this,"caretElem");g(this,"handleReadOnlyChanged",()=>{this.update()});if(this.editor=t,this.caretElem=B("div",["editor-cursor"],this.editor.contentElement),he.isFirefox){const e=aM();e&&e<=79&&(this.caretElem.style.transition="none")}this.editor.on("readonlyChanged",this.handleReadOnlyChanged)}destroy(){this.editor.off("readonlyChanged",this.handleReadOnlyChanged)}visible(){const t=window.getComputedStyle(this.caretElem);return t.display!=="none"&&t.opacity!=="0"}hasCaret(){if(this.editor.readonly||!this.editor.selection.range.isCollapsed())return!1;const t=this.editor.selection.range.start;if(!(t instanceof _e))return!1;const e=this.editor.getBlockById(t.blockId);return!!et(this.editor,e)}update(){if(Lb(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",w5(this.editor);return}const{range:e}=this.editor.selection;p(N1,e.isCollapsed,"range is not collapsed");const r=e.start;p(N1,r instanceof _e,"only simple block position can has caret");const i=this.editor.getBlockById(r.blockId);p(N1,et(this.editor,i),"only text kind block can has caret");let o;const s=i.querySelector("span.inputting-insertion");s?(o=Is(s),o=new DOMRect(o.right,o.top,1,o.height)):o=Xn(i,r);const l=this.editor.contentElement.getBoundingClientRect(),c=o.left-l.left,d=o.top-l.top;t.style.left=`${c}px`,t.style.top=`${d}px`,t.style.height=`${o.height}px`;const h=this.editor.input.inputElement;h.style.left=`${c}px`,h.style.top=`${d+o.height-24}px`,he.isMobileSafari&&(h.style.left=`${c-4}px`,h.style.height=`${o.height}px`);const E=an(i,{horizontal:!0}).getBoundingClientRect(),x=E.left-l.left,v=x+E.width;c<x||c>v?(w5(this.editor),t.style.display="none"):t.style.display=""}}function uM(n){wv(n),n.selection.range.getSelectedBlocks().forEach(t=>Sv(n,t.block,t.start,t.end))}const fM=I("editor-dom");function S5(n){return an(n.rootContainer).clientHeight}function dM(n){return n.getFirstBlock().getBoundingClientRect().top}function hM(n){return n.getLastBlock().getBoundingClientRect().bottom}function mh(n){const e=an(n.rootContainer).getBoundingClientRect(),r=e.x<0?0:e.x,i=e.y<0?0:e.y,o=e.right>window.innerWidth?window.innerWidth:e.right,s=e.bottom>window.innerHeight?window.innerHeight:e.bottom;return new DOMRect(r,i,o-r,s-i)}function mM(n,t){const e=mh(n),r=n.getBlockById(t.blockId),o=Dr(n,r,t);return Ms(e,o.x,o.y)&&Ms(e,o.right,o.bottom)}function L5(n,t){const e=mh(n),r=t.getBoundingClientRect();return r.top>=e.top&&r.top<=e.bottom||r.bottom<=e.bottom&&r.bottom>=e.top}function I5(n,t){const e=mh(n),r=t.getBoundingClientRect();if(r.top>=e.top&&r.top<=e.bottom&&r.bottom<=e.bottom&&r.bottom>=e.top)return 100;const i=Math.max(0,Math.min(r.right,e.right)-Math.max(r.left,e.left)),o=Math.max(0,Math.min(r.bottom,e.bottom)-Math.max(r.top,e.top)),s=i*o,l=r.width*r.height;return s/l*100}function gM(n,t){const e=mh(n),r=t.getBoundingClientRect();return Ms(e,r.x,r.y)||Ms(e,r.right,r.bottom)}function pM(n){if(!Tg(n.rootContainer)){fM.warn("editorScrollIntoView: editor is not visible");return}const t=n.rootContainer.getBoundingClientRect();if(t.height<1&&t.width<1)return;const e=n.selection,r=e.range.focus;if(!r.isSimple()){const C=r,E=n.getContainerById(C.childContainerId);gM(n,E)||E.scrollIntoView();return}if(e.range.start.blockId===e.range.end.blockId){const C=n.getBlockById(e.range.start.blockId);if(we(C)&&L5(n,C)&&I5(n,C)>=95)return;const E=Kd(C);if(_t(n,E)&&L5(n,C)){if(I5(n,C)>=95)return;const x=Gt(E);if(x){_s(x,{elementToScroll:an(n.rootContainer)});return}}}const i=r,o=n.getBlockById(i.blockId);if(mM(n,i))return;if(we(o)){const C=Gt(o);if(C){["image"].includes(cn(o))?setTimeout(()=>{_s(C,{elementToScroll:an(n.rootContainer)})},500):_s(C,{elementToScroll:an(n.rootContainer)});return}}const s=Dr(n,o,i),l=o.getBoundingClientRect(),c=re(o),d=B("div",["editor-block-anchor"],c),h=cr(o);d.style.top=`${(s.top-l.top)/h}px`,_s(d,{elementToScroll:an(n.rootContainer)}),setTimeout(()=>{d.remove()},200)}function CM(n,t){if(t.isCollapsed())return!1;const e=ke(n.rootContainer),r=Je(n.rootContainer),{start:i,end:o}=t;return i.blockId===st(e)&&i.offset===0&&o.blockId===st(r)&&o.offset===dt(n,r)}const D5=I("range-in-block");function _5(n,t){const e=t.getEditor(),r=e.getBlockById(t.start.blockId),i=e.getBlockById(t.end.blockId),o=r===n||ee(n,r),s=i===n||ee(n,i);return!!(o||s)}function M5(n,t){const e=n.doc.toJSON(),r=new Set(Object.values(e.blocks).map(s=>s.map(l=>l.id)).flat());let i,o=me(t);if(o){for(;o&&!r.has(st(o));)o=me(o);p(D5,o,"no prev block while deleting a block"),i=Te(n,o,dt(n,o))}else{const s=Gt(t);p(D5,s,"no prev and next block while deleting a block"),i=Te(n,s,0)}return i}const EM=I("block-to-html");function P1(n,t,e,r){const i=Ns(n,t.type);if(i.convertTo)return i.convertTo(n,t,e,"html",r);if(i.blockKind!=="text")return`[${t.type}]`;p(EM,t.text,"no text");const o=ue(t.text);return`<div>${kd(o)}</div>`}const U5=I("block-to-text");function AM(n,t,e){let r="";return t.forEach(i=>{if(p(U5,typeof i.insert=="string","invalid op"),i.attributes&&i.attributes.box===!0){const o=i.attributes,s=n.editorBoxes.getBoxClass(o.type);if(s!=null&&s.convertTo){r+=s.convertTo(n,o,e,"text");return}if(i.attributes.text){r+=i.attributes.text;return}r+=`[${o.type}]`}r+=i.insert}),r}function gh(n,t,e,r){const i=Ns(n,t.type);return i.convertTo?i.convertTo(n,t,e,"text",r):i.blockKind!=="text"?`[${t.type}]`:(p(U5,t.text,"no text"),AM(n,t.text,e))}function F1(n,t,e,r){const i=Ns(n,t.type);return i.convertTo?i.convertTo(n,t,e,"markdown",r):gh(n,t,e,r)}function ph(n,t){return t.blocks.root.map((i,o)=>P1(n,i,t,[{containerId:"root",blockIndex:o}])).join(`
25
25
  `)}function O5(n,t){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${ph(n,t)}</body></html>`}function Js(n,t){return t.blocks.root.map((i,o)=>gh(n,i,t,[{containerId:"root",blockIndex:o}])).join(`
26
26
  `)}function N5(n,t){const e=t.blocks.root.map((i,o)=>F1(n,i,t,[{containerId:"root",blockIndex:o}]));return e[e.length-1]=e[e.length-1].trimEnd(),e.join(`
27
- `)}const xM=I("get-text-position");function pa(n,t){const e=t!=null?t:n.selection.range.start;e instanceof _e||p(xM,!1,`invalid insert pos type: ${typeof e}`);const{blockId:r}=e,i=n.getBlockById(r),o=bt(i),s=it(i),l=ft(s),{offset:c}=e;return{block:i,container:s,containerId:l,blockIndex:o,offset:c}}const Ca=I("insert-text");function K1(n,t,e,r){var s;const i=n.doc.getBlockData(t,e);if(p(Ca,i,"no block data"),p(Ca,i.text,"no block text"),un(i.text)===0)return p(Ca,r===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,i.id);if(r===0)return;const o=qe(i.text,r-1,1).middle;if(!((s=o[0].attributes)!=null&&s.box))return o[0].attributes}function bM(n,t,e){const r=it(t),i=ft(r),o=bt(t);return K1(n,i,o,e)}function P5(n,t,e,r,i){const o=it(t),s=ft(o),l=bt(t),c=bM(n,t,e),d=sh(e,r,c!=null?c:null);return n.doc.localUpdateBlockText(s,l,d,i),bn(n,t)}function F5(n,t,e,r){const i=it(t),o=ft(i),s=bt(t),l=sh(e," ",r);return n.doc.localUpdateBlockText(o,s,l),bn(n,t)}function vM(n,t){let e=0;if(t===0)return!1;for(let r=0;r<n.length;r++){const i=n[r];p(Ca,typeof i.insert=="string","invalid text op, no insert");const o=e+Zd(i);if(o===t)return!1;if(o>t)return!0;e=o}return!1}function V1(n,t,e,r,i){const o=n.doc.getBlockData(e,r);p(Ca,o,"no block data"),p(Ca,o.text,"no block text");const s=K1(n,e,r,i);s&&Object.keys(s).includes("link")&&(vM(o.text,i)||delete s.link);const l=sh(i,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,r,l),bn(n,n.getBlockById(o.id))}function $1(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:r,offset:i}=pa(n);V1(n,t,e,r,i)}const Ch=I("update-composition-text");function K5(n){const t=n.selection.range.start;t instanceof _e||p(Ch,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,r=n.getBlockById(e);p(Ch,et(n,r),"not a text kind block");const i=it(r),o=ft(i),s=bt(r),l=n.doc.getBlockData(o,s);p(Ch,l,"no block data in doc"),p(Ch,l.text,"no text data in text block");const c=Ot(r);eh(n,Fo(r),e,c,l.text)}function H1(n){V8(n)}function Ea(n,t,e,r,i,o){return n.doc.localInsertBlock(t,e,r,i,o),n.getBlockById(r.id)}const lu=I("delete-block-text");function j1(n,t,e,r,i){if(!n.isBlockWritable(t))return lu.error("block is not writable"),0;p(lu,et(n,t),"block is not a text kind block");const o=it(t),s=ft(o),l=bt(t),c=n.doc.getBlockData(s,l);p(lu,c,"no block data in doc"),p(lu,c.text,"no text data in text block");let d=e;_n(t,e)||(d=Ho(t,d));let h=e+r;p(lu,h<=dt(n,t),`invalid offset and count: ${e}, ${r}`),_n(t,h)||(h=Xs(t,h));const C=h-d,E=r5(d,C);return n.doc.localUpdateBlockText(s,l,E,i),console.log("delete"),C}const z1=I("break-text-block");function V5(n,t){const r=n.getBlockData(t).quoted;return r?{quoted:r}:{}}function Aa(n,t,e,r){p(z1,et(n,t),`block is not a text kind block: ${It(t)}`),p(z1,e>=0&&e<=dt(n,t),`invalid offset: ${e}`);const i=it(t),o=ft(i),s=bt(t),l=r!=null&&r.copyBlockAttributes?V5(n,t):{};if(!(r!=null&&r.forceInsertAfter)&&(e===0||e===dt(n,t))){const x=e===0?s:s+1,v={...hi(""),...l,...r==null?void 0:r.newBlockData},k=Te(n,t.id,0),L=Ea(n,o,x,v,k);return{block:t,newBlock:L}}p(z1,_n(t,e),"not a valid offset");const c=bn(n,t),{right:d}=In(c,e),h=un(d);h>0&&j1(n,t,e,h);const C={...hi(d),...l,...r==null?void 0:r.newBlockData},E=Ea(n,o,s+1,C,Te(n,C.id,0));return{block:t,newBlock:E}}const BM=I("prepare-insert-new-block");function TM(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=Ce(d);return p(BM,e>=0&&e<=h.length,`invalid blockIndex: ${e}`),{containerId:t,blockIndex:e}}const r=n.selection.range.start;if(!r.isSimple())return null;const i=n.getBlockById(r.blockId);if(t=ft(it(i)),e=bt(i),!et(n,i))return{containerId:t,blockIndex:e+1};const s=r.offset;if(s===0||s===dt(n,i))return{containerId:t,blockIndex:s===0?e:e+1};const c=Aa(n,i,s).newBlock;return{containerId:t,blockIndex:bt(c)}}const yM=I("auto-insert-block");function $5(n,t,e,r,i,o){const s=TM(n,e,r);p(yM,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},c={anchor:l,focus:l};return Ea(n,s.containerId,s.blockIndex,t,i!=null?i:c,o)}const RM=I("delete-block");function Eh(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(r=>{n.getChildContainerData(r).forEach(o=>{Eh(n,o,e)})}))}function Ah(n,t,e){const r=it(t),i=ft(r),o=bt(t),s=n.doc.getBlockData(i,o);return p(RM,s,"no block data in doc"),n.doc.localDeleteBlock(i,o,We(n,{anchor:e.start,focus:e.end})),s}function G1(n,t,e){return n.undoManager.runInGroup(()=>{const r=it(t);Sr(r)===1&&n.insertTextBlock("",ft(r),0);let i=e?Ko(n,e):null;if(!i){const l=n.selection.range;_5(t,l)?i=M5(n,t):i=l}const o=Ah(n,t,i),s=[];return Eh(n,o,s),s.length>0&&n.doc.localDeleteChildContainers(s),o})}function kM(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(i=>{Eh(n,i,e)}),n.doc.localDeleteChildContainers(e)}function H5(n,t){const e=[...t];t.forEach(r=>{n.doc.getContainerBlocks(r).forEach(o=>{Eh(n,o,e)})}),n.doc.localDeleteChildContainers(e)}const W1=I("merge-text-block");function j5(n,t,e){p(W1,et(n,t),"only text block can be merged"),p(W1,et(n,e),"only text block can be merged");const r=jo(n,t),i=jo(n,e),o=r.text,s=i.text;p(W1,o&&s,"block data has no text");const l=it(t),c=ft(l),d=bt(t),h=dt(n,t),C=V1(n,s,c,d,h),E=Te(n,t,un(o));return G1(n,e,E),C}const mi=I("clear-selected-contents");function xh(n,t){p(mi,et(n,t.block),"not a text kind block");const{start:e,end:r}=t;p(mi,e.isSimple(),"not a simple block position"),p(mi,r.isSimple(),"not a simple block position");const i=e.offset,o=r.offset;p(mi,i<=o,`invalid delete text offset: ${i}, ${o}`),i!==o&&n.deleteTextFromBlock(t.block,i,o-i)}function z5(n,t,e){const r=ft(t),i=Ce(t),o=e.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",r,0,{newRange:o});e.focus&&n.selection.selectBlock(s,0),i.reverse().forEach(l=>{n.deleteBlock(l)})}function wM(n,t){const{block:e,start:r,end:i}=t;if(et(n,e)){xh(n,t);return}if(we(e)||r.isSimple()){p(mi,i.isSimple(),"invalid range");const s=it(e),l=bt(e),c=n.insertTextBlock("",ft(s),l);n.selection.selectBlock(c,0),n.deleteBlock(e);return}p(mi,_t(n,e),"invalid block kind"),p(mi,!r.isSimple()&&!i.isSimple(),"invalid range"),ca(n,e,r,i),n.selection.range.getSelectedContainers().forEach((s,l)=>{z5(n,s,{focus:l===0})})}function SM(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(p(mi,e.length>0,"no selected block"),e.length===1){wM(n,e[0]);return}const r=e[0],i=r.block,o=it(i);p(mi,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(et(n,i)){xh(n,r);const h=Te(n,r.block,r.start.offset);if(e.slice(1,e.length-1).reverse().forEach(E=>n.deleteBlock(E.block)),et(n,l)){xh(n,s),n.mergeTextBlock(i,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(et(n,l)){xh(n,s),e.slice(0,e.length-1).reverse().forEach(h=>n.deleteBlock(h.block)),n.selection.selectBlock(s.block,0);return}if(e.length===Sr(o)){z5(n,o,{focus:!0});return}const c=me(i),d=Gt(l);p(mi,c||d,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function q1(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),SM(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const LM=I("core");function G5(n,t,e){const r=it(t),i=ft(r),o=bt(t);return n.doc.localUpdateBlockText(i,o,e),setTimeout(()=>{n.selection.updateSelection(null)}),bn(n,t)}function W5(n,t,e){if(!n.isBlockWritable(t)){LM.error("block is not writable");return}const r=n.getBlockText(t),i=fn.diff(r,e);G5(n,t,i)}function bh(n,t,e){const r=bn(n,t),i=typeof e=="string"?Ys(e):e,o=fn.diff(r,i);return G5(n,t,o)}const au=I("update-block-data");function vh(n,t,e,r){const i=it(t),o=ft(i),s=bt(t),l=n.doc.getBlockData(o,s),c={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(e));return d.forEach(E=>{if(!h.has(E)){if(E==="id"||E==="type"||E==="text")return;au.debug(`delete key: ${E}`),c.delete.push(E)}}),Object.entries(e).forEach(([E,x])=>{p(au,E!=="id"&&E!=="type",`invalid block data delta, ${E}`);const v=l[E];if(x==null){v!=null&&(au.debug(`delete key: ${E}`),c.delete.push(E));return}v!==x&&(Nc.default(v,x)||E==="text"&&fn.diff(v,x).length===0||(d.has(E)?(au.debug(`replace key: ${E}`),c.delete.push(E)):au.debug(`insert key: ${E}`),c.insert[E]=x))}),n.doc.localUpdateBlockData(o,s,c,r),jo(n,t)}function q5(n,t,e,r){const o={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,o,r)}function X1(n,t,e){if(!_t(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const i=qn(n,t).getChildContainers(n,t)[0],o=ke(i);X1(n,o,e)}function Zs(n){const t=[];let e={};return n.forEach(r=>{t.push(...r.blocks.root);const{root:i,...o}=r.blocks;e={...e,...o}}),{blocks:{...e,root:t},meta:{},comments:{}}}const cu=I("clone-block");function zo(n,t,e,r){const i=n.getBlockClass(e.type);if(i.blockToDoc)return i.blockToDoc(t,e,(h,C)=>(p(cu,e!==C,"invalid child block"),zo(n,h,e,r)));let o={};const s=new Map,l=gt.default(e);l.children&&(l.children=l.children.map(h=>{const C=Z(),E=t.blocks[h];p(cu,Array.isArray(E),"invalid child blocks");const x=E.map(M=>zo(n,t,M,r)),v=Zs(x),{root:k,...L}=v.blocks;return o={...o,...L},o[C]=v.blocks.root,s.set(h,C),C}));const c=Array.from(s.entries()),d=h=>{for(const C of c){const[E,x]=C;{const v=`${E}/`;if(h.startsWith(v)){const k=h.substring(v.length),L=`${x}/${k}`;return cu.debug(`replace key: ${h} -> ${L}`),L}}{const v=`${E}_`;if(h.startsWith(v)){const k=h.substring(v.length),L=`${x}_${k}`;return cu.debug(`replace key: ${h} -> ${L}`),L}}}return h};return Array.from(Object.entries(l)).forEach(([h,C])=>{const E=d(h);E!==h&&delete l.key,l[E]=C}),l.id=Z(),r&&(r.blockIdMap.set(e.id,l.id),s.forEach((h,C)=>r.containerIdMap.set(C,h))),{blocks:{root:[l],...o},meta:{},comments:{}}}function Q1(n,t,e,r){const i=t.blocks[e];p(cu,Array.isArray(i),"invalid child blocks");const o=i.map(l=>zo(n,t,l,r));return Zs(o)}function Y1(n,t,e){const r=t.blocks.root.map(i=>zo(n.editorBlocks,t,i,e));return gt.default(Zs(r))}const X5=I("insert-doc");function Q5(n,t,e,r,i){if(_t(n,t)){X5.warn("failed to insert doc into a complex block");return}const o=Y1(n,r,i),s=it(t),l=bt(t),c=ft(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var F,G,W,rt;const d=[];Object.entries(o.blocks).forEach(([at,At])=>{at!=="root"&&d.push({containerId:at,blocks:At})}),d.length>0&&n.doc.localInsertChildContainers(d);const h=o.blocks.root;if(we(t)){n.deleteBlock(t);let at;h.reverse().forEach(At=>{const Mt=n.insertBlock(c,l,At,void 0,{noFocus:!0});at||(at=Mt)}),at&&n.selection.selectBlock(at,dt(n,at));return}if(p(X5,et(n,t),"not a text block"),ce(n,t)){const at=bt(t);let At,Mt=!1;for(let Bt=0;Bt<h.length;Bt++){if(Bt===0){const ne=n.getBlockByIndex(c,at),Tn=h[Bt].type==="text"||h[Bt].type==="list",xe=ne&&It(ne)===h[Bt].type;if(ne&&et(n,ne)&&ce(n,ne)&&Tn&&xe){n.insertTextToBlock(t,0,(F=h[Bt].text)!=null?F:[]),Object.keys(h[Bt]).length>3&&n.updateBlockData(ne,N8(h[Bt],["id","text","type","heading","quoted"]));continue}zi(ne)&&(Mt=!0)}const se=n.insertBlock(c,at+Bt,h[Bt],void 0,{noFocus:!0});Bt===h.length-1&&(At=se)}At&&n.selection.selectBlock(At,dt(n,At)),Mt&&n.deleteBlock(t);return}if(h.length===1){const at=h[0];if(Gc(n,at.type)){n.insertTextToBlock(t,e,(G=at.text)!=null?G:[]);return}n.breakTextBlock(t,e),n.insertBlock(c,l+1,at);return}const C=e===dt(n,t),E=e===0,x=h[0],v=h[h.length-1];let k;!C&&!E?k=n.breakTextBlock(t,e,{forceInsertAfter:!0}):k=t;const L=E?l:l+1;C?(k=n.insertBlock(c,l+1,v),n.selection.selectBlock(k,dt(n,k))):(n.selection.selectBlock(k,0),Gc(n,v.type)?n.insertTextToBlock(k,0,(W=v.text)!=null?W:[]):n.insertBlock(c,L,v));const M=n.selection.range;let U=L;Gc(n,x.type)?E?(n.insertBlock(c,L,x),U+=1):n.insertTextToBlock(t,e,(rt=x.text)!=null?rt:[]):(n.insertBlock(c,L,x),U+=1),h.slice(1,h.length-1).reverse().forEach(at=>{n.insertBlock(c,U,at)}),n.selection.setRange(M)}),n.doc.endBatchUpdate()}function J1(n,t,e,r,i){const o=Y1(n,r,i),s=ft(t),l=[];return n.undoManager.runInGroup(()=>{const c=[];Object.entries(o.blocks).forEach(([h,C])=>{h!=="root"&&c.push({containerId:h,blocks:C})}),n.doc.localInsertChildContainers(c),o.blocks.root.reverse().forEach(h=>{const C=n.insertBlock(s,e,h,void 0,{noFocus:!0,noScroll:!0});l.push(C)})}),l}function Y5(n,t,e,r){const i=Sr(t);J1(n,t,i,e,r);for(let o=0;o<i;o++){const s=ke(t);n.deleteBlock(s)}}const uu=I("add-text-attribute");function IM(n,t,e,r){const{start:i,end:o}=e;p(uu,i.blockId===o.blockId&&i.blockId===st(t),"invalid range"),p(uu,r,"invalid attribute name");const s=n.getBlockText(t),l=ha(i.offset,o.offset-i.offset,s,r,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function J5(n,t,e,r,i){const{start:o,end:s}=e;p(uu,o.blockId===s.blockId&&o.blockId===st(t),"invalid range"),p(uu,r,"invalid attribute name");const l=n.getBlockText(t),c=nu(o.offset,s.offset-o.offset,l,r,i);return n.setBlockText(t,c),c}function xa(n,t,e,r,i){const{start:o,end:s}=e;p(uu,o.blockId===s.blockId&&o.blockId===st(t),"invalid range");const l=n.getBlockText(t),c=j3(o.offset,s.offset-o.offset,l,r,i);return n.setBlockText(t,c),c}function Z5(n,t,e,r){const i=ui(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{i.forEach(o=>{const{block:s,start:l,end:c}=o;if(!et(n,s))return;if(ce(n,s)){r(n,st(s),t,e);return}const d=We(n,{anchor:l,focus:c});t==="color"||t==="backgroundColor"?xa(n,s,d,t,e):(xa(n,s,d,"color",null),xa(n,s,d,"backgroundColor",null))})})}function tB(n,t,e){const r=ui(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:o,start:s,end:l}=i;if(!et(n,o))return;if(ce(n,o)){(t==="clearColor"||t==="clearAll")&&e(n,st(o),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,st(o),"backgroundColor",null);return}const c=We(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&xa(n,o,c,"color",null),(t==="clearBackground"||t==="clearAll")&&xa(n,o,c,"backgroundColor",null)})})}function eB(n,t,e){const r=t.getSelectedBlocks().filter(l=>et(n,l.block));if(r.length===0)return[null,null];const i=l=>{if(dt(n,l.block)===0)return e(n,st(l.block));const c=l.start,d=l.end,h=n.getBlockText(l.block);return W3(c.offset,d.offset-c.offset,h)};let[o,s]=i(r[0]);return o===null&&s===null?[o,s]:(r.forEach(l=>{const[c,d]=i(l);c===null||o===null?o=null:o=c===o?o:null,d===null||s===null?s=null:s=d===s?s:null}),[o,s])}const Qn=I("adjust-selection-pos");function nB(n){const t=[];for(;n;){const e=it(n);if(t.unshift(e),Qt(e))return t;const r=nt(e);p(Qn,r,"child container has not parent container"),n=r}p(Qn,!1,"should not come here: getParentContainers")}function rB(n,t){for(;t;){const e=it(t);if(e===n)return t;const r=nt(e);p(Qn,r,"could not find parent block for a child container"),t=r}p(Qn,!1,"no parent block in specified container")}function DM(n,t){const e=nB(n),r=nB(t);p(Qn,e.length>0&&r.length>0,"block has not parent container"),p(Qn,e[0]===r[0],"root container does not equal");let i=e[0];for(let l=1;l<e.length||r.length;l++)if(e[l]!==r[l]){i=e[l-1];break}const o=rB(i,n),s=rB(i,t);return{parentContainer:i,newBlock1:o,newBlock2:s}}function iB(n,t){let e=nt(t);for(p(Qn,e,"element is not in a block");e;){const r=it(e);p(Qn,_r(r),"not a child container");const i=nt(r);if(p(Qn,i,"child container has not parent block"),i===n)return r;e=i}p(Qn,!1,"failed to find parent container in complex block")}function Bh(n,t,e){const r=n.getBlockById(t.blockId),i=n.getBlockById(e.blockId);if(r===i)return t instanceof _e&&e instanceof _e?{anchor:t,focus:e}:t instanceof Mr&&e instanceof Mr?Gd(n,r,t,e):null;const o=it(r),s=it(i);if(o===s)return t instanceof Mr&&(t=lt(r,0,"home")),e instanceof Mr&&(e=lt(i,dt(n,i),"end")),p(Qn,t instanceof _e,"not valid position type"),p(Qn,e instanceof _e,"not valid position type"),{anchor:t,focus:e};if(r.contains(s))return null;if(i.contains(o)){if(t instanceof _e&&e instanceof Mr){const v=n.getContainerById(e.childContainerId);if(v===o)return{anchor:e,focus:e};const k=nt(o);if(k&&k===nt(v)){const L=Ee(k,ft(o)),M=Ee(k,ft(v));return Gd(n,k,L,M)}}return null}const l=yd(r,i)>0,{newBlock1:c,newBlock2:d}=DM(r,i);if(c===d){const v=c,k=iB(v,r),L=iB(v,i);return t=Ee(c,ft(k)),e=Ee(c,ft(L)),Qn.debug(`select in complex block: ${k.id}, ${L.id}`),Gd(n,v,t,e)}let h=l?dt(n,c):0;c===r&&t instanceof _e&&(h=t.offset);let E=l?0:dt(n,d);return d===i&&e instanceof _e&&(E=e.offset),t=lt(c,h,l?"end":"home"),e=lt(d,E,l?"home":"end"),{anchor:t,focus:e}}const _M=I("move-complex-block-position");function MM(n,t,e){const r=n.getBlockById(t.blockId);p(_M,_t(n,r),"is not a complex block");const i=qn(n,r),o=n.getContainerById(t.childContainerId),s=i.getNextContainer(n,r,o,e,{noWrap:!0});return s?Ee(r,ft(s)):null}const fu=I("move-simple-block-position");function oB(n,t){const e=xn(n,t,{visibleOnly:!0});p(fu,e.length>0,"complex block has not any child container");const r=e[0];return ke(r)}function sB(n,t){const e=xn(n,t,{visibleOnly:!0});p(fu,e.length>0,"complex block has not any child container");const r=e[e.length-1];return Je(r)}function lB(n,t,e){const r=e?oB(n,t):sB(n,t);return _t(n,r)?lB(n,r,e):r}function UM(n,t){const e=n.getBlockById(t.blockId);return _t(n,e)&&t.offset===0?oB(n,e):$s(e)}function OM(n,t){const e=n.getBlockById(t.blockId);return _t(n,e)&&t.offset===1?sB(n,e):Vs(e)}function Z1(n){return n==="ArrowLeft"||n==="ArrowUp"}function tp(n,t,e){const r=it(t);if(Qt(r))return null;const i=nt(r);p(fu,i,"child container has not parent block"),p(fu,_t(n,i),"is not a complex block");const o=qn(n,i).getNextContainer(n,i,r,e);return o?Z1(e)?Je(o):ke(o):tp(n,i,e)}function NM(n,t,e){const r=it(t);if(Qt(r))return null;const i=nt(r);if(p(fu,i,"child container has not parent block"),Z1(e)){const l=me(i);if(l)return l}else{const l=Gt(i);if(l)return l}const o=tp(n,i,e);if(o)return o;let s=i;for(;!Qt(it(s));)s=nt(it(s));return Z1(e)?me(s):Gt(s)}function PM(n,t,e){return!_t(n,t)||qn(n,t).enableKeyboardSelect?t:lB(n,t,e==="ArrowDown"||e==="ArrowRight")}function FM(n,t,e){const r=n.getBlockById(t.blockId),o=Jt(n,r).moveCaret(n,r,t,e);if(o)return o;let s=e==="ArrowDown"||e==="ArrowRight"?UM(n,t):OM(n,t);if(s||(s=tp(n,r,e),s||(s=NM(n,r,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Qt(it(r)))return null;const l=n.insertTextBlock("",ft(n.rootContainer),Sr(n.rootContainer));return lt(l,0,"home")}return null}if(s=PM(n,s,e),et(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return u_(n,s,r,t,l);if(e==="ArrowUp")return c_(n,s,r,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?lt(s,dt(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?lt(s,0,"home"):null}function KM(n,t,e){if(t==="ArrowLeft")return e.start;const r=e.end,i=n.getBlockById(r.blockId);if(et(n,i))return r;const o=Gt(i);if(o)return lt(o,0,"home");if(!Qt(it(i))||n.readonly)return r;const s=n.insertTextBlock("",ft(n.rootContainer),Sr(n.rootContainer));return lt(s,0,"home")}function VM(n,t,e){const r=n.selection.range;let i;if(r instanceof Ge)e==="move"&&!r.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?i=KM(n,t,r):i=FM(n,r.getFocusedPos(),t);else if(i=MM(n,r.focus,t),e==="move"){const o=i!=null?i:r.focus,s=n.getContainerById(o.childContainerId);if(t==="ArrowLeft"||t==="ArrowUp"){const l=Je(s);i=lt(l,0,"home")}else{const l=ke(s);i=lt(l,dt(n,l),"end")}}return i?e==="move"?{anchor:i,focus:i}:Bh(n,r.anchor,i):null}function Go(n,t,e){const r=VM(n,t,e);if(!r)return!1;const{anchor:i,focus:o}=r;return n.selection.setSelection(i,o),(t==="ArrowLeft"||t==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function aB(n){return Go(n,"ArrowLeft","move"),!0}function cB(n){return Go(n,"ArrowRight","move"),!0}function uB(n){return Go(n,"ArrowUp","move"),!0}function fB(n){if(Go(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=it(t);if(Qt(e)||Je(e)!==t)return!0;const r=n.rootContainer;return n.insertTextBlock("",ft(r),Sr(r)),!0}function dB(n){return Go(n,"ArrowDown","select"),!0}function hB(n){return Go(n,"ArrowLeft","select"),!0}function mB(n){return Go(n,"ArrowRight","select"),!0}function gB(n){return Go(n,"ArrowUp","select"),!0}const pB=I("word-offset");function ep(n,t){const e=n.selection.range.focus;p(pB,e.isSimple(),"invalid range type");const r=n.getBlockById(e.blockId);if(ce(n,r))return lt(r,0,"home");if(e.offset===0||!et(n,r)){const s=me(r);if(!s)return null;const l=lt(s,dt(n,s),"end");if(t==="select"&&et(n,s)){const c=_1(n,s,l.offset);return lt(s,c,"normal")}return l}const i=_1(n,r,e.offset);return lt(r,i,"normal")}function np(n,t){const e=n.selection.range.focus;p(pB,e.isSimple(),"invalid range type");const r=n.getBlockById(e.blockId);if(ce(n,r))return lt(r,0,"end");if(e.offset===dt(n,r)||!et(n,r)){const s=Gt(r);if(!s)return null;const l=lt(s,0,"home");if(t==="select"&&et(n,s)){const c=M1(n,s,l.offset);return lt(s,c,"end")}return l}const i=M1(n,r,e.offset);return lt(r,i,"normal")}function CB(n){if(!n.selection.range.focus.isSimple())return!1;const e=ep(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function EB(n){if(!n.selection.range.focus.isSimple())return!1;const e=np(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function AB(n){if(!n.selection.range.focus.isSimple())return!1;const e=ep(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function xB(n){if(!n.selection.range.focus.isSimple())return!1;const e=np(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}I("find-block");function rp(n,t){if(!_t(n,t))return t;const r=qn(n,t).getChildContainers(n,t)[0],o=Ce(r)[0];return rp(n,o)}function ip(n,t){if(!_t(n,t))return t;const e=qn(n,t).getChildContainers(n,t),r=e[e.length-1],i=Ce(r),o=i[i.length-1];return ip(n,o)}function op(n){const t=ip(n,Je(n.rootContainer)),e=lt(t,dt(n,t),"end");return n.selection.setSelection(e),!0}function bB(n){const t=rp(n,n.getFirstBlock()),e=lt(t,0,"home");return n.selection.setSelection(e),!0}function vB(n){const t=rp(n,n.getFirstBlock()),e=lt(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function sp(n){const t=ip(n,Je(n.rootContainer)),e=lt(t,dt(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const BB=I("line-offset");function TB(n){const t=n.selection.range.focus;p(BB,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!et(n,e))return lt(e,0,"home");let i=J3(e,t).start;const{next:o}=$d(e,i);return o&&dr(o)&&qc(o)==="br"&&(i+=1),lt(e,i,"home")}function yB(n){const t=n.selection.range.focus;p(BB,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===dt(n,e)||!et(n,e))return lt(e,dt(n,e),"end");const r=J3(e,t);return lt(e,r.end,"end")}function RB(n){if(!n.selection.range.focus.isSimple())return!1;const e=TB(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function kB(n){if(!n.selection.range.focus.isSimple())return!1;const e=yB(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function wB(n){if(!n.selection.range.focus.isSimple())return!1;const e=TB(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function SB(n){if(!n.selection.range.focus.isSimple())return!1;const e=yB(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const LB=I("find-block-position");function $M(n,t,e,r){p(LB,_t(n,t),"is not a complex block");const i=qn(n,t).getChildContainers(n,t);p(LB,i.length>0,"complex block has not any child container");const o=Dr(n,e,r),s=o.left+o.width/2,l=o.top+o.height/2,c=t3(n,t,s,l);return lp(n,c,e,r)}function lp(n,t,e,r){if(_t(n,t))return $M(n,t,e,r);const i=st(t);let o=Number.MAX_SAFE_INTEGER;const s=Dr(n,e,r),l=s.left+s.width/2,c=s.top+s.height/2;let d=lt(i,0,"home");const h=dt(n,t);for(let C=0;C<=h;C++){const E=lt(i,C,"normal"),x=Dr(n,t,E),v=Ki(x,l,c);v<o&&(o=v,d=E)}return d}const IB=I("page-offset");function HM(n,t){const e=S5(n)*.9,i=t.getBoundingClientRect().bottom-e;if(i<dM(n))return n.getFirstBlock();const o=me(t);if(!o)return n.getFirstBlock();let s=o;for(;s;){if(s.getBoundingClientRect().y<i)return s;s=me(s)}return n.getFirstBlock()}function jM(n,t){const e=S5(n)*.9,r=t.getBoundingClientRect(),i=hM(n),o=r.top+e;if(o>i)return n.getLastBlock();const s=Gt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>o)return l;l=Gt(l)}return n.getLastBlock()}function DB(n){const t=n.selection.range.focus;p(IB,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),r=HM(n,e);let i;return r===n.getFirstBlock()?i=lt(r,0,"home"):i=lp(n,r,e,t),i}function _B(n){const t=n.selection.range.focus;p(IB,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),r=jM(n,e);let i;return r===n.getLastBlock()?i=lt(r,dt(n,r),"end"):i=lp(n,r,e,t),i}function MB(n){if(!n.selection.range.focus.isSimple())return!1;const e=DB(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function UB(n){if(!n.selection.range.focus.isSimple())return!1;const e=_B(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function OB(n){if(!n.selection.range.focus.isSimple())return!1;const e=DB(n);if(!e)return!1;const r=Bh(n,n.selection.getAnchorPos(),e);if(!r)return!1;const{anchor:i,focus:o}=r;return n.selection.setSelection(i,o),n.selection.updateLastCaretRect(),!0}function NB(n){if(!n.selection.range.focus.isSimple())return!1;const e=_B(n);if(!e)return!1;const r=Bh(n,n.selection.getAnchorPos(),e);if(!r)return!1;const{anchor:i,focus:o}=r;return n.selection.setSelection(i,o),n.selection.updateLastCaretRect(),!0}const du=I("select-all");function PB(n,t){const e=ke(n),r=Je(n);return t.start.offset===0&&t.start.blockId===st(e)&&t.end.offset===dt(t.getEditor(),r)&&t.end.blockId===st(r)}function zM(n,t){const e=t.getEditor(),r=qn(e,n).getChildContainers(e,n),i=r[0],o=r[r.length-1],s=st(n);return t.start.blockId===s&&t.start.childContainerId===ft(i)&&t.end.blockId===s&&t.end.childContainerId===ft(o)}function GM(n,t){p(du,t,"no parent block"),p(du,_t(n,t),"not a complex block");const e=qn(n,t).getChildContainers(n,t),r=e[0],i=e[e.length-1];n.selection.setRange(We(n,{anchor:Ee(t,ft(r)),focus:Ee(t,ft(i))}))}function FB(n,t){const e=it(t);ap(n,e)}function KB(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&et(n,t)){const i=e.start,o=e.end,s=dt(n,t);if(i.offset>0||o.offset<s)return n.selection.selectBlock(t,0,s),!1}return z(n.rootContainer,"select-all"),FB(n,ke(n.rootContainer)),!1}return p(du,!e.isSimple(),"invalid range type"),zM(t,e)?(FB(n,t),!1):(p(du,t,"no parent block"),p(du,_t(n,t),"not a complex block"),GM(n,t),!0)}function ap(n,t){const e=Ce(t),r=e[0],i=e[e.length-1],o=lt(r,0,"home"),s=lt(i,dt(n,i),"end");n.selection.setSelection(o,s,{noScroll:!0})}function WM(n){sp(n),n.focus()}const cp=I("selected-block-to-doc");function VB(n,t,e){!t.children||t.children.forEach(r=>{const i=n.getChildContainerData(r);i.forEach(o=>{VB(n,o,e)}),e.blocks[r]=gt.default(i)})}function Th(n,t){const e=Jt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const r=gt.default(jo(n,t.block));if(et(n,t.block)){const o=t.start,s=t.end;if(p(cp,r.text,"no block text"),o.offset===s.offset)return{blocks:{root:[{...r,text:[]}]},meta:{},comments:{}};const{middle:l}=qe(r.text,o.offset,s.offset-o.offset);return{blocks:{root:[{...r,text:l}]},meta:{},comments:{}}}if(we(t.block))return{blocks:{root:[r]},meta:{},comments:{}};p(cp,_t(n,t.block),"not complex block"),p(cp,r.children,"no children");const i={blocks:{root:[r]},meta:{},comments:{}};return VB(n,r,i),i}function up(n,t){const e=lt(t,0,"normal"),r=lt(t,dt(n,t),"end");return Th(n,{block:t,start:e,end:r})}const qM=I("block-to-doc");function XM(n,t){p(qM,t.length>0,"invalid params, no blocks");const e=t.map(r=>up(n,r));return Zs(e)}function yh(n){const e=n.selection.range.getSelectedBlocks().map(r=>Th(n,r));return Zs(e)}function $B(n,t){const e=n.getContainerById(t),o=Ce(e).map(s=>({start:lt(s,0,"home"),end:lt(s,dt(n,s),"end"),block:s})).map(s=>Th(n,s));return Zs(o)}const Rh=I("editor-selection");class QM{constructor(t){g(this,"editor");g(this,"caret");g(this,"_range");g(this,"lastCaretRect");g(this,"handleBlockDelete",(t,e,r,i)=>{if(r||i.child)return;const o=this.range;if(_5(e,o)){Rh.debug("adjust selection because remote deleted current block");const s=M5(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),r=st(e);this.caret=new cM(t);const i=lt(r,0,"normal");this._range=We(t,{anchor:i,focus:i}),this.lastCaretRect=null,this.editor.addListener("blockDeleted",this.handleBlockDelete),setTimeout(()=>{this.updateFocusedBlock(null)})}destroy(){this.caret.destroy()}get range(){return this._range}get focusedBlock(){return this.getFocusedBlock()}get startBlock(){return this.getStartBlock()}get endBlock(){return this.getEndBlock()}getFocusedBlock(){const t=this.range.focus;return this.editor.getBlockById(t.blockId)}getStartBlock(){const t=this.range.start;return this.editor.getBlockById(t.blockId)}getEndBlock(){const t=this.range.end;return this.editor.getBlockById(t.blockId)}selectBlock(t,e,r){const i=lt(t,e,"normal");let o;r&&(o=lt(t,r,"normal")),this.setSelection(i,o)}setSelection(t,e,r){if(e||(e=t),this.verifyPos(t),this.verifyPos(e),!this.selectionChanging(t,e))return this.range;const i=We(this.editor,{anchor:t,focus:e});if(this.range.isEqual(i))return this.range;const o=this._range;return this._range=i,this.selectionChanged(),this.updateFocusedBlock(o),kt(this.editor.rootContainer,"select-all")&&(!i.isSimple()||!CM(this.editor,i))&&ot(this.editor.rootContainer,"select-all"),r!=null&&r.noScroll||this.scrollIntoView(),this.range}setRange(t,e){return this.setSelection(t.anchor,t.focus,e)}updateSelection(){this.caret.update(),uM(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(t,e){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const t=this.range.focus;if(!ai(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Dr(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){pM(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=dt(this.editor,e)||p(Rh,!1,"invalid block position, out of range");else{const r=t.childContainerId;!!this.editor.getContainerById(r)||p(Rh,!1,"invalid complex block position, no container found")}}updateFocusedBlock(t){if(t&&this.range.start.blockId===t.start.blockId)return;let e;t&&t.start.blockId===t.end.blockId&&(e=this.editor.findBlockById(t.start.blockId));let r;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(r=this.editor.getBlockById(this.range.start.blockId));let i=!1;e&&kt(e,"focused")&&(ot(e,"focused"),i=!0),this.removeAllBlockFocusedClass(),r&&this.setBlockFocused(r)&&(i=!0),i&&this.editor.emit("focusBlockChanged",this.editor,r!=null?r:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(t){const e=yh(this.editor);return t==="text"?Js(this.editor,e):t==="markdown"?N5(this.editor,e):O5(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{ot(t,"focused"),ot(t,"child-focused")})}setBlockFocused(t){if(kt(t,"focused"))return!1;z(t,"focused");let e=it(t);for(;_r(e);){const r=nt(e);p(Rh,r,"parent block not found"),z(r,"child-focused"),e=it(r)}return!0}}function YM(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);!e||n.selection.selectBlock(e,0,dt(n,e))}function JM(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!et(n,e))return;let r=ep(n,"select"),i=np(n,"select");if(!r||!i)return;const o=t.blockId;r.blockId!==o&&(r=lt(e,0,"home")),i.blockId!==o&&(i=lt(e,dt(n,e),"end")),n.selection.setSelection(r,i)}class ZM{constructor(t){g(this,"editor");g(this,"startPos",null);g(this,"lastCaretRect");g(this,"mouseDownEvent",null);g(this,"autoScroll",null);g(this,"handleMouseDown",(t,e)=>{var i;this.mouseDownEvent=t;const r=r3(this.editor,t.x,t.y);if(r){if(r instanceof ci)return;if(!this.autoScroll&&e.autoScroll){const s=r.getSelectedBlocks(),l=an(s[0].block);this.autoScroll=new Ud({scrollElement:l,edge:{top:50,bottom:50}})}const o=this.editor.selection.range;if(t.shiftKey&&o.isSimple()){const s=o.anchor;this.editor.selection.setSelection(s,r.focus),this.startPos=r.start}else this.editor.selection.setSelection(r.anchor,r.focus),this.startPos=r.start;this.editor.selection.updateLastCaretRect(),e.autoScroll&&((i=this.autoScroll)==null||i.active())}});g(this,"handleMouseMove",t=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-t.x)<3&&Math.abs(this.mouseDownEvent.y-t.y)<3)return;const e=Wd(this.editor,t.x,t.y);if(!e)return;const r=Bh(this.editor,this.startPos,e.end);if(!r)return;const{anchor:i,focus:o}=r;this.editor.selection.setSelection(i,o)});g(this,"handleMouseUp",t=>{var e;(e=this.autoScroll)==null||e.inactive(),this.startPos=null});this.editor=t,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(t){JM(this.editor)}handleTripleClick(t){YM(this.editor)}}function tU(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function eU(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const HB=I("delete-text");function jB(n,t,e,r){const i=r!=null?r:n.selection.range.start;i instanceof _e||p(HB,!1,`invalid insert pos type: ${typeof i}`);const{blockId:o}=i,s=n.getBlockById(o);p(HB,et(n,s),"block is not a text kind block");let{offset:l}=i;if(t==="backward"){if(l-e<0)return 0;if(!_n(s,l-e)){const c=Ho(s,l);e=l-c}}else if(t==="forward"&&l+e>dt(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function zB(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const nU=I("handle-backspace");function fp(n,t){if(!ce(n,t))return;const e=it(t);Sr(e)!==1&&n.deleteBlock(t)}function rU(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,r=n.getBlockById(e.blockId);if(et(n,r))if(e.offset===0){if(zB(n,r))return;const i=me(r);if(i){if(!n.isBlockWritable(i))return;if(et(n,i))n.mergeTextBlock(i,r,{focus:!0});else if(_t(n,i)){fp(n,r);const o=ua(n,i);o?n.selection.selectBlock(o,dt(n,o)):n.selection.selectBlock(i,0,dt(n,i))}else fp(n,r),p(nU,we(i),"prev block is not embed block"),n.selection.selectBlock(i,1)}else{const o=it(r);if(_r(o)){const s=Yv(n,o);if(s){if(!n.isBlockWritable(s))return;fp(n,r),n.selection.selectBlock(s,dt(n,s))}}}}else jB(n,"backward",1,null),n.selection.updateLastCaretRect();else{const i=bt(r),o=it(r);n.insertTextBlock("",ft(o),i),n.deleteBlock(r)}}function iU(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,r=n.getBlockById(e.blockId);if(et(n,r))if(e.offset===dt(n,r)){const i=Gt(r);if(i){if(!n.isBlockWritable(i))return;et(n,i)?n.mergeTextBlock(r,i,{focus:!0}):ce(n,r)?n.deleteBlock(r,Te(n,i,0)):n.deleteBlock(i)}}else jB(n,"forward",1,null);else{const i=bt(r),o=it(r);n.insertTextBlock("",ft(o),i),n.deleteBlock(r)}}function oU(n){const{range:t}=n.selection,{start:e,end:r}=t,i=n.getBlockById(e.blockId),o=n.getBlockById(r.blockId);if(i!==o||!_t(n,i))return!1;if(ai(e))return!0;const s=ca(n,i,e,r),l=xn(n,i);return s.length===l.length}function sU(n,t){if(oU(n)){const s=n.getFocusedBlock(),l=bt(s),c=ft(it(s));n.insertTextBlock("",c,l+1);return}const e=n.getFocusedBlock(),{start:r,end:i}=n.selection.range,o=r.blockId===i.blockId&&we(e);if(!n.selection.range.isCollapsed()&&!o&&n.clearSelectedContents(),et(n,e)){if(ce(n,e)&&zB(n,e))return;const s=n.selection.range.start,l=n.breakTextBlock(e,s.offset,{copyBlockAttributes:!0});s.offset!==0?n.selection.selectBlock(l,0):n.selection.scrollIntoView()}else{const s=n.insertTextBlock();n.selection.selectBlock(s,0)}}function lU(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:r}=e;if(!et(n,r))return!1;const i=e.end;return n.insertBoxToBlock(r,i.offset,{type:"br",id:Z(),box:!0,created:Date.now()}),!0}const aU=I("input-handler-actions");function cU(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(sU(n),!0))}function uU(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(iU(n),!0))}function fU(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(rU(n),!0))}function dU(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(lU(n),!0))}function hU(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{aU.error(t)}),!0)}const kh={ArrowDown:fB,ArrowUp:uB,ArrowLeft:aB,ArrowRight:cB,"Shift+ArrowDown":dB,"Shift+ArrowUp":gB,"Shift+ArrowLeft":hB,"Shift+ArrowRight":mB,"CtrlOrCmd+ArrowLeft":CB,"CtrlOrCmd+ArrowRight":EB,"CtrlOrCmd+Shift+ArrowLeft":AB,"CtrlOrCmd+Shift+ArrowRight":xB,"CtrlOrCmd+ArrowUp":bB,"CtrlOrCmd+ArrowDown":op,"CtrlOrCmd+Shift+ArrowUp":vB,"CtrlOrCmd+Shift+ArrowDown":sp,"CtrlOrCmd+A":KB,Home:wB,End:SB,"Shift+Home":RB,"Shift+End":kB,PageUp:MB,PageDown:UB,"Shift+PageUp":OB,"Shift+PageDown":NB,"CtrlOrCmd+Z":tU,"CtrlOrCmd+Shift+Z":eU,Enter:cU,Delete:uU,Backspace:fU,"Shift+Enter":dU,"CtrlOrCmd+Shift+V":hU};function GB(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function WB(n,t,e){if(t.type==="embed"){const o=t.embedData,s=o.src;if(s&&typeof s=="string"){const l=e.get(s);if(l)o.src=l;else{let c="";s.split("|").forEach(h=>{const C=e.get(h);C&&(c+=c?`|${C}`:`${C}`)}),c&&(o.src=c)}}return}const r=t.text;r&&r.forEach(o=>{if(o.attributes&&o.attributes.src&&typeof o.attributes.src=="string"){const s=e.get(o.attributes.src);s&&(o.attributes.src=s)}});const i=t.children;i&&i.forEach(o=>{n.blocks[o].forEach(l=>{WB(n,l,e)})})}function qB(n,t,e){if(e.size===0)return;t.blocks.root.forEach(i=>{const o=n.editorBlocks.getBlockClass(i.type);o.replaceResources?o.replaceResources(i,e):WB(t,i,e)})}async function mU(n,t){let e=t.filter(s=>s.indexOf(":")===-1);const r=[];e.forEach(s=>{const l=s.split("|");r.push(...l)}),e=Array.from(new Set(r)),e=r;const i=await n.doc.addResources(e),o=new Map;if(e.length!==i.length)return o;for(let s=0;s<e.length;s++)o.set(e[s],i[s]);return o}function gU(n,t){var l,c,d,h;const r=t.meta.serverId;if(!r||typeof r!="string")return!1;const i=(c=(l=n.doc).getServerMeta)==null?void 0:c.call(l);if(!i)return!1;const o=/.*(?=\/)/;return((d=(i.serverId||"").match(o))==null?void 0:d[0])===((h=r.match(o))==null?void 0:h[0])}async function dp(n,t){const r=t.meta.resources;if(!r||Object.keys(r).length===0)return;let i=new Map;if(gU(n,t)){const s=Array.from(Object.keys(r));i=await mU(n,s),qB(n,t,i)}const o=new Map;Object.entries(r).forEach(([s,l])=>{i.get(s)===void 0&&s!==l&&o.set(s,l)}),o.size!==0&&qB(n,t,o)}async function pU(n,t,e){await dp(n,t),n.undoManager.runInGroup(()=>{const{start:r,end:i}=n.selection.range,o=n.getBlockById(r.blockId);if(r.blockId===i.blockId&&we(o)){const s=it(o),l=n.getBlockIndex(o),[c]=n.insertDocAt(s,l+1,t,e);c&&n.selection.selectBlock(c,dt(n,c))}else{n.clearSelectedContents();const{block:s,offset:l}=pa(n);n.insertDoc(s,l,t,e)}})}const CU=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function EU(n){let t;for(const e of CU)if(t=n[e],t)break;return t||null}function hp(n,t,e,r){if(e.type==="embed"){const l=e.embedData.src;if(l&&typeof l=="string")for(const c of l.split("|"))r.add(c);return}const i=e.text;i&&i.forEach(s=>{if(s.attributes&&s.attributes.src&&typeof s.attributes.src=="string")if($o(s)){const l=n.editorBoxes.getBoxClass(s.attributes.type);if(l.getResources){const c=l.getResources(n,s.attributes);c?c.forEach(d=>{r.add(d)}):r.add(s.attributes.src)}else r.add(s.attributes.src)}else r.add(s.attributes.src)});const o=e.children;o&&o.forEach(s=>{t.blocks[s].forEach(c=>{hp(n,t,c,r)})})}function AU(n,t){const e=new Set;return t.blocks.root.forEach(i=>{const o=n.editorBlocks.getBlockClass(i.type);if(o.getResources){const s=o.getResources(n,i);s?s.forEach(l=>{e.add(l)}):hp(n,t,i,e)}else hp(n,t,i,e)}),Array.from(e)}function wh(n,t){return he.isFirefox?`<!doctype html><html><head><meta charset="utf8" /></head><body><canvas data-editor-doc="${Hi(JSON.stringify(t))}" id="ones-editor-doc">${n}</body></html>`:`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Hi(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Sh(n,t){var o,s,l;const e=(l=(s=(o=n.doc).getServerMeta)==null?void 0:s.call(o))!=null?l:{},r=AU(n,t),i={};r.forEach(c=>{const d=n.doc.buildResourceUrl(c,{withToken:!0});i[c]=d}),t.meta={...e,resources:i}}function xU(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let r=yh(n);const i=e==null?void 0:e(n,t,r);if(i===!0)return;typeof i=="object"&&i!==null&&(r=i),Sh(n,r);const o=ph(n,r),s=Js(n,r),l=wh(o,r);t.clipboardData.setData("text/html",l),t.clipboardData.setData("text/plain",s),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(r))}async function Lh(n,t){if(!window.isSecureContext)throw new Error("Can't copy block in insecure context.");const e=up(n,t);Sh(n,e);const r=ph(n,e),i=Js(n,e),o=wh(r,e);return Mg([{type:"text/plain",data:new Blob([i],{type:"text/plain"})},{type:"text/html",data:new Blob([o],{type:"text/html"})}])}class bU{constructor(t){g(this,"editor");g(this,"handlers",[]);g(this,"onPasteText",async(t,e)=>{const r=new DataTransfer;r.setData("text/plain",t);const i=await this.editor.dataConverter.fromData(this.editor,r,e);if(i){const o=[];this.pasteDocs(i,null,o)}});this.editor=t}onInsertText(t,e){if(!et(this.editor,this.editor.getFocusedBlock()))return;const{containerId:r,blockIndex:i,offset:o}=pa(this.editor);this.handleBeforeInsertText(r,i,o,e)||(this.defaultInsertText(this.editor,r,i,o,e),this.handleAfterInsertText(r,i,o,e),this.editor.selection.updateLastCaretRect())}onKeyDown(t){if(this.handleBeforeKeyDown(t))return!0;const e=this.defaultHandleKeydown(this.editor,t);return this.handleAfterKeyDown(t)?!0:e}onChanged(t){for(let e=0;e<this.handlers.length;e++){const r=this.handlers[e];r.handleChanged&&r.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const r=this.handlers[e];r.handleRemoteChanged&&r.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){if(!et(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:r,offset:i}=pa(this.editor);for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,r,i)}}onUpdateCompositionText(t,e,r){if(!et(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText(e,r),this.editor.selection.caret.update();const{containerId:i,blockIndex:o,offset:s}=pa(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,i,o,s,r)}this.editor.selection.updateLastCaretRect()}onCopy(t){xU(this.editor,t,(e,r,i)=>{for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,r,i);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onCut(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeCut&&i.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const r=this.editor.selection.focusedBlock;we(r)&&this.editor.deleteBlock(r)}else q1(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;const e=this.editor.dataConverter.fromData(this.editor,t.clipboardData),r=Array.from(t.clipboardData.files);e.then(async i=>{i&&this.pasteDocs(i,t,r)})}onFocus(){z(this.editor.rootElement,"active")}onBlur(){ot(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,r)=>{var s,l;const i=(s=e.order)!=null?s:1;return((l=r.order)!=null?l:1)-i})}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,r,i){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,r,i))return!0}return!1}handleAfterInsertText(t,e,r,i){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,r,i))return!0}return!1}handleBeforeKeyDown(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeKeyDown&&i.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterKeyDown&&i.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeKeyDown&&i.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterKeyDown&&i.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,r,i,o){$1(this.editor,o)}defaultHandleKeydown(t,e){return GB(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePasteDoc&&await i.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await pU(this.editor,t,e);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPasteDoc&&await i.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e,r){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforePaste&&await s.handleBeforePaste(this.editor,e,t,r))return}const i=EU(t);if(!!i){await this.pasteDoc(i);for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleAfterPaste&&await s.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}forEach(t){this.handlers.forEach(t)}}function vU(n,t,e){const r=ji(t,e);return r.remove(),r}I("copy-dom-attributes");const XB=["onabort","onanimationcancel","onanimationend","onanimationiteration","onanimationstart","onauxclick","onblur","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onformdata","ongotpointercapture","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onlostpointercapture","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onpause","onplay","onplaying","onpointercancel","onpointerdown","onpointerenter","onpointerleave","onpointermove","onpointerout","onpointerover","onpointerup","onprogress","onratechange","onreset","onresize","onscroll","onsecuritypolicyviolation","onseeked","onseeking","onselect","onselectionchange","onselectstart","onslotchange","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","ontouchcancel","ontouchend","ontouchmove","ontouchstart","ontransitioncancel","ontransitionend","ontransitionrun","ontransitionstart","onvolumechange","onwaiting","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","onwheel"];function BU(n,t){for(let l=0;l<XB.length;l++){const c=XB[l];t[c]=n[c]}const e=n.attributes,r=t.attributes,i=[],o=[];for(let l=0;l<e.length;l++){const c=e[l],d=r.getNamedItem(c.name);d?d.value!==c.value&&(d.value=c.value,o.push(c)):i.push(c)}const s=[];for(let l=0;l<r.length;l++){const c=r[l];e.getNamedItem(c.name)||s.push(c)}i.forEach(l=>{t.setAttribute(l.name,l.value)}),o.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function QB(n){const t=Array.from(n.childNodes).filter(e=>!gv(e));return t.forEach(e=>{e.remove()}),t}function YB(n,t,e){var d;const r=n.getContainerById(t),i=ji(r,e),o=Fo(i),s=n.doc.getBlockData(t,e),l=Jt(n,i);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,i,s))n.editorBlockRenders.updateBlock(n,o,i,s);else{const h=n.editorBlocks.createBlock(o,r,s),C=QB(h);QB(i),C.forEach(x=>{i.appendChild(x)});const E=Pd(h);if(E){const x=Pd(i);x&&x.remove(),i.appendChild(E)}BU(h,i)}Iv(n,i,s),n.blockHooks.forEach(h=>{var C;(C=h.update)==null||C.call(h,n,o,r,i,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const TU=I("transform-selection");function JB(n,t,e,r){const{range:i}=n.selection,{anchor:o,focus:s}=i;if(o.blockId!==t&&s.blockId!==t)return i;p(TU,o.isSimple()&&s.isSimple(),"invalid text pos type");let l=o;if(o.blockId===t){const d=fn.transformCursor(o.offset,e,r);l=lt(t,d,"normal")}let c=s;if(s.blockId===t){const d=fn.transformCursor(s.offset,e,r);c=lt(t,d,"normal")}return We(n,{anchor:l,focus:c})}const yU=I("handle-block-text-changed");function RU(n,t,e,r,i){const o=n.getContainerById(t),s=ji(o,e),l=n.doc.getBlockData(t,e);if(p(yU,l.text,"no block text"),fv(n,s).setBlockText(n,s,l.text),!i){const c=JB(n,l.id,r,i);n.selection.setRange(c,{noScroll:!0})}}function kU(n,t){const e=gt.default(n);return t.delete.forEach(i=>{delete e[i]}),{...e,...t.insert}}function ZB(n,t,e,r){const i=Jt(n,t);i.handleDeleteBlock&&i.handleDeleteBlock(n,t,e,r),n.emit("blockDeleted",n,t,e,r)}function wU(n,t,e,r){const i=n.getBlockByIndex(t,e);i.querySelectorAll('[data-type="editor-block"]').forEach(o=>{ZB(n,o,r,{child:!0})}),ZB(n,i,r,{child:!1})}const Or=I("editor-doc");class SU extends ra{constructor(e,r,i){super();g(this,"localEvents",[]);this.editor=e,this.externalDoc=r,this.externalDoc.registerCallback(this),this.registerLocalEvents(i)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var r,i;return(i=(r=this.externalDoc).getVersionHelper)==null?void 0:i.call(r)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}findContainerBlocks(e){return this.externalDoc.findContainerBlocks(e)}getBlockData(e,r){return this.externalDoc.getBlockData(e,r)}verifyBlockWritable(e,r){const i=this.editor.getBlockByIndex(e,r);p(Or,this.editor.isBlockWritable(i),`block is not writable, ${e}, ${r}`)}localUpdateBlockText(e,r,i,o){p(Or,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,r);const s=this.getBlockData(e,r),l=s.text;p(Or,l,`no text, ${e}, ${r}`);const c=JB(this.editor,s.id,i,!0),d=fn.apply(l,i);this.localEvents.forEach(C=>C.onBeforeUpdateBlockText(e,s.id,l,d,c.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,r,i);return this.editor.selection.setRange(c,o),h}localUpdateBlockData(e,r,i,o){p(Or,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,r);if(!this.editor.isBlockWritable(s)){const h=Array.from(i.delete).filter(E=>E!=="comments"),C=Object.keys(i.insert).filter(E=>E!=="comments");(h.length>0||C.length>0)&&p(Or,!1,`block is not writable, comment supported only, ${JSON.stringify(i)}}`)}const l=gt.default(this.getBlockData(e,r)),c=gt.default(kU(l,i));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,c,o));const d=this.externalDoc.localUpdateBlockData(e,r,i,o);return this.editor.selection.setRange(Ko(this.editor,o)),d}localInsertBlock(e,r,i,o,s){p(Or,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(e,r,i,o));const l=this.externalDoc.localInsertBlock(e,r,i,o);return s!=null&&s.noFocus||this.editor.selection.setRange(Ko(this.editor,o),s),l}localDeleteBlock(e,r,i){p(Or,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,r);const o=gt.default(this.getBlockData(e,r));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,r,o,i));const s=this.externalDoc.localDeleteBlock(e,r,i);return this.editor.selection.setRange(Ko(this.editor,i)),s}localDeleteChildContainers(e){return p(Or,!this.editor.readonly,"editor is readonly"),e.forEach(r=>{const i=gt.default(this.getContainerBlocks(r));this.localEvents.forEach(o=>o.onBeforeDeleteChildContainer(r,i))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainers(e){p(Or,!this.editor.readonly,"editor is readonly");const r=gt.default(e);r.forEach(i=>{this.localEvents.forEach(o=>o.onBeforeInsertChildContainer(i.containerId,i.blocks))}),this.externalDoc.localInsertChildContainers(r)}onRequestReload(e){Or.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(i=>{var o;return(o=i.onRequestReload)==null?void 0:o.call(i,e)});const r=!1;this.editor.emit("docChanged",this.editor,r)}onUpdateBlockText(e,r,i,o){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,r,i,o)}),RU(this.editor,e,r,i,o),this.editor.emit("docChanged",this.editor,o)}onUpdateBlockData(e,r,i,o){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,r,i,o)}),YB(this.editor,e,r),this.editor.emit("docChanged",this.editor,o)}onInsertBlock(e,r,i,o){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,e,r,i,o)});const s=this.editor.getContainerById(e);sI(this.editor,s,r,i),this.editor.emit("docChanged",this.editor,o)}onDeleteBlock(e,r,i){wU(this.editor,e,r,i),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,r,i)});const o=this.editor.getContainerById(e);vU(this.editor,o,r),this.editor.emit("docChanged",this.editor,i)}onInsertChildContainer(e,r,i){this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,e,r,i)})}onDeleteChildContainer(e,r){this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,e,r)})}onCustomMessage(e){this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,e)})}onStatusChanged(e){this.callbacks.forEach(r=>{var i;return(i=r.onStatusChanged)==null?void 0:i.call(r,e)})}onError(e){this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,e)})}uploadResource(e,r){return this.externalDoc.uploadResource(e,r)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,r){return this.externalDoc.buildResourceUrl(e,r)}request(e,r){return this.externalDoc.request(e,r)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}triggerReAuth(){var e,r;return(r=(e=this.externalDoc).triggerReAuth)==null?void 0:r.call(e)}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,r,i;return(i=(r=(e=this.externalDoc).getServerMeta)==null?void 0:r.call(e))!=null?i:{}}reset(e){Or.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function t2(n,t){if(n.length===0){n.push(t);return}const e=n[n.length-1];if(!e.combinable(t)){n.push(t);return}e.combine(t)}const Ih=I("undo-action");class ba{constructor(t,e,r){g(this,"beforeRange");g(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=r}undo(t){return!1}redo(t){return!1}combinable(t){return p(Ih,t,"no other action"),!1}combine(t){p(Ih,!1,"no other")}setAfterRange(t){this.afterRange&&Ih.warn("after range has already set"),this.afterRange=t}findContainerById(t,e){return!!t.doc.findContainerBlocks(e)}findBlockById(t,e){const r=t.doc.findContainerBlocks(this.containerId);return r?r.some(i=>i.id===e):!1}checkBlockData(t,e){if(Array.isArray(e.children)){const r=t.doc.toJSON();for(let i=0;i<e.children.length;i++){const o=e.children[i];if(!r.blocks[o])return Ih.warn(`container (${o}) not found, deleted by others?`),!1}}return!0}}const va=I("block-action");class e2 extends ba{constructor(e,r,i,o,s){super(e,r,s);g(this,"blockData");g(this,"blockIndex");this.blockData=gt.default(o),this.blockIndex=i}deleteBlock(e,r){if(!this.findContainerById(e,this.containerId))return va.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockData.id))return va.warn(`block (${this.blockData.id}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const o=e.getBlockById(this.blockData.id);if(!o)return!1;try{p(va,this.blockIndex===bt(o),"invalid block index"),Ah(e,o,Ko(e,r))}catch(s){va.warn(s.message),e.selection.selectBlock(o,0)}return!0}insertBlock(e,r){if(!this.findContainerById(e,this.containerId))return va.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.checkBlockData(e,this.blockData))return!1;try{Ea(e,this.containerId,this.blockIndex,gt.default(this.blockData),r)}catch(i){va.warn(i.message);const o=e.doc.getContainerBlocks(this.containerId),s=Math.min(o.length-1,this.blockIndex),l=e.getBlockByIndex(this.containerId,s);e.selection.selectBlock(l,0)}return!0}}I("insert-block-action");class LU extends e2{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class IU extends e2{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class DU extends ba{constructor(e){super(e,ft(e.rootContainer),e.selection.range.toDocRange());g(this,"actions",[])}addAction(e){t2(this.actions,e),this.afterRange=e.afterRange}undo(e){let r=!1;return this.actions.concat().reverse().forEach(i=>{i.undo(e)&&(r=!0)}),r}redo(e){let r=!1;return this.actions.forEach(i=>{i.redo(e)&&(r=!0)}),r}setAfterRange(e){this.afterRange=e;const r=this.actions[this.actions.length-1];!r||r instanceof ba&&(r.afterRange||r.setAfterRange(e))}}const Wo=I("update-block-data-action");class Dh extends ba{constructor(e,r,i,o,s,l){super(e,r,l);g(this,"beforeBlockData");g(this,"afterBlockData");g(this,"blockId");this.blockId=i,p(Wo,this.blockId===o.id,"invalid block id"),p(Wo,this.blockId===s.id,"invalid block id"),this.beforeBlockData=gt.default(o),this.afterBlockData=gt.default(s),p(Wo,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){if(!e.findBlockById(this.blockId))return Wo.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const r=e.getBlockById(this.blockId);if(!r||!this.checkBlockData(e,this.beforeBlockData))return!1;const i=e.getContainerById(this.containerId);return p(Wo,i,"no container"),vh(e,r,Dh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){if(!e.findBlockById(this.blockId))return Wo.warn(`block (${this.blockId}) not found, deleted by others?`),!1;p(Wo,e,"no editor");const r=e.getBlockById(this.blockId);if(!r||!this.checkBlockData(e,this.beforeBlockData))return!1;const i=e.getContainerById(this.containerId);return p(Wo,i,"no container"),vh(e,r,Dh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const r=gt.default(e);return delete r.id,delete r.type,r}}const tl=I("update-block-text-action");class hu extends ba{constructor(e,r,i,o,s,l){super(e,r,l);g(this,"beforeRichTextData");g(this,"afterRichTextData");g(this,"blockId");g(this,"type");this.blockId=i,this.beforeRichTextData=gt.default(o),this.afterRichTextData=gt.default(s),this.type=hu.calType(o,s)}static calType(e,r){p(tl,e,"no old data"),p(tl,r,"no new data");const o=fn.diff(e,r),s=new Set;let l=!1;const c=h=>$b(h)?`cjk_${h}`:Kb(h)?"number":wd(h)?"space":Vb(h)?"letter":"unknown";let d=!1;return o.forEach(h=>{h.insert?h.insert===" "?s.add("insert_letter"):typeof h.insert=="string"&&h.insert.startsWith(" ")&&h.insert.length>1?(l=!0,d=!0,s.add(`insert_${c(h.insert.substr(1))}`)):s.add(`insert_${c(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(e){if(!this.findContainerById(e,this.containerId))return tl.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return tl.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockId);return i?(bh(e,i,this.beforeRichTextData),!0):!1}redo(e){if(!this.findContainerById(e,this.containerId))return tl.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return tl.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockId);return i?(bh(e,i,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof hu)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const r=e.beforeRange,i=r.anchor;if(!i.isSimple())return!1;const o=this.afterRange;if(!o)return!1;const s=o.anchor;return!(!s.isSimple()||s.blockId!==r.anchor.blockId||s.offset!==i.offset)}combine(e){p(tl,e instanceof hu,"invalid action type");const r=e;this.afterRichTextData=r.afterRichTextData,this.afterRange=e.afterRange}}const n2=I("child-container-action");class r2 extends ba{constructor(t,e,r){super(t,e,t.selection.range.toDocRange()),this.blocks=r}deleteChildContainer(t){return this.findContainerById(t,this.containerId)?(t.doc.localDeleteChildContainers([this.containerId]),!0):(n2.warn(`container (${this.containerId}) not found, deleted by others?`),!1)}insertChildContainer(t){return this.findContainerById(t,this.containerId)?(n2.warn(`container (${this.containerId}) already exists`),!1):(t.doc.localInsertChildContainers([{containerId:this.containerId,blocks:gt.default(this.blocks)}]),!0)}}class _U extends r2{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class MU extends r2{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Nr=I("undo");class UU{constructor(t){g(this,"editor");g(this,"actions",[]);g(this,"undoCursor");g(this,"currentGroup",null);g(this,"groupCounter",0);g(this,"undoRedoing",!1);g(this,"handleSelectionChange",t=>{if(this.currentGroup){this.currentGroup.setAfterRange(t.selection.range.toDocRange());return}const e=this.actions[this.actions.length-1];!e||e.afterRange||e.setAfterRange(t.selection.range.toDocRange())});this.editor=t,this.undoCursor=-1,this.editor.addListener("selectionChanged",this.handleSelectionChange)}reset(){this.actions=[],this.undoCursor=-1}prepareSaveUndoState(){this.undoCursor!==-1&&(this.actions.splice(this.undoCursor),this.undoCursor=-1)}addAction(t){this.currentGroup?this.currentGroup.addAction(t):(t2(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(p(Nr,!this.currentGroup,"current group already exists"),this.currentGroup=new DU(this.editor),this.groupCounter=1):(p(Nr,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){p(Nr,this.currentGroup,"current group not exists"),p(Nr,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Nr.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(t){this.beginGroup();try{const e=t();return setTimeout(()=>this.editor.selection.caret.update()),e}catch(e){throw Nr.error(`failed to run action: ${e.message}`),e}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const t=this.actions[this.undoCursor];if(t.undo(this.editor)){try{this.editor.selection.setRange(Ko(this.editor,t.beforeRange))}catch(e){Nr.error(`undo: failed to restore caret pos: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}redo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor<this.actions.length;){const t=this.actions[this.undoCursor];if(this.undoCursor+=1,t.redo(this.editor)){try{const e=t.afterRange;e?this.editor.selection.setRange(Ko(this.editor,e)):Nr.warn("no after range")}catch(e){Nr.error(`redo: failed to set caret pos after redo: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var e;const t=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(e=this.actions[t])!=null?e:null}undoTo(t){for(;;){const e=this.lastAction();if(!e||e===t)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(t,e,r,i,o){this.undoRedoing||(this.prepareSaveUndoState(),fn.diff(r,i).length!==0&&this.addAction(new hu(this.editor,t,e,r,i,o)))}onBeforeUpdateBlockData(t,e,r,i,o){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Dh(this.editor,t,e,r,i,o);this.addAction(s)}onBeforeInsertBlock(t,e,r,i){this.undoRedoing||(this.prepareSaveUndoState(),p(Nr,e>=0,"invalid block index"),p(Nr,r,"no block data"),this.addAction(new LU(this.editor,t,e,r,i)))}onBeforeDeleteBlock(t,e,r,i){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new IU(this.editor,t,e,r,i)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new _U(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new MU(this.editor,t,e)))}}class OU{async fromData(t,e){const r=e.getData("text/x-ones-editor-doc");if(r)return{"text/x-ones-editor-doc":JSON.parse(r)}}}class NU{constructor(){g(this,"converters",[]);g(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new OU)}prepareData(t){const e=new DataTransfer;for(let r=0;r<this.converterTypes.length;r++)e.setData(this.converterTypes[r],t.getData(this.converterTypes[r]));return e}async fromData(t,e,r){let i={};const o=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,o,r);l&&(i={...i,...l})}return i}addConverter(t){this.converters.push(t)}}function PU(n){n.editorBlocks.registerBlockClass(Mn),n.editorBlocks.registerBlockClass(Qv),n.editorBoxes.registerBoxClass(E5),n.editorBoxes.registerBoxClass(A5),n.editorBoxes.registerBoxClass(v5),n.editorBoxes.registerBoxClass(B5),n.editorInsertions.registerInsertionClass(T5),n.editorBlockRenders.registerRender(new mv)}function FU(n,t){PU(n),t!=null&&t.blocks&&t.blocks.forEach(e=>n.editorBlocks.registerBlockClass(e)),t!=null&&t.boxes&&t.boxes.forEach(e=>n.editorBoxes.registerBoxClass(e)),t!=null&&t.embeds&&t.embeds.forEach(e=>n.editorEmbeds.registerEmbedClass(e)),t!=null&&t.insertions&&t.insertions.forEach(e=>n.editorInsertions.registerInsertionClass(e)),t!=null&&t.decorators&&t.decorators.forEach(e=>n.editorDecorators.registerDecorator(e)),t!=null&&t.dataConverters&&t.dataConverters.forEach(e=>n.dataConverter.addConverter(e)),t!=null&&t.commandProviders&&t.commandProviders.forEach(e=>n.editorCommandProviders.registerCommandProvider(e)),t!=null&&t.textRenders&&t.textRenders.forEach(e=>n.editorBlockRenders.registerRender(e))}const _h=I("range-commands");function i2(n,t){n.forEach(e=>{e.source=t,e.children&&i2(e.children,t)})}function o2(n,t,e){const r=st(t);p(_h,r===e.start.blockId,"invalid start range"),p(_h,r===e.end.blockId,"invalid end range");const i=n.editorCommandProviders.getCommandProviders();let o=[];if(i.forEach(s=>{const l=s.getAvailableCommands(n,t,e);i2(l,s.id),o.push(...l)}),i.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,o);l&&(o=l)}}),_t(n,t)){if(!aa(e.start))return o;p(_h,!e.start.isSimple(),"invalid start pos"),p(_h,!e.end.isSimple(),"invalid end pos");const s=e.start.childContainerId,l=li(n,s),d=Ce(l)[0];if(d){const h=dt(n,d),C=We(n,{anchor:lt(d,0,"home"),focus:lt(d,h,"end")}),E=o2(n,d,C);o.push(...E)}}return o}function s2(n){const t=n.getEditor(),e=n.getSelectedBlocks(),r=[],i=n.isReverse()?e[0]:e[e.length-1],o=We(t,{anchor:i.start,focus:i.end});return o2(t,i.block,o).forEach(l=>{r.push(l)}),r}function l2(n,t,e,r,i,o){var h;const s=n.editorCommandProviders.getCommandProviders();for(let C=0;C<s.length;C++){const E=s[C];if(E.beforeExecuteCommand&&E.beforeExecuteCommand(n,t,e,r,i))return!1}const l=n.editorCommandProviders.getCommandProvider(r.source),c={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,r,i,{}))return o[st(t)]=c,!0;let d=!1;return _t(n,t)&&ca(n,t,e.start,e.end).forEach(E=>{Ce(E).forEach(v=>{const k=dt(n,v),L=We(n,{anchor:lt(v,0,"home"),focus:lt(v,k,"end")});l2(n,v,L,r,i,o)&&(d=!0)})}),s.forEach(C=>{C.afterExecuteCommand&&C.afterExecuteCommand(n,t,e,r,i,o)}),d}function a2(n,t,e){const r=n.getEditor(),i={},o=r.editorCommandProviders.getCommandProvider(t.source);return o.executeRangeCommand&&o.executeRangeCommand(r,n,t,e,i)||(n.getSelectedBlocks().forEach(l=>{const c=We(r,{anchor:l.start,focus:l.end});l2(r,l.block,c,t,e,i)}),r.focus()),i}const KU=I("command-providers");class c2{constructor(t){g(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(r=>r.id===t);return p(KU,e,`no command provider, id=${t}`),e}getCommands(t){return s2(t)}executeCommand(t,e,r){return this.editor.undoManager.runInGroup(()=>a2(t,e,r))}getEmptyBlockTextAttributes(t,e){let r={};if(this.providers.forEach(i=>{var s;const o=(s=i.getEmptyBlockTextAttributes)==null?void 0:s.call(i,t,e);o&&(r={...r,...o})}),Object.keys(r).length!==0)return r}}function VU(n,t){const e=it(t),r=ft(e),i=bt(t);YB(n,r,i)}const $U=I("table-scroll");class u2{constructor(t,e,r,i,o){g(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=r,this.handler=i,this.data=o,e.addEventListener(r,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class HU{constructor(t){g(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(r=>r.destroy()),this.handlers.delete(t)})}addEventListener(t,e,r,i){const o=this.handlers.get(t);if(o){if(o.find(s=>s.handler===r&&s.name===e)){$U.warn(`event has already registered: ${e}`);return}o.push(new u2(this.editor,t,e,r,i))}else{const s=new u2(this.editor,t,e,r,i);this.handlers.set(t,[s])}}removeEventListener(t,e,r){if(!t){for(const[o,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const c=s[l];if(e)e===c.name&&r===c.handler&&s.splice(l,1);else if(r===c.handler){s.splice(l,1),c.destroy(),s.length===0&&this.handlers.delete(o);continue}}return}const i=this.handlers.get(t);if(i){const o=i.findIndex(s=>s.handler===r&&s.name===e);if(o!==-1){const s=i[o];i.splice(o,1),s.destroy(),i.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const r=this.handlers.get(t);if(r)if(e)for(let i=0;i<r.length;i++){const o=r[i];o.name===e&&(r.splice(i,1),o.destroy())}else r.forEach(i=>{i.destroy()}),this.handlers.delete(t)}}const f2=I("update-block-text");function jU(n,t){const e=n.getBoxById(t.id),r=nt(e);p(f2,r,"no parent block"),p(f2,et(n,r),"not a text block");const i=n.getBlockText(r),o=c5(i,"id",t.id,t);W5(n,r,o)}function zU(n,t){for(const e of n.blockHooks)if(e.writable){const r=e.writable(n,t);if(typeof r=="boolean")return r}return!0}function GU(n){if(n.readonly)return!1;const t=ui(n);return!!n.isBlockWritable(t.map(e=>e.block))}class WU{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}getItem(t){return window.localStorage.getItem(this.getKey(t))}setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class qU{constructor(){g(this,"shortcuts",[])}handleKeyboardEvents(t,e){const r=this.shortcuts;for(const i of r){const o=Object.entries(i);for(const[s,l]of o)if(oi(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const no=I("editor");class XU extends ve.TypedEmitter{constructor(e,r,i){var o,s,l,c,d,h,C,E;super();g(this,"parent");g(this,"rootElement");g(this,"contentElement");g(this,"rootContainerObject");g(this,"rootContainer");g(this,"input");g(this,"selection");g(this,"selectionHandler");g(this,"doc");g(this,"id");g(this,"clientId");g(this,"compositingText","");g(this,"undoManager");g(this,"shortcuts",new qU);g(this,"dataConverter",new NU);g(this,"editorBlocks",new Gv(this));g(this,"editorBoxes",new b5(this));g(this,"editorInsertions",new R5(this));g(this,"editorEmbeds",new qv(this));g(this,"editorDecorators",new k5(this));g(this,"editorCommandProviders",new c2(this));g(this,"editorBlockRenders",new X9(this));g(this,"blockHooks",[]);g(this,"domEvents",new HU(this));g(this,"customs",new Map);g(this,"options");g(this,"inputHandlers",new bU(this));g(this,"settingsProvider");g(this,"_readonly",!1);g(this,"getColor",e=>{const r=this.options.colors;return r.length===0?"#FF1A75":r[e%r.length]});no.debug("create editor"),this.setMaxListeners(100),this.options={colors:(o=i==null?void 0:i.colors)!=null?o:["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"],componentsOptions:(l=(s=i==null?void 0:i.components)==null?void 0:s.options)!=null?l:{},scrollContainer:i==null?void 0:i.scrollContainer,enableComments:(c=i==null?void 0:i.enableComments)!=null?c:!0},this.settingsProvider=(d=i==null?void 0:i.settingsProvider)!=null?d:new WU(this),FU(this,i==null?void 0:i.components),this.blockHooks.push(...(C=(h=i==null?void 0:i.components)==null?void 0:h.blockHooks)!=null?C:[]),this.id=(E=i==null?void 0:i.id)!=null?E:Z(),this.clientId=Z(),this.undoManager=new UU(this),this.doc=new SU(this,r,this.undoManager),this.parent=e,this.rootElement=B("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=B("div",["editor-content"],this.rootElement),this.rootContainerObject=Hv(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new lM(this,this.inputHandlers),this.selection=new QM(this),this.selectionHandler=new ZM(this),i!=null&&i.shortcuts&&this.shortcuts.shortcuts.push(...i.shortcuts),he.isMobile&&z(this.rootElement,"mobile"),he.isSafari&&z(this.rootElement,"safari"),this._readonly&&z(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?z(this.rootElement,"readonly"):ot(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:an(this.rootContainer)}addCustom(e,r){const i=this.customs.get(e);if(i)return i;const o=r(this);return this.customs.set(e,o),o}getCustom(e){const r=this.customs.get(e);return p(no,r,`${e} does not exists`),r}replaceCustom(e,r){const i=this.customs.get(e);return i&&i.destroy(),this.customs.set(e,r),r}findCustom(e){return this.customs.get(e)}findCustomByType(e){const r=this.customs.values();for(const i of r)if(i instanceof e)return i;return null}destroyCustom(e){const r=this.customs.get(e);r&&(this.customs.delete(e),r.destroy())}getComponentOptions(e){return this.options.componentsOptions[e]}registerLocalEvents(e){this.doc.registerLocalEvents(e)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(e,r,i){return this.editorBlocks.createBlock(e,r,i)}createBox(e,r){return this.editorBoxes.createBox(e,r)}createInsertion(e,r){return this.editorInsertions.createInsertion(e,r)}destroy(){no.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(e=>e.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus()}focusToBlock(e,r){X1(this,e,r)}isWritable(){return GU(this)}isBlockWritable(e){return zU(this,e)}getChildContainerData(e){const r=this.doc.getContainerBlocks(e);return(!r||!Array.isArray(r))&&(p(no,r,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),p(no,Array.isArray(r),`container data is not an array: ${JSON.stringify(r)}`)),r}createChildContainer(e,r,i){return jv(this,e,r,i)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const e=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return e[e.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(e){const r=this.rootContainer.querySelector(`#${e}`);return r&&p(no,Ps(r),"not an valid block element"),r!=null?r:null}findBoxById(e){const r=this.rootContainer.querySelector(`#${e}`);return r&&p(no,Fd(r),"not an valid box element"),r!=null?r:null}getBlockById(e){const r=this.findBlockById(e);return p(no,r,`no block, id=${e}`),r}getBoxById(e){const r=this.findBoxById(e);return p(no,r,`no box, id=${e}`),r}getBlockByIndex(e,r){const i=this.getContainerById(e);return ji(i,r)}getBlockIndex(e){if(typeof e=="string"){const r=this.getBlockById(e);return bt(r)}return bt(e)}getContainerById(e){return li(this,e)}getParentContainer(e){return it(e)}reloadBlock(e){VU(this,e)}contains(e){const r=e instanceof Element?e:e.parentElement;return r?r.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,r,i,o,s){const l={blockId:i.id,offset:0},c={anchor:l,focus:l};return Ea(this,e,r,i,o!=null?o:c,s)}insertEmbed(e,r,i,o,s){const l={id:Z(),type:"embed",embedType:i,embedData:o};return this.insertBlock(e,r,l,s)}deleteBlock(e,r){G1(this,e,r)}mergeTextBlock(e,r){return j5(this,e,r)}breakTextBlock(e,r,i){return Aa(this,e,r,i).newBlock}getTextPosition(){return pa(this)}getBlockString(e,r){const i=this.getBlockText(e);return ue(i,r)}getBlockData(e){return jo(this,e)}getBoxData(e){return p5(this,e)}getBlockText(e){return bn(this,e)}setBlockText(e,r){W5(this,e,r)}deleteTextFromBlock(e,r,i,o){return j1(this,e,r,i,o)}insertTextToBlock(e,r,i,o){return P5(this,e,r,i,o)}insertBoxToBlock(e,r,i){return F5(this,e,r,i)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,r,i,o){Q5(this,e,r,i,o)}insertDocAt(e,r,i,o){return J1(this,e,r,i,o)}deleteChildContainers(e){H5(this,e)}replaceBlockText(e,r){return bh(this,e,r)}updateBlockData(e,r,i){const o={...this.getBlockData(e),...r},{id:s,type:l,...c}=o;return vh(this,e,c,(i!=null?i:this.selection.range).toDocRange())}updateEmbedData(e,r,i){return q5(this,e,r,i)}updateBoxData(e){jU(this,e)}getSelectedText(){const e=yh(this);return Js(this,e)}clearSelectedContents(){q1(this)}insertTextBlock(e,r,i,o){const s=hi(e!=null?e:"");return $5(this,s,r,i,o==null?void 0:o.newRange,o==null?void 0:o.insertBlockOptions)}updateCompositionText(e,r){if(e&&!r&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!r){H1(this);return}r?(this.compositingText="",Sd()?e||H1(this):$1(this,e)):(this.compositingText=e,K5(this))}}function mu(n,t,e){return new XU(n,t,e)}function QU(n){const t=(r,i)=>{const o=r.findIndex(l=>l.id===i.id);if(o===-1){r.push(i);return}const s=r[o];if(s.value!==i.value){r.splice(o,1);return}if(!!s.states){if(!i.states){s.states=[];return}s.states=pg.default(s.states,i.states)}},e=[];return n.forEach(r=>{r.forEach(i=>{t(e,i)})}),e}const YU=["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"];class gu extends ve.TypedEmitter{constructor(e){super();g(this,"users",new Map);g(this,"cursors",new Map);g(this,"addingUser",!1);g(this,"colors");this.colors=e&&e.length>0?e:YU}setCursor(e){this.addUser(e.user);const r=this.cursors.get(e.user.userId);if(r&&Nc.default(r,e))return;this.cursors.set(e.user.userId,e);const i=new Set([e.range.anchor.blockId,e.range.focus.blockId]),o=new Set(i);r&&new Set([r.range.anchor.blockId,r.range.focus.blockId]).forEach(l=>{i.has(l)||o.add(l)}),this.emit("remote-carets-change",[...o])}addUsers(e){this.addingUser=!0,e.forEach(r=>this.addUser(r)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(e){this.users.set(e.userId,e),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(e){var r;return(r=this.users.get(e))!=null?r:null}removeUser(e){this.users.delete(e),this.emit("change",Array.from(this.users.values()));const r=this.cursors.get(e);if(r){const i=new Set(new Set([r==null?void 0:r.range.anchor.blockId,r==null?void 0:r.range.focus.blockId]));this.cursors.delete(e),this.emit("remote-carets-change",[...i])}}updateUsers(e){this.users.forEach(r=>{e.find(i=>i.userId===r.userId)||this.removeUser(r.userId)}),this.users.clear(),this.addingUser=!0;try{e.forEach(r=>{this.addUser(r)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const r=new Map;return Array.from(this.cursors.values()).filter(i=>i.range.anchor.blockId===e&&ch(i.range)).forEach(i=>{const o=i.range.focus.offset;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}),r}getCursors(e){return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e||r.range.focus.blockId===e)}onUpdateBlockText(e,r,i){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(ch(l.range)){const{anchor:c,focus:d}=l.range;c.blockId===e.id&&(c.offset=fn.transformCursor(c.offset,r,i)),d.blockId===e.id&&(d.offset=fn.transformCursor(d.offset,r,i))}})}getFixedUserColor(e,r){let i=0;Array.from(e).forEach(s=>{i+=s.charCodeAt(0)});const o=i%this.colors.length;return this.colors[o]}destroy(){this.removeAllListeners()}}const en=I("local-doc");class mp extends ra{constructor(e,r){super();g(this,"doc");g(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[hi("")]}},this.serviceUrl=(r==null?void 0:r.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return gt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}findContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,r){const i=this.getContainerBlocks(e);p(en,i,`no container data: ${e}`);const o=i[r];return p(en,o,`no block data: ${r}`),o}localUpdateBlockText(e,r,i){const o=this.getBlockData(e,r);p(en,o.text,"no text for data");const s=fn.apply(o.text,i);return o.text=s,p(en,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,e,r,i,!0)}),s}localUpdateBlockData(e,r,i){const o=this.getBlockData(e,r);return i.delete.forEach(s=>delete o[s]),Object.entries(i.insert).forEach(([s,l])=>{o[s]=l}),p(en,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,r,i,!0)}),o}localInsertBlock(e,r,i){const o=this.getContainerBlocks(e);return p(en,o,`no container data: ${e}`),p(en,r>=0&&r<=o.length,`invalid block index: ${r}, ${o.length}`),o.splice(r,0,i),p(en,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,r,i,!0)}),i}localDeleteBlock(e,r){const i=this.getContainerBlocks(e);p(en,i,`no container data: ${e}`),p(en,r>=0&&r<=i.length,`invalid block index: ${r}, ${i.length}`);const o=i[r];return i.splice(r,1),p(en,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,r,!0)}),o}localInsertChildContainers(e){e.forEach(({containerId:r,blocks:i})=>{this.doc.blocks[r]=i,p(en,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,r,i,!0)})})}localDeleteChildContainers(e){en.debug(`delete child containers: ${e}`),e.forEach(r=>{p(en,this.doc.blocks[r],`no child container: ${r}`),delete this.doc.blocks[r]}),e.forEach(r=>{p(en,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,r,!0)})})}uploadResource(e,r){p(en,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,r){p(en,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new gu}setDoc(e){this.doc=gt.default(e),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,"change doc")})}destroy(){this.clearCallbacks()}}class JU{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function gp(n,t,e){n.addCustom(t,()=>{var o;const r=(o=e())!=null?o:void 0;return new JU(r)})}const d2=I("find-block");function h2(n,t){const e=Vs(t);if(!e){if(fr(t))return null;const r=Fs(t);return p(d2,r,"no parent block"),h2(n,r)}return _t(n,e)?ua(n,e,{visibleOnly:!0}):e}function m2(n,t){const e=$s(t);if(!e){if(fr(t))return null;const r=Fs(t);return p(d2,r,"no parent block"),m2(n,r)}return _t(n,e)?Zg(n,e,{visibleOnly:!0}):e}const ZU=I("remote-cursor");class tO{constructor(){g(this,"remoteUsers",new gu)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const r=e;this.handleUpdateUsers(r.users)}else e.type==="caret"?this.handleUpdateCaret(e):ZU.debug(`unknown remote message received: ${t}`)}handleUpdateUsers(t){this.remoteUsers.updateUsers(t)}handleUpdateCaret(t){const e=this.remoteUsers.findUser(t.userId);!e||this.remoteUsers.setCursor({oneseditor:"cursor",user:e,range:t.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function eO(n){const{blocks:t,meta:e,comments:r,...i}=n;return{rootBlocks:t,meta:e,comments:r,childBlocks:i}}function nO(n){const{blocks:t,meta:e,comments:r}=n,{root:i,...o}=t;return{blocks:i,meta:e,comments:r,...o}}function ro(n){const{childBlocks:t,meta:e,comments:r,rootBlocks:i}=eO(gt.default(n));return{blocks:{root:i,...t},meta:e,comments:r}}function io(n){return n==="root"?"blocks":n}function Ba(n){return n==="blocks"?"root":n}const rO={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new ln.default(n)},apply(n,t){const e=new ln.default(n),r=new ln.default(t);return e.compose(r).ops},compose(n,t){const e=new ln.default(n),r=new ln.default(t);return e.compose(r).ops},diff(n,t){const e=new ln.default(n),r=new ln.default(t);return e.diff(r).ops},transform(n,t,e){const r=new ln.default(n);return new ln.default(t).transform(r,e==="left").ops},transformCursor(n,t,e){return t.transformPosition(n,!e)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,t,e){if(!n)return null;const r=new ln.default(t),i=this.transformCursor(n.index,r,e),o=this.transformCursor(n.index+n.length,r,e);return{...n,index:i,length:o-i}}}};var qo={},pp=db.default.EventEmitter;qo.EventEmitter=pp,qo.mixin=iO;function iO(n){for(var t in pp.prototype)n.prototype[t]=pp.prototype[t]}var g2=["info","warn","error"];function p2(){var n={};g2.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var oO=p2;p2.prototype.setMethods=function(n){n=n||{};var t=this;g2.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var sO=oO,lO=new sO,C2=lO;function el(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,el):this.stack=new Error().stack}el.prototype=Object.create(Error.prototype),el.prototype.constructor=el,el.prototype.name="ShareDBError",el.CODES={ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT:"ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT",ERR_APPLY_SNAPSHOT_NOT_PROVIDED:"ERR_APPLY_SNAPSHOT_NOT_PROVIDED",ERR_CLIENT_ID_BADLY_FORMED:"ERR_CLIENT_ID_BADLY_FORMED",ERR_CANNOT_PING_OFFLINE:"ERR_CANNOT_PING_OFFLINE",ERR_CONNECTION_SEQ_INTEGER_OVERFLOW:"ERR_CONNECTION_SEQ_INTEGER_OVERFLOW",ERR_CONNECTION_STATE_TRANSITION_INVALID:"ERR_CONNECTION_STATE_TRANSITION_INVALID",ERR_DATABASE_ADAPTER_NOT_FOUND:"ERR_DATABASE_ADAPTER_NOT_FOUND",ERR_DATABASE_DOES_NOT_SUPPORT_SUBSCRIBE:"ERR_DATABASE_DOES_NOT_SUPPORT_SUBSCRIBE",ERR_DATABASE_METHOD_NOT_IMPLEMENTED:"ERR_DATABASE_METHOD_NOT_IMPLEMENTED",ERR_DEFAULT_TYPE_MISMATCH:"ERR_DEFAULT_TYPE_MISMATCH",ERR_DOC_MISSING_VERSION:"ERR_DOC_MISSING_VERSION",ERR_DOC_ALREADY_CREATED:"ERR_DOC_ALREADY_CREATED",ERR_DOC_DOES_NOT_EXIST:"ERR_DOC_DOES_NOT_EXIST",ERR_DOC_TYPE_NOT_RECOGNIZED:"ERR_DOC_TYPE_NOT_RECOGNIZED",ERR_DOC_WAS_DELETED:"ERR_DOC_WAS_DELETED",ERR_INFLIGHT_OP_MISSING:"ERR_INFLIGHT_OP_MISSING",ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION:"ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION",ERR_MAX_SUBMIT_RETRIES_EXCEEDED:"ERR_MAX_SUBMIT_RETRIES_EXCEEDED",ERR_MESSAGE_BADLY_FORMED:"ERR_MESSAGE_BADLY_FORMED",ERR_MILESTONE_ARGUMENT_INVALID:"ERR_MILESTONE_ARGUMENT_INVALID",ERR_OP_ALREADY_SUBMITTED:"ERR_OP_ALREADY_SUBMITTED",ERR_OP_NOT_ALLOWED_IN_PROJECTION:"ERR_OP_NOT_ALLOWED_IN_PROJECTION",ERR_OP_SUBMIT_REJECTED:"ERR_OP_SUBMIT_REJECTED",ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM:"ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM",ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM:"ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM",ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT:"ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT",ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED:"ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED",ERR_OT_OP_BADLY_FORMED:"ERR_OT_OP_BADLY_FORMED",ERR_OT_OP_NOT_APPLIED:"ERR_OT_OP_NOT_APPLIED",ERR_OT_OP_NOT_PROVIDED:"ERR_OT_OP_NOT_PROVIDED",ERR_PRESENCE_TRANSFORM_FAILED:"ERR_PRESENCE_TRANSFORM_FAILED",ERR_PROTOCOL_VERSION_NOT_SUPPORTED:"ERR_PROTOCOL_VERSION_NOT_SUPPORTED",ERR_QUERY_EMITTER_LISTENER_NOT_ASSIGNED:"ERR_QUERY_EMITTER_LISTENER_NOT_ASSIGNED",ERR_SNAPSHOT_READ_SILENT_REJECTION:"ERR_SNAPSHOT_READ_SILENT_REJECTION",ERR_SNAPSHOT_READS_REJECTED:"ERR_SNAPSHOT_READS_REJECTED",ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND:"ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND",ERR_TYPE_CANNOT_BE_PROJECTED:"ERR_TYPE_CANNOT_BE_PROJECTED",ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE:"ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE",ERR_UNKNOWN_ERROR:"ERR_UNKNOWN_ERROR"};var Mh=el,pu={},E2=aO;function aO(n,t,e,r){var i=function(s,l,c,d){t(c,s,l,"left"),t(d,l,s,"right")},o=n.transformX=function(s,l){e(s),e(l);for(var c=[],d=0;d<l.length;d++){for(var h=l[d],C=[],E=0;E<s.length;){var x=[];if(i(s[E],h,C,x),E++,x.length===1)h=x[0];else if(x.length===0){for(var v=E;v<s.length;v++)r(C,s[v]);h=null;break}else{for(var k=o(s.slice(E),x),L=0;L<k[0].length;L++)r(C,k[0][L]);for(var M=0;M<k[1].length;M++)r(c,k[1][M]);h=null;break}}h!=null&&r(c,h),s=C}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?t([],s[0],l[0],c):c==="left"?o(s,l)[0]:o(l,s)[1]}}var A2={exports:{}},Xo=A2.exports={name:"text0",uri:"http://sharejs.org/types/textv0",create:function(n){if(n!=null&&typeof n!="string")throw new Error("Initial data must be a string");return n||""}},Cp=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},Ep=function(n){if(typeof n.p!="number")throw new Error("component missing position field");if(typeof n.i=="string"==(typeof n.d=="string"))throw new Error("component needs an i or d field");if(n.p<0)throw new Error("position cannot be negative")},Uh=function(n){for(var t=0;t<n.length;t++)Ep(n[t])};Xo.apply=function(n,t){var e;Uh(t);for(var r=0;r<t.length;r++){var i=t[r];if(i.i!=null)n=Cp(n,i.p,i.i);else{if(e=n.slice(i.p,i.p+i.d.length),i.d!==e)throw new Error("Delete component '"+i.d+"' does not match deleted text '"+e+"'");n=n.slice(0,i.p)+n.slice(i.p+i.d.length)}}return n};var oo=Xo._append=function(n,t){if(!(t.i===""||t.d===""))if(n.length===0)n.push(t);else{var e=n[n.length-1];e.i!=null&&t.i!=null&&e.p<=t.p&&t.p<=e.p+e.i.length?n[n.length-1]={i:Cp(e.i,t.p-e.p,t.i),p:e.p}:e.d!=null&&t.d!=null&&t.p<=e.p&&e.p<=t.p+t.d.length?n[n.length-1]={d:Cp(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};Xo.compose=function(n,t){Uh(n),Uh(t);for(var e=n.slice(),r=0;r<t.length;r++)oo(e,t[r]);return e},Xo.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var r=n[e];r.p==null&&(r.p=0),oo(t,r)}return t};var Ap=function(n,t,e){return t.i!=null?t.p<n||t.p===n&&e?n+t.i.length:n:n<=t.p?n:n<=t.p+t.d.length?t.p:n-t.d.length};Xo.transformCursor=function(n,t,e){for(var r=e==="right",i=0;i<t.length;i++)n=Ap(n,t[i],r);return n};var cO=Xo._tc=function(n,t,e,r){if(Ep(t),Ep(e),t.i!=null)oo(n,{i:t.i,p:Ap(t.p,e,r==="right")});else if(e.i!=null){var i=t.d;t.p<e.p&&(oo(n,{d:i.slice(0,e.p-t.p),p:t.p}),i=i.slice(e.p-t.p)),i!==""&&oo(n,{d:i,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)oo(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)oo(n,t);else{var o={d:"",p:t.p};t.p<e.p&&(o.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(o.d+=t.d.slice(e.p+e.d.length-t.p));var s=Math.max(t.p,e.p),l=Math.min(t.p+t.d.length,e.p+e.d.length),c=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(c!==d)throw new Error("Delete ops delete different text in the same region of the document");o.d!==""&&(o.p=Ap(o.p,e),oo(n,o))}return n},uO=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Xo.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=uO(n[t]);return n},E2(Xo,cO,Uh,oo);var Oh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},fO=function(n){return!!n&&n.constructor===Object},Pr=function(n){return JSON.parse(JSON.stringify(n))},St={name:"json0",uri:"http://sharejs.org/types/JSONv0"},so={};St.registerSubtype=function(n){so[n.name]=n},St.create=function(n){return n===void 0?null:Pr(n)},St.invertComponent=function(n){var t={p:n.p};return n.t&&so[n.t]&&(t.t=n.t,t.o=so[n.t].invert(n.o)),n.si!==void 0&&(t.sd=n.si),n.sd!==void 0&&(t.si=n.sd),n.oi!==void 0&&(t.od=n.oi),n.od!==void 0&&(t.oi=n.od),n.li!==void 0&&(t.ld=n.li),n.ld!==void 0&&(t.li=n.ld),n.na!==void 0&&(t.na=-n.na),n.lm!==void 0&&(t.lm=n.p[n.p.length-1],t.p=n.p.slice(0,n.p.length-1).concat([n.lm])),t},St.invert=function(n){for(var t=n.slice().reverse(),e=[],r=0;r<t.length;r++)e.push(St.invertComponent(t[r]));return e},St.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Oh(n[t].p))throw new Error("Missing path")},St.checkList=function(n){if(!Oh(n))throw new Error("Referenced element not a list")},St.checkObj=function(n){if(!fO(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Cu(n){n.t="text0";var t={p:n.p.pop()};n.si!=null&&(t.i=n.si),n.sd!=null&&(t.d=n.sd),n.o=[t]}function Eu(n){n.p.push(n.o[0].p),n.o[0].i!=null&&(n.si=n.o[0].i),n.o[0].d!=null&&(n.sd=n.o[0].d),delete n.t,delete n.o}St.apply=function(n,t){St.checkValidOp(t),t=Pr(t);for(var e={data:n},r=0;r<t.length;r++){var i=t[r];(i.si!=null||i.sd!=null)&&Cu(i);for(var o=null,s=e,l="data",c=0;c<i.p.length;c++){var d=i.p[c];if(o=s,s=s[l],l=d,o==null)throw new Error("Path invalid")}if(i.t&&i.o!==void 0&&so[i.t])s[l]=so[i.t].apply(s[l],i.o);else if(i.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=i.na}else if(i.li!==void 0&&i.ld!==void 0)St.checkList(s),s[l]=i.li;else if(i.li!==void 0)St.checkList(s),s.splice(l,0,i.li);else if(i.ld!==void 0)St.checkList(s),s.splice(l,1);else if(i.lm!==void 0){if(St.checkList(s),i.lm!=l){var h=s[l];s.splice(l,1),s.splice(i.lm,0,h)}}else if(i.oi!==void 0)St.checkObj(s),s[l]=i.oi;else if(i.od!==void 0)St.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},St.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},St.incrementalApply=function(n,t,e){for(var r=0;r<t.length;r++){var i=[t[r]];n=St.apply(n,i),e(i,n)}return n};var dO=St.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var r=0;r<n.length;r++)if(n[r]!==t[r]&&(!e||r!==n.length-1))return!1;return!0};St.append=function(n,t){if(t=Pr(t),n.length===0){n.push(t);return}var e=n[n.length-1];if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Cu(t),Cu(e)),dO(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&so[t.t]){if(e.o=so[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var r=t.p,i=0;i<e.o.length-1;i++)t.o=[e.o.pop()],t.p=r.slice(),Eu(t),n.push(t);Eu(e)}}else e.na!=null&&t.na!=null?n[n.length-1]={p:e.p,na:e.na+t.na}:e.li!==void 0&&t.li===void 0&&t.ld===e.li?e.ld!==void 0?delete e.li:n.pop():e.od!==void 0&&e.oi===void 0&&t.oi!==void 0&&t.od===void 0?e.oi=t.oi:e.oi!==void 0&&t.od!==void 0?t.oi!==void 0?e.oi=t.oi:e.od!==void 0?delete e.oi:n.pop():t.lm!==void 0&&t.p[t.p.length-1]===t.lm||n.push(t);else(t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Eu(t),Eu(e)),n.push(t)},St.compose=function(n,t){St.checkValidOp(n),St.checkValidOp(t);for(var e=Pr(n),r=0;r<t.length;r++)St.append(e,t[r]);return e},St.normalize=function(n){var t=[];n=Oh(n)?n:[n];for(var e=0;e<n.length;e++){var r=n[e];r.p==null&&(r.p=[]),St.append(t,r)}return t},St.commonLengthForOps=function(n,t){var e=n.p.length,r=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&r++,e===0)return-1;if(r===0)return null;e--,r--;for(var i=0;i<e;i++){var o=n.p[i];if(i>=r||o!==t.p[i])return null}return e},St.canOpAffectPath=function(n,t){return St.commonLengthForOps({p:t},n)!=null},St.transformComponent=function(n,t,e,r){t=Pr(t);var i=St.commonLengthForOps(e,t),o=St.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,o!=null&&l>s&&t.p[o]==e.p[o]){if(t.ld!==void 0){var c=Pr(e);c.p=c.p.slice(s),t.ld=St.apply(Pr(t.ld),[c])}else if(t.od!==void 0){var c=Pr(e);c.p=c.p.slice(s),t.od=St.apply(Pr(t.od),[c])}}if(i!=null){var d=s==l,c=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Cu(t),c=Pr(e),Cu(c)),c.t&&so[c.t]){if(t.t&&t.t===c.t){var h=so[t.t].transform(t.o,c.o,r);if(t.si!=null||t.sd!=null)for(var C=t.p,E=0;E<h.length;E++)t.o=[h[E]],t.p=C.slice(),Eu(t),St.append(n,t);else(!Oh(h)||h.length>0)&&(t.o=h,St.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[i]===t.p[i])if(d){if(t.ld!==void 0)if(t.li!==void 0&&r==="left")t.ld=Pr(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&d&&t.p[i]===e.p[i]?r==="right"&&t.p[i]++:e.p[i]<=t.p[i]&&t.p[i]++,t.lm!==void 0&&d&&e.p[i]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[i]===t.p[i])return n;var C=e.p[i],x=t.p[i],v=t.lm;(C<v||C===v&&x<v)&&t.lm--}if(e.p[i]<t.p[i])t.p[i]--;else if(e.p[i]===t.p[i]){if(l<s)return n;if(t.ld!==void 0)if(t.li!==void 0)delete t.ld;else return n}}else if(e.lm!==void 0)if(t.lm!==void 0&&s===l){var x=t.p[i],v=t.lm,k=e.p[i],L=e.lm;if(k!==L)if(x===k)if(r==="left")t.p[i]=L,x===v&&(t.lm=L);else return n;else x>k&&t.p[i]--,x>L?t.p[i]++:x===L&&k>L&&(t.p[i]++,x===v&&t.lm++),(v>k||v===k&&v>x)&&t.lm--,v>L?t.lm++:v===L&&(L>k&&v>x||L<k&&v<x?r==="right"&&t.lm++:v>x?t.lm++:v===k&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var x=e.p[i],v=e.lm;C=t.p[i],C>x&&t.p[i]--,C>v&&t.p[i]++}else{var x=e.p[i],v=e.lm;C=t.p[i],C===x?t.p[i]=v:(C>x&&t.p[i]--,(C>v||C===v&&x>v)&&t.p[i]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[i]===e.p[i])if(t.oi!==void 0&&d){if(r==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[i]===e.p[i])if(r==="left")St.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[i]==e.p[i]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return St.append(n,t),n},E2(St,St.transformComponent,St.checkValidOp,St.append);var hO=A2.exports;St.registerSubtype(hO);var mO=St,gO={type:mO};(function(n){n.defaultType=gO.type,n.map={},n.register=function(t){t.name&&(n.map[t.name]=t),t.uri&&(n.map[t.uri]=t)},n.register(n.defaultType)})(pu);var Fr={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var r in e)return!0;return!1},n.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},n.isValidVersion=function(e){return e===null?!0:n.isInteger(e)&&e>=0},n.isValidTimestamp=function(e){return n.isValidVersion(e)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var e=arguments[0],r=1;r<arguments.length;r++){var i=arguments[r];e=e[i]||(r===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],r=arguments[arguments.length-1],i=1;i<arguments.length-1;i++){var o=arguments[i];e=e[o]||(e[o]=i===arguments.length-2?r():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],r=[e],i=1;i<arguments.length-1;i++){var o=arguments[i];if(!e.hasOwnProperty(o))break;e=e[o],r.push(e)}for(var i=r.length-1;i>=0;i--){var s=r[i],o=arguments[i+1],l=s[o];(i===r.length-1||!n.hasKeys(l))&&delete s[o]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,r){var i=!1;return e.forEach(function(o){o&&(o(r),i=!0)}),i},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];setTimeout(function(){e.apply(null,r)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})(Fr);var x2=Array.isArray,b2=Object.keys,pO=Object.prototype.hasOwnProperty,CO=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=x2(t),i=x2(e),o,s,l;if(r&&i){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!n(t[o],e[o]))return!1;return!0}if(r!=i)return!1;var c=t instanceof Date,d=e instanceof Date;if(c!=d)return!1;if(c&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,C=e instanceof RegExp;if(h!=C)return!1;if(h&&C)return t.toString()==e.toString();var E=b2(t);if(s=E.length,s!==b2(e).length)return!1;for(o=s;o--!==0;)if(!pO.call(e,E[o]))return!1;for(o=s;o--!==0;)if(l=E[o],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},v2=qo,EO=C2,Yn=Mh,Nh=pu,Kr=Fr,AO=Kr.clone,xO=CO,Un=Yn.CODES,bO=Ft;function Ft(n,t,e){v2.EventEmitter.call(this),this.connection=n,this.collection=t,this.id=e,this.version=null,this.type=null,this.data=void 0,this.inflightFetch=[],this.inflightSubscribe=null,this.pendingFetch=[],this.pendingSubscribe=[],this.subscribed=!1,this.wantSubscribe=!1,this._wantsDestroy=!1,this.inflightOp=null,this.pendingOps=[],this.type=null,this.applyStack=null,this.preventCompose=!1,this.submitSource=!1,this.paused=!1,this._dataStateVersion=0}v2.mixin(Ft),Ft.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this;t.whenNothingPending(function(){t.wantSubscribe?t.unsubscribe(function(e){if(e)return n?n(e):t.emit("error",e);t.connection._destroyDoc(t),n&&n()}):(t.connection._destroyDoc(t),n&&n())})},Ft.prototype._setType=function(n){if(typeof n=="string"&&(n=Nh.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Yn(Un.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},Ft.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Ft.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new Yn(Un.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return t&&this.once("no write pending",t);var e=new Yn(Un.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}return n.v>this.version?this.fetch(t):t&&t()}if(this.version>n.v)return t&&t();this.version=n.v;var r=n.type===void 0?Nh.defaultType:n.type;this._setType(r),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),t&&t()},Ft.prototype.whenNothingPending=function(n){var t=this;Kr.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},Ft.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Ft.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Ft.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Ft.prototype._emitResponseError=function(n,t){if(n&&n.code===Un.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,t&&t(),this._emitNothingPending();return}if(t){t(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},Ft.prototype._handleFetch=function(n,t){var e=this.pendingFetch;this.pendingFetch=[];var r=this.inflightFetch.shift();if(r&&e.push(r),e.length&&(r=function(i){Kr.callEach(e,i)}),n)return this._emitResponseError(n,r);this.ingestSnapshot(t,r),this._emitNothingPending()},Ft.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var r=this.pendingFetch;this.pendingFetch=[],e.callback&&r.push(e.callback);var i;if(r.length&&(i=function(o){Kr.callEach(r,o)}),n)return this._emitResponseError(n,i);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,i):i&&i(),this._emitNothingPending(),this._flushSubscribe()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Un.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&t.src===this.inflightOp.src&&t.seq===this.inflightOp.seq){this._opAcknowledged(t);return}if(this.version==null||t.v>this.version){this.fetch();return}if(!(t.v<this.version)){if(this.inflightOp){var e=Ph(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var r=0;r<this.pendingOps.length;r++){var e=Ph(this.pendingOps[r],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(i){return this._hardRollback(i)}}},Ft.prototype._onConnectionStateChanged=function(){this.connection.canSend?(this.flush(),this._resubscribe()):(this.inflightOp&&(this.pendingOps.unshift(this.inflightOp),this.inflightOp=null),this.subscribed=!1,this.inflightSubscribe&&(this.inflightSubscribe.wantSubscribe?(this.pendingSubscribe.unshift(this.inflightSubscribe),this.inflightSubscribe=null):this._handleSubscribe()),this.inflightFetch.length&&(this.pendingFetch=this.pendingFetch.concat(this.inflightFetch),this.inflightFetch.length=0))},Ft.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(t){return t.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},Ft.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);vO(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},Ft.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},Ft.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},Ft.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,r=e&&e.wantSubscribe===n;if(r){e.callback=BO([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},Ft.prototype._flushSubscribe=function(){if(!(this.inflightSubscribe||!this.pendingSubscribe.length)){if(this.connection.canSend){this.inflightSubscribe=this.pendingSubscribe.shift(),this.wantSubscribe=this.inflightSubscribe.wantSubscribe,this.wantSubscribe?this.connection.sendSubscribe(this):(this.subscribed=!1,this.connection.sendUnsubscribe(this));return}if(!this.pendingSubscribe[0].wantSubscribe){this.inflightSubscribe=this.pendingSubscribe.shift();var n=this;Kr.nextTick(function(){n._handleSubscribe()})}}};function vO(n,t,e){if(t){var r=n.pop();n.push(function(i){r&&r(i),e&&e(i)})}else n.push(e)}function BO(n){return n=n.filter(Kr.truthy),n.length?function(t){Kr.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function TO(n){delete n.op,delete n.create,delete n.del}function Ph(n,t){if(n.del)return TO(t);if(t.del)return new Yn(Un.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Yn(Un.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Yn(Un.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var e=n.type.transformX(n.op,t.op);n.op=e[0],t.op=e[1]}else{var r=n.type.transform(n.op,t.op,"left"),i=n.type.transform(t.op,n.op,"right");n.op=r,t.op=i}}}Ft.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Yn(Un.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,t),!t&&this.type===Nh.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,r=0;r<n.op.length;r++){var i=n.op[r],o={op:[i]};this.emit("before op",o.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Ph(this.applyStack[s],o);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,o.op)),this.emit("op",o.op,t,n.src)}this.emit("op batch",n.op,t),this._popApplyStack(e);return}this.emit("before op",n.op,t,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,t,n.src),this.emit("op batch",n.op,t);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",t);return}if(n.del){var c=this.data;this._setType(null),this.emit("del",c,t);return}},Ft.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var t=this.inflightOp;if(!t){var e=new Yn(Un.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",e)}if(t.sentAt=Date.now(),t.retries=t.retries==null?0:t.retries+1,t.seq==null){if(this.connection.seq>=Kr.MAX_SAFE_INTEGER)return this.emit("error",new Yn(Un.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));t.seq=this.connection.seq++}this.connection.sendOp(this,t),t.src==null&&(t.src=n)}},Ft.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var r=new Yn(Un.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(r):this.emit("error",r)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(o){return this._hardRollback(o)}var i=this;Kr.nextTick(function(){i.flush()})},Ft.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var r=this._tryCompose(n);if(r){r.callbacks.push(e);return}}n.type=this.type,n.callbacks=[e],this.pendingOps.push(n)},Ft.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var t=this.applyStack[0];if(this.applyStack=null,!!t){var e=this.pendingOps.indexOf(t);if(e!==-1)for(var r=this.pendingOps.splice(e),e=0;e<r.length;e++){var t=r[e],i=this._tryCompose(t);i?i.callbacks=i.callbacks.concat(t.callbacks):this.pendingOps.push(t)}}},Ft.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!xO(n.source,t.source))){if(t.create&&"op"in n)return t.create.data=this.type.apply(t.create.data,n.op),t;if("op"in t&&"op"in n&&this.type.compose)return t.op=this.type.compose(t.op,n.op),t}}},Ft.prototype.submitOp=function(n,t,e){typeof t=="function"&&(e=t,t=null);var r={op:n},i=t&&t.source;this._submit(r,i,e)},Ft.prototype.create=function(n,t,e,r){if(typeof t=="function"?(r=t,e=null,t=null):typeof e=="function"&&(r=e,e=null),t||(t=Nh.defaultType.uri),this.type){var i=new Yn(Un.ERR_DOC_ALREADY_CREATED,"Document already exists");return r?r(i):this.emit("error",i)}var o={create:{type:t,data:n}},s=e&&e.source;this._submit(o,s,r)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Yn(Un.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var r={del:!0},i=n&&n.source;this._submit(r,i,t)},Ft.prototype.pause=function(){this.paused=!0},Ft.prototype.resume=function(){this.paused=!1,this.flush()},Ft.prototype.toSnapshot=function(){return{v:this.version,data:AO(this.data),type:this.type.uri}},Ft.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return EO.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},Ft.prototype._rollback=function(n){var t=this.inflightOp;if("op"in t&&t.type.invert){try{t.op=t.type.invert(t.op)}catch{return this._hardRollback(n)}for(var e=0;e<this.pendingOps.length;e++){var r=Ph(this.pendingOps[e],t);if(r)return this._hardRollback(r)}try{this._otApply(t,!1)}catch(i){return this._hardRollback(i)}this._clearInflightOp(n);return}this._hardRollback(n)},Ft.prototype._hardRollback=function(n){var t=[];this.inflightOp&&t.push(this.inflightOp),t=t.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var e=this;this.fetch(function(){for(var r=!!t.length,i=0;i<t.length;i++)r=Kr.callEach(t[i].callbacks,n)&&r;if(n&&!r)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=Kr.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var nl={};nl.ACTIONS={initLegacy:"init",handshake:"hs",queryFetch:"qf",querySubscribe:"qs",queryUnsubscribe:"qu",queryUpdate:"q",bulkFetch:"bf",bulkSubscribe:"bs",bulkUnsubscribe:"bu",fetch:"f",subscribe:"s",unsubscribe:"u",op:"op",snapshotFetch:"nf",snapshotFetchByTimestamp:"nt",pingPong:"pp",presence:"p",presenceSubscribe:"ps",presenceUnsubscribe:"pu",presenceRequest:"pr"};var B2=qo,T2=nl.ACTIONS,yO=Fr,RO=On;function On(n,t,e,r,i,o,s){B2.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=r,this.query=i,this.results=null,o&&o.results&&(this.results=o.results,delete o.results),this.extra=void 0,this.options=o,this.callback=s,this.ready=!1,this.sent=!1}B2.mixin(On),On.prototype.hasPending=function(){return!this.ready},On.prototype.send=function(){if(!!this.connection.canSend){var n={a:this.action,id:this.id,c:this.collection,q:this.query};if(this.options&&(n.o=this.options),this.results){for(var t=[],e=0;e<this.results.length;e++){var r=this.results[e];t.push([r.id,r.version])}n.r=t}this.connection.send(n),this.sent=!0}},On.prototype.destroy=function(n){this.connection.canSend&&this.action===T2.querySubscribe&&this.connection.send({a:T2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&yO.nextTick(n)},On.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},On.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},On.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},On.prototype._handleResponse=function(n,t,e){var r=this.callback;if(this.callback=null,n)return this._finishResponse(n,r);if(!t)return this._finishResponse(null,r);var i=this,o=1,s=function(h){if(h)return i._finishResponse(h,r);--o||i._finishResponse(null,r)};if(Array.isArray(t))o+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){o++;var c=t[l],d=this.connection.get(c.c||this.collection,l);d.ingestSnapshot(c,s)}s()},On.prototype._ingestSnapshots=function(n,t){for(var e=[],r=0;r<n.length;r++){var i=n[r],o=this.connection.get(i.c||this.collection,i.d);o.ingestSnapshot(i,t),e.push(o)}return e},On.prototype._finishResponse=function(n,t){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),t?t(n):this.emit("error",n);t&&t(null,this.results,this.extra)},On.prototype._handleError=function(n){this.emit("error",n)},On.prototype._handleDiff=function(n){for(var t=0;t<n.length;t++){var e=n[t];e.type==="insert"&&(e.values=this._ingestSnapshots(e.values))}for(var t=0;t<n.length;t++){var e=n[t];switch(e.type){case"insert":var r=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(r)),this.emit("insert",r,e.index);break;case"remove":var o=e.howMany||1,i=this.results.splice(e.index,o);this.emit("remove",i,e.index);break;case"move":var o=e.howMany||1,s=this.results.splice(e.from,o);Array.prototype.splice.apply(this.results,[e.to,0].concat(s)),this.emit("move",s,e.from,e.to);break}}this.emit("changed",this.results)},On.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var y2=qo,kO=nl.ACTIONS,wO=Fr,R2=gi;function gi(n,t){if(y2.EventEmitter.call(this),!t||typeof t!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=t,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}y2.mixin(gi),gi.prototype.submit=function(n,t){this.value=n,this.send(t)},gi.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},gi.prototype.destroy=function(n){var t=this;this.submit(null,function(e){if(e)return t._callbackOrEmit(e,n);delete t.presence.localPresences[t.presenceId],n&&n()})},gi.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},gi.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},gi.prototype._message=function(){return{a:kO.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},gi.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},gi.prototype._callbackOrEmit=function(n,t){if(t)return wO.nextTick(t,n);n&&this.emit("error",n)};var SO=Fr,k2=xp;function xp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}xp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},xp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&SO.nextTick(n)};var bp={exports:{}};(function(n,t){(function(e,r){r(t)})(Dn,function(e){function r(y,S){S=S|0;for(var _=Math.max(y.length-S,0),N=Array(_),H=0;H<_;H++)N[H]=y[S+H];return N}var i=function(y){var S=r(arguments,1);return function(){var _=r(arguments);return y.apply(null,S.concat(_))}},o=function(y){return function(){var S=r(arguments),_=S.pop();y.call(this,S,_)}};function s(y){var S=typeof y;return y!=null&&(S=="object"||S=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function d(y){setTimeout(y,0)}function h(y){return function(S){var _=r(arguments,1);y(function(){S.apply(null,_)})}}var C;l?C=setImmediate:c?C=process.nextTick:C=d;var E=h(C);function x(y){return o(function(S,_){var N;try{N=y.apply(this,S)}catch(H){return _(H)}s(N)&&typeof N.then=="function"?N.then(function(H){v(_,null,H)},function(H){v(_,H.message?H:new Error(H))}):_(null,N)})}function v(y,S,_){try{y(S,_)}catch(N){E(k,N)}}function k(y){throw y}var L=typeof Symbol=="function";function M(y){return L&&y[Symbol.toStringTag]==="AsyncFunction"}function U(y){return M(y)?x(y):y}function F(y){return function(S){var _=r(arguments,1),N=o(function(H,$){var X=this;return y(S,function(J,ct){U(J).apply(X,H.concat(ct))},$)});return _.length?N.apply(this,_):N}}var G=typeof Dn=="object"&&Dn&&Dn.Object===Object&&Dn,W=typeof self=="object"&&self&&self.Object===Object&&self,rt=G||W||Function("return this")(),at=rt.Symbol,At=Object.prototype,Mt=At.hasOwnProperty,Bt=At.toString,se=at?at.toStringTag:void 0;function ne(y){var S=Mt.call(y,se),_=y[se];try{y[se]=void 0;var N=!0}catch{}var H=Bt.call(y);return N&&(S?y[se]=_:delete y[se]),H}var Tn=Object.prototype,xe=Tn.toString;function Pn(y){return xe.call(y)}var Si="[object Null]",yn="[object Undefined]",gn=at?at.toStringTag:void 0;function Li(y){return y==null?y===void 0?yn:Si:gn&&gn in Object(y)?ne(y):Pn(y)}var ho="[object AsyncFunction]",Ar="[object Function]",AA="[object GeneratorFunction]",xA="[object Proxy]";function bA(y){if(!s(y))return!1;var S=Li(y);return S==Ar||S==AA||S==ho||S==xA}var ds=9007199254740991;function El(y){return typeof y=="number"&&y>-1&&y%1==0&&y<=ds}function Al(y){return y!=null&&El(y.length)&&!bA(y)}var mo={};function Ht(){}function Ii(y){return function(){if(y!==null){var S=y;y=null,S.apply(this,arguments)}}}var hs=typeof Symbol=="function"&&Symbol.iterator,uc=function(y){return hs&&y[hs]&&y[hs]()};function am(y,S){for(var _=-1,N=Array(y);++_<y;)N[_]=S(_);return N}function pn(y){return y!=null&&typeof y=="object"}var xl="[object Arguments]";function cm(y){return pn(y)&&Li(y)==xl}var xr=Object.prototype,um=xr.hasOwnProperty,vA=xr.propertyIsEnumerable,bl=cm(function(){return arguments}())?cm:function(y){return pn(y)&&um.call(y,"callee")&&!vA.call(y,"callee")},ye=Array.isArray;function vl(){return!1}var Bl=typeof e=="object"&&e&&!e.nodeType&&e,fm=Bl&&!0&&n&&!n.nodeType&&n,Tl=fm&&fm.exports===Bl,dm=Tl?rt.Buffer:void 0,yl=dm?dm.isBuffer:void 0,ms=yl||vl,vf=9007199254740991,Bf=/^(?:0|[1-9]\d*)$/;function Tf(y,S){var _=typeof y;return S=S==null?vf:S,!!S&&(_=="number"||_!="symbol"&&Bf.test(y))&&y>-1&&y%1==0&&y<S}var yf="[object Arguments]",Rf="[object Array]",kf="[object Boolean]",wf="[object Date]",Sf="[object Error]",Lf="[object Function]",BA="[object Map]",TA="[object Number]",yA="[object Object]",hm="[object RegExp]",mm="[object Set]",RA="[object String]",kA="[object WeakMap]",wA="[object ArrayBuffer]",SA="[object DataView]",gm="[object Float32Array]",LA="[object Float64Array]",IA="[object Int8Array]",DA="[object Int16Array]",If="[object Int32Array]",_A="[object Uint8Array]",Df="[object Uint8ClampedArray]",MA="[object Uint16Array]",UA="[object Uint32Array]",fe={};fe[gm]=fe[LA]=fe[IA]=fe[DA]=fe[If]=fe[_A]=fe[Df]=fe[MA]=fe[UA]=!0,fe[yf]=fe[Rf]=fe[wA]=fe[kf]=fe[SA]=fe[wf]=fe[Sf]=fe[Lf]=fe[BA]=fe[TA]=fe[yA]=fe[hm]=fe[mm]=fe[RA]=fe[kA]=!1;function OA(y){return pn(y)&&El(y.length)&&!!fe[Li(y)]}function NA(y){return function(S){return y(S)}}var pm=typeof e=="object"&&e&&!e.nodeType&&e,Rl=pm&&!0&&n&&!n.nodeType&&n,PA=Rl&&Rl.exports===pm,fc=PA&&G.process,Cm=function(){try{var y=Rl&&Rl.require&&Rl.require("util").types;return y||fc&&fc.binding&&fc.binding("util")}catch{}}(),Em=Cm&&Cm.isTypedArray,FA=Em?NA(Em):OA,KA=Object.prototype,VA=KA.hasOwnProperty;function $A(y,S){var _=ye(y),N=!_&&bl(y),H=!_&&!N&&ms(y),$=!_&&!N&&!H&&FA(y),X=_||N||H||$,J=X?am(y.length,String):[],ct=J.length;for(var Ct in y)(S||VA.call(y,Ct))&&!(X&&(Ct=="length"||H&&(Ct=="offset"||Ct=="parent")||$&&(Ct=="buffer"||Ct=="byteLength"||Ct=="byteOffset")||Tf(Ct,ct)))&&J.push(Ct);return J}var dc=Object.prototype;function HA(y){var S=y&&y.constructor,_=typeof S=="function"&&S.prototype||dc;return y===_}function hc(y,S){return function(_){return y(S(_))}}var jA=hc(Object.keys,Object),zA=Object.prototype,GA=zA.hasOwnProperty;function Am(y){if(!HA(y))return jA(y);var S=[];for(var _ in Object(y))GA.call(y,_)&&_!="constructor"&&S.push(_);return S}function mc(y){return Al(y)?$A(y):Am(y)}function xm(y){var S=-1,_=y.length;return function(){return++S<_?{value:y[S],key:S}:null}}function WA(y){var S=-1;return function(){var N=y.next();return N.done?null:(S++,{value:N.value,key:S})}}function qA(y){var S=mc(y),_=-1,N=S.length;return function H(){var $=S[++_];return $==="__proto__"?H():_<N?{value:y[$],key:$}:null}}function XA(y){if(Al(y))return xm(y);var S=uc(y);return S?WA(S):qA(y)}function br(y){return function(){if(y===null)throw new Error("Callback was already called.");var S=y;y=null,S.apply(this,arguments)}}function kl(y){return function(S,_,N){if(N=Ii(N||Ht),y<=0||!S)return N(null);var H=XA(S),$=!1,X=0,J=!1;function ct(ut,xt){if(X-=1,ut)$=!0,N(ut);else{if(xt===mo||$&&X<=0)return $=!0,N(null);J||Ct()}}function Ct(){for(J=!0;X<y&&!$;){var ut=H();if(ut===null){$=!0,X<=0&&N(null);return}X+=1,_(ut.value,ut.key,br(ct))}J=!1}Ct()}}function Di(y,S,_,N){kl(S)(y,U(_),N)}function ze(y,S){return function(_,N,H){return y(_,S,N,H)}}function _f(y,S,_){_=Ii(_||Ht);var N=0,H=0,$=y.length;$===0&&_(null);function X(J,ct){J?_(J):(++H===$||ct===mo)&&_(null)}for(;N<$;N++)S(y[N],N,br(X))}var QA=ze(Di,1/0),Xr=function(y,S,_){var N=Al(y)?_f:QA;N(y,U(S),_)};function Qr(y){return function(S,_,N){return y(Xr,S,U(_),N)}}function Mf(y,S,_,N){N=N||Ht,S=S||[];var H=[],$=0,X=U(_);y(S,function(J,ct,Ct){var ut=$++;X(J,function(xt,Yt){H[ut]=Yt,Ct(xt)})},function(J){N(J,H)})}var gc=Qr(Mf),Uf=F(gc);function go(y){return function(S,_,N,H){return y(kl(_),S,U(N),H)}}var _i=go(Mf),Of=ze(_i,1),Nf=F(Of);function gs(y,S){for(var _=-1,N=y==null?0:y.length;++_<N&&S(y[_],_,y)!==!1;);return y}function Pf(y){return function(S,_,N){for(var H=-1,$=Object(S),X=N(S),J=X.length;J--;){var ct=X[y?J:++H];if(_($[ct],ct,$)===!1)break}return S}}var ps=Pf();function Cs(y,S){return y&&ps(y,S,mc)}function bm(y,S,_,N){for(var H=y.length,$=_+(N?1:-1);N?$--:++$<H;)if(S(y[$],$,y))return $;return-1}function YA(y){return y!==y}function vm(y,S,_){for(var N=_-1,H=y.length;++N<H;)if(y[N]===S)return N;return-1}function wl(y,S,_){return S===S?vm(y,S,_):bm(y,YA,_)}var pc=function(y,S,_){typeof S=="function"&&(_=S,S=null),_=Ii(_||Ht);var N=mc(y),H=N.length;if(!H)return _(null);S||(S=H);var $={},X=0,J=!1,ct=Object.create(null),Ct=[],ut=[],xt={};Cs(y,function(pe,ae){if(!ye(pe)){Yt(ae,[pe]),ut.push(ae);return}var be=pe.slice(0,pe.length-1),Br=be.length;if(Br===0){Yt(ae,pe),ut.push(ae);return}xt[ae]=Br,gs(be,function(R){if(!y[R])throw new Error("async.auto task `"+ae+"` has a non-existent dependency `"+R+"` in "+be.join(", "));on(R,function(){Br--,Br===0&&Yt(ae,pe)})})}),Ax(),Ne();function Yt(pe,ae){Ct.push(function(){vr(pe,ae)})}function Ne(){if(Ct.length===0&&X===0)return _(null,$);for(;Ct.length&&X<S;){var pe=Ct.shift();pe()}}function on(pe,ae){var be=ct[pe];be||(be=ct[pe]=[]),be.push(ae)}function Vn(pe){var ae=ct[pe]||[];gs(ae,function(be){be()}),Ne()}function vr(pe,ae){if(!J){var be=br(function(R,Oi){if(X--,arguments.length>2&&(Oi=r(arguments,1)),R){var bs={};Cs($,function($n,Vt){bs[Vt]=$n}),bs[pe]=Oi,J=!0,ct=Object.create(null),_(R,bs)}else $[pe]=Oi,Vn(pe)});X++;var Br=U(ae[ae.length-1]);ae.length>1?Br($,be):Br(be)}}function Ax(){for(var pe,ae=0;ut.length;)pe=ut.pop(),ae++,gs(xx(pe),function(be){--xt[be]===0&&ut.push(be)});if(ae!==H)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function xx(pe){var ae=[];return Cs(y,function(be,Br){ye(be)&&wl(be,pe,0)>=0&&ae.push(Br)}),ae}};function po(y,S){for(var _=-1,N=y==null?0:y.length,H=Array(N);++_<N;)H[_]=S(y[_],_,y);return H}var JA="[object Symbol]";function ZA(y){return typeof y=="symbol"||pn(y)&&Li(y)==JA}var tx=1/0,Ff=at?at.prototype:void 0,Bm=Ff?Ff.toString:void 0;function Kf(y){if(typeof y=="string")return y;if(ye(y))return po(y,Kf)+"";if(ZA(y))return Bm?Bm.call(y):"";var S=y+"";return S=="0"&&1/y==-tx?"-0":S}function ex(y,S,_){var N=-1,H=y.length;S<0&&(S=-S>H?0:H+S),_=_>H?H:_,_<0&&(_+=H),H=S>_?0:_-S>>>0,S>>>=0;for(var $=Array(H);++N<H;)$[N]=y[N+S];return $}function nx(y,S,_){var N=y.length;return _=_===void 0?N:_,!S&&_>=N?y:ex(y,S,_)}function Vf(y,S){for(var _=y.length;_--&&wl(S,y[_],0)>-1;);return _}function rx(y,S){for(var _=-1,N=y.length;++_<N&&wl(S,y[_],0)>-1;);return _}function ix(y){return y.split("")}var ox="\\ud800-\\udfff",sx="\\u0300-\\u036f",lx="\\ufe20-\\ufe2f",de="\\u20d0-\\u20ff",le=sx+lx+de,ax="\\ufe0e\\ufe0f",cx="\\u200d",ux=RegExp("["+cx+ox+le+ax+"]");function fx(y){return ux.test(y)}var Tm="\\ud800-\\udfff",dx="\\u0300-\\u036f",ym="\\ufe20-\\ufe2f",hx="\\u20d0-\\u20ff",Ye=dx+ym+hx,$f="\\ufe0e\\ufe0f",Co="["+Tm+"]",Cc="["+Ye+"]",Sl="\\ud83c[\\udffb-\\udfff]",Fn="(?:"+Cc+"|"+Sl+")",Hf="[^"+Tm+"]",jf="(?:\\ud83c[\\udde6-\\uddff]){2}",zf="[\\ud800-\\udbff][\\udc00-\\udfff]",Rm="\\u200d",Gf=Fn+"?",Wf="["+$f+"]?",Rn="(?:"+Rm+"(?:"+[Hf,jf,zf].join("|")+")"+Wf+Gf+")*",mx=Wf+Gf+Rn,Kn="(?:"+[Hf+Cc+"?",Cc,jf,zf,Co].join("|")+")",gx=RegExp(Sl+"(?="+Sl+")|"+Kn+mx,"g");function km(y){return y.match(gx)||[]}function Yr(y){return fx(y)?km(y):ix(y)}function Ec(y){return y==null?"":Kf(y)}var qf=/^\s+|\s+$/g;function ge(y,S,_){if(y=Ec(y),y&&(_||S===void 0))return y.replace(qf,"");if(!y||!(S=Kf(S)))return y;var N=Yr(y),H=Yr(S),$=rx(N,H),X=Vf(N,H)+1;return nx(N,$,X).join("")}var Mi=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,Xf=/,/,px=/(=.+)?(\s*)$/,Qf=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function Cx(y){return y=y.toString().replace(Qf,""),y=y.match(Mi)[2].replace(" ",""),y=y?y.split(Xf):[],y=y.map(function(S){return ge(S.replace(px,""))}),y}function wm(y,S){var _={};Cs(y,function(N,H){var $,X=M(N),J=!X&&N.length===1||X&&N.length===0;if(ye(N))$=N.slice(0,-1),N=N[N.length-1],_[H]=$.concat($.length>0?ct:N);else if(J)_[H]=N;else{if($=Cx(N),N.length===0&&!X&&$.length===0)throw new Error("autoInject task functions require explicit parameters.");X||$.pop(),_[H]=$.concat(ct)}function ct(Ct,ut){var xt=po($,function(Yt){return Ct[Yt]});xt.push(ut),U(N).apply(null,xt)}}),pc(_,S)}function nr(){this.head=this.tail=null,this.length=0}function Yf(y,S){y.length=1,y.head=y.tail=S}nr.prototype.removeLink=function(y){return y.prev?y.prev.next=y.next:this.head=y.next,y.next?y.next.prev=y.prev:this.tail=y.prev,y.prev=y.next=null,this.length-=1,y},nr.prototype.empty=function(){for(;this.head;)this.shift();return this},nr.prototype.insertAfter=function(y,S){S.prev=y,S.next=y.next,y.next?y.next.prev=S:this.tail=S,y.next=S,this.length+=1},nr.prototype.insertBefore=function(y,S){S.prev=y.prev,S.next=y,y.prev?y.prev.next=S:this.head=S,y.prev=S,this.length+=1},nr.prototype.unshift=function(y){this.head?this.insertBefore(this.head,y):Yf(this,y)},nr.prototype.push=function(y){this.tail?this.insertAfter(this.tail,y):Yf(this,y)},nr.prototype.shift=function(){return this.head&&this.removeLink(this.head)},nr.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},nr.prototype.toArray=function(){for(var y=Array(this.length),S=this.head,_=0;_<this.length;_++)y[_]=S.data,S=S.next;return y},nr.prototype.remove=function(y){for(var S=this.head;S;){var _=S.next;y(S)&&this.removeLink(S),S=_}return this};function Ll(y,S,_){if(S==null)S=1;else if(S===0)throw new Error("Concurrency must not be zero");var N=U(y),H=0,$=[],X=!1;function J(xt,Yt,Ne){if(Ne!=null&&typeof Ne!="function")throw new Error("task callback must be a function");if(ut.started=!0,ye(xt)||(xt=[xt]),xt.length===0&&ut.idle())return E(function(){ut.drain()});for(var on=0,Vn=xt.length;on<Vn;on++){var vr={data:xt[on],callback:Ne||Ht};Yt?ut._tasks.unshift(vr):ut._tasks.push(vr)}X||(X=!0,E(function(){X=!1,ut.process()}))}function ct(xt){return function(Yt){H-=1;for(var Ne=0,on=xt.length;Ne<on;Ne++){var Vn=xt[Ne],vr=wl($,Vn,0);vr===0?$.shift():vr>0&&$.splice(vr,1),Vn.callback.apply(Vn,arguments),Yt!=null&&ut.error(Yt,Vn.data)}H<=ut.concurrency-ut.buffer&&ut.unsaturated(),ut.idle()&&ut.drain(),ut.process()}}var Ct=!1,ut={_tasks:new nr,concurrency:S,payload:_,saturated:Ht,unsaturated:Ht,buffer:S/4,empty:Ht,drain:Ht,error:Ht,started:!1,paused:!1,push:function(xt,Yt){J(xt,!1,Yt)},kill:function(){ut.drain=Ht,ut._tasks.empty()},unshift:function(xt,Yt){J(xt,!0,Yt)},remove:function(xt){ut._tasks.remove(xt)},process:function(){if(!Ct){for(Ct=!0;!ut.paused&&H<ut.concurrency&&ut._tasks.length;){var xt=[],Yt=[],Ne=ut._tasks.length;ut.payload&&(Ne=Math.min(Ne,ut.payload));for(var on=0;on<Ne;on++){var Vn=ut._tasks.shift();xt.push(Vn),$.push(Vn),Yt.push(Vn.data)}H+=1,ut._tasks.length===0&&ut.empty(),H===ut.concurrency&&ut.saturated();var vr=br(ct(xt));N(Yt,vr)}Ct=!1}},length:function(){return ut._tasks.length},running:function(){return H},workersList:function(){return $},idle:function(){return ut._tasks.length+H===0},pause:function(){ut.paused=!0},resume:function(){ut.paused!==!1&&(ut.paused=!1,E(ut.process))}};return ut}function Eo(y,S){return Ll(y,1,S)}var Es=ze(Di,1);function Jr(y,S,_,N){N=Ii(N||Ht);var H=U(_);Es(y,function($,X,J){H(S,$,function(ct,Ct){S=Ct,J(ct)})},function($){N($,S)})}function Ac(){var y=po(arguments,U);return function(){var S=r(arguments),_=this,N=S[S.length-1];typeof N=="function"?S.pop():N=Ht,Jr(y,S,function(H,$,X){$.apply(_,H.concat(function(J){var ct=r(arguments,1);X(J,ct)}))},function(H,$){N.apply(_,[H].concat($))})}}var xc=function(){return Ac.apply(null,r(arguments).reverse())},Jf=Array.prototype.concat,Il=function(y,S,_,N){N=N||Ht;var H=U(_);_i(y,S,function($,X){H($,function(J){return J?X(J):X(null,r(arguments,1))})},function($,X){for(var J=[],ct=0;ct<X.length;ct++)X[ct]&&(J=Jf.apply(J,X[ct]));return N($,J)})},Sm=ze(Il,1/0),bc=ze(Il,1),vc=function(){var y=r(arguments),S=[null].concat(y);return function(){var _=arguments[arguments.length-1];return _.apply(this,S)}};function Dl(y){return y}function Ao(y,S){return function(_,N,H,$){$=$||Ht;var X=!1,J;_(N,function(ct,Ct,ut){H(ct,function(xt,Yt){xt?ut(xt):y(Yt)&&!J?(X=!0,J=S(!0,ct),ut(null,mo)):ut()})},function(ct){ct?$(ct):$(null,X?J:S(!1))})}}function Cn(y,S){return S}var As=Qr(Ao(Dl,Cn)),Zr=go(Ao(Dl,Cn)),_l=ze(Zr,1);function Zf(y){return function(S){var _=r(arguments,1);_.push(function(N){var H=r(arguments,1);typeof console=="object"&&(N?console.error&&console.error(N):console[y]&&gs(H,function($){console[y]($)}))}),U(S).apply(null,_)}}var Lm=Zf("dir");function Im(y,S,_){_=br(_||Ht);var N=U(y),H=U(S);function $(J){if(J)return _(J);var ct=r(arguments,1);ct.push(X),H.apply(this,ct)}function X(J,ct){if(J)return _(J);if(!ct)return _(null);N($)}X(null,!0)}function td(y,S,_){_=br(_||Ht);var N=U(y),H=function($){if($)return _($);var X=r(arguments,1);if(S.apply(this,X))return N(H);_.apply(null,[null].concat(X))};N(H)}function Dm(y,S,_){td(y,function(){return!S.apply(this,arguments)},_)}function _m(y,S,_){_=br(_||Ht);var N=U(S),H=U(y);function $(J){if(J)return _(J);H(X)}function X(J,ct){if(J)return _(J);if(!ct)return _(null);N($)}H(X)}function xo(y){return function(S,_,N){return y(S,N)}}function Bc(y,S,_){Xr(y,xo(U(S)),_)}function Ml(y,S,_,N){kl(S)(y,xo(U(_)),N)}var bo=ze(Ml,1);function Tc(y){return M(y)?y:o(function(S,_){var N=!0;S.push(function(){var H=arguments;N?E(function(){_.apply(null,H)}):_.apply(null,H)}),y.apply(this,S),N=!1})}function rr(y){return!y}var vo=Qr(Ao(rr,rr)),Ul=go(Ao(rr,rr)),yc=ze(Ul,1);function Mm(y){return function(S){return S==null?void 0:S[y]}}function xs(y,S,_,N){var H=new Array(S.length);y(S,function($,X,J){_($,function(ct,Ct){H[X]=!!Ct,J(ct)})},function($){if($)return N($);for(var X=[],J=0;J<S.length;J++)H[J]&&X.push(S[J]);N(null,X)})}function ir(y,S,_,N){var H=[];y(S,function($,X,J){_($,function(ct,Ct){ct?J(ct):(Ct&&H.push({index:X,value:$}),J())})},function($){$?N($):N(null,po(H.sort(function(X,J){return X.index-J.index}),Mm("value")))})}function Rc(y,S,_,N){var H=Al(S)?xs:ir;H(y,S,U(_),N||Ht)}var kc=Qr(Rc),Ol=go(Rc),wc=ze(Ol,1);function Um(y,S){var _=br(S||Ht),N=U(Tc(y));function H($){if($)return _($);N(H)}H()}var Sc=function(y,S,_,N){N=N||Ht;var H=U(_);_i(y,S,function($,X){H($,function(J,ct){return J?X(J):X(null,{key:ct,val:$})})},function($,X){for(var J={},ct=Object.prototype.hasOwnProperty,Ct=0;Ct<X.length;Ct++)if(X[Ct]){var ut=X[Ct].key,xt=X[Ct].val;ct.call(J,ut)?J[ut].push(xt):J[ut]=[xt]}return N($,J)})},Bo=ze(Sc,1/0),K=ze(Sc,1),q=Zf("log");function j(y,S,_,N){N=Ii(N||Ht);var H={},$=U(_);Di(y,S,function(X,J,ct){$(X,J,function(Ct,ut){if(Ct)return ct(Ct);H[J]=ut,ct()})},function(X){N(X,H)})}var mt=ze(j,1/0),wt=ze(j,1);function Wt(y,S){return S in y}function Le(y,S){var _=Object.create(null),N=Object.create(null);S=S||Dl;var H=U(y),$=o(function(J,ct){var Ct=S.apply(null,J);Wt(_,Ct)?E(function(){ct.apply(null,_[Ct])}):Wt(N,Ct)?N[Ct].push(ct):(N[Ct]=[ct],H.apply(null,J.concat(function(){var ut=r(arguments);_[Ct]=ut;var xt=N[Ct];delete N[Ct];for(var Yt=0,Ne=xt.length;Yt<Ne;Yt++)xt[Yt].apply(null,ut)})))});return $.memo=_,$.unmemoized=y,$}var Xt;c?Xt=process.nextTick:l?Xt=setImmediate:Xt=d;var Lc=h(Xt);function ed(y,S,_){_=_||Ht;var N=Al(S)?[]:{};y(S,function(H,$,X){U(H)(function(J,ct){arguments.length>2&&(ct=r(arguments,1)),N[$]=ct,X(J)})},function(H){_(H,N)})}function kn(y,S){ed(Xr,y,S)}function Nl(y,S,_){ed(kl(S),y,_)}var nd=function(y,S){var _=U(y);return Ll(function(N,H){_(N[0],H)},S,1)},To=function(y,S){var _=nd(y,S);return _.push=function(N,H,$){if($==null&&($=Ht),typeof $!="function")throw new Error("task callback must be a function");if(_.started=!0,ye(N)||(N=[N]),N.length===0)return E(function(){_.drain()});H=H||0;for(var X=_._tasks.head;X&&H>=X.priority;)X=X.next;for(var J=0,ct=N.length;J<ct;J++){var Ct={data:N[J],priority:H,callback:$};X?_._tasks.insertBefore(X,Ct):_._tasks.push(Ct)}E(_.process)},delete _.unshift,_};function Pl(y,S){if(S=Ii(S||Ht),!ye(y))return S(new TypeError("First argument to race must be an array of functions"));if(!y.length)return S();for(var _=0,N=y.length;_<N;_++)U(y[_])(S)}function yo(y,S,_,N){var H=r(y).reverse();Jr(H,S,_,N)}function qt(y){var S=U(y);return o(function(N,H){return N.push(function(X,J){if(X)H(null,{error:X});else{var ct;arguments.length<=2?ct=J:ct=r(arguments,1),H(null,{value:ct})}}),S.apply(this,N)})}function Om(y){var S;return ye(y)?S=po(y,qt):(S={},Cs(y,function(_,N){S[N]=qt.call(this,_)})),S}function rd(y,S,_,N){Rc(y,S,function(H,$){_(H,function(X,J){$(X,!J)})},N)}var Fl=Qr(rd),id=go(rd),Nm=ze(id,1);function Pm(y){return function(){return y}}function Ro(y,S,_){var N=5,H=0,$={times:N,intervalFunc:Pm(H)};function X(ut,xt){if(typeof xt=="object")ut.times=+xt.times||N,ut.intervalFunc=typeof xt.interval=="function"?xt.interval:Pm(+xt.interval||H),ut.errorFilter=xt.errorFilter;else if(typeof xt=="number"||typeof xt=="string")ut.times=+xt||N;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof y=="function"?(_=S||Ht,S=y):(X($,y),_=_||Ht),typeof S!="function")throw new Error("Invalid arguments for async.retry");var J=U(S),ct=1;function Ct(){J(function(ut){ut&&ct++<$.times&&(typeof $.errorFilter!="function"||$.errorFilter(ut))?setTimeout(Ct,$.intervalFunc(ct)):_.apply(null,arguments)})}Ct()}var ti=function(y,S){S||(S=y,y=null);var _=U(S);return o(function(N,H){function $(X){_.apply(null,N.concat(X))}y?Ro(y,$,H):Ro($,H)})};function Kl(y,S){ed(Es,y,S)}var Vl=Qr(Ao(Boolean,Dl)),Ui=go(Ao(Boolean,Dl)),$l=ze(Ui,1);function od(y,S,_){var N=U(S);gc(y,function($,X){N($,function(J,ct){if(J)return X(J);X(null,{value:$,criteria:ct})})},function($,X){if($)return _($);_(null,po(X.sort(H),Mm("value")))});function H($,X){var J=$.criteria,ct=X.criteria;return J<ct?-1:J>ct?1:0}}function Hl(y,S,_){var N=U(y);return o(function(H,$){var X=!1,J;function ct(){var Ct=y.name||"anonymous",ut=new Error('Callback function "'+Ct+'" timed out.');ut.code="ETIMEDOUT",_&&(ut.info=_),X=!0,$(ut)}H.push(function(){X||($.apply(null,arguments),clearTimeout(J))}),J=setTimeout(ct,S),N.apply(null,H)})}var Fm=Math.ceil,jl=Math.max;function ko(y,S,_,N){for(var H=-1,$=jl(Fm((S-y)/(_||1)),0),X=Array($);$--;)X[N?$:++H]=y,y+=_;return X}function wo(y,S,_,N){var H=U(_);_i(ko(0,y,1),S,H,N)}var Km=ze(wo,1/0),Vm=ze(wo,1);function $m(y,S,_,N){arguments.length<=3&&(N=_,_=S,S=ye(y)?[]:{}),N=Ii(N||Ht);var H=U(_);Xr(y,function($,X,J){H(S,$,X,J)},function($){N($,S)})}function zl(y,S){var _=null,N;S=S||Ht,bo(y,function(H,$){U(H)(function(X,J){arguments.length>2?N=r(arguments,1):N=J,_=X,$(!X)})},function(){S(_,N)})}function Gl(y){return function(){return(y.unmemoized||y).apply(null,arguments)}}function Wl(y,S,_){_=br(_||Ht);var N=U(S);if(!y())return _(null);var H=function($){if($)return _($);if(y())return N(H);var X=r(arguments,1);_.apply(null,[null].concat(X))};N(H)}function Hm(y,S,_){Wl(function(){return!y.apply(this,arguments)},S,_)}var sd=function(y,S){if(S=Ii(S||Ht),!ye(y))return S(new Error("First argument to waterfall must be an array of functions"));if(!y.length)return S();var _=0;function N($){var X=U(y[_++]);$.push(br(H)),X.apply(null,$)}function H($){if($||_===y.length)return S.apply(null,arguments);N(r(arguments,1))}N([])},Ex={apply:i,applyEach:Uf,applyEachSeries:Nf,asyncify:x,auto:pc,autoInject:wm,cargo:Eo,compose:xc,concat:Sm,concatLimit:Il,concatSeries:bc,constant:vc,detect:As,detectLimit:Zr,detectSeries:_l,dir:Lm,doDuring:Im,doUntil:Dm,doWhilst:td,during:_m,each:Bc,eachLimit:Ml,eachOf:Xr,eachOfLimit:Di,eachOfSeries:Es,eachSeries:bo,ensureAsync:Tc,every:vo,everyLimit:Ul,everySeries:yc,filter:kc,filterLimit:Ol,filterSeries:wc,forever:Um,groupBy:Bo,groupByLimit:Sc,groupBySeries:K,log:q,map:gc,mapLimit:_i,mapSeries:Of,mapValues:mt,mapValuesLimit:j,mapValuesSeries:wt,memoize:Le,nextTick:Lc,parallel:kn,parallelLimit:Nl,priorityQueue:To,queue:nd,race:Pl,reduce:Jr,reduceRight:yo,reflect:qt,reflectAll:Om,reject:Fl,rejectLimit:id,rejectSeries:Nm,retry:Ro,retryable:ti,seq:Ac,series:Kl,setImmediate:E,some:Vl,someLimit:Ui,someSeries:$l,sortBy:od,timeout:Hl,times:Km,timesLimit:wo,timesSeries:Vm,transform:$m,tryEach:zl,unmemoize:Gl,until:Hm,waterfall:sd,whilst:Wl,all:vo,allLimit:Ul,allSeries:yc,any:Vl,anyLimit:Ui,anySeries:$l,find:As,findLimit:Zr,findSeries:_l,forEach:Bc,forEachSeries:bo,forEachLimit:Ml,forEachOf:Xr,forEachOfSeries:Es,forEachOfLimit:Di,inject:Jr,foldl:Jr,foldr:yo,select:kc,selectLimit:Ol,selectSeries:wc,wrapSync:x};e.default=Ex,e.apply=i,e.applyEach=Uf,e.applyEachSeries=Nf,e.asyncify=x,e.auto=pc,e.autoInject=wm,e.cargo=Eo,e.compose=xc,e.concat=Sm,e.concatLimit=Il,e.concatSeries=bc,e.constant=vc,e.detect=As,e.detectLimit=Zr,e.detectSeries=_l,e.dir=Lm,e.doDuring=Im,e.doUntil=Dm,e.doWhilst=td,e.during=_m,e.each=Bc,e.eachLimit=Ml,e.eachOf=Xr,e.eachOfLimit=Di,e.eachOfSeries=Es,e.eachSeries=bo,e.ensureAsync=Tc,e.every=vo,e.everyLimit=Ul,e.everySeries=yc,e.filter=kc,e.filterLimit=Ol,e.filterSeries=wc,e.forever=Um,e.groupBy=Bo,e.groupByLimit=Sc,e.groupBySeries=K,e.log=q,e.map=gc,e.mapLimit=_i,e.mapSeries=Of,e.mapValues=mt,e.mapValuesLimit=j,e.mapValuesSeries=wt,e.memoize=Le,e.nextTick=Lc,e.parallel=kn,e.parallelLimit=Nl,e.priorityQueue=To,e.queue=nd,e.race=Pl,e.reduce=Jr,e.reduceRight=yo,e.reflect=qt,e.reflectAll=Om,e.reject=Fl,e.rejectLimit=id,e.rejectSeries=Nm,e.retry=Ro,e.retryable=ti,e.seq=Ac,e.series=Kl,e.setImmediate=E,e.some=Vl,e.someLimit=Ui,e.someSeries=$l,e.sortBy=od,e.timeout=Hl,e.times=Km,e.timesLimit=wo,e.timesSeries=Vm,e.transform=$m,e.tryEach=zl,e.unmemoize=Gl,e.until=Hm,e.waterfall=sd,e.whilst=Wl,e.all=vo,e.allLimit=Ul,e.allSeries=yc,e.any=Vl,e.anyLimit=Ui,e.anySeries=$l,e.find=As,e.findLimit=Zr,e.findSeries=_l,e.forEach=Bc,e.forEachSeries=bo,e.forEachLimit=Ml,e.forEachOf=Xr,e.forEachOfSeries=Es,e.forEachOfLimit=Di,e.inject=Jr,e.foldl=Jr,e.foldr=yo,e.select=kc,e.selectLimit=Ol,e.selectSeries=wc,e.wrapSync=x,Object.defineProperty(e,"__esModule",{value:!0})})})(bp,bp.exports);var w2={exports:{}},vp=w2.exports=function(n,t){if(t||(t=16),n===void 0&&(n=128),n<=0)return"0";for(var e=Math.log(Math.pow(2,n))/Math.log(t),r=2;e===1/0;r*=2)e=Math.log(Math.pow(2,n/r))/Math.log(t)*r;for(var i=e-Math.floor(e),o="",r=0;r<Math.floor(e);r++){var s=Math.floor(Math.random()*t).toString(t);o=s+o}if(i){var l=Math.pow(t,i),s=Math.floor(Math.random()*l).toString(t);o=s+o}var c=parseInt(o,t);return c!==1/0&&c>=Math.pow(2,n)?vp(n,t):o};vp.rack=function(n,t,e){var r=function(o){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=vp(n,t)}while(Object.hasOwnProperty.call(i,l));return i[l]=o,l},i=r.hats={};return r.get=function(o){return r.hats[o]},r.set=function(o,s){return r.hats[o]=s,r},r.bits=n||128,r.base=t||16,r};var S2=qo,LO=R2,IO=k2,Fh=Fr,Bp=bp.exports,DO=w2.exports,L2=nl.ACTIONS,I2=Ve;function Ve(n,t){if(S2.EventEmitter.call(this),!t||typeof t!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=t,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}S2.mixin(Ve),Ve.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Ve.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Ve.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||DO();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Ve.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(r){if(r)return t._callbackOrEmit(r,n);var i=Object.keys(t._remotePresenceInstances);Bp.parallel([function(o){Bp.each(e,function(s,l){t.localPresences[s].destroy(l)},o)},function(o){if(!t._wantsDestroy)return o();Bp.each(i,function(s,l){t._remotePresenceInstances[s].destroy(l)},o)}],function(o){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(o,n)})})},Ve.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?L2.presenceSubscribe:L2.presenceUnsubscribe,r=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[r]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,r,this)},Ve.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Ve.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Ve.prototype._receiveUpdate=function(n,t){var e=Fh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var r=this,i=Fh.digOrCreate(this._remotePresenceInstances,t.id,function(){return r._createRemotePresence(t.id)});i.receiveUpdate(t)},Ve.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Ve.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var t in this.localPresences){var e=this.localPresences[t];e.value!==null&&e.send()}},Ve.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Ve.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Ve.prototype._resubscribe=function(){var n=[];for(var t in this._subscriptionCallbacksBySeq){var e=this._subscriptionCallback(t);n.push(e)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var r=this;this.subscribe(function(i){r._callEachOrEmit(n,i)})},Ve.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Ve.prototype._callbackOrEmit=function(n,t){if(t)return Fh.nextTick(t,n);n&&this.emit("error",n)},Ve.prototype._createLocalPresence=function(n){return new LO(this,n)},Ve.prototype._createRemotePresence=function(n){return new IO(this,n)},Ve.prototype._callEachOrEmit=function(n,t){var e=Fh.callEach(n,t);!e&&t&&this.emit("error",t)};var Au=R2,D2=Mh,_O=Fr,_2=D2.CODES,MO=Vr;function Vr(n,t){Au.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this._doc=this.connection.get(this.collection,this.id),this._isSending=!1,this._docDataVersionByPresenceVersion={},this._opHandler=this._transformAgainstOp.bind(this),this._createOrDelHandler=this._handleCreateOrDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._destroyHandler=this.destroy.bind(this),this._registerWithDoc()}Vr.prototype=Object.create(Au.prototype),Vr.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:_2.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(e,t)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,Au.prototype.submit.call(this,n,t)},Vr.prototype.destroy=function(n){this._doc.removeListener("op",this._opHandler),this._doc.removeListener("create",this._createOrDelHandler),this._doc.removeListener("del",this._createOrDelHandler),this._doc.removeListener("load",this._loadHandler),this._doc.removeListener("destroy",this._destroyHandler),Au.prototype.destroy.call(this,n)},Vr.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(t){t.t=n._doc.type.uri,t.v=n._doc.version,n.connection.send(t)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},Vr.prototype._registerWithDoc=function(){this._doc.on("op",this._opHandler),this._doc.on("create",this._createOrDelHandler),this._doc.on("del",this._createOrDelHandler),this._doc.on("load",this._loadHandler),this._doc.on("destroy",this._destroyHandler)},Vr.prototype._transformAgainstOp=function(n,t){var e=this,r=this._doc._dataStateVersion;this._pendingMessages.forEach(function(i){var o=e._docDataVersionByPresenceVersion[i.pv];if(!(o>=r))try{i.p=e._transformPresence(i.p,n,t),e._docDataVersionByPresenceVersion[i.pv]=r}catch(l){var s=e._getCallback(i.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(i){this.emit("error",i)}},Vr.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Vr.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Vr.prototype._message=function(){var n=Au.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},Vr.prototype._transformPresence=function(n,t,e){var r=this._doc.type;if(!_O.supportsPresence(r))throw new D2(_2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+r.name);return r.transformPresence(n,t,e)};var M2={};(function(n){var t=pu,e=Mh,r=Fr,i=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new e(i.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[c];if(d==null||typeof d!="object")return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(i.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(i.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(i.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(i.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new e(i.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return t.map[l]&&t.map[l].uri},n.apply=function(l,c){if(typeof l!="object")return new e(i.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new e(i.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new e(i.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=c.create,h=t.map[d.type];if(!h)return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(E){return E}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var C=o(l,c.op);if(C)return C;l.v++}else l.v++};function o(l,c){if(!l.type)return new e(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new e(i.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,c)}catch(h){return new e(i.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,c,d){if(c.v!=null&&c.v!==d.v)return new e(i.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(c.create||"op"in c)return new e(i.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in c||c.create||c.del)||"op"in d&&c.create)return new e(i.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in c){if(!l)return new e(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,d.op,"left")}catch(h){return h}}}c.v!=null&&c.v++},n.applyOps=function(l,c,d){d=d||{};for(var h=0;h<c.length;h++){var C=c[h];if(d._normalizeLegacyJson0Ops)try{s(l,C)}catch{return new e(i.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=C.v;var E=n.apply(l,C);if(E)return E}},n.transformPresence=function(l,c,d){var h=this.checkOp(c);if(h)return h;var C=l.t;if(typeof C=="string"&&(C=t.map[C]),!C)return{code:i.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!r.supportsPresence(C))return{code:i.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:C.transformPresence(l.p,c.op,d)}catch(E){return{code:i.ERR_PRESENCE_TRANSFORM_FAILED,message:E.message||E}}l.v++};function s(l,c){if(l.type===t.defaultType.uri){var d=c.op;if(!!d){var h=l.data;d.length>1&&(h=r.clone(h));for(var C=0;C<d.length;C++){var E=d[C];typeof E.lm=="string"&&(E.lm=+E.lm);for(var x=E.p,v=h,k=0;k<x.length;k++){var L=x[k];Object.prototype.toString.call(v)=="[object Array]"?x[k]=+L:v.constructor===Object&&(x[k]=L.toString()),v=v[L]}C<d.length-1&&(h=t.defaultType.apply(h,[E]))}}}}})(M2);var xu=k2,UO=M2,OO=gr;function gr(n,t){xu.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this.src=null,this.presenceVersion=null,this._doc=this.connection.get(this.collection,this.id),this._pending=null,this._opCache=null,this._pendingSetPending=!1,this._opHandler=this._handleOp.bind(this),this._createDelHandler=this._handleCreateDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._registerWithDoc()}gr.prototype=Object.create(xu.prototype),gr.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},gr.prototype.destroy=function(n){this._doc.removeListener("op",this._opHandler),this._doc.removeListener("create",this._createDelHandler),this._doc.removeListener("del",this._createDelHandler),this._doc.removeListener("load",this._loadHandler),xu.prototype.destroy.call(this,n)},gr.prototype._registerWithDoc=function(){this._doc.on("op",this._opHandler),this._doc.on("create",this._createDelHandler),this._doc.on("del",this._createDelHandler),this._doc.on("load",this._loadHandler)},gr.prototype._setPendingPresence=function(){if(!this._pendingSetPending){this._pendingSetPending=!0;var n=this;this._doc.whenNothingPending(function(){if(n._pendingSetPending=!1,!!n._pending){if(n._pending.pv<n.presenceVersion)return n._pending=null;if(n._pending.v>n._doc.version)return n._doc.fetch();!n._catchUpStalePresence()||(n.value=n._pending.p,n.presenceVersion=n._pending.pv,n._pending=null,n.presence._updateRemotePresence(n))}})}},gr.prototype._handleOp=function(n,t,e){var r=e===this.src;this._transformAgainstOp(n,r),this._cacheOp(n,r),this._setPendingPresence()},xu.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},xu.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},gr.prototype._transformAgainstOp=function(n,t){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,t)}catch(e){return this.presence.emit("error",e)}this.presence._updateRemotePresence(this)}},gr.prototype._catchUpStalePresence=function(){if(this._pending.v>=this._doc.version)return!0;if(!this._opCache)return this._startCachingOps(),this._doc.fetch(),this.presence.subscribe(),!1;for(;this._opCache[this._pending.v];){var n=this._opCache[this._pending.v],t=n.op,e=n.isOwnOp;t===null?(this._pending.p=null,this._pending.v++):UO.transformPresence(this._pending,t,e)}var r=this._pending.v>=this._doc.version;return r&&this._stopCachingOps(),r},gr.prototype._startCachingOps=function(){this._opCache=[]},gr.prototype._stopCachingOps=function(){this._opCache=null},gr.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var U2=I2,NO=MO,PO=OO;function Ta(n,t,e){var r=Ta.channel(t,e);U2.call(this,n,r),this.collection=t,this.id=e}var FO=Ta;Ta.prototype=Object.create(U2.prototype),Ta.channel=function(n,t){return n+"."+t},Ta.prototype._createLocalPresence=function(n){return new NO(this,n)},Ta.prototype._createRemotePresence=function(n){return new PO(this,n)};var KO=VO;function VO(n,t,e,r,i){this.id=n,this.v=t,this.type=e,this.data=r,this.m=i}var $O=KO,O2=qo,N2=bu;function bu(n,t,e,r,i){if(O2.EventEmitter.call(this),typeof i!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=r,this.collection=e,this.callback=i,this.sent=!1}O2.mixin(bu),bu.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},bu.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},bu.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,r=new $O(this.id,t.v,t.type,t.data,e);this.callback(null,r)};var P2=N2,HO=Fr,jO=nl.ACTIONS,zO=Tp;function Tp(n,t,e,r,i,o){if(P2.call(this,n,t,e,r,o),!HO.isValidVersion(i))throw new Error("Snapshot version must be a positive integer or null");this.version=i}Tp.prototype=Object.create(P2.prototype),Tp.prototype._message=function(){return{a:jO.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var F2=N2,GO=Fr,WO=nl.ACTIONS,qO=yp;function yp(n,t,e,r,i,o){if(F2.call(this,n,t,e,r,o),!GO.isValidTimestamp(i))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=i}yp.prototype=Object.create(F2.prototype),yp.prototype._message=function(){return{a:WO.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var XO=bO,QO=RO,YO=I2,K2=FO,JO=zO,ZO=qO,V2=qo,ya=Mh,ie=nl.ACTIONS,$2=pu,$r=Fr,vu=C2,Bu=ya.CODES;function H2(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var tN=Rt;function Rt(n){V2.EventEmitter.call(this),this.collections={},this.nextQueryId=1,this.nextSnapshotRequestId=1,this.queries={},this._presences={},this._snapshotRequests={},this.seq=1,this._presenceSeq=1,this.id=null,this.agent=null,this.debug=!1,this.state=H2(n),this.bindToSocket(n)}V2.mixin(Rt),Rt.prototype.bindToSocket=function(n){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=n;var t=H2(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(r){try{var i=typeof r.data=="string"?JSON.parse(r.data):r.data}catch{vu.warn("Failed to parse message",r);return}e.debug&&vu.info("RECV",JSON.stringify(i));var o={data:i};if(e.emit("receive",o),!!o.data)try{e.handleMessage(o.data)}catch(s){$r.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(r){e.emit("connection error",r)},n.onclose=function(r){r==="closed"||r==="Closed"?e._setState("closed",r):r==="stopped"||r==="Stopped by server"?e._setState("stopped",r):e._setState("disconnected",r)}},Rt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=j2(n.error,n),delete n.error),n.a){case ie.initLegacy:return this._handleLegacyInit(n);case ie.handshake:return this._handleHandshake(t,n);case ie.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case ie.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case ie.queryUnsubscribe:return;case ie.queryUpdate:var e=this.queries[n.id];if(!e)return;if(t)return e._handleError(t);n.diff&&e._handleDiff(n.diff),n.hasOwnProperty("extra")&&e._handleExtra(n.extra);return;case ie.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case ie.bulkSubscribe:case ie.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case ie.snapshotFetch:case ie.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case ie.fetch:var r=this.getExisting(n.c,n.d);r&&r._handleFetch(t,n.data);return;case ie.subscribe:case ie.unsubscribe:var r=this.getExisting(n.c,n.d);r&&r._handleSubscribe(t,n.data);return;case ie.op:var r=this.getExisting(n.c,n.d);r&&r._handleOp(t,n);return;case ie.presence:return this._handlePresence(t,n);case ie.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case ie.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case ie.presenceRequest:return this._handlePresenceRequest(t,n);case ie.pingPong:return this._handlePingPong(t);default:vu.warn("Ignoring unrecognized message",n)}};function j2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}Rt.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var r in t.data){var i=t.data[r],o=this.getExisting(t.c,r);o&&(n?o[e](n):i.error?o[e](j2(i.error)):o[e](null,i))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var r=t.b[s],o=this.getExisting(t.c,r);o&&o[e](n)}else if(t.b)for(var r in t.b){var o=this.getExisting(t.c,r);o&&o[e](n)}else vu.error("Invalid bulk message",t)},Rt.prototype._reset=function(){this.agent=null},Rt.prototype._setState=function(n,t){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var e=new ya(Bu.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",e)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var r in this.queries){var i=this.queries[r];i._onConnectionStateChanged()}for(var o in this.collections){var s=this.collections[o];for(var r in s)s[r]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var r in this._snapshotRequests){var c=this._snapshotRequests[r];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},Rt.prototype.startBulk=function(){this.bulk||(this.bulk={})},Rt.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var t=this.bulk[n];this._sendBulk("f",n,t.f),this._sendBulk("s",n,t.s),this._sendBulk("u",n,t.u)}this.bulk=null},Rt.prototype._sendBulk=function(n,t,e){if(!!e){var r=[],i={},o=0,s;for(var l in e){var c=e[l];c==null?r.push(l):(i[l]=c,s=l,o++)}if(r.length===1){var l=r[0];this.send({a:n,c:t,d:l})}else r.length&&this.send({a:"b"+n,c:t,b:r});if(o===1){var d=i[s];this.send({a:n,c:t,d:s,v:d})}else o&&this.send({a:"b"+n,c:t,b:i})}},Rt.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var r=this.bulk[t.collection]||(this.bulk[t.collection]={}),i=r[n]||(r[n]={}),o=i.hasOwnProperty(t.id);return i[t.id]=e,o}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},Rt.prototype.sendFetch=function(n){return this._sendActions(ie.fetch,n,n.version)},Rt.prototype.sendSubscribe=function(n){return this._sendActions(ie.subscribe,n,n.version)},Rt.prototype.sendUnsubscribe=function(n){return this._sendActions(ie.unsubscribe,n)},Rt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:ie.op,c:n.collection,d:n.id,v:n.version,src:t.src,seq:t.seq,x:{}};"op"in t&&(e.op=t.op),t.create&&(e.create=t.create),t.del&&(e.del=t.del),n.submitSource&&(e.x.source=t.source),this.send(e)},Rt.prototype.send=function(n){this.debug&&vu.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},Rt.prototype.ping=function(){if(!this.canSend)throw new ya(Bu.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:ie.pingPong};this.send(n)},Rt.prototype.close=function(){this.socket.close()},Rt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},Rt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),r=e[t];return r||(r=e[t]=new XO(this,n,t),this.emit("doc",r)),r._wantsDestroy=!1,r},Rt.prototype._destroyDoc=function(n){!n._wantsDestroy||($r.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},Rt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},Rt.prototype._createQuery=function(n,t,e,r,i){var o=this.nextQueryId++,s=new QO(n,this,o,t,e,r,i);return this.queries[o]=s,s.send(),s},Rt.prototype._destroyQuery=function(n){delete this.queries[n.id]},Rt.prototype.createFetchQuery=function(n,t,e,r){return this._createQuery(ie.queryFetch,n,t,e,r)},Rt.prototype.createSubscribeQuery=function(n,t,e,r){return this._createQuery(ie.querySubscribe,n,t,e,r)},Rt.prototype.hasPending=function(){return!!(this._firstDoc(Kh)||this._firstQuery(Kh)||this._firstSnapshotRequest())};function Kh(n){return n.hasPending()}Rt.prototype.hasWritePending=function(){return!!this._firstDoc(eN)};function eN(n){return n.hasWritePending()}Rt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Kh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Kh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var r=this._firstSnapshotRequest();if(r){r.once("ready",this._nothingPendingRetry(n));return}$r.nextTick(n)},Rt.prototype._nothingPendingRetry=function(n){var t=this;return function(){$r.nextTick(function(){t.whenNothingPending(n)})}},Rt.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var r in e){var i=e[r];if(n(i))return i}}},Rt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},Rt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},Rt.prototype.fetchSnapshot=function(n,t,e,r){typeof e=="function"&&(r=e,e=null);var i=this.nextSnapshotRequestId++,o=new JO(this,i,n,t,e,r);this._snapshotRequests[o.requestId]=o,o.send()},Rt.prototype.fetchSnapshotByTimestamp=function(n,t,e,r){typeof e=="function"&&(r=e,e=null);var i=this.nextSnapshotRequestId++,o=new ZO(this,i,n,t,e,r);this._snapshotRequests[o.requestId]=o,o.send()},Rt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},Rt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},Rt.prototype._initializeHandshake=function(){this.send({a:ie.handshake,id:this.id})},Rt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},Rt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},Rt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new ya(Bu.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if($2.map[n.type]!==$2.defaultType)return this.emit("error",new ya(Bu.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new ya(Bu.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},Rt.prototype.getPresence=function(n){var t=this,e=$r.digOrCreate(this._presences,n,function(){return new YO(t,n)});return e._wantsDestroy=!1,e},Rt.prototype.getDocPresence=function(n,t){var e=K2.channel(n,t),r=this,i=$r.digOrCreate(this._presences,e,function(){return new K2(r,n,t)});return i._wantsDestroy=!1,i},Rt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var r={a:n,ch:e.channel,seq:t};return this.send(r),r.seq},Rt.prototype._addPresence=function(n){$r.digOrCreate(this._presences,n.channel,function(){return n})},Rt.prototype._handlePresenceSubscribe=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},Rt.prototype._handlePresenceUnsubscribe=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},Rt.prototype._handlePresence=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},Rt.prototype._handlePresenceRequest=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var z2=tN,nN=pu;const Tu={err:1001,msg:"user auth error",name:"AuthError"},Vh={err:1002,msg:"you don't have required permission",name:"PermissionError"},Rp={err:1003,msg:"Too many user connected",name:"MaxUserError"},yu={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},rN={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},iN={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},Ra="x-live-editor-token",Ru="x-live-editor-base-url",dn=I("auth-connection");function oN(n){try{n()}catch(t){dn.error(t)}}class sN{constructor(t,e){g(this,"enabled",!0);g(this,"connection");g(this,"ws");g(this,"retryCount");g(this,"events",new fb.EventEmitter);g(this,"token",null);g(this,"resourceToken",null);g(this,"reAuth",async()=>{if(this.connection&&this.reauthFunc){const t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}});this.url=t,this.reauthFunc=e,this.retryCount=0,window.addEventListener("offline",()=>{var r;this.token="fake",(r=this.connection)==null||r.close()})}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return Hi(this.getBaseURL())}async auth(t){p(dn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,r=await window.fetch(e,{method:"GET",headers:{[Ra]:t.token,[Ru]:this.getBase64BaseURL()},credentials:"include"});return r.status,this.enabled?(this.token=t.token,await r.json()):{read:"",user:""}}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[Ru]:Hi(this.getBaseURL())}})}async init(t){const e=await this.auth(t);if(!this.enabled)return;this.resourceToken=e.read,this.ws=new w6.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(z2.prototype),p(dn,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};const r=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=i=>{var s;const o=i;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in o||o.a==="pong")this.handleMessage(o);else{Object.prototype.hasOwnProperty.call(o,"a")&&o.a!=="init"&&o.a!=="hs"&&(this.retryCount>0&&(dn.info("retrying re-auth success"),this.emitAuthRecover()),this.retryCount=0);try{r(o)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,o);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,o);return}throw l}}},z2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc){this.retryCount>=5&&(dn.warn("retry auth times exceed 5, broadcast auth error"),this.emitAuthError()),this.retryCount+=1,dn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();if(await this.auth(t),!this.enabled){this.retryCount=10,setTimeout(()=>this.handleAuthError(),0);return}this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){dn.error(t),setTimeout(()=>this.handleAuthError(),0)}}}emitPermissionError(){const t=new Error(Vh.msg);t.code=Vh.err,this.events.emit("error",t)}emitAuthRecover(){this.events.emit("authRecover")}emitAuthError(){const t=new Error(Tu.msg);t.code=Tu.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(yu.msg);t.code=yu.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t,e){t.orgMsg=e,this.events.emit("writeConflictError",t)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(t){const e=t;if(e.a==="pong")return;const r=e.err;if(r===Tu.err)dn.warn("auth error"),this.handleAuthError();else if(r===Rp.err)dn.warn(Rp.msg),this.emitMaxUsersError();else if(r===yu.err){dn.warn(yu.msg);try{this.emitRequestReloadError()}catch(i){dn.error(`error occurred while process reload error: ${JSON.stringify(i)}`)}finally{this.end(!1)}}else r===Vh.err?this.emitPermissionError():(dn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError())}get(t,e){return p(dn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(p(dn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onAuthError(t){this.events.addListener("error",t)}onAuthRecover(t){this.events.addListener("authRecover",t)}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){p(dn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){p(dn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.enabled=!1,this.reauthFunc=void 0,this.events.removeAllListeners(),oN(()=>{var r;return(r=this.connection)==null?void 0:r.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}I("utils/file");function lN(){function n(){return new Promise(t=>{const e=new FileReader;e.onload=()=>{t(e.result)},e.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}lN();async function aN(n){const e=n.size,r=Math.floor((e+102400-1)/102400),i=new S6.Hash;for(let s=0;s<r;s++){const l=s*102400;let c=l+102400;c>e&&(c=e);const h=await n.slice(l,c,n.type).arrayBuffer();i.update(new Uint8Array(h))}const o=i.digest();return Hi(o)}const pi=I("sharedb-doc/client"),cN=hb.default.create();class uN{constructor(t,e,r){g(this,"connection");g(this,"auth");g(this,"doc",null);g(this,"reauthFunc");g(this,"clientId",Z());g(this,"getDoc",async()=>{const t=r=>new Promise((i,o)=>{r.fetch(s=>{s?o(s):i()})});p(pi,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth),window.addEventListener("online",async()=>{await this.connection.init({...this.auth,token:"fake"})});const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),pi.debug(e),e});this.auth=t;const i=`${e}/${this.auth.appId}/${this.auth.docId}`;nN.register(Cd.type),this.connection=new sN(i,r),this.reauthFunc=r}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return p(pi,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}close(t){this.connection.end(t),this.doc=null}on(t,e){this.connection.addEventListener(t,r=>{(t==="error"||this.doc)&&e(r)})}onAuthError(t){this.connection.onAuthError(t)}onAuthRecover(t){this.connection.onAuthRecover(t)}onWriteConflictError(t){this.connection.onWriteConflictError(t)}onMaxUsersError(t){this.connection.onMaxUsersError(t)}onRequestReloadError(t){this.connection.onRequestReloadError(t)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const t=this.connection.url;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}async getFileUrlByHash(t,e,r,i,o){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...o},data:{name:r,size:i}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const r=`${this.apiServer()}/resources`;try{const i=`${r}/hash`,o=await this.request(i,{method:"post",headers:{[Ra]:this.connection.token},data:{resources:t}});return o.data&&Array.isArray(o.data)?o.data:[]}catch{return[]}}async uploadFile(t,e,r,i,o){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=x=>{pi.info(`on progress: ${x.loaded}`);let v=x.loaded*100/s;v>100&&(v=100),i(v)},c=await aN(e),d=await this.getFileUrlByHash(t,c,e.name,e.size,r);if(d)return i(-1),d;let h=t;o!=null&&o.thumbnail&&(h+="/thumbnail");const C=new FormData;C.append("file-size",`${e.size}`),C.append("file-hash",c),C.append("file",e,e.name);const E=await this.request(h,{method:"post",data:C,withCredentials:!0,headers:{...r},onUploadProgress:l});return pi.info(E),i(100),Array.isArray(E.data)?E.data[0]:E.data}async uploadResource(t,e=()=>{},r){const o=`${this.apiServer()}/resources`;p(pi,this.connection.token,"no connection token");const s=await this.uploadFile(o,t,{[Ra]:this.connection.token},e,r);return p(pi,s,"no result"),s}async request(t,e){var o,s;let r=this.connection.token,i;for(let l=0;l<2;l++){const c=e||{};c.url=t,c.headers||(c.headers={}),p(pi,r,"no token"),c.headers={...c.headers,[Ra]:r,[Ru]:this.connection.getBase64BaseURL()};try{return await cN(t,c)}catch(d){if(i=d,((o=d==null?void 0:d.response)==null?void 0:o.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;r=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw p(pi,i,"no error"),i}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,i=(await this.request(e)).data.versions;return i.forEach(o=>{o.extra&&(o.extra=JSON.parse(o.extra))}),i}async getVersion(t){const r=`${this.apiServer()}/versions/${t}`,i=await this.request(r);return JSON.parse(i.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,r=await this.request(e);return JSON.parse(r.data.data)}async getVersionOps(t,e){let i=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(i+=`&from=${e}`);const o=await this.request(i),s=o.data.ops,l=mb.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let d;return c?(p(pi,c.create,"no createDoc.create"),d=c.create.data):d=JSON.parse(o.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:o.data.ops}}async updateVersionExtra(t,e,r){const o=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(o,{method:"post",data:{extra:JSON.stringify(r)}})}async revertVersion(t){const r=`${this.apiServer()}/versions/revert/${t}`;await this.request(r,{method:"post",data:{}})}async createVersion(t,e){const i=`${this.apiServer()}/versions`;return(await this.request(i,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const r=`${this.apiServer()}/resources/external/${Hi(t)}`;return(await this.request(r)).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let i=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const o=[];if(e!=null&&e.withToken&&o.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&o.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),o.length>0){const s=o.join("&");i+=`?${s}`}return i}reAuth(){this.connection.reAuth()}}function fN(){return{blocks:[{id:Z(),type:"text",text:[]}],comments:{},meta:{}}}const kp=I("block-ids");class dN{constructor(){g(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((i,o)=>o-i);for(let i=0;i<e.length;i++){const o=e[i];if(o>=t){const s=this.ids.get(o);p(kp,s!==void 0,"old id is not exists"),this.ids.delete(o),this.ids.set(o+1,s)}}const r=Z();this.ids.set(t,r)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((r,i)=>r-i);for(let r=0;r<e.length;r++){const i=e[r];if(i>t){const o=this.ids.get(i);p(kp,o!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i-1,o)}}}getId(t){let e=this.ids.get(t);return e||(e=Z(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class hN{constructor(){g(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new dN,this.ids.set(t,e)),e}onInsertBlock(t,e){this.getContainerIds(t).onInsertBlock(e)}onDeleteBlock(t,e){this.getContainerIds(t).onDeleteBlock(e)}getBlockId(t,e){return this.getContainerIds(t).getId(e)}getBlockIndexById(t){const e=Array.from(this.ids.entries());for(let r=0;r<e.length;r++){const i=e[r],o=i[1].getById(t);if(o)return{containerId:i[0],blockIndex:o[0]}}return p(kp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class G2{constructor(t=new Set,e=new Map){this.deletedKeys=t,this.insertedValues=e}insert(t,e){this.insertedValues.set(t,e)}delete(t){this.deletedKeys.add(t)}toDocBlockDelta(){const t={};return this.insertedValues.forEach((e,r)=>{t[r]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const wp=I("op-parse-handler");class mN{constructor(t,e){g(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const r={...t,containerId:(i=>i==="blocks"?"root":i)(t.containerId)};this.actions.push(r)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,r){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:r})}onDeleteBlockData(t,e,r){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:r})}onInsertBlockData(t,e,r,i){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:r,value:i})}onUpdateBlockText(t,e,r){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:r})}onDeleteContainer(t){this.pushActions({type:"deleteContainer",containerId:t})}onCreateContainer(t,e){this.pushActions({type:"createContainer",containerId:t,data:e})}onDeleteComment(t){this.pushActions({type:"deleteComment",commentId:t})}onCreateComment(t){this.pushActions({type:"createComment",commentId:t})}onUpdateComment(t){this.pushActions({type:"updateComment",commentId:t})}end(){const t=this.actions,e=new Set,r=new Map,i=new hN,o=t.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of o)if(s.type==="deleteBlock"){const l=s,c=i.getBlockId(l.containerId,l.blockIndex);i.onDeleteBlock(l.containerId,l.blockIndex);const d=r.get(c);d&&(wp.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),r.delete(c));const h=`${l.containerId}-${l.blockIndex}`;e.add(h),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,c=`${l.containerId}-${l.blockIndex}`;if(e.has(c)){wp.warn("delete block data after delete block, ignore it");continue}const d=i.getBlockId(l.containerId,l.blockIndex);let h=r.get(d);h||(h=new G2,r.set(d,h)),h.delete(l.key)}else p(wp,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,c=i.getBlockId(l.containerId,l.blockIndex);let d=r.get(c);d||(d=new G2,r.set(c,d)),d.insert(l.key,l.value)}else if(s.type==="updateBlockText"){const l=s;this.outerHandler.onUpdateBlockText(l.containerId,l.blockIndex,l.richTextData,this.local)}else if(s.type==="createComment"){const l=s;this.outerHandler.onCreateComment(l.commentId,this.local)}else if(s.type==="updateComment"){const l=s;this.outerHandler.onUpdateComment(l.commentId,this.local)}}),Array.from(r.entries()).forEach(([s,l])=>{const{containerId:c,blockIndex:d}=i.getBlockIndexById(s);this.outerHandler.onUpdateBlockData(c,d,l.toDocBlockDelta(),this.local)})}}const $e=I("op-parser");class W2{}class Sp{constructor(t){g(this,"key");this.key=t}}function gN(n,t,e){const r=t.concat(),i=r[0];if(typeof i!="number"||(r.shift(),r.length===1))return!1;const o=r[0];if(typeof o!="object"||!o.i||Object.keys(o).length!==1)return!1;for(let l=1;l<r.length;l++){const c=r[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const h=c[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=o.i;p($e,s.id,"block id is required"),p($e,s.type,"block type is required");for(let l=1;l<r.length;l++){const c=r[l],d=c[0],h=c[1];s[d]=h.i}return e.onInsertBlock(n,i,s),!0}function Lp(n,t,e,r){if(e==="upsert"&&gN(n,t,r))return;p($e,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const i=t.concat(),o=i[0];i.shift();const s=[];for(;i.length>0;){const l=i[0];if(l==="text"){const c=i[1];if(p($e,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),p($e,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),i.splice(0,2),e==="upsert"){const h=c.e;r.onUpdateBlockText(n,o,h)}p($e,i.length===0,`invalid block ops.length !== 0, ${JSON.stringify(i)}`)}else if(Array.isArray(l)){p($e,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];p($e,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const d=l[1];if(c==="text"){if(p($e,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&r.onInsertBlockData(n,o,c,d.i),d.r&&e==="remove"&&r.onDeleteBlockData(n,o,c),d.et==="rich-text"&&e==="upsert"){const C=d.e;r.onUpdateBlockText(n,o,C)}}else e==="remove"&&d.r&&s.push(new Sp(c)),e==="upsert"&&d.i&&r.onInsertBlockData(n,o,c,d.i);i.shift()}else if(typeof l=="object"){const c=l;e==="remove"&&c.r&&s.push(new W2),e==="upsert"&&c.i&&r.onInsertBlock(n,o,c.i),i.shift()}else{p($e,typeof l=="string","data is not string"),p($e,l!=="text","data !== 'text'"),p($e,i.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(i)}`);const c=l,d=i[1];e==="remove"&&d.r&&s.push(new Sp(c)),e==="upsert"&&d.i&&r.onInsertBlockData(n,o,c,d.i),i.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof W2?r.onDeleteBlock(n,o):l instanceof Sp?r.onDeleteBlockData(n,o,l.key):p($e,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function pN(n,t,e){$e.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function CN(n,t,e){const r=n[1],i=n[2];p($e,r,`invalid comment op, no commentId: ${JSON.stringify(n)}`),p($e,i,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof i=="string"?$e.error(`unknown comment op, ${JSON.stringify(n)}`):i.i&&i.r?t==="upsert"&&e.onUpdateComment(r):i.i?t==="upsert"&&e.onCreateComment(r):i.r?t==="remove"&&e.onDeleteComment(r):$e.error(`unknown comment op, ${JSON.stringify(n)}`)}function Ip(n,t,e){const r=n[0];if(Array.isArray(r)){r.forEach(s=>{Ip(s,t,e)});return}const i=r;if(p($e,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){pN(n);return}if(i==="comments"){CN(n,t,e);return}const o=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{Lp(o,s,t,e)}):n.slice(1).forEach(s=>{Lp(o,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(o),s.i&&t==="upsert"&&e.onCreateContainer(o,s.i)}else p($e,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Lp(o,n.slice(1),t,e)}function Dp(n,t,e){const r=new mN(t,e);for(let i=0;i<2;i++){const o=i===0?"remove":"upsert",s=gt.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{Ip(c,o,r)}):Ip(s,o,r)}r.end()}const EN=I("sharedb-comments");function _p(n){const t=n.blocks;p(EN,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([r,i])=>{Array.isArray(i)&&(e.blocks[r]=i)}),gt.default(e)}function q2(n){const{id:t,groupId:e,userId:r,displayName:i,avatarUrl:o,abstract:s,created:l,modified:c}=n;return{id:t,groupId:e,userId:r,displayName:i,avatarUrl:o,abstract:s,created:l,modified:c}}function Mp(n,t){const e=nO(t),{comments:r,meta:i,blocks:o,...s}=e,l={...n,blocks:o,...s},c=gt.default(l);return delete c.children,c}const oe=I("sharedb-doc/doc-container"),X2="ot-json1";Cd.type.registerSubtype(rO.type),Cd.type.name=X2,Cd.type.invert=null;class ku extends ra{constructor(e,r,i=!0){super();g(this,"doc");g(this,"client");g(this,"localPresence");g(this,"remoteCaretHandler",new tO);g(this,"batching",0);g(this,"status","clean");g(this,"disableLogout");g(this,"destroyed",!1);g(this,"handleNothingPending",()=>{this.setStatus("clean")});g(this,"handleCreate",()=>{this.handleReload("doc created")});g(this,"handleDel",()=>{});g(this,"handleReload",e=>{this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)})});g(this,"handleReset",async e=>{const r=new Error(`reset doc: ${e}`);r.code="ResetDoc",this.callbacks.forEach(i=>{var o;return(o=i.onError)==null?void 0:o.call(i,r)}),this.destroy()});g(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});g(this,"insertObject",async(e,r,i)=>{const o=[e,r,{i}];return this.submitOp(o)});g(this,"deleteObject",async(e,r)=>{const i=[e,r,{r:!0}];return this.submitOp(i)});g(this,"replaceObject",async(e,r,i)=>{const o=[e,r,{r:!0,i}];return this.submitOp(o)});g(this,"updateObject",async(e,r,i)=>{const o=this.data()[e][r],s=[e,r];return Object.entries(i).forEach(([l,c])=>{if(!Nc.default(o[l],c))if(o[l]===void 0){if(c!=null){const d={i:c};s.push([l,d])}}else if(c==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:c};s.push([l,d])}}),Object.entries(o).forEach(([l,c])=>{if((i[l]===void 0||i[l]===null)&&c!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});g(this,"broadcastMessage",async e=>{const r={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(r)});g(this,"data",()=>this.doc.data);g(this,"submitOp",async e=>new Promise((r,i)=>{if(this.destroyed){oe.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},o=>{o?(oe.error(`invalid op, ${o.message}, ${JSON.stringify(e)}`),i(o),oe.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):r()}),this.doc.data||(oe.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));g(this,"createDoc",async e=>new Promise((r,i)=>{this.doc.create(e,X2,o=>{o?i(o):r()})}));g(this,"submitInsertChildContainers",async e=>{if(e.length===0)return Promise.resolve();const r=e.map(({containerId:i,blocks:o})=>[io(i),{i:o}]);return this.submitOp([r])});g(this,"submitDeleteChildContainer",async e=>{const r=[io(e),{r:!0}];return this.submitOp(r)});g(this,"submitInsertBlock",async(e,r,i)=>{const o=[io(e),r,{i}];return this.submitOp(o)});g(this,"submitDeleteBlock",async(e,r)=>{const i=[io(e),r,{r:!0}];return this.submitOp(i)});g(this,"submitUpdateBlockData",async(e,r,i)=>{if(i.delete.length===0&&Object.keys(i.insert).length===0)return Promise.resolve();const o=[io(e),r],s=new Set(i.delete);Object.entries(i.insert).forEach(([c,d])=>{if(s.has(c)){const h={r:!0,i:d};o.push([c,h])}});const l=new Set(Object.keys(i.insert));return i.delete.forEach(c=>{if(l.has(c))return;const d={r:!0};o.push([c,d])}),Object.entries(i.insert).forEach(([c,d])=>{if(s.has(c))return;const h={i:d};o.push([c,h])}),this.submitOp(o)});g(this,"submitUpdateRichText",async(e,r,i)=>{const o=[io(e),r,"text",{e:i,et:"rich-text"}];return this.submitOp(o)});g(this,"handleOp",(e,r,i)=>{if(this.destroyed){oe.warn("handleOp: destroyed");return}try{Dp(e,this,!!r)}catch(o){throw oe.error(o),o}});this.client=e,this.doc=r,this.doc.preventCompose=!0,this.disableLogout=i,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,p(oe,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const r=new uN(e.auth,e.serverUrl,e.reauthFunc),i=await r.getDoc(),o=new ku(r,i,e.disableLogout);if(i.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await o.createDoc(e.templateData||fN())}return await o.initPresence(),await o.subscribe(),o.initEvents(),o}catch(r){throw oe.error(r),oe.error(`failed to load doc: ${JSON.stringify(r)}`),r}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(r=>{var i;return(i=r.onStatusChanged)==null?void 0:i.call(r,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onAuthError(e=>{this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,e)})}),this.client.onAuthRecover(()=>{this.callbacks.forEach(e=>{var r;return(r=e.onAuthRecover)==null?void 0:r.call(e)})}),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((e,r)=>{if(this.localPresence)e();else{const i=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);i.on("receive",(o,s)=>{this.onCustomMessage(s)}),i.subscribe(o=>{o?r(o):(this.localPresence=i.create(Z()),e())})}})}subscribe(){return new Promise((e,r)=>{this.doc.subscribe(i=>{i?r(i):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return ro(this.data())}getContainerBlocks(e){const r=this.data();p(oe,r,"no doc data");const i=r[io(e)];return p(oe,i,`no container data: ${e}`),gt.default(i)}findContainerBlocks(e){const r=this.data();p(oe,r,"no doc data");const i=r[io(e)];return i!=null?i:null}getBlockData(e,r){const i=this.data();p(oe,i,"no doc data");const o=i[io(e)];p(oe,o,`no container data: ${e}`);const s=o[r];return p(oe,s,`no block data: ${r}`),gt.default(s)}localInsertBlock(e,r,i){return this.submitInsertBlock(e,r,i),this.getBlockData(e,r)}localDeleteBlock(e,r){const i=this.getBlockData(e,r);return this.submitDeleteBlock(e,r),i}localUpdateBlockText(e,r,i){const o=this.getBlockData(e,r);p(oe,o.text,"no block text");const s=gt.default(o.text);this.submitUpdateRichText(e,r,i);const l=fn.apply(s,i);return p(oe,l,"no block text"),l}localUpdateBlockData(e,r,i){const o=gt.default(this.getBlockData(e,r));return this.submitUpdateBlockData(e,r,i),o}localInsertChildContainers(e){this.submitInsertChildContainers(e)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(r=>{this.submitDeleteChildContainer(r)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(r=>q2(r))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const r=this.data().comments[e];return _p(r)}localCreateComment(e,r){const i=Mp(e,r),s=["comments",i.id,{i}];return this.submitOp(s)}localDeleteComment(e){const r=["comments",e,{r:!0}];return this.submitOp(r)}localUpdateComment(e,r){const i=Mp(e,r),o=["comments",e.id,{r:!0,i}];return this.submitOp(o)}destroy(){var e;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(e,r,i){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(o=>{var s;return(s=o.onDeleteBlock)==null?void 0:s.call(o,Ba(e),r,i)})}onInsertBlock(e,r,i,o){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Ba(e),r,i,o)})}onUpdateBlockData(e,r,i,o){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Ba(e),r,i,o)})}onUpdateBlockText(e,r,i,o){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Ba(e),r,i,o)})}onDeleteContainer(e,r){p(oe,this.callbacks.length>0,"no callbacks"),p(oe,e!=="root","should not delete root container in doc"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,Ba(e),r)})}onCreateContainer(e,r,i){p(oe,this.callbacks.length>0,"no callbacks"),p(oe,e!=="root","should not create root container in doc"),this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,Ba(e),r,i)})}onDeleteComment(e,r){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteComment)==null?void 0:o.call(i,e,r)})}onCreateComment(e,r){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onCreateComment)==null?void 0:o.call(i,e,r)})}onUpdateComment(e,r){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onUpdateComment)==null?void 0:o.call(i,e,r)})}onCustomMessage(e){const r=e;(r==null?void 0:r.type)==="custom"&&(r==null?void 0:r.clientId)!==this.client.clientId?this.callbacks.forEach(i=>{var o;return(o=i.onCustomMessage)==null?void 0:o.call(i,r.data)}):(r==null?void 0:r.type)==="onlineUsers"&&setTimeout(()=>{const i={type:"custom",data:e,clientId:"-"};this.onCustomMessage(i)})}onAuthRecover(){this.callbacks.forEach(e=>{var r;return(r=e.onAuthRecover)==null?void 0:r.call(e)})}async addResources(e){let r=[];return e.forEach(o=>{const s=o.split("|");r.push(...s)}),r=Array.from(new Set(r)),await this.client.getFileUrlsByHashes(r)}async uploadResource(e,r){var o;return{resourceId:await this.client.uploadResource(e,(o=r==null?void 0:r.onProgress)!=null?o:()=>{})}}buildResourceUrl(e,r){return this.client.buildResourceUrl(e,r)}request(e,r){return this.client.request(e,r)}getUser(){const e=this.client.clientId,{permission:r,userId:i,displayName:o,avatarUrl:s}=this.client.auth;return{permission:r,clientId:e,userId:i,displayName:o,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const r=await this.client.getVersion(e);return ro(r)}async getLatestVersion(){const e=await this.client.getLatestVersion();return ro(e)}async getHistoryData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r),s=o.map(l=>({user:l.meta.createdBy,data:l}));return{doc:ro(i),historyData:s}}async getVersionData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r);return{doc:ro(i),versionData:o}}async updateVersionExtra(e,r,i){await this.client.updateVersionExtra(e,r,i)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,r){return this.client.createVersion(e,r)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,r){Dp(e.data.op,r,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}triggerReAuth(){this.client.reAuth()}}I("remote-cursor");class Q2{constructor(t){g(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});g(this,"broadcastCaretPos",Ke.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));g(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const r=this.editor.findBlockById(e);r&&this.editor.reloadBlock(r)})});this.editor=t,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const Y2=I("remote-cursor-decorator");class Up{decorateText(t,e,r){const i=t.doc.getRemoteUsers();if(!i)return{};const o=new Map,{containerId:s,blockIndex:l}=e[e.length-1];p(Y2,typeof s=="string","invalid path containerId"),p(Y2,typeof l=="number","invalid path blockIndex");const c=t.doc.getBlockData(s,l),d=un(r);return i.getSimpleCursors(c.id).forEach((C,E)=>{E>d&&(E=d);const x=C.map(k=>({id:Z(),type:"remote-cursor",name:k.user.displayName,time:k.time,rainbowIndex:k.user.rainbowIndex})),v=o.get(E);v?v.push(...x):o.set(E,x)}),{insertions:o}}}const Op=I("sharedb-doc/share-db-server"),AN=hb.default.create();class xN{constructor(t,e){g(this,"auth");g(this,"clientId",Z());this.serverUrl=e,this.auth=t}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return p(Op,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}apiServer(){const t=`${this.serverUrl}/${this.auth.appId}/${this.auth.docId}`;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}getBaseURL(){const t=new URL(this.apiServer());return`${t.protocol}//${t.host}${t.pathname}`}getBase64BaseURL(){return Hi(this.getBaseURL())}async request(t,e){var o;const r=this.auth.token,i=e||{};i.url=t,i.headers||(i.headers={}),p(Op,r,"no token"),i.headers={...i.headers,[Ra]:r,[Ru]:this.getBase64BaseURL()};try{return await AN(t,i)}catch(s){throw(o=s.response)!=null&&o.data&&(s.responseData=s.response.data),s}}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,i=(await this.request(e)).data.versions;return i.forEach(o=>{o.extra&&(o.extra=JSON.parse(o.extra))}),i}async getVersion(t){const r=`${this.apiServer()}/versions/${t}`,i=await this.request(r);return JSON.parse(i.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,r=await this.request(e);return JSON.parse(r.data.data)}async getVersionOps(t,e){let i=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(i+=`&from=${e}`);const o=await this.request(i),s=o.data.ops,l=mb.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let d;return c?(p(Op,c.create,"no createDoc.create"),d=c.create.data):d=JSON.parse(o.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:o.data.ops}}async updateVersionExtra(t,e,r){const o=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(o,{method:"post",data:{extra:JSON.stringify(r)}})}async revertVersion(t){const r=`${this.apiServer()}/versions/revert/${t}`;await this.request(r,{method:"post",data:{}})}async createVersion(t,e){const i=`${this.apiServer()}/versions`;return(await this.request(i,{method:"post",data:{publish:e,tag:t}})).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let i=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const o=[];if(e!=null&&e.withToken,e!=null&&e.downloadFileName&&o.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),o.length>0){const s=o.join("&");i+=`?${s}`}return i}}I("sharedb-doc/share-db-server");class J2 extends ra{constructor(e){super();g(this,"remoteUsers",new gu);g(this,"client");this.options=e,this.client=new xN(e.auth,e.serverUrl)}destroy(){}buildResourceUrl(e,r){return this.client.buildResourceUrl(e,r)}getRemoteUsers(){return this.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const r=await this.client.getVersion(e);return ro(r)}async getLatestVersion(){const e=await this.client.getLatestVersion();return ro(e)}async getHistoryData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r),s=o.map(l=>({user:l.meta.createdBy,data:l}));return{doc:ro(i),historyData:s}}async getVersionData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r);return{doc:ro(i),versionData:o}}async updateVersionExtra(e,r,i){await this.client.updateVersionExtra(e,r,i)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,r){return this.client.createVersion(e,r)}parseHistoryData(e,r){Dp(e.data.op,r,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}class Z2 extends ve.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,r){if(Qt(li(this.editor,t)))return;const i=this.editor.getBlockByIndex(t,e),o=nt(this.editor.getContainerById(t));o&&this.emit("change",this.editor,o,i,r)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function bN(n,t){n.addCustom("child-block-tracker",()=>new Z2(n)).addListener("change",t)}function vN(n,t){n.addCustom("child-block-tracker",()=>new Z2(n)).removeListener("change",t)}const uat="",BN={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",name:"\u6587\u672C\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},TN={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},yN={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};D.mergeLang({"zh-CN":BN,"en-US":TN,"ja-JP":yN});const fat="";I("button");function pr(n,t,e,r,i){const o=B("button",["editor-button"],null);return o.setAttribute("data-button-id",n),i&&o.setAttribute(`data-editor-tooltip-${i}`,t),e?typeof e=="string"?e.startsWith("<")?o.innerHTML=e:o.innerText=e:o.appendChild(e):o.innerText=t,r&&(r.indexOf("checked")!==-1&&z(o,"checked"),r.indexOf("disabled")!==-1&&(o.disabled=!0),r.indexOf("primary")!==-1&&z(o,"primary")),o}const dat="",$h=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
27
+ `)}const xM=I("get-text-position");function pa(n,t){const e=t!=null?t:n.selection.range.start;e instanceof _e||p(xM,!1,`invalid insert pos type: ${typeof e}`);const{blockId:r}=e,i=n.getBlockById(r),o=bt(i),s=it(i),l=ft(s),{offset:c}=e;return{block:i,container:s,containerId:l,blockIndex:o,offset:c}}const Ca=I("insert-text");function K1(n,t,e,r){var s;const i=n.doc.getBlockData(t,e);if(p(Ca,i,"no block data"),p(Ca,i.text,"no block text"),un(i.text)===0)return p(Ca,r===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,i.id);if(r===0)return;const o=qe(i.text,r-1,1).middle;if(!((s=o[0].attributes)!=null&&s.box))return o[0].attributes}function bM(n,t,e){const r=it(t),i=ft(r),o=bt(t);return K1(n,i,o,e)}function P5(n,t,e,r,i){const o=it(t),s=ft(o),l=bt(t),c=bM(n,t,e),d=sh(e,r,c!=null?c:null);return n.doc.localUpdateBlockText(s,l,d,i),bn(n,t)}function F5(n,t,e,r){const i=it(t),o=ft(i),s=bt(t),l=sh(e," ",r);return n.doc.localUpdateBlockText(o,s,l),bn(n,t)}function vM(n,t){let e=0;if(t===0)return!1;for(let r=0;r<n.length;r++){const i=n[r];p(Ca,typeof i.insert=="string","invalid text op, no insert");const o=e+Zd(i);if(o===t)return!1;if(o>t)return!0;e=o}return!1}function V1(n,t,e,r,i){const o=n.doc.getBlockData(e,r);p(Ca,o,"no block data"),p(Ca,o.text,"no block text");const s=K1(n,e,r,i);s&&Object.keys(s).includes("link")&&(vM(o.text,i)||delete s.link);const l=sh(i,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,r,l),bn(n,n.getBlockById(o.id))}function $1(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:r,offset:i}=pa(n);V1(n,t,e,r,i)}const Ch=I("update-composition-text");function K5(n){const t=n.selection.range.start;t instanceof _e||p(Ch,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,r=n.getBlockById(e);p(Ch,et(n,r),"not a text kind block");const i=it(r),o=ft(i),s=bt(r),l=n.doc.getBlockData(o,s);p(Ch,l,"no block data in doc"),p(Ch,l.text,"no text data in text block");const c=Ot(r);eh(n,Fo(r),e,c,l.text)}function H1(n){V8(n)}function Ea(n,t,e,r,i,o){return n.doc.localInsertBlock(t,e,r,i,o),n.getBlockById(r.id)}const lu=I("delete-block-text");function j1(n,t,e,r,i){if(!n.isBlockWritable(t))return lu.error("block is not writable"),0;p(lu,et(n,t),"block is not a text kind block");const o=it(t),s=ft(o),l=bt(t),c=n.doc.getBlockData(s,l);p(lu,c,"no block data in doc"),p(lu,c.text,"no text data in text block");let d=e;_n(t,e)||(d=Ho(t,d));let h=e+r;p(lu,h<=dt(n,t),`invalid offset and count: ${e}, ${r}`),_n(t,h)||(h=Xs(t,h));const C=h-d,E=r5(d,C);return n.doc.localUpdateBlockText(s,l,E,i),console.log("delete"),C}const z1=I("break-text-block");function V5(n,t){const r=n.getBlockData(t).quoted;return r?{quoted:r}:{}}function Aa(n,t,e,r){p(z1,et(n,t),`block is not a text kind block: ${It(t)}`),p(z1,e>=0&&e<=dt(n,t),`invalid offset: ${e}`);const i=it(t),o=ft(i),s=bt(t),l=r!=null&&r.copyBlockAttributes?V5(n,t):{};if(!(r!=null&&r.forceInsertAfter)&&(e===0||e===dt(n,t))){const x=e===0?s:s+1,v={...hi(""),...l,...r==null?void 0:r.newBlockData},k=Te(n,t.id,0),L=Ea(n,o,x,v,k);return{block:t,newBlock:L}}p(z1,_n(t,e),"not a valid offset");const c=bn(n,t),{right:d}=In(c,e),h=un(d);h>0&&j1(n,t,e,h);const C={...hi(d),...l,...r==null?void 0:r.newBlockData},E=Ea(n,o,s+1,C,Te(n,C.id,0));return{block:t,newBlock:E}}const BM=I("prepare-insert-new-block");function TM(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=Ce(d);return p(BM,e>=0&&e<=h.length,`invalid blockIndex: ${e}`),{containerId:t,blockIndex:e}}const r=n.selection.range.start;if(!r.isSimple())return null;const i=n.getBlockById(r.blockId);if(t=ft(it(i)),e=bt(i),!et(n,i))return{containerId:t,blockIndex:e+1};const s=r.offset;if(s===0||s===dt(n,i))return{containerId:t,blockIndex:s===0?e:e+1};const c=Aa(n,i,s).newBlock;return{containerId:t,blockIndex:bt(c)}}const yM=I("auto-insert-block");function $5(n,t,e,r,i,o){const s=TM(n,e,r);p(yM,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},c={anchor:l,focus:l};return Ea(n,s.containerId,s.blockIndex,t,i!=null?i:c,o)}const RM=I("delete-block");function Eh(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(r=>{n.getChildContainerData(r).forEach(o=>{Eh(n,o,e)})}))}function Ah(n,t,e){const r=it(t),i=ft(r),o=bt(t),s=n.doc.getBlockData(i,o);return p(RM,s,"no block data in doc"),n.doc.localDeleteBlock(i,o,We(n,{anchor:e.start,focus:e.end})),s}function G1(n,t,e){return n.undoManager.runInGroup(()=>{const r=it(t);Sr(r)===1&&n.insertTextBlock("",ft(r),0);let i=e?Ko(n,e):null;if(!i){const l=n.selection.range;_5(t,l)?i=M5(n,t):i=l}const o=Ah(n,t,i),s=[];return Eh(n,o,s),s.length>0&&n.doc.localDeleteChildContainers(s),o})}function kM(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(i=>{Eh(n,i,e)}),n.doc.localDeleteChildContainers(e)}function H5(n,t){const e=[...t];t.forEach(r=>{n.doc.getContainerBlocks(r).forEach(o=>{Eh(n,o,e)})}),n.doc.localDeleteChildContainers(e)}const W1=I("merge-text-block");function j5(n,t,e){p(W1,et(n,t),"only text block can be merged"),p(W1,et(n,e),"only text block can be merged");const r=jo(n,t),i=jo(n,e),o=r.text,s=i.text;p(W1,o&&s,"block data has no text");const l=it(t),c=ft(l),d=bt(t),h=dt(n,t),C=V1(n,s,c,d,h),E=Te(n,t,un(o));return G1(n,e,E),C}const mi=I("clear-selected-contents");function xh(n,t){p(mi,et(n,t.block),"not a text kind block");const{start:e,end:r}=t;p(mi,e.isSimple(),"not a simple block position"),p(mi,r.isSimple(),"not a simple block position");const i=e.offset,o=r.offset;p(mi,i<=o,`invalid delete text offset: ${i}, ${o}`),i!==o&&n.deleteTextFromBlock(t.block,i,o-i)}function z5(n,t,e){const r=ft(t),i=Ce(t),o=e.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",r,0,{newRange:o});e.focus&&n.selection.selectBlock(s,0),i.reverse().forEach(l=>{n.deleteBlock(l)})}function wM(n,t){const{block:e,start:r,end:i}=t;if(et(n,e)){xh(n,t);return}if(we(e)||r.isSimple()){p(mi,i.isSimple(),"invalid range");const s=it(e),l=bt(e),c=n.insertTextBlock("",ft(s),l);n.selection.selectBlock(c,0),n.deleteBlock(e);return}p(mi,_t(n,e),"invalid block kind"),p(mi,!r.isSimple()&&!i.isSimple(),"invalid range"),ca(n,e,r,i),n.selection.range.getSelectedContainers().forEach((s,l)=>{z5(n,s,{focus:l===0})})}function SM(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(p(mi,e.length>0,"no selected block"),e.length===1){wM(n,e[0]);return}const r=e[0],i=r.block,o=it(i);p(mi,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(et(n,i)){xh(n,r);const h=Te(n,r.block,r.start.offset);if(e.slice(1,e.length-1).reverse().forEach(E=>n.deleteBlock(E.block)),et(n,l)){xh(n,s),n.mergeTextBlock(i,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(et(n,l)){xh(n,s),e.slice(0,e.length-1).reverse().forEach(h=>n.deleteBlock(h.block)),n.selection.selectBlock(s.block,0);return}if(e.length===Sr(o)){z5(n,o,{focus:!0});return}const c=me(i),d=Gt(l);p(mi,c||d,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function q1(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),SM(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const LM=I("core");function G5(n,t,e){const r=it(t),i=ft(r),o=bt(t);return n.doc.localUpdateBlockText(i,o,e),setTimeout(()=>{n.selection.updateSelection(null)}),bn(n,t)}function W5(n,t,e){if(!n.isBlockWritable(t)){LM.error("block is not writable");return}const r=n.getBlockText(t),i=fn.diff(r,e);G5(n,t,i)}function bh(n,t,e){const r=bn(n,t),i=typeof e=="string"?Ys(e):e,o=fn.diff(r,i);return G5(n,t,o)}const au=I("update-block-data");function vh(n,t,e,r){const i=it(t),o=ft(i),s=bt(t),l=n.doc.getBlockData(o,s),c={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(e));return d.forEach(E=>{if(!h.has(E)){if(E==="id"||E==="type"||E==="text")return;au.debug(`delete key: ${E}`),c.delete.push(E)}}),Object.entries(e).forEach(([E,x])=>{p(au,E!=="id"&&E!=="type",`invalid block data delta, ${E}`);const v=l[E];if(x==null){v!=null&&(au.debug(`delete key: ${E}`),c.delete.push(E));return}v!==x&&(Nc.default(v,x)||E==="text"&&fn.diff(v,x).length===0||(d.has(E)?(au.debug(`replace key: ${E}`),c.delete.push(E)):au.debug(`insert key: ${E}`),c.insert[E]=x))}),n.doc.localUpdateBlockData(o,s,c,r),jo(n,t)}function q5(n,t,e,r){const o={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,o,r)}function X1(n,t,e){if(!_t(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const i=qn(n,t).getChildContainers(n,t)[0],o=ke(i);X1(n,o,e)}function Zs(n){const t=[];let e={};return n.forEach(r=>{t.push(...r.blocks.root);const{root:i,...o}=r.blocks;e={...e,...o}}),{blocks:{...e,root:t},meta:{},comments:{}}}const cu=I("clone-block");function zo(n,t,e,r){const i=n.getBlockClass(e.type);if(i.blockToDoc)return i.blockToDoc(t,e,(h,C)=>(p(cu,e!==C,"invalid child block"),zo(n,h,e,r)));let o={};const s=new Map,l=gt.default(e);l.children&&(l.children=l.children.map(h=>{const C=Z(),E=t.blocks[h];p(cu,Array.isArray(E),"invalid child blocks");const x=E.map(M=>zo(n,t,M,r)),v=Zs(x),{root:k,...L}=v.blocks;return o={...o,...L},o[C]=v.blocks.root,s.set(h,C),C}));const c=Array.from(s.entries()),d=h=>{for(const C of c){const[E,x]=C;{const v=`${E}/`;if(h.startsWith(v)){const k=h.substring(v.length),L=`${x}/${k}`;return cu.debug(`replace key: ${h} -> ${L}`),L}}{const v=`${E}_`;if(h.startsWith(v)){const k=h.substring(v.length),L=`${x}_${k}`;return cu.debug(`replace key: ${h} -> ${L}`),L}}}return h};return Array.from(Object.entries(l)).forEach(([h,C])=>{const E=d(h);E!==h&&delete l.key,l[E]=C}),l.id=Z(),r&&(r.blockIdMap.set(e.id,l.id),s.forEach((h,C)=>r.containerIdMap.set(C,h))),{blocks:{root:[l],...o},meta:{},comments:{}}}function Q1(n,t,e,r){const i=t.blocks[e];p(cu,Array.isArray(i),"invalid child blocks");const o=i.map(l=>zo(n,t,l,r));return Zs(o)}function Y1(n,t,e){const r=t.blocks.root.map(i=>zo(n.editorBlocks,t,i,e));return gt.default(Zs(r))}const X5=I("insert-doc");function Q5(n,t,e,r,i){if(_t(n,t)){X5.warn("failed to insert doc into a complex block");return}const o=Y1(n,r,i),s=it(t),l=bt(t),c=ft(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var F,G,W,rt;const d=[];Object.entries(o.blocks).forEach(([at,At])=>{at!=="root"&&d.push({containerId:at,blocks:At})}),d.length>0&&n.doc.localInsertChildContainers(d);const h=o.blocks.root;if(we(t)){n.deleteBlock(t);let at;h.reverse().forEach(At=>{const Mt=n.insertBlock(c,l,At,void 0,{noFocus:!0});at||(at=Mt)}),at&&n.selection.selectBlock(at,dt(n,at));return}if(p(X5,et(n,t),"not a text block"),ce(n,t)){const at=bt(t);let At,Mt=!1;for(let Bt=0;Bt<h.length;Bt++){if(Bt===0){const ne=n.getBlockByIndex(c,at),Tn=h[Bt].type==="text"||h[Bt].type==="list",xe=ne&&It(ne)===h[Bt].type;if(ne&&et(n,ne)&&ce(n,ne)&&Tn&&xe){n.insertTextToBlock(t,0,(F=h[Bt].text)!=null?F:[]),Object.keys(h[Bt]).length>3&&n.updateBlockData(ne,N8(h[Bt],["id","text","type","heading","quoted"]));continue}zi(ne)&&(Mt=!0)}const se=n.insertBlock(c,at+Bt,h[Bt],void 0,{noFocus:!0});Bt===h.length-1&&(At=se)}At&&n.selection.selectBlock(At,dt(n,At)),Mt&&n.deleteBlock(t);return}if(h.length===1){const at=h[0];if(Gc(n,at.type)){n.insertTextToBlock(t,e,(G=at.text)!=null?G:[]);return}n.breakTextBlock(t,e),n.insertBlock(c,l+1,at);return}const C=e===dt(n,t),E=e===0,x=h[0],v=h[h.length-1];let k;!C&&!E?k=n.breakTextBlock(t,e,{forceInsertAfter:!0}):k=t;const L=E?l:l+1;C?(k=n.insertBlock(c,l+1,v),n.selection.selectBlock(k,dt(n,k))):(n.selection.selectBlock(k,0),Gc(n,v.type)?n.insertTextToBlock(k,0,(W=v.text)!=null?W:[]):n.insertBlock(c,L,v));const M=n.selection.range;let U=L;Gc(n,x.type)?E?(n.insertBlock(c,L,x),U+=1):n.insertTextToBlock(t,e,(rt=x.text)!=null?rt:[]):(n.insertBlock(c,L,x),U+=1),h.slice(1,h.length-1).reverse().forEach(at=>{n.insertBlock(c,U,at)}),n.selection.setRange(M)}),n.doc.endBatchUpdate()}function J1(n,t,e,r,i){const o=Y1(n,r,i),s=ft(t),l=[];return n.undoManager.runInGroup(()=>{const c=[];Object.entries(o.blocks).forEach(([h,C])=>{h!=="root"&&c.push({containerId:h,blocks:C})}),n.doc.localInsertChildContainers(c),o.blocks.root.reverse().forEach(h=>{const C=n.insertBlock(s,e,h,void 0,{noFocus:!0,noScroll:!0});l.push(C)})}),l}function Y5(n,t,e,r){const i=Sr(t);J1(n,t,i,e,r);for(let o=0;o<i;o++){const s=ke(t);n.deleteBlock(s)}}const uu=I("add-text-attribute");function IM(n,t,e,r){const{start:i,end:o}=e;p(uu,i.blockId===o.blockId&&i.blockId===st(t),"invalid range"),p(uu,r,"invalid attribute name");const s=n.getBlockText(t),l=ha(i.offset,o.offset-i.offset,s,r,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function J5(n,t,e,r,i){const{start:o,end:s}=e;p(uu,o.blockId===s.blockId&&o.blockId===st(t),"invalid range"),p(uu,r,"invalid attribute name");const l=n.getBlockText(t),c=nu(o.offset,s.offset-o.offset,l,r,i);return n.setBlockText(t,c),c}function xa(n,t,e,r,i){const{start:o,end:s}=e;p(uu,o.blockId===s.blockId&&o.blockId===st(t),"invalid range");const l=n.getBlockText(t),c=j3(o.offset,s.offset-o.offset,l,r,i);return n.setBlockText(t,c),c}function Z5(n,t,e,r){const i=ui(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{i.forEach(o=>{const{block:s,start:l,end:c}=o;if(!et(n,s))return;if(ce(n,s)){r(n,st(s),t,e);return}const d=We(n,{anchor:l,focus:c});t==="color"||t==="backgroundColor"?xa(n,s,d,t,e):(xa(n,s,d,"color",null),xa(n,s,d,"backgroundColor",null))})})}function tB(n,t,e){const r=ui(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:o,start:s,end:l}=i;if(!et(n,o))return;if(ce(n,o)){(t==="clearColor"||t==="clearAll")&&e(n,st(o),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,st(o),"backgroundColor",null);return}const c=We(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&xa(n,o,c,"color",null),(t==="clearBackground"||t==="clearAll")&&xa(n,o,c,"backgroundColor",null)})})}function eB(n,t,e){const r=t.getSelectedBlocks().filter(l=>et(n,l.block));if(r.length===0)return[null,null];const i=l=>{if(dt(n,l.block)===0)return e(n,st(l.block));const c=l.start,d=l.end,h=n.getBlockText(l.block);return W3(c.offset,d.offset-c.offset,h)};let[o,s]=i(r[0]);return o===null&&s===null?[o,s]:(r.forEach(l=>{const[c,d]=i(l);c===null||o===null?o=null:o=c===o?o:null,d===null||s===null?s=null:s=d===s?s:null}),[o,s])}const Qn=I("adjust-selection-pos");function nB(n){const t=[];for(;n;){const e=it(n);if(t.unshift(e),Qt(e))return t;const r=nt(e);p(Qn,r,"child container has not parent container"),n=r}p(Qn,!1,"should not come here: getParentContainers")}function rB(n,t){for(;t;){const e=it(t);if(e===n)return t;const r=nt(e);p(Qn,r,"could not find parent block for a child container"),t=r}p(Qn,!1,"no parent block in specified container")}function DM(n,t){const e=nB(n),r=nB(t);p(Qn,e.length>0&&r.length>0,"block has not parent container"),p(Qn,e[0]===r[0],"root container does not equal");let i=e[0];for(let l=1;l<e.length||r.length;l++)if(e[l]!==r[l]){i=e[l-1];break}const o=rB(i,n),s=rB(i,t);return{parentContainer:i,newBlock1:o,newBlock2:s}}function iB(n,t){let e=nt(t);for(p(Qn,e,"element is not in a block");e;){const r=it(e);p(Qn,_r(r),"not a child container");const i=nt(r);if(p(Qn,i,"child container has not parent block"),i===n)return r;e=i}p(Qn,!1,"failed to find parent container in complex block")}function Bh(n,t,e){const r=n.getBlockById(t.blockId),i=n.getBlockById(e.blockId);if(r===i)return t instanceof _e&&e instanceof _e?{anchor:t,focus:e}:t instanceof Mr&&e instanceof Mr?Gd(n,r,t,e):null;const o=it(r),s=it(i);if(o===s)return t instanceof Mr&&(t=lt(r,0,"home")),e instanceof Mr&&(e=lt(i,dt(n,i),"end")),p(Qn,t instanceof _e,"not valid position type"),p(Qn,e instanceof _e,"not valid position type"),{anchor:t,focus:e};if(r.contains(s))return null;if(i.contains(o)){if(t instanceof _e&&e instanceof Mr){const v=n.getContainerById(e.childContainerId);if(v===o)return{anchor:e,focus:e};const k=nt(o);if(k&&k===nt(v)){const L=Ee(k,ft(o)),M=Ee(k,ft(v));return Gd(n,k,L,M)}}return null}const l=yd(r,i)>0,{newBlock1:c,newBlock2:d}=DM(r,i);if(c===d){const v=c,k=iB(v,r),L=iB(v,i);return t=Ee(c,ft(k)),e=Ee(c,ft(L)),Qn.debug(`select in complex block: ${k.id}, ${L.id}`),Gd(n,v,t,e)}let h=l?dt(n,c):0;c===r&&t instanceof _e&&(h=t.offset);let E=l?0:dt(n,d);return d===i&&e instanceof _e&&(E=e.offset),t=lt(c,h,l?"end":"home"),e=lt(d,E,l?"home":"end"),{anchor:t,focus:e}}const _M=I("move-complex-block-position");function MM(n,t,e){const r=n.getBlockById(t.blockId);p(_M,_t(n,r),"is not a complex block");const i=qn(n,r),o=n.getContainerById(t.childContainerId),s=i.getNextContainer(n,r,o,e,{noWrap:!0});return s?Ee(r,ft(s)):null}const fu=I("move-simple-block-position");function oB(n,t){const e=xn(n,t,{visibleOnly:!0});p(fu,e.length>0,"complex block has not any child container");const r=e[0];return ke(r)}function sB(n,t){const e=xn(n,t,{visibleOnly:!0});p(fu,e.length>0,"complex block has not any child container");const r=e[e.length-1];return Je(r)}function lB(n,t,e){const r=e?oB(n,t):sB(n,t);return _t(n,r)?lB(n,r,e):r}function UM(n,t){const e=n.getBlockById(t.blockId);return _t(n,e)&&t.offset===0?oB(n,e):$s(e)}function OM(n,t){const e=n.getBlockById(t.blockId);return _t(n,e)&&t.offset===1?sB(n,e):Vs(e)}function Z1(n){return n==="ArrowLeft"||n==="ArrowUp"}function tp(n,t,e){const r=it(t);if(Qt(r))return null;const i=nt(r);p(fu,i,"child container has not parent block"),p(fu,_t(n,i),"is not a complex block");const o=qn(n,i).getNextContainer(n,i,r,e);return o?Z1(e)?Je(o):ke(o):tp(n,i,e)}function NM(n,t,e){const r=it(t);if(Qt(r))return null;const i=nt(r);if(p(fu,i,"child container has not parent block"),Z1(e)){const l=me(i);if(l)return l}else{const l=Gt(i);if(l)return l}const o=tp(n,i,e);if(o)return o;let s=i;for(;!Qt(it(s));)s=nt(it(s));return Z1(e)?me(s):Gt(s)}function PM(n,t,e){return!_t(n,t)||qn(n,t).enableKeyboardSelect?t:lB(n,t,e==="ArrowDown"||e==="ArrowRight")}function FM(n,t,e){const r=n.getBlockById(t.blockId),o=Jt(n,r).moveCaret(n,r,t,e);if(o)return o;let s=e==="ArrowDown"||e==="ArrowRight"?UM(n,t):OM(n,t);if(s||(s=tp(n,r,e),s||(s=NM(n,r,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Qt(it(r)))return null;const l=n.insertTextBlock("",ft(n.rootContainer),Sr(n.rootContainer));return lt(l,0,"home")}return null}if(s=PM(n,s,e),et(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return u_(n,s,r,t,l);if(e==="ArrowUp")return c_(n,s,r,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?lt(s,dt(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?lt(s,0,"home"):null}function KM(n,t,e){if(t==="ArrowLeft")return e.start;const r=e.end,i=n.getBlockById(r.blockId);if(et(n,i))return r;const o=Gt(i);if(o)return lt(o,0,"home");if(!Qt(it(i))||n.readonly)return r;const s=n.insertTextBlock("",ft(n.rootContainer),Sr(n.rootContainer));return lt(s,0,"home")}function VM(n,t,e){const r=n.selection.range;let i;if(r instanceof Ge)e==="move"&&!r.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?i=KM(n,t,r):i=FM(n,r.getFocusedPos(),t);else if(i=MM(n,r.focus,t),e==="move"){const o=i!=null?i:r.focus,s=n.getContainerById(o.childContainerId);if(t==="ArrowLeft"||t==="ArrowUp"){const l=Je(s);i=lt(l,0,"home")}else{const l=ke(s);i=lt(l,dt(n,l),"end")}}return i?e==="move"?{anchor:i,focus:i}:Bh(n,r.anchor,i):null}function Go(n,t,e){const r=VM(n,t,e);if(!r)return!1;const{anchor:i,focus:o}=r;return n.selection.setSelection(i,o),(t==="ArrowLeft"||t==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function aB(n){return Go(n,"ArrowLeft","move"),!0}function cB(n){return Go(n,"ArrowRight","move"),!0}function uB(n){return Go(n,"ArrowUp","move"),!0}function fB(n){if(Go(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=it(t);if(Qt(e)||Je(e)!==t)return!0;const r=n.rootContainer;return n.insertTextBlock("",ft(r),Sr(r)),!0}function dB(n){return Go(n,"ArrowDown","select"),!0}function hB(n){return Go(n,"ArrowLeft","select"),!0}function mB(n){return Go(n,"ArrowRight","select"),!0}function gB(n){return Go(n,"ArrowUp","select"),!0}const pB=I("word-offset");function ep(n,t){const e=n.selection.range.focus;p(pB,e.isSimple(),"invalid range type");const r=n.getBlockById(e.blockId);if(ce(n,r))return lt(r,0,"home");if(e.offset===0||!et(n,r)){const s=me(r);if(!s)return null;const l=lt(s,dt(n,s),"end");if(t==="select"&&et(n,s)){const c=_1(n,s,l.offset);return lt(s,c,"normal")}return l}const i=_1(n,r,e.offset);return lt(r,i,"normal")}function np(n,t){const e=n.selection.range.focus;p(pB,e.isSimple(),"invalid range type");const r=n.getBlockById(e.blockId);if(ce(n,r))return lt(r,0,"end");if(e.offset===dt(n,r)||!et(n,r)){const s=Gt(r);if(!s)return null;const l=lt(s,0,"home");if(t==="select"&&et(n,s)){const c=M1(n,s,l.offset);return lt(s,c,"end")}return l}const i=M1(n,r,e.offset);return lt(r,i,"normal")}function CB(n){if(!n.selection.range.focus.isSimple())return!1;const e=ep(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function EB(n){if(!n.selection.range.focus.isSimple())return!1;const e=np(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function AB(n){if(!n.selection.range.focus.isSimple())return!1;const e=ep(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function xB(n){if(!n.selection.range.focus.isSimple())return!1;const e=np(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}I("find-block");function rp(n,t){if(!_t(n,t))return t;const r=qn(n,t).getChildContainers(n,t)[0],o=Ce(r)[0];return rp(n,o)}function ip(n,t){if(!_t(n,t))return t;const e=qn(n,t).getChildContainers(n,t),r=e[e.length-1],i=Ce(r),o=i[i.length-1];return ip(n,o)}function op(n){const t=ip(n,Je(n.rootContainer)),e=lt(t,dt(n,t),"end");return n.selection.setSelection(e),!0}function bB(n){const t=rp(n,n.getFirstBlock()),e=lt(t,0,"home");return n.selection.setSelection(e),!0}function vB(n){const t=rp(n,n.getFirstBlock()),e=lt(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function sp(n){const t=ip(n,Je(n.rootContainer)),e=lt(t,dt(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const BB=I("line-offset");function TB(n){const t=n.selection.range.focus;p(BB,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!et(n,e))return lt(e,0,"home");let i=J3(e,t).start;const{next:o}=$d(e,i);return o&&dr(o)&&qc(o)==="br"&&(i+=1),lt(e,i,"home")}function yB(n){const t=n.selection.range.focus;p(BB,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===dt(n,e)||!et(n,e))return lt(e,dt(n,e),"end");const r=J3(e,t);return lt(e,r.end,"end")}function RB(n){if(!n.selection.range.focus.isSimple())return!1;const e=TB(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function kB(n){if(!n.selection.range.focus.isSimple())return!1;const e=yB(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function wB(n){if(!n.selection.range.focus.isSimple())return!1;const e=TB(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function SB(n){if(!n.selection.range.focus.isSimple())return!1;const e=yB(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const LB=I("find-block-position");function $M(n,t,e,r){p(LB,_t(n,t),"is not a complex block");const i=qn(n,t).getChildContainers(n,t);p(LB,i.length>0,"complex block has not any child container");const o=Dr(n,e,r),s=o.left+o.width/2,l=o.top+o.height/2,c=t3(n,t,s,l);return lp(n,c,e,r)}function lp(n,t,e,r){if(_t(n,t))return $M(n,t,e,r);const i=st(t);let o=Number.MAX_SAFE_INTEGER;const s=Dr(n,e,r),l=s.left+s.width/2,c=s.top+s.height/2;let d=lt(i,0,"home");const h=dt(n,t);for(let C=0;C<=h;C++){const E=lt(i,C,"normal"),x=Dr(n,t,E),v=Ki(x,l,c);v<o&&(o=v,d=E)}return d}const IB=I("page-offset");function HM(n,t){const e=S5(n)*.9,i=t.getBoundingClientRect().bottom-e;if(i<dM(n))return n.getFirstBlock();const o=me(t);if(!o)return n.getFirstBlock();let s=o;for(;s;){if(s.getBoundingClientRect().y<i)return s;s=me(s)}return n.getFirstBlock()}function jM(n,t){const e=S5(n)*.9,r=t.getBoundingClientRect(),i=hM(n),o=r.top+e;if(o>i)return n.getLastBlock();const s=Gt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>o)return l;l=Gt(l)}return n.getLastBlock()}function DB(n){const t=n.selection.range.focus;p(IB,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),r=HM(n,e);let i;return r===n.getFirstBlock()?i=lt(r,0,"home"):i=lp(n,r,e,t),i}function _B(n){const t=n.selection.range.focus;p(IB,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),r=jM(n,e);let i;return r===n.getLastBlock()?i=lt(r,dt(n,r),"end"):i=lp(n,r,e,t),i}function MB(n){if(!n.selection.range.focus.isSimple())return!1;const e=DB(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function UB(n){if(!n.selection.range.focus.isSimple())return!1;const e=_B(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function OB(n){if(!n.selection.range.focus.isSimple())return!1;const e=DB(n);if(!e)return!1;const r=Bh(n,n.selection.getAnchorPos(),e);if(!r)return!1;const{anchor:i,focus:o}=r;return n.selection.setSelection(i,o),n.selection.updateLastCaretRect(),!0}function NB(n){if(!n.selection.range.focus.isSimple())return!1;const e=_B(n);if(!e)return!1;const r=Bh(n,n.selection.getAnchorPos(),e);if(!r)return!1;const{anchor:i,focus:o}=r;return n.selection.setSelection(i,o),n.selection.updateLastCaretRect(),!0}const du=I("select-all");function PB(n,t){const e=ke(n),r=Je(n);return t.start.offset===0&&t.start.blockId===st(e)&&t.end.offset===dt(t.getEditor(),r)&&t.end.blockId===st(r)}function zM(n,t){const e=t.getEditor(),r=qn(e,n).getChildContainers(e,n),i=r[0],o=r[r.length-1],s=st(n);return t.start.blockId===s&&t.start.childContainerId===ft(i)&&t.end.blockId===s&&t.end.childContainerId===ft(o)}function GM(n,t){p(du,t,"no parent block"),p(du,_t(n,t),"not a complex block");const e=qn(n,t).getChildContainers(n,t),r=e[0],i=e[e.length-1];n.selection.setRange(We(n,{anchor:Ee(t,ft(r)),focus:Ee(t,ft(i))}))}function FB(n,t){const e=it(t);ap(n,e)}function KB(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&et(n,t)){const i=e.start,o=e.end,s=dt(n,t);if(i.offset>0||o.offset<s)return n.selection.selectBlock(t,0,s),!1}return z(n.rootContainer,"select-all"),FB(n,ke(n.rootContainer)),!1}return p(du,!e.isSimple(),"invalid range type"),zM(t,e)?(FB(n,t),!1):(p(du,t,"no parent block"),p(du,_t(n,t),"not a complex block"),GM(n,t),!0)}function ap(n,t){const e=Ce(t),r=e[0],i=e[e.length-1],o=lt(r,0,"home"),s=lt(i,dt(n,i),"end");n.selection.setSelection(o,s,{noScroll:!0})}function WM(n){sp(n),n.focus()}const cp=I("selected-block-to-doc");function VB(n,t,e){!t.children||t.children.forEach(r=>{const i=n.getChildContainerData(r);i.forEach(o=>{VB(n,o,e)}),e.blocks[r]=gt.default(i)})}function Th(n,t){const e=Jt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const r=gt.default(jo(n,t.block));if(et(n,t.block)){const o=t.start,s=t.end;if(p(cp,r.text,"no block text"),o.offset===s.offset)return{blocks:{root:[{...r,text:[]}]},meta:{},comments:{}};const{middle:l}=qe(r.text,o.offset,s.offset-o.offset);return{blocks:{root:[{...r,text:l}]},meta:{},comments:{}}}if(we(t.block))return{blocks:{root:[r]},meta:{},comments:{}};p(cp,_t(n,t.block),"not complex block"),p(cp,r.children,"no children");const i={blocks:{root:[r]},meta:{},comments:{}};return VB(n,r,i),i}function up(n,t){const e=lt(t,0,"normal"),r=lt(t,dt(n,t),"end");return Th(n,{block:t,start:e,end:r})}const qM=I("block-to-doc");function XM(n,t){p(qM,t.length>0,"invalid params, no blocks");const e=t.map(r=>up(n,r));return Zs(e)}function yh(n){const e=n.selection.range.getSelectedBlocks().map(r=>Th(n,r));return Zs(e)}function $B(n,t){const e=n.getContainerById(t),o=Ce(e).map(s=>({start:lt(s,0,"home"),end:lt(s,dt(n,s),"end"),block:s})).map(s=>Th(n,s));return Zs(o)}const Rh=I("editor-selection");class QM{constructor(t){g(this,"editor");g(this,"caret");g(this,"_range");g(this,"lastCaretRect");g(this,"handleBlockDelete",(t,e,r,i)=>{if(r||i.child)return;const o=this.range;if(_5(e,o)){Rh.debug("adjust selection because remote deleted current block");const s=M5(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),r=st(e);this.caret=new cM(t);const i=lt(r,0,"normal");this._range=We(t,{anchor:i,focus:i}),this.lastCaretRect=null,this.editor.addListener("blockDeleted",this.handleBlockDelete),setTimeout(()=>{this.updateFocusedBlock(null)})}destroy(){this.caret.destroy()}get range(){return this._range}get focusedBlock(){return this.getFocusedBlock()}get startBlock(){return this.getStartBlock()}get endBlock(){return this.getEndBlock()}getFocusedBlock(){const t=this.range.focus;return this.editor.getBlockById(t.blockId)}getStartBlock(){const t=this.range.start;return this.editor.getBlockById(t.blockId)}getEndBlock(){const t=this.range.end;return this.editor.getBlockById(t.blockId)}selectBlock(t,e,r){const i=lt(t,e,"normal");let o;r&&(o=lt(t,r,"normal")),this.setSelection(i,o)}setSelection(t,e,r){if(e||(e=t),this.verifyPos(t),this.verifyPos(e),!this.selectionChanging(t,e))return this.range;const i=We(this.editor,{anchor:t,focus:e});if(this.range.isEqual(i))return this.range;const o=this._range;return this._range=i,this.selectionChanged(),this.updateFocusedBlock(o),kt(this.editor.rootContainer,"select-all")&&(!i.isSimple()||!CM(this.editor,i))&&ot(this.editor.rootContainer,"select-all"),r!=null&&r.noScroll||this.scrollIntoView(),this.range}setRange(t,e){return this.setSelection(t.anchor,t.focus,e)}updateSelection(){this.caret.update(),uM(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(t,e){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const t=this.range.focus;if(!ai(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Dr(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){pM(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=dt(this.editor,e)||p(Rh,!1,"invalid block position, out of range");else{const r=t.childContainerId;!!this.editor.getContainerById(r)||p(Rh,!1,"invalid complex block position, no container found")}}updateFocusedBlock(t){if(t&&this.range.start.blockId===t.start.blockId)return;let e;t&&t.start.blockId===t.end.blockId&&(e=this.editor.findBlockById(t.start.blockId));let r;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(r=this.editor.getBlockById(this.range.start.blockId));let i=!1;e&&kt(e,"focused")&&(ot(e,"focused"),i=!0),this.removeAllBlockFocusedClass(),r&&this.setBlockFocused(r)&&(i=!0),i&&this.editor.emit("focusBlockChanged",this.editor,r!=null?r:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(t){const e=yh(this.editor);return t==="text"?Js(this.editor,e):t==="markdown"?N5(this.editor,e):O5(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{ot(t,"focused"),ot(t,"child-focused")})}setBlockFocused(t){if(kt(t,"focused"))return!1;z(t,"focused");let e=it(t);for(;_r(e);){const r=nt(e);p(Rh,r,"parent block not found"),z(r,"child-focused"),e=it(r)}return!0}}function YM(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);!e||n.selection.selectBlock(e,0,dt(n,e))}function JM(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!et(n,e))return;let r=ep(n,"select"),i=np(n,"select");if(!r||!i)return;const o=t.blockId;r.blockId!==o&&(r=lt(e,0,"home")),i.blockId!==o&&(i=lt(e,dt(n,e),"end")),n.selection.setSelection(r,i)}class ZM{constructor(t){g(this,"editor");g(this,"startPos",null);g(this,"lastCaretRect");g(this,"mouseDownEvent",null);g(this,"autoScroll",null);g(this,"handleMouseDown",(t,e)=>{var i;this.mouseDownEvent=t;const r=r3(this.editor,t.x,t.y);if(r){if(r instanceof ci)return;if(!this.autoScroll&&e.autoScroll){const s=r.getSelectedBlocks(),l=an(s[0].block);this.autoScroll=new Ud({scrollElement:l,edge:{top:50,bottom:50}})}const o=this.editor.selection.range;if(t.shiftKey&&o.isSimple()){const s=o.anchor;this.editor.selection.setSelection(s,r.focus),this.startPos=r.start}else this.editor.selection.setSelection(r.anchor,r.focus),this.startPos=r.start;this.editor.selection.updateLastCaretRect(),e.autoScroll&&((i=this.autoScroll)==null||i.active())}});g(this,"handleMouseMove",t=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-t.x)<3&&Math.abs(this.mouseDownEvent.y-t.y)<3)return;const e=Wd(this.editor,t.x,t.y);if(!e)return;const r=Bh(this.editor,this.startPos,e.end);if(!r)return;const{anchor:i,focus:o}=r;this.editor.selection.setSelection(i,o)});g(this,"handleMouseUp",t=>{var e;(e=this.autoScroll)==null||e.inactive(),this.startPos=null});this.editor=t,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(t){JM(this.editor)}handleTripleClick(t){YM(this.editor)}}function tU(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function eU(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const HB=I("delete-text");function jB(n,t,e,r){const i=r!=null?r:n.selection.range.start;i instanceof _e||p(HB,!1,`invalid insert pos type: ${typeof i}`);const{blockId:o}=i,s=n.getBlockById(o);p(HB,et(n,s),"block is not a text kind block");let{offset:l}=i;if(t==="backward"){if(l-e<0)return 0;if(!_n(s,l-e)){const c=Ho(s,l);e=l-c}}else if(t==="forward"&&l+e>dt(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function zB(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const nU=I("handle-backspace");function fp(n,t){if(!ce(n,t))return;const e=it(t);Sr(e)!==1&&n.deleteBlock(t)}function rU(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,r=n.getBlockById(e.blockId);if(et(n,r))if(e.offset===0){if(zB(n,r))return;const i=me(r);if(i){if(!n.isBlockWritable(i))return;if(et(n,i))n.mergeTextBlock(i,r,{focus:!0});else if(_t(n,i)){fp(n,r);const o=ua(n,i);o?n.selection.selectBlock(o,dt(n,o)):n.selection.selectBlock(i,0,dt(n,i))}else fp(n,r),p(nU,we(i),"prev block is not embed block"),n.selection.selectBlock(i,1)}else{const o=it(r);if(_r(o)){const s=Yv(n,o);if(s){if(!n.isBlockWritable(s))return;fp(n,r),n.selection.selectBlock(s,dt(n,s))}}}}else jB(n,"backward",1,null),n.selection.updateLastCaretRect();else{const i=bt(r),o=it(r);n.insertTextBlock("",ft(o),i),n.deleteBlock(r)}}function iU(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,r=n.getBlockById(e.blockId);if(et(n,r))if(e.offset===dt(n,r)){const i=Gt(r);if(i){if(!n.isBlockWritable(i))return;et(n,i)?n.mergeTextBlock(r,i,{focus:!0}):ce(n,r)?n.deleteBlock(r,Te(n,i,0)):n.deleteBlock(i)}}else jB(n,"forward",1,null);else{const i=bt(r),o=it(r);n.insertTextBlock("",ft(o),i),n.deleteBlock(r)}}function oU(n){const{range:t}=n.selection,{start:e,end:r}=t,i=n.getBlockById(e.blockId),o=n.getBlockById(r.blockId);if(i!==o||!_t(n,i))return!1;if(ai(e))return!0;const s=ca(n,i,e,r),l=xn(n,i);return s.length===l.length}function sU(n,t){if(oU(n)){const s=n.getFocusedBlock(),l=bt(s),c=ft(it(s));n.insertTextBlock("",c,l+1);return}const e=n.getFocusedBlock(),{start:r,end:i}=n.selection.range,o=r.blockId===i.blockId&&we(e);if(!n.selection.range.isCollapsed()&&!o&&n.clearSelectedContents(),et(n,e)){if(ce(n,e)&&zB(n,e))return;const s=n.selection.range.start,l=n.breakTextBlock(e,s.offset,{copyBlockAttributes:!0});s.offset!==0?n.selection.selectBlock(l,0):n.selection.scrollIntoView()}else{const s=n.insertTextBlock();n.selection.selectBlock(s,0)}}function lU(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:r}=e;if(!et(n,r))return!1;const i=e.end;return n.insertBoxToBlock(r,i.offset,{type:"br",id:Z(),box:!0,created:Date.now()}),!0}const aU=I("input-handler-actions");function cU(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(sU(n),!0))}function uU(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(iU(n),!0))}function fU(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(rU(n),!0))}function dU(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(lU(n),!0))}function hU(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{aU.error(t)}),!0)}const kh={ArrowDown:fB,ArrowUp:uB,ArrowLeft:aB,ArrowRight:cB,"Shift+ArrowDown":dB,"Shift+ArrowUp":gB,"Shift+ArrowLeft":hB,"Shift+ArrowRight":mB,"CtrlOrCmd+ArrowLeft":CB,"CtrlOrCmd+ArrowRight":EB,"CtrlOrCmd+Shift+ArrowLeft":AB,"CtrlOrCmd+Shift+ArrowRight":xB,"CtrlOrCmd+ArrowUp":bB,"CtrlOrCmd+ArrowDown":op,"CtrlOrCmd+Shift+ArrowUp":vB,"CtrlOrCmd+Shift+ArrowDown":sp,"CtrlOrCmd+A":KB,Home:wB,End:SB,"Shift+Home":RB,"Shift+End":kB,PageUp:MB,PageDown:UB,"Shift+PageUp":OB,"Shift+PageDown":NB,"CtrlOrCmd+Z":tU,"CtrlOrCmd+Shift+Z":eU,Enter:cU,Delete:uU,Backspace:fU,"Shift+Enter":dU,"CtrlOrCmd+Shift+V":hU};function GB(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function WB(n,t,e){if(t.type==="embed"){const o=t.embedData,s=o.src;if(s&&typeof s=="string"){const l=e.get(s);if(l)o.src=l;else{let c="";s.split("|").forEach(h=>{const C=e.get(h);C&&(c+=c?`|${C}`:`${C}`)}),c&&(o.src=c)}}return}const r=t.text;r&&r.forEach(o=>{if(o.attributes&&o.attributes.src&&typeof o.attributes.src=="string"){const s=e.get(o.attributes.src);s&&(o.attributes.src=s)}});const i=t.children;i&&i.forEach(o=>{n.blocks[o].forEach(l=>{WB(n,l,e)})})}function qB(n,t,e){if(e.size===0)return;t.blocks.root.forEach(i=>{const o=n.editorBlocks.getBlockClass(i.type);o.replaceResources?o.replaceResources(i,e):WB(t,i,e)})}async function mU(n,t){let e=t.filter(s=>s.indexOf(":")===-1);const r=[];e.forEach(s=>{const l=s.split("|");r.push(...l)}),e=Array.from(new Set(r)),e=r;const i=await n.doc.addResources(e),o=new Map;if(e.length!==i.length)return o;for(let s=0;s<e.length;s++)o.set(e[s],i[s]);return o}function gU(n,t){var l,c,d,h;const r=t.meta.serverId;if(!r||typeof r!="string")return!1;const i=(c=(l=n.doc).getServerMeta)==null?void 0:c.call(l);if(!i)return!1;const o=/.*(?=\/)/;return((d=(i.serverId||"").match(o))==null?void 0:d[0])===((h=r.match(o))==null?void 0:h[0])}async function dp(n,t){const r=t.meta.resources;if(!r||Object.keys(r).length===0)return;let i=new Map;if(gU(n,t)){const s=Array.from(Object.keys(r));i=await mU(n,s),qB(n,t,i)}const o=new Map;Object.entries(r).forEach(([s,l])=>{i.get(s)===void 0&&s!==l&&o.set(s,l)}),o.size!==0&&qB(n,t,o)}async function pU(n,t,e){await dp(n,t),n.undoManager.runInGroup(()=>{const{start:r,end:i}=n.selection.range,o=n.getBlockById(r.blockId);if(r.blockId===i.blockId&&we(o)){const s=it(o),l=n.getBlockIndex(o),[c]=n.insertDocAt(s,l+1,t,e);c&&n.selection.selectBlock(c,dt(n,c))}else{n.clearSelectedContents();const{block:s,offset:l}=pa(n);n.insertDoc(s,l,t,e)}})}const CU=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function EU(n){let t;for(const e of CU)if(t=n[e],t)break;return t||null}function hp(n,t,e,r){if(e.type==="embed"){const l=e.embedData.src;if(l&&typeof l=="string")for(const c of l.split("|"))r.add(c);return}const i=e.text;i&&i.forEach(s=>{if(s.attributes&&s.attributes.src&&typeof s.attributes.src=="string")if($o(s)){const l=n.editorBoxes.getBoxClass(s.attributes.type);if(l.getResources){const c=l.getResources(n,s.attributes);c?c.forEach(d=>{r.add(d)}):r.add(s.attributes.src)}else r.add(s.attributes.src)}else r.add(s.attributes.src)});const o=e.children;o&&o.forEach(s=>{t.blocks[s].forEach(c=>{hp(n,t,c,r)})})}function AU(n,t){const e=new Set;return t.blocks.root.forEach(i=>{const o=n.editorBlocks.getBlockClass(i.type);if(o.getResources){const s=o.getResources(n,i);s?s.forEach(l=>{e.add(l)}):hp(n,t,i,e)}else hp(n,t,i,e)}),Array.from(e)}function wh(n,t){return he.isFirefox?`<!doctype html><html><head><meta charset="utf8" /></head><body><canvas data-editor-doc="${Hi(JSON.stringify(t))}" id="ones-editor-doc">${n}</body></html>`:`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Hi(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Sh(n,t){var o,s,l;const e=(l=(s=(o=n.doc).getServerMeta)==null?void 0:s.call(o))!=null?l:{},r=AU(n,t),i={};r.forEach(c=>{const d=n.doc.buildResourceUrl(c,{withToken:!0});i[c]=d}),t.meta={...e,resources:i}}function xU(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let r=yh(n);const i=e==null?void 0:e(n,t,r);if(i===!0)return;typeof i=="object"&&i!==null&&(r=i),Sh(n,r);const o=ph(n,r),s=Js(n,r),l=wh(o,r);t.clipboardData.setData("text/html",l),t.clipboardData.setData("text/plain",s),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(r))}async function Lh(n,t){if(!window.isSecureContext)throw new Error("Can't copy block in insecure context.");const e=up(n,t);Sh(n,e);const r=ph(n,e),i=Js(n,e),o=wh(r,e);return Mg([{type:"text/plain",data:new Blob([i],{type:"text/plain"})},{type:"text/html",data:new Blob([o],{type:"text/html"})}])}class bU{constructor(t){g(this,"editor");g(this,"handlers",[]);g(this,"onPasteText",async(t,e)=>{const r=new DataTransfer;r.setData("text/plain",t);const i=await this.editor.dataConverter.fromData(this.editor,r,e);if(i){const o=[];this.pasteDocs(i,null,o)}});this.editor=t}onInsertText(t,e){if(!et(this.editor,this.editor.getFocusedBlock()))return;const{containerId:r,blockIndex:i,offset:o}=pa(this.editor);this.handleBeforeInsertText(r,i,o,e)||(this.defaultInsertText(this.editor,r,i,o,e),this.handleAfterInsertText(r,i,o,e),this.editor.selection.updateLastCaretRect())}onKeyDown(t){if(this.handleBeforeKeyDown(t))return!0;const e=this.defaultHandleKeydown(this.editor,t);return this.handleAfterKeyDown(t)?!0:e}onChanged(t){for(let e=0;e<this.handlers.length;e++){const r=this.handlers[e];r.handleChanged&&r.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const r=this.handlers[e];r.handleRemoteChanged&&r.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){if(!et(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:r,offset:i}=pa(this.editor);for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,r,i)}}onUpdateCompositionText(t,e,r){if(!et(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText(e,r),this.editor.selection.caret.update();const{containerId:i,blockIndex:o,offset:s}=pa(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,i,o,s,r)}this.editor.selection.updateLastCaretRect()}onCopy(t){xU(this.editor,t,(e,r,i)=>{for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,r,i);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onCut(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeCut&&i.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const r=this.editor.selection.focusedBlock;we(r)&&this.editor.deleteBlock(r)}else q1(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;const e=this.editor.dataConverter.fromData(this.editor,t.clipboardData),r=Array.from(t.clipboardData.files);e.then(async i=>{i&&this.pasteDocs(i,t,r)})}onFocus(){z(this.editor.rootElement,"active")}onBlur(){ot(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,r)=>{var s,l;const i=(s=e.order)!=null?s:1;return((l=r.order)!=null?l:1)-i})}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,r,i){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,r,i))return!0}return!1}handleAfterInsertText(t,e,r,i){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,r,i))return!0}return!1}handleBeforeKeyDown(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeKeyDown&&i.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterKeyDown&&i.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeKeyDown&&i.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterKeyDown&&i.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,r,i,o){$1(this.editor,o)}defaultHandleKeydown(t,e){return GB(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePasteDoc&&await i.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await pU(this.editor,t,e);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPasteDoc&&await i.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e,r){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforePaste&&await s.handleBeforePaste(this.editor,e,t,r))return}const i=EU(t);if(!!i){await this.pasteDoc(i);for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleAfterPaste&&await s.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}forEach(t){this.handlers.forEach(t)}}function vU(n,t,e){const r=ji(t,e);return r.remove(),r}I("copy-dom-attributes");const XB=["onabort","onanimationcancel","onanimationend","onanimationiteration","onanimationstart","onauxclick","onblur","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onformdata","ongotpointercapture","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onlostpointercapture","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onpause","onplay","onplaying","onpointercancel","onpointerdown","onpointerenter","onpointerleave","onpointermove","onpointerout","onpointerover","onpointerup","onprogress","onratechange","onreset","onresize","onscroll","onsecuritypolicyviolation","onseeked","onseeking","onselect","onselectionchange","onselectstart","onslotchange","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","ontouchcancel","ontouchend","ontouchmove","ontouchstart","ontransitioncancel","ontransitionend","ontransitionrun","ontransitionstart","onvolumechange","onwaiting","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","onwheel"];function BU(n,t){for(let l=0;l<XB.length;l++){const c=XB[l];t[c]=n[c]}const e=n.attributes,r=t.attributes,i=[],o=[];for(let l=0;l<e.length;l++){const c=e[l],d=r.getNamedItem(c.name);d?d.value!==c.value&&(d.value=c.value,o.push(c)):i.push(c)}const s=[];for(let l=0;l<r.length;l++){const c=r[l];e.getNamedItem(c.name)||s.push(c)}i.forEach(l=>{t.setAttribute(l.name,l.value)}),o.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function QB(n){const t=Array.from(n.childNodes).filter(e=>!gv(e));return t.forEach(e=>{e.remove()}),t}function YB(n,t,e){var d;const r=n.getContainerById(t),i=ji(r,e),o=Fo(i),s=n.doc.getBlockData(t,e),l=Jt(n,i);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,i,s))n.editorBlockRenders.updateBlock(n,o,i,s);else{const h=n.editorBlocks.createBlock(o,r,s),C=QB(h);QB(i),C.forEach(x=>{i.appendChild(x)});const E=Pd(h);if(E){const x=Pd(i);x&&x.remove(),i.appendChild(E)}BU(h,i)}Iv(n,i,s),n.blockHooks.forEach(h=>{var C;(C=h.update)==null||C.call(h,n,o,r,i,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const TU=I("transform-selection");function JB(n,t,e,r){const{range:i}=n.selection,{anchor:o,focus:s}=i;if(o.blockId!==t&&s.blockId!==t)return i;p(TU,o.isSimple()&&s.isSimple(),"invalid text pos type");let l=o;if(o.blockId===t){const d=fn.transformCursor(o.offset,e,r);l=lt(t,d,"normal")}let c=s;if(s.blockId===t){const d=fn.transformCursor(s.offset,e,r);c=lt(t,d,"normal")}return We(n,{anchor:l,focus:c})}const yU=I("handle-block-text-changed");function RU(n,t,e,r,i){const o=n.getContainerById(t),s=ji(o,e),l=n.doc.getBlockData(t,e);if(p(yU,l.text,"no block text"),fv(n,s).setBlockText(n,s,l.text),!i){const c=JB(n,l.id,r,i);n.selection.setRange(c,{noScroll:!0})}}function kU(n,t){const e=gt.default(n);return t.delete.forEach(i=>{delete e[i]}),{...e,...t.insert}}function ZB(n,t,e,r){const i=Jt(n,t);i.handleDeleteBlock&&i.handleDeleteBlock(n,t,e,r),n.emit("blockDeleted",n,t,e,r)}function wU(n,t,e,r){const i=n.getBlockByIndex(t,e);i.querySelectorAll('[data-type="editor-block"]').forEach(o=>{ZB(n,o,r,{child:!0})}),ZB(n,i,r,{child:!1})}const Or=I("editor-doc");class SU extends ra{constructor(e,r,i){super();g(this,"localEvents",[]);this.editor=e,this.externalDoc=r,this.externalDoc.registerCallback(this),this.registerLocalEvents(i)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var r,i;return(i=(r=this.externalDoc).getVersionHelper)==null?void 0:i.call(r)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}findContainerBlocks(e){return this.externalDoc.findContainerBlocks(e)}getBlockData(e,r){return this.externalDoc.getBlockData(e,r)}verifyBlockWritable(e,r){const i=this.editor.getBlockByIndex(e,r);p(Or,this.editor.isBlockWritable(i),`block is not writable, ${e}, ${r}`)}localUpdateBlockText(e,r,i,o){p(Or,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,r);const s=this.getBlockData(e,r),l=s.text;p(Or,l,`no text, ${e}, ${r}`);const c=JB(this.editor,s.id,i,!0),d=fn.apply(l,i);this.localEvents.forEach(C=>C.onBeforeUpdateBlockText(e,s.id,l,d,c.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,r,i);return this.editor.selection.setRange(c,o),h}localUpdateBlockData(e,r,i,o){p(Or,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,r);if(!this.editor.isBlockWritable(s)){const h=Array.from(i.delete).filter(E=>E!=="comments"),C=Object.keys(i.insert).filter(E=>E!=="comments");(h.length>0||C.length>0)&&p(Or,!1,`block is not writable, comment supported only, ${JSON.stringify(i)}}`)}const l=gt.default(this.getBlockData(e,r)),c=gt.default(kU(l,i));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,c,o));const d=this.externalDoc.localUpdateBlockData(e,r,i,o);return this.editor.selection.setRange(Ko(this.editor,o)),d}localInsertBlock(e,r,i,o,s){p(Or,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(e,r,i,o));const l=this.externalDoc.localInsertBlock(e,r,i,o);return s!=null&&s.noFocus||this.editor.selection.setRange(Ko(this.editor,o),s),l}localDeleteBlock(e,r,i){p(Or,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,r);const o=gt.default(this.getBlockData(e,r));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,r,o,i));const s=this.externalDoc.localDeleteBlock(e,r,i);return this.editor.selection.setRange(Ko(this.editor,i)),s}localDeleteChildContainers(e){return p(Or,!this.editor.readonly,"editor is readonly"),e.forEach(r=>{const i=gt.default(this.getContainerBlocks(r));this.localEvents.forEach(o=>o.onBeforeDeleteChildContainer(r,i))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainers(e){p(Or,!this.editor.readonly,"editor is readonly");const r=gt.default(e);r.forEach(i=>{this.localEvents.forEach(o=>o.onBeforeInsertChildContainer(i.containerId,i.blocks))}),this.externalDoc.localInsertChildContainers(r)}onRequestReload(e){Or.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(i=>{var o;return(o=i.onRequestReload)==null?void 0:o.call(i,e)});const r=!1;this.editor.emit("docChanged",this.editor,r)}onUpdateBlockText(e,r,i,o){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,r,i,o)}),RU(this.editor,e,r,i,o),this.editor.emit("docChanged",this.editor,o)}onUpdateBlockData(e,r,i,o){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,r,i,o)}),YB(this.editor,e,r),this.editor.emit("docChanged",this.editor,o)}onInsertBlock(e,r,i,o){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,e,r,i,o)});const s=this.editor.getContainerById(e);sI(this.editor,s,r,i),this.editor.emit("docChanged",this.editor,o)}onDeleteBlock(e,r,i){wU(this.editor,e,r,i),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,r,i)});const o=this.editor.getContainerById(e);vU(this.editor,o,r),this.editor.emit("docChanged",this.editor,i)}onInsertChildContainer(e,r,i){this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,e,r,i)})}onDeleteChildContainer(e,r){this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,e,r)})}onCustomMessage(e){this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,e)})}onStatusChanged(e){this.callbacks.forEach(r=>{var i;return(i=r.onStatusChanged)==null?void 0:i.call(r,e)})}onError(e){this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,e)})}uploadResource(e,r){return this.externalDoc.uploadResource(e,r)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,r){return this.externalDoc.buildResourceUrl(e,r)}request(e,r){return this.externalDoc.request(e,r)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}triggerReAuth(){var e,r;return(r=(e=this.externalDoc).triggerReAuth)==null?void 0:r.call(e)}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,r,i;return(i=(r=(e=this.externalDoc).getServerMeta)==null?void 0:r.call(e))!=null?i:{}}reset(e){Or.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function t2(n,t){if(n.length===0){n.push(t);return}const e=n[n.length-1];if(!e.combinable(t)){n.push(t);return}e.combine(t)}const Ih=I("undo-action");class ba{constructor(t,e,r){g(this,"beforeRange");g(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=r}undo(t){return!1}redo(t){return!1}combinable(t){return p(Ih,t,"no other action"),!1}combine(t){p(Ih,!1,"no other")}setAfterRange(t){this.afterRange&&Ih.warn("after range has already set"),this.afterRange=t}findContainerById(t,e){return!!t.doc.findContainerBlocks(e)}findBlockById(t,e){const r=t.doc.findContainerBlocks(this.containerId);return r?r.some(i=>i.id===e):!1}checkBlockData(t,e){if(Array.isArray(e.children)){const r=t.doc.toJSON();for(let i=0;i<e.children.length;i++){const o=e.children[i];if(!r.blocks[o])return Ih.warn(`container (${o}) not found, deleted by others?`),!1}}return!0}}const va=I("block-action");class e2 extends ba{constructor(e,r,i,o,s){super(e,r,s);g(this,"blockData");g(this,"blockIndex");this.blockData=gt.default(o),this.blockIndex=i}deleteBlock(e,r){if(!this.findContainerById(e,this.containerId))return va.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockData.id))return va.warn(`block (${this.blockData.id}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const o=e.getBlockById(this.blockData.id);if(!o)return!1;try{p(va,this.blockIndex===bt(o),"invalid block index"),Ah(e,o,Ko(e,r))}catch(s){va.warn(s.message),e.selection.selectBlock(o,0)}return!0}insertBlock(e,r){if(!this.findContainerById(e,this.containerId))return va.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.checkBlockData(e,this.blockData))return!1;try{Ea(e,this.containerId,this.blockIndex,gt.default(this.blockData),r)}catch(i){va.warn(i.message);const o=e.doc.getContainerBlocks(this.containerId),s=Math.min(o.length-1,this.blockIndex),l=e.getBlockByIndex(this.containerId,s);e.selection.selectBlock(l,0)}return!0}}I("insert-block-action");class LU extends e2{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class IU extends e2{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class DU extends ba{constructor(e){super(e,ft(e.rootContainer),e.selection.range.toDocRange());g(this,"actions",[])}addAction(e){t2(this.actions,e),this.afterRange=e.afterRange}undo(e){let r=!1;return this.actions.concat().reverse().forEach(i=>{i.undo(e)&&(r=!0)}),r}redo(e){let r=!1;return this.actions.forEach(i=>{i.redo(e)&&(r=!0)}),r}setAfterRange(e){this.afterRange=e;const r=this.actions[this.actions.length-1];!r||r instanceof ba&&(r.afterRange||r.setAfterRange(e))}}const Wo=I("update-block-data-action");class Dh extends ba{constructor(e,r,i,o,s,l){super(e,r,l);g(this,"beforeBlockData");g(this,"afterBlockData");g(this,"blockId");this.blockId=i,p(Wo,this.blockId===o.id,"invalid block id"),p(Wo,this.blockId===s.id,"invalid block id"),this.beforeBlockData=gt.default(o),this.afterBlockData=gt.default(s),p(Wo,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){if(!e.findBlockById(this.blockId))return Wo.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const r=e.getBlockById(this.blockId);if(!r||!this.checkBlockData(e,this.beforeBlockData))return!1;const i=e.getContainerById(this.containerId);return p(Wo,i,"no container"),vh(e,r,Dh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){if(!e.findBlockById(this.blockId))return Wo.warn(`block (${this.blockId}) not found, deleted by others?`),!1;p(Wo,e,"no editor");const r=e.getBlockById(this.blockId);if(!r||!this.checkBlockData(e,this.beforeBlockData))return!1;const i=e.getContainerById(this.containerId);return p(Wo,i,"no container"),vh(e,r,Dh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const r=gt.default(e);return delete r.id,delete r.type,r}}const tl=I("update-block-text-action");class hu extends ba{constructor(e,r,i,o,s,l){super(e,r,l);g(this,"beforeRichTextData");g(this,"afterRichTextData");g(this,"blockId");g(this,"type");this.blockId=i,this.beforeRichTextData=gt.default(o),this.afterRichTextData=gt.default(s),this.type=hu.calType(o,s)}static calType(e,r){p(tl,e,"no old data"),p(tl,r,"no new data");const o=fn.diff(e,r),s=new Set;let l=!1;const c=h=>$b(h)?`cjk_${h}`:Kb(h)?"number":wd(h)?"space":Vb(h)?"letter":"unknown";let d=!1;return o.forEach(h=>{h.insert?h.insert===" "?s.add("insert_letter"):typeof h.insert=="string"&&h.insert.startsWith(" ")&&h.insert.length>1?(l=!0,d=!0,s.add(`insert_${c(h.insert.substr(1))}`)):s.add(`insert_${c(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(e){if(!this.findContainerById(e,this.containerId))return tl.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return tl.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockId);return i?(bh(e,i,this.beforeRichTextData),!0):!1}redo(e){if(!this.findContainerById(e,this.containerId))return tl.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return tl.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockId);return i?(bh(e,i,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof hu)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const r=e.beforeRange,i=r.anchor;if(!i.isSimple())return!1;const o=this.afterRange;if(!o)return!1;const s=o.anchor;return!(!s.isSimple()||s.blockId!==r.anchor.blockId||s.offset!==i.offset)}combine(e){p(tl,e instanceof hu,"invalid action type");const r=e;this.afterRichTextData=r.afterRichTextData,this.afterRange=e.afterRange}}const n2=I("child-container-action");class r2 extends ba{constructor(t,e,r){super(t,e,t.selection.range.toDocRange()),this.blocks=r}deleteChildContainer(t){return this.findContainerById(t,this.containerId)?(t.doc.localDeleteChildContainers([this.containerId]),!0):(n2.warn(`container (${this.containerId}) not found, deleted by others?`),!1)}insertChildContainer(t){return this.findContainerById(t,this.containerId)?(n2.warn(`container (${this.containerId}) already exists`),!1):(t.doc.localInsertChildContainers([{containerId:this.containerId,blocks:gt.default(this.blocks)}]),!0)}}class _U extends r2{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class MU extends r2{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Nr=I("undo");class UU{constructor(t){g(this,"editor");g(this,"actions",[]);g(this,"undoCursor");g(this,"currentGroup",null);g(this,"groupCounter",0);g(this,"undoRedoing",!1);g(this,"handleSelectionChange",t=>{if(this.currentGroup){this.currentGroup.setAfterRange(t.selection.range.toDocRange());return}const e=this.actions[this.actions.length-1];!e||e.afterRange||e.setAfterRange(t.selection.range.toDocRange())});this.editor=t,this.undoCursor=-1,this.editor.addListener("selectionChanged",this.handleSelectionChange)}reset(){this.actions=[],this.undoCursor=-1}prepareSaveUndoState(){this.undoCursor!==-1&&(this.actions.splice(this.undoCursor),this.undoCursor=-1)}addAction(t){this.currentGroup?this.currentGroup.addAction(t):(t2(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(p(Nr,!this.currentGroup,"current group already exists"),this.currentGroup=new DU(this.editor),this.groupCounter=1):(p(Nr,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){p(Nr,this.currentGroup,"current group not exists"),p(Nr,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Nr.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(t){this.beginGroup();try{const e=t();return setTimeout(()=>this.editor.selection.caret.update()),e}catch(e){throw Nr.error(`failed to run action: ${e.message}`),e}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const t=this.actions[this.undoCursor];if(t.undo(this.editor)){try{this.editor.selection.setRange(Ko(this.editor,t.beforeRange))}catch(e){Nr.error(`undo: failed to restore caret pos: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}redo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor<this.actions.length;){const t=this.actions[this.undoCursor];if(this.undoCursor+=1,t.redo(this.editor)){try{const e=t.afterRange;e?this.editor.selection.setRange(Ko(this.editor,e)):Nr.warn("no after range")}catch(e){Nr.error(`redo: failed to set caret pos after redo: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var e;const t=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(e=this.actions[t])!=null?e:null}undoTo(t){for(;;){const e=this.lastAction();if(!e||e===t)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(t,e,r,i,o){this.undoRedoing||(this.prepareSaveUndoState(),fn.diff(r,i).length!==0&&this.addAction(new hu(this.editor,t,e,r,i,o)))}onBeforeUpdateBlockData(t,e,r,i,o){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Dh(this.editor,t,e,r,i,o);this.addAction(s)}onBeforeInsertBlock(t,e,r,i){this.undoRedoing||(this.prepareSaveUndoState(),p(Nr,e>=0,"invalid block index"),p(Nr,r,"no block data"),this.addAction(new LU(this.editor,t,e,r,i)))}onBeforeDeleteBlock(t,e,r,i){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new IU(this.editor,t,e,r,i)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new _U(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new MU(this.editor,t,e)))}}class OU{async fromData(t,e){const r=e.getData("text/x-ones-editor-doc");if(r)return{"text/x-ones-editor-doc":JSON.parse(r)}}}class NU{constructor(){g(this,"converters",[]);g(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new OU)}prepareData(t){const e=new DataTransfer;for(let r=0;r<this.converterTypes.length;r++)e.setData(this.converterTypes[r],t.getData(this.converterTypes[r]));return e}async fromData(t,e,r){let i={};const o=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,o,r);l&&(i={...i,...l})}return i}addConverter(t){this.converters.push(t)}}function PU(n){n.editorBlocks.registerBlockClass(Mn),n.editorBlocks.registerBlockClass(Qv),n.editorBoxes.registerBoxClass(E5),n.editorBoxes.registerBoxClass(A5),n.editorBoxes.registerBoxClass(v5),n.editorBoxes.registerBoxClass(B5),n.editorInsertions.registerInsertionClass(T5),n.editorBlockRenders.registerRender(new mv)}function FU(n,t){PU(n),t!=null&&t.blocks&&t.blocks.forEach(e=>n.editorBlocks.registerBlockClass(e)),t!=null&&t.boxes&&t.boxes.forEach(e=>n.editorBoxes.registerBoxClass(e)),t!=null&&t.embeds&&t.embeds.forEach(e=>n.editorEmbeds.registerEmbedClass(e)),t!=null&&t.insertions&&t.insertions.forEach(e=>n.editorInsertions.registerInsertionClass(e)),t!=null&&t.decorators&&t.decorators.forEach(e=>n.editorDecorators.registerDecorator(e)),t!=null&&t.dataConverters&&t.dataConverters.forEach(e=>n.dataConverter.addConverter(e)),t!=null&&t.commandProviders&&t.commandProviders.forEach(e=>n.editorCommandProviders.registerCommandProvider(e)),t!=null&&t.textRenders&&t.textRenders.forEach(e=>n.editorBlockRenders.registerRender(e))}const _h=I("range-commands");function i2(n,t){n.forEach(e=>{e.source=t,e.children&&i2(e.children,t)})}function o2(n,t,e){const r=st(t);p(_h,r===e.start.blockId,"invalid start range"),p(_h,r===e.end.blockId,"invalid end range");const i=n.editorCommandProviders.getCommandProviders();let o=[];if(i.forEach(s=>{const l=s.getAvailableCommands(n,t,e);i2(l,s.id),o.push(...l)}),i.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,o);l&&(o=l)}}),_t(n,t)){if(!aa(e.start))return o;p(_h,!e.start.isSimple(),"invalid start pos"),p(_h,!e.end.isSimple(),"invalid end pos");const s=e.start.childContainerId,l=li(n,s),d=Ce(l)[0];if(d){const h=dt(n,d),C=We(n,{anchor:lt(d,0,"home"),focus:lt(d,h,"end")}),E=o2(n,d,C);o.push(...E)}}return o}function s2(n){const t=n.getEditor(),e=n.getSelectedBlocks(),r=[],i=n.isReverse()?e[0]:e[e.length-1],o=We(t,{anchor:i.start,focus:i.end});return o2(t,i.block,o).forEach(l=>{r.push(l)}),r}function l2(n,t,e,r,i,o){var h;const s=n.editorCommandProviders.getCommandProviders();for(let C=0;C<s.length;C++){const E=s[C];if(E.beforeExecuteCommand&&E.beforeExecuteCommand(n,t,e,r,i))return!1}const l=n.editorCommandProviders.getCommandProvider(r.source),c={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,r,i,{}))return o[st(t)]=c,!0;let d=!1;return _t(n,t)&&ca(n,t,e.start,e.end).forEach(E=>{Ce(E).forEach(v=>{const k=dt(n,v),L=We(n,{anchor:lt(v,0,"home"),focus:lt(v,k,"end")});l2(n,v,L,r,i,o)&&(d=!0)})}),s.forEach(C=>{C.afterExecuteCommand&&C.afterExecuteCommand(n,t,e,r,i,o)}),d}function a2(n,t,e){const r=n.getEditor(),i={},o=r.editorCommandProviders.getCommandProvider(t.source);return o.executeRangeCommand&&o.executeRangeCommand(r,n,t,e,i)||(n.getSelectedBlocks().forEach(l=>{const c=We(r,{anchor:l.start,focus:l.end});l2(r,l.block,c,t,e,i)}),r.focus()),i}const KU=I("command-providers");class c2{constructor(t){g(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(r=>r.id===t);return p(KU,e,`no command provider, id=${t}`),e}getCommands(t){return s2(t)}executeCommand(t,e,r){return this.editor.undoManager.runInGroup(()=>a2(t,e,r))}getEmptyBlockTextAttributes(t,e){let r={};if(this.providers.forEach(i=>{var s;const o=(s=i.getEmptyBlockTextAttributes)==null?void 0:s.call(i,t,e);o&&(r={...r,...o})}),Object.keys(r).length!==0)return r}}function VU(n,t){const e=it(t),r=ft(e),i=bt(t);YB(n,r,i)}const $U=I("table-scroll");class u2{constructor(t,e,r,i,o){g(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=r,this.handler=i,this.data=o,e.addEventListener(r,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class HU{constructor(t){g(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(r=>r.destroy()),this.handlers.delete(t)})}addEventListener(t,e,r,i){const o=this.handlers.get(t);if(o){if(o.find(s=>s.handler===r&&s.name===e)){$U.warn(`event has already registered: ${e}`);return}o.push(new u2(this.editor,t,e,r,i))}else{const s=new u2(this.editor,t,e,r,i);this.handlers.set(t,[s])}}removeEventListener(t,e,r){if(!t){for(const[o,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const c=s[l];if(e)e===c.name&&r===c.handler&&s.splice(l,1);else if(r===c.handler){s.splice(l,1),c.destroy(),s.length===0&&this.handlers.delete(o);continue}}return}const i=this.handlers.get(t);if(i){const o=i.findIndex(s=>s.handler===r&&s.name===e);if(o!==-1){const s=i[o];i.splice(o,1),s.destroy(),i.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const r=this.handlers.get(t);if(r)if(e)for(let i=0;i<r.length;i++){const o=r[i];o.name===e&&(r.splice(i,1),o.destroy())}else r.forEach(i=>{i.destroy()}),this.handlers.delete(t)}}const f2=I("update-block-text");function jU(n,t){const e=n.getBoxById(t.id),r=nt(e);p(f2,r,"no parent block"),p(f2,et(n,r),"not a text block");const i=n.getBlockText(r),o=c5(i,"id",t.id,t);W5(n,r,o)}function zU(n,t){for(const e of n.blockHooks)if(e.writable){const r=e.writable(n,t);if(typeof r=="boolean")return r}return!0}function GU(n){if(n.readonly)return!1;const t=ui(n);return!!n.isBlockWritable(t.map(e=>e.block))}class WU{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}getItem(t){return window.localStorage.getItem(this.getKey(t))}setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class qU{constructor(){g(this,"shortcuts",[])}handleKeyboardEvents(t,e){const r=this.shortcuts;for(const i of r){const o=Object.entries(i);for(const[s,l]of o)if(oi(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const no=I("editor");class XU extends ve.TypedEmitter{constructor(e,r,i){var o,s,l,c,d,h,C,E;super();g(this,"parent");g(this,"rootElement");g(this,"contentElement");g(this,"rootContainerObject");g(this,"rootContainer");g(this,"input");g(this,"selection");g(this,"selectionHandler");g(this,"doc");g(this,"id");g(this,"clientId");g(this,"compositingText","");g(this,"undoManager");g(this,"shortcuts",new qU);g(this,"dataConverter",new NU);g(this,"editorBlocks",new Gv(this));g(this,"editorBoxes",new b5(this));g(this,"editorInsertions",new R5(this));g(this,"editorEmbeds",new qv(this));g(this,"editorDecorators",new k5(this));g(this,"editorCommandProviders",new c2(this));g(this,"editorBlockRenders",new X9(this));g(this,"blockHooks",[]);g(this,"domEvents",new HU(this));g(this,"customs",new Map);g(this,"options");g(this,"inputHandlers",new bU(this));g(this,"settingsProvider");g(this,"_readonly",!1);g(this,"getColor",e=>{const r=this.options.colors;return r.length===0?"#FF1A75":r[e%r.length]});no.debug("create editor"),this.setMaxListeners(100),this.options={colors:(o=i==null?void 0:i.colors)!=null?o:["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"],componentsOptions:(l=(s=i==null?void 0:i.components)==null?void 0:s.options)!=null?l:{},scrollContainer:i==null?void 0:i.scrollContainer,enableComments:(c=i==null?void 0:i.enableComments)!=null?c:!0},this.settingsProvider=(d=i==null?void 0:i.settingsProvider)!=null?d:new WU(this),FU(this,i==null?void 0:i.components),this.blockHooks.push(...(C=(h=i==null?void 0:i.components)==null?void 0:h.blockHooks)!=null?C:[]),this.id=(E=i==null?void 0:i.id)!=null?E:Z(),this.clientId=Z(),this.undoManager=new UU(this),this.doc=new SU(this,r,this.undoManager),this.parent=e,this.rootElement=B("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=B("div",["editor-content"],this.rootElement),this.rootContainerObject=Hv(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new lM(this,this.inputHandlers),this.selection=new QM(this),this.selectionHandler=new ZM(this),i!=null&&i.shortcuts&&this.shortcuts.shortcuts.push(...i.shortcuts),he.isMobile&&z(this.rootElement,"mobile"),he.isSafari&&z(this.rootElement,"safari"),this._readonly&&z(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?z(this.rootElement,"readonly"):ot(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:an(this.rootContainer)}addCustom(e,r){const i=this.customs.get(e);if(i)return i;const o=r(this);return this.customs.set(e,o),o}getCustom(e){const r=this.customs.get(e);return p(no,r,`${e} does not exists`),r}replaceCustom(e,r){const i=this.customs.get(e);return i&&i.destroy(),this.customs.set(e,r),r}findCustom(e){return this.customs.get(e)}findCustomByType(e){const r=this.customs.values();for(const i of r)if(i instanceof e)return i;return null}destroyCustom(e){const r=this.customs.get(e);r&&(this.customs.delete(e),r.destroy())}getComponentOptions(e){return this.options.componentsOptions[e]}registerLocalEvents(e){this.doc.registerLocalEvents(e)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(e,r,i){return this.editorBlocks.createBlock(e,r,i)}createBox(e,r){return this.editorBoxes.createBox(e,r)}createInsertion(e,r){return this.editorInsertions.createInsertion(e,r)}destroy(){no.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(e=>e.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus()}focusToBlock(e,r){X1(this,e,r)}isWritable(){return GU(this)}isBlockWritable(e){return zU(this,e)}getChildContainerData(e){const r=this.doc.getContainerBlocks(e);return(!r||!Array.isArray(r))&&(p(no,r,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),p(no,Array.isArray(r),`container data is not an array: ${JSON.stringify(r)}`)),r}createChildContainer(e,r,i){return jv(this,e,r,i)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const e=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return e[e.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(e){const r=this.rootContainer.querySelector(`#${e}`);return r&&p(no,Ps(r),"not an valid block element"),r!=null?r:null}findBoxById(e){const r=this.rootContainer.querySelector(`#${e}`);return r&&p(no,Fd(r),"not an valid box element"),r!=null?r:null}getBlockById(e){const r=this.findBlockById(e);return p(no,r,`no block, id=${e}`),r}getBoxById(e){const r=this.findBoxById(e);return p(no,r,`no box, id=${e}`),r}getBlockByIndex(e,r){const i=this.getContainerById(e);return ji(i,r)}getBlockIndex(e){if(typeof e=="string"){const r=this.getBlockById(e);return bt(r)}return bt(e)}getContainerById(e){return li(this,e)}getParentContainer(e){return it(e)}reloadBlock(e){VU(this,e)}contains(e){const r=e instanceof Element?e:e.parentElement;return r?r.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,r,i,o,s){const l={blockId:i.id,offset:0},c={anchor:l,focus:l};return Ea(this,e,r,i,o!=null?o:c,s)}insertEmbed(e,r,i,o,s){const l={id:Z(),type:"embed",embedType:i,embedData:o};return this.insertBlock(e,r,l,s)}deleteBlock(e,r){G1(this,e,r)}mergeTextBlock(e,r){return j5(this,e,r)}breakTextBlock(e,r,i){return Aa(this,e,r,i).newBlock}getTextPosition(){return pa(this)}getBlockString(e,r){const i=this.getBlockText(e);return ue(i,r)}getBlockData(e){return jo(this,e)}getBoxData(e){return p5(this,e)}getBlockText(e){return bn(this,e)}setBlockText(e,r){W5(this,e,r)}deleteTextFromBlock(e,r,i,o){return j1(this,e,r,i,o)}insertTextToBlock(e,r,i,o){return P5(this,e,r,i,o)}insertBoxToBlock(e,r,i){return F5(this,e,r,i)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,r,i,o){Q5(this,e,r,i,o)}insertDocAt(e,r,i,o){return J1(this,e,r,i,o)}deleteChildContainers(e){H5(this,e)}replaceBlockText(e,r){return bh(this,e,r)}updateBlockData(e,r,i){const o={...this.getBlockData(e),...r},{id:s,type:l,...c}=o;return vh(this,e,c,(i!=null?i:this.selection.range).toDocRange())}updateEmbedData(e,r,i){return q5(this,e,r,i)}updateBoxData(e){jU(this,e)}getSelectedText(){const e=yh(this);return Js(this,e)}clearSelectedContents(){q1(this)}insertTextBlock(e,r,i,o){const s=hi(e!=null?e:"");return $5(this,s,r,i,o==null?void 0:o.newRange,o==null?void 0:o.insertBlockOptions)}updateCompositionText(e,r){if(e&&!r&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!r){H1(this);return}r?(this.compositingText="",Sd()?e||H1(this):$1(this,e)):(this.compositingText=e,K5(this))}}function mu(n,t,e){return new XU(n,t,e)}function QU(n){const t=(r,i)=>{const o=r.findIndex(l=>l.id===i.id);if(o===-1){r.push(i);return}const s=r[o];if(s.value!==i.value){r.splice(o,1);return}if(!!s.states){if(!i.states){s.states=[];return}s.states=pg.default(s.states,i.states)}},e=[];return n.forEach(r=>{r.forEach(i=>{t(e,i)})}),e}const YU=["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"];class gu extends ve.TypedEmitter{constructor(e){super();g(this,"users",new Map);g(this,"cursors",new Map);g(this,"addingUser",!1);g(this,"colors");this.colors=e&&e.length>0?e:YU}setCursor(e){this.addUser(e.user);const r=this.cursors.get(e.user.userId);if(r&&Nc.default(r,e))return;this.cursors.set(e.user.userId,e);const i=new Set([e.range.anchor.blockId,e.range.focus.blockId]),o=new Set(i);r&&new Set([r.range.anchor.blockId,r.range.focus.blockId]).forEach(l=>{i.has(l)||o.add(l)}),this.emit("remote-carets-change",[...o])}addUsers(e){this.addingUser=!0,e.forEach(r=>this.addUser(r)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(e){this.users.set(e.userId,e),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(e){var r;return(r=this.users.get(e))!=null?r:null}removeUser(e){this.users.delete(e),this.emit("change",Array.from(this.users.values()));const r=this.cursors.get(e);if(r){const i=new Set(new Set([r==null?void 0:r.range.anchor.blockId,r==null?void 0:r.range.focus.blockId]));this.cursors.delete(e),this.emit("remote-carets-change",[...i])}}updateUsers(e){this.users.forEach(r=>{e.find(i=>i.userId===r.userId)||this.removeUser(r.userId)}),this.users.clear(),this.addingUser=!0;try{e.forEach(r=>{this.addUser(r)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const r=new Map;return Array.from(this.cursors.values()).filter(i=>i.range.anchor.blockId===e&&ch(i.range)).forEach(i=>{const o=i.range.focus.offset;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}),r}getCursors(e){return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e||r.range.focus.blockId===e)}onUpdateBlockText(e,r,i){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(ch(l.range)){const{anchor:c,focus:d}=l.range;c.blockId===e.id&&(c.offset=fn.transformCursor(c.offset,r,i)),d.blockId===e.id&&(d.offset=fn.transformCursor(d.offset,r,i))}})}getFixedUserColor(e,r){let i=0;Array.from(e).forEach(s=>{i+=s.charCodeAt(0)});const o=i%this.colors.length;return this.colors[o]}destroy(){this.removeAllListeners()}}const en=I("local-doc");class mp extends ra{constructor(e,r){super();g(this,"doc");g(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[hi("")]}},this.serviceUrl=(r==null?void 0:r.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return gt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}findContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,r){const i=this.getContainerBlocks(e);p(en,i,`no container data: ${e}`);const o=i[r];return p(en,o,`no block data: ${r}`),o}localUpdateBlockText(e,r,i){const o=this.getBlockData(e,r);p(en,o.text,"no text for data");const s=fn.apply(o.text,i);return o.text=s,p(en,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,e,r,i,!0)}),s}localUpdateBlockData(e,r,i){const o=this.getBlockData(e,r);return i.delete.forEach(s=>delete o[s]),Object.entries(i.insert).forEach(([s,l])=>{o[s]=l}),p(en,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,r,i,!0)}),o}localInsertBlock(e,r,i){const o=this.getContainerBlocks(e);return p(en,o,`no container data: ${e}`),p(en,r>=0&&r<=o.length,`invalid block index: ${r}, ${o.length}`),o.splice(r,0,i),p(en,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,r,i,!0)}),i}localDeleteBlock(e,r){const i=this.getContainerBlocks(e);p(en,i,`no container data: ${e}`),p(en,r>=0&&r<=i.length,`invalid block index: ${r}, ${i.length}`);const o=i[r];return i.splice(r,1),p(en,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,r,!0)}),o}localInsertChildContainers(e){e.forEach(({containerId:r,blocks:i})=>{this.doc.blocks[r]=i,p(en,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,r,i,!0)})})}localDeleteChildContainers(e){en.debug(`delete child containers: ${e}`),e.forEach(r=>{p(en,this.doc.blocks[r],`no child container: ${r}`),delete this.doc.blocks[r]}),e.forEach(r=>{p(en,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,r,!0)})})}uploadResource(e,r){p(en,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,r){p(en,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new gu}setDoc(e){this.doc=gt.default(e),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,"change doc")})}destroy(){this.clearCallbacks()}}class JU{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function gp(n,t,e){n.addCustom(t,()=>{var o;const r=(o=e())!=null?o:void 0;return new JU(r)})}const d2=I("find-block");function h2(n,t){const e=Vs(t);if(!e){if(fr(t))return null;const r=Fs(t);return p(d2,r,"no parent block"),h2(n,r)}return _t(n,e)?ua(n,e,{visibleOnly:!0}):e}function m2(n,t){const e=$s(t);if(!e){if(fr(t))return null;const r=Fs(t);return p(d2,r,"no parent block"),m2(n,r)}return _t(n,e)?Zg(n,e,{visibleOnly:!0}):e}const ZU=I("remote-cursor");class tO{constructor(){g(this,"remoteUsers",new gu)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const r=e;this.handleUpdateUsers(r.users)}else e.type==="caret"?this.handleUpdateCaret(e):ZU.debug(`unknown remote message received: ${t}`)}handleUpdateUsers(t){this.remoteUsers.updateUsers(t)}handleUpdateCaret(t){const e=this.remoteUsers.findUser(t.userId);!e||this.remoteUsers.setCursor({oneseditor:"cursor",user:e,range:t.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function eO(n){const{blocks:t,meta:e,comments:r,...i}=n;return{rootBlocks:t,meta:e,comments:r,childBlocks:i}}function nO(n){const{blocks:t,meta:e,comments:r}=n,{root:i,...o}=t;return{blocks:i,meta:e,comments:r,...o}}function ro(n){const{childBlocks:t,meta:e,comments:r,rootBlocks:i}=eO(gt.default(n));return{blocks:{root:i,...t},meta:e,comments:r}}function io(n){return n==="root"?"blocks":n}function Ba(n){return n==="blocks"?"root":n}const rO={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new ln.default(n)},apply(n,t){const e=new ln.default(n),r=new ln.default(t);return e.compose(r).ops},compose(n,t){const e=new ln.default(n),r=new ln.default(t);return e.compose(r).ops},diff(n,t){const e=new ln.default(n),r=new ln.default(t);return e.diff(r).ops},transform(n,t,e){const r=new ln.default(n);return new ln.default(t).transform(r,e==="left").ops},transformCursor(n,t,e){return t.transformPosition(n,!e)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,t,e){if(!n)return null;const r=new ln.default(t),i=this.transformCursor(n.index,r,e),o=this.transformCursor(n.index+n.length,r,e);return{...n,index:i,length:o-i}}}};var qo={},pp=db.default.EventEmitter;qo.EventEmitter=pp,qo.mixin=iO;function iO(n){for(var t in pp.prototype)n.prototype[t]=pp.prototype[t]}var g2=["info","warn","error"];function p2(){var n={};g2.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var oO=p2;p2.prototype.setMethods=function(n){n=n||{};var t=this;g2.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var sO=oO,lO=new sO,C2=lO;function el(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,el):this.stack=new Error().stack}el.prototype=Object.create(Error.prototype),el.prototype.constructor=el,el.prototype.name="ShareDBError",el.CODES={ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT:"ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT",ERR_APPLY_SNAPSHOT_NOT_PROVIDED:"ERR_APPLY_SNAPSHOT_NOT_PROVIDED",ERR_CLIENT_ID_BADLY_FORMED:"ERR_CLIENT_ID_BADLY_FORMED",ERR_CANNOT_PING_OFFLINE:"ERR_CANNOT_PING_OFFLINE",ERR_CONNECTION_SEQ_INTEGER_OVERFLOW:"ERR_CONNECTION_SEQ_INTEGER_OVERFLOW",ERR_CONNECTION_STATE_TRANSITION_INVALID:"ERR_CONNECTION_STATE_TRANSITION_INVALID",ERR_DATABASE_ADAPTER_NOT_FOUND:"ERR_DATABASE_ADAPTER_NOT_FOUND",ERR_DATABASE_DOES_NOT_SUPPORT_SUBSCRIBE:"ERR_DATABASE_DOES_NOT_SUPPORT_SUBSCRIBE",ERR_DATABASE_METHOD_NOT_IMPLEMENTED:"ERR_DATABASE_METHOD_NOT_IMPLEMENTED",ERR_DEFAULT_TYPE_MISMATCH:"ERR_DEFAULT_TYPE_MISMATCH",ERR_DOC_MISSING_VERSION:"ERR_DOC_MISSING_VERSION",ERR_DOC_ALREADY_CREATED:"ERR_DOC_ALREADY_CREATED",ERR_DOC_DOES_NOT_EXIST:"ERR_DOC_DOES_NOT_EXIST",ERR_DOC_TYPE_NOT_RECOGNIZED:"ERR_DOC_TYPE_NOT_RECOGNIZED",ERR_DOC_WAS_DELETED:"ERR_DOC_WAS_DELETED",ERR_INFLIGHT_OP_MISSING:"ERR_INFLIGHT_OP_MISSING",ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION:"ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION",ERR_MAX_SUBMIT_RETRIES_EXCEEDED:"ERR_MAX_SUBMIT_RETRIES_EXCEEDED",ERR_MESSAGE_BADLY_FORMED:"ERR_MESSAGE_BADLY_FORMED",ERR_MILESTONE_ARGUMENT_INVALID:"ERR_MILESTONE_ARGUMENT_INVALID",ERR_OP_ALREADY_SUBMITTED:"ERR_OP_ALREADY_SUBMITTED",ERR_OP_NOT_ALLOWED_IN_PROJECTION:"ERR_OP_NOT_ALLOWED_IN_PROJECTION",ERR_OP_SUBMIT_REJECTED:"ERR_OP_SUBMIT_REJECTED",ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM:"ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM",ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM:"ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM",ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT:"ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT",ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED:"ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED",ERR_OT_OP_BADLY_FORMED:"ERR_OT_OP_BADLY_FORMED",ERR_OT_OP_NOT_APPLIED:"ERR_OT_OP_NOT_APPLIED",ERR_OT_OP_NOT_PROVIDED:"ERR_OT_OP_NOT_PROVIDED",ERR_PRESENCE_TRANSFORM_FAILED:"ERR_PRESENCE_TRANSFORM_FAILED",ERR_PROTOCOL_VERSION_NOT_SUPPORTED:"ERR_PROTOCOL_VERSION_NOT_SUPPORTED",ERR_QUERY_EMITTER_LISTENER_NOT_ASSIGNED:"ERR_QUERY_EMITTER_LISTENER_NOT_ASSIGNED",ERR_SNAPSHOT_READ_SILENT_REJECTION:"ERR_SNAPSHOT_READ_SILENT_REJECTION",ERR_SNAPSHOT_READS_REJECTED:"ERR_SNAPSHOT_READS_REJECTED",ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND:"ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND",ERR_TYPE_CANNOT_BE_PROJECTED:"ERR_TYPE_CANNOT_BE_PROJECTED",ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE:"ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE",ERR_UNKNOWN_ERROR:"ERR_UNKNOWN_ERROR"};var Mh=el,pu={},E2=aO;function aO(n,t,e,r){var i=function(s,l,c,d){t(c,s,l,"left"),t(d,l,s,"right")},o=n.transformX=function(s,l){e(s),e(l);for(var c=[],d=0;d<l.length;d++){for(var h=l[d],C=[],E=0;E<s.length;){var x=[];if(i(s[E],h,C,x),E++,x.length===1)h=x[0];else if(x.length===0){for(var v=E;v<s.length;v++)r(C,s[v]);h=null;break}else{for(var k=o(s.slice(E),x),L=0;L<k[0].length;L++)r(C,k[0][L]);for(var M=0;M<k[1].length;M++)r(c,k[1][M]);h=null;break}}h!=null&&r(c,h),s=C}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?t([],s[0],l[0],c):c==="left"?o(s,l)[0]:o(l,s)[1]}}var A2={exports:{}},Xo=A2.exports={name:"text0",uri:"http://sharejs.org/types/textv0",create:function(n){if(n!=null&&typeof n!="string")throw new Error("Initial data must be a string");return n||""}},Cp=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},Ep=function(n){if(typeof n.p!="number")throw new Error("component missing position field");if(typeof n.i=="string"==(typeof n.d=="string"))throw new Error("component needs an i or d field");if(n.p<0)throw new Error("position cannot be negative")},Uh=function(n){for(var t=0;t<n.length;t++)Ep(n[t])};Xo.apply=function(n,t){var e;Uh(t);for(var r=0;r<t.length;r++){var i=t[r];if(i.i!=null)n=Cp(n,i.p,i.i);else{if(e=n.slice(i.p,i.p+i.d.length),i.d!==e)throw new Error("Delete component '"+i.d+"' does not match deleted text '"+e+"'");n=n.slice(0,i.p)+n.slice(i.p+i.d.length)}}return n};var oo=Xo._append=function(n,t){if(!(t.i===""||t.d===""))if(n.length===0)n.push(t);else{var e=n[n.length-1];e.i!=null&&t.i!=null&&e.p<=t.p&&t.p<=e.p+e.i.length?n[n.length-1]={i:Cp(e.i,t.p-e.p,t.i),p:e.p}:e.d!=null&&t.d!=null&&t.p<=e.p&&e.p<=t.p+t.d.length?n[n.length-1]={d:Cp(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};Xo.compose=function(n,t){Uh(n),Uh(t);for(var e=n.slice(),r=0;r<t.length;r++)oo(e,t[r]);return e},Xo.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var r=n[e];r.p==null&&(r.p=0),oo(t,r)}return t};var Ap=function(n,t,e){return t.i!=null?t.p<n||t.p===n&&e?n+t.i.length:n:n<=t.p?n:n<=t.p+t.d.length?t.p:n-t.d.length};Xo.transformCursor=function(n,t,e){for(var r=e==="right",i=0;i<t.length;i++)n=Ap(n,t[i],r);return n};var cO=Xo._tc=function(n,t,e,r){if(Ep(t),Ep(e),t.i!=null)oo(n,{i:t.i,p:Ap(t.p,e,r==="right")});else if(e.i!=null){var i=t.d;t.p<e.p&&(oo(n,{d:i.slice(0,e.p-t.p),p:t.p}),i=i.slice(e.p-t.p)),i!==""&&oo(n,{d:i,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)oo(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)oo(n,t);else{var o={d:"",p:t.p};t.p<e.p&&(o.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(o.d+=t.d.slice(e.p+e.d.length-t.p));var s=Math.max(t.p,e.p),l=Math.min(t.p+t.d.length,e.p+e.d.length),c=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(c!==d)throw new Error("Delete ops delete different text in the same region of the document");o.d!==""&&(o.p=Ap(o.p,e),oo(n,o))}return n},uO=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Xo.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=uO(n[t]);return n},E2(Xo,cO,Uh,oo);var Oh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},fO=function(n){return!!n&&n.constructor===Object},Pr=function(n){return JSON.parse(JSON.stringify(n))},St={name:"json0",uri:"http://sharejs.org/types/JSONv0"},so={};St.registerSubtype=function(n){so[n.name]=n},St.create=function(n){return n===void 0?null:Pr(n)},St.invertComponent=function(n){var t={p:n.p};return n.t&&so[n.t]&&(t.t=n.t,t.o=so[n.t].invert(n.o)),n.si!==void 0&&(t.sd=n.si),n.sd!==void 0&&(t.si=n.sd),n.oi!==void 0&&(t.od=n.oi),n.od!==void 0&&(t.oi=n.od),n.li!==void 0&&(t.ld=n.li),n.ld!==void 0&&(t.li=n.ld),n.na!==void 0&&(t.na=-n.na),n.lm!==void 0&&(t.lm=n.p[n.p.length-1],t.p=n.p.slice(0,n.p.length-1).concat([n.lm])),t},St.invert=function(n){for(var t=n.slice().reverse(),e=[],r=0;r<t.length;r++)e.push(St.invertComponent(t[r]));return e},St.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Oh(n[t].p))throw new Error("Missing path")},St.checkList=function(n){if(!Oh(n))throw new Error("Referenced element not a list")},St.checkObj=function(n){if(!fO(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Cu(n){n.t="text0";var t={p:n.p.pop()};n.si!=null&&(t.i=n.si),n.sd!=null&&(t.d=n.sd),n.o=[t]}function Eu(n){n.p.push(n.o[0].p),n.o[0].i!=null&&(n.si=n.o[0].i),n.o[0].d!=null&&(n.sd=n.o[0].d),delete n.t,delete n.o}St.apply=function(n,t){St.checkValidOp(t),t=Pr(t);for(var e={data:n},r=0;r<t.length;r++){var i=t[r];(i.si!=null||i.sd!=null)&&Cu(i);for(var o=null,s=e,l="data",c=0;c<i.p.length;c++){var d=i.p[c];if(o=s,s=s[l],l=d,o==null)throw new Error("Path invalid")}if(i.t&&i.o!==void 0&&so[i.t])s[l]=so[i.t].apply(s[l],i.o);else if(i.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=i.na}else if(i.li!==void 0&&i.ld!==void 0)St.checkList(s),s[l]=i.li;else if(i.li!==void 0)St.checkList(s),s.splice(l,0,i.li);else if(i.ld!==void 0)St.checkList(s),s.splice(l,1);else if(i.lm!==void 0){if(St.checkList(s),i.lm!=l){var h=s[l];s.splice(l,1),s.splice(i.lm,0,h)}}else if(i.oi!==void 0)St.checkObj(s),s[l]=i.oi;else if(i.od!==void 0)St.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},St.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},St.incrementalApply=function(n,t,e){for(var r=0;r<t.length;r++){var i=[t[r]];n=St.apply(n,i),e(i,n)}return n};var dO=St.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var r=0;r<n.length;r++)if(n[r]!==t[r]&&(!e||r!==n.length-1))return!1;return!0};St.append=function(n,t){if(t=Pr(t),n.length===0){n.push(t);return}var e=n[n.length-1];if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Cu(t),Cu(e)),dO(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&so[t.t]){if(e.o=so[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var r=t.p,i=0;i<e.o.length-1;i++)t.o=[e.o.pop()],t.p=r.slice(),Eu(t),n.push(t);Eu(e)}}else e.na!=null&&t.na!=null?n[n.length-1]={p:e.p,na:e.na+t.na}:e.li!==void 0&&t.li===void 0&&t.ld===e.li?e.ld!==void 0?delete e.li:n.pop():e.od!==void 0&&e.oi===void 0&&t.oi!==void 0&&t.od===void 0?e.oi=t.oi:e.oi!==void 0&&t.od!==void 0?t.oi!==void 0?e.oi=t.oi:e.od!==void 0?delete e.oi:n.pop():t.lm!==void 0&&t.p[t.p.length-1]===t.lm||n.push(t);else(t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Eu(t),Eu(e)),n.push(t)},St.compose=function(n,t){St.checkValidOp(n),St.checkValidOp(t);for(var e=Pr(n),r=0;r<t.length;r++)St.append(e,t[r]);return e},St.normalize=function(n){var t=[];n=Oh(n)?n:[n];for(var e=0;e<n.length;e++){var r=n[e];r.p==null&&(r.p=[]),St.append(t,r)}return t},St.commonLengthForOps=function(n,t){var e=n.p.length,r=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&r++,e===0)return-1;if(r===0)return null;e--,r--;for(var i=0;i<e;i++){var o=n.p[i];if(i>=r||o!==t.p[i])return null}return e},St.canOpAffectPath=function(n,t){return St.commonLengthForOps({p:t},n)!=null},St.transformComponent=function(n,t,e,r){t=Pr(t);var i=St.commonLengthForOps(e,t),o=St.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,o!=null&&l>s&&t.p[o]==e.p[o]){if(t.ld!==void 0){var c=Pr(e);c.p=c.p.slice(s),t.ld=St.apply(Pr(t.ld),[c])}else if(t.od!==void 0){var c=Pr(e);c.p=c.p.slice(s),t.od=St.apply(Pr(t.od),[c])}}if(i!=null){var d=s==l,c=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Cu(t),c=Pr(e),Cu(c)),c.t&&so[c.t]){if(t.t&&t.t===c.t){var h=so[t.t].transform(t.o,c.o,r);if(t.si!=null||t.sd!=null)for(var C=t.p,E=0;E<h.length;E++)t.o=[h[E]],t.p=C.slice(),Eu(t),St.append(n,t);else(!Oh(h)||h.length>0)&&(t.o=h,St.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[i]===t.p[i])if(d){if(t.ld!==void 0)if(t.li!==void 0&&r==="left")t.ld=Pr(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&d&&t.p[i]===e.p[i]?r==="right"&&t.p[i]++:e.p[i]<=t.p[i]&&t.p[i]++,t.lm!==void 0&&d&&e.p[i]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[i]===t.p[i])return n;var C=e.p[i],x=t.p[i],v=t.lm;(C<v||C===v&&x<v)&&t.lm--}if(e.p[i]<t.p[i])t.p[i]--;else if(e.p[i]===t.p[i]){if(l<s)return n;if(t.ld!==void 0)if(t.li!==void 0)delete t.ld;else return n}}else if(e.lm!==void 0)if(t.lm!==void 0&&s===l){var x=t.p[i],v=t.lm,k=e.p[i],L=e.lm;if(k!==L)if(x===k)if(r==="left")t.p[i]=L,x===v&&(t.lm=L);else return n;else x>k&&t.p[i]--,x>L?t.p[i]++:x===L&&k>L&&(t.p[i]++,x===v&&t.lm++),(v>k||v===k&&v>x)&&t.lm--,v>L?t.lm++:v===L&&(L>k&&v>x||L<k&&v<x?r==="right"&&t.lm++:v>x?t.lm++:v===k&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var x=e.p[i],v=e.lm;C=t.p[i],C>x&&t.p[i]--,C>v&&t.p[i]++}else{var x=e.p[i],v=e.lm;C=t.p[i],C===x?t.p[i]=v:(C>x&&t.p[i]--,(C>v||C===v&&x>v)&&t.p[i]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[i]===e.p[i])if(t.oi!==void 0&&d){if(r==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[i]===e.p[i])if(r==="left")St.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[i]==e.p[i]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return St.append(n,t),n},E2(St,St.transformComponent,St.checkValidOp,St.append);var hO=A2.exports;St.registerSubtype(hO);var mO=St,gO={type:mO};(function(n){n.defaultType=gO.type,n.map={},n.register=function(t){t.name&&(n.map[t.name]=t),t.uri&&(n.map[t.uri]=t)},n.register(n.defaultType)})(pu);var Fr={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var r in e)return!0;return!1},n.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},n.isValidVersion=function(e){return e===null?!0:n.isInteger(e)&&e>=0},n.isValidTimestamp=function(e){return n.isValidVersion(e)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var e=arguments[0],r=1;r<arguments.length;r++){var i=arguments[r];e=e[i]||(r===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],r=arguments[arguments.length-1],i=1;i<arguments.length-1;i++){var o=arguments[i];e=e[o]||(e[o]=i===arguments.length-2?r():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],r=[e],i=1;i<arguments.length-1;i++){var o=arguments[i];if(!e.hasOwnProperty(o))break;e=e[o],r.push(e)}for(var i=r.length-1;i>=0;i--){var s=r[i],o=arguments[i+1],l=s[o];(i===r.length-1||!n.hasKeys(l))&&delete s[o]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,r){var i=!1;return e.forEach(function(o){o&&(o(r),i=!0)}),i},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];setTimeout(function(){e.apply(null,r)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})(Fr);var x2=Array.isArray,b2=Object.keys,pO=Object.prototype.hasOwnProperty,CO=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=x2(t),i=x2(e),o,s,l;if(r&&i){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!n(t[o],e[o]))return!1;return!0}if(r!=i)return!1;var c=t instanceof Date,d=e instanceof Date;if(c!=d)return!1;if(c&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,C=e instanceof RegExp;if(h!=C)return!1;if(h&&C)return t.toString()==e.toString();var E=b2(t);if(s=E.length,s!==b2(e).length)return!1;for(o=s;o--!==0;)if(!pO.call(e,E[o]))return!1;for(o=s;o--!==0;)if(l=E[o],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},v2=qo,EO=C2,Yn=Mh,Nh=pu,Kr=Fr,AO=Kr.clone,xO=CO,Un=Yn.CODES,bO=Ft;function Ft(n,t,e){v2.EventEmitter.call(this),this.connection=n,this.collection=t,this.id=e,this.version=null,this.type=null,this.data=void 0,this.inflightFetch=[],this.inflightSubscribe=null,this.pendingFetch=[],this.pendingSubscribe=[],this.subscribed=!1,this.wantSubscribe=!1,this._wantsDestroy=!1,this.inflightOp=null,this.pendingOps=[],this.type=null,this.applyStack=null,this.preventCompose=!1,this.submitSource=!1,this.paused=!1,this._dataStateVersion=0}v2.mixin(Ft),Ft.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this;t.whenNothingPending(function(){t.wantSubscribe?t.unsubscribe(function(e){if(e)return n?n(e):t.emit("error",e);t.connection._destroyDoc(t),n&&n()}):(t.connection._destroyDoc(t),n&&n())})},Ft.prototype._setType=function(n){if(typeof n=="string"&&(n=Nh.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Yn(Un.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},Ft.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Ft.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new Yn(Un.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return t&&this.once("no write pending",t);var e=new Yn(Un.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}return n.v>this.version?this.fetch(t):t&&t()}if(this.version>n.v)return t&&t();this.version=n.v;var r=n.type===void 0?Nh.defaultType:n.type;this._setType(r),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),t&&t()},Ft.prototype.whenNothingPending=function(n){var t=this;Kr.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},Ft.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Ft.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Ft.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Ft.prototype._emitResponseError=function(n,t){if(n&&n.code===Un.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,t&&t(),this._emitNothingPending();return}if(t){t(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},Ft.prototype._handleFetch=function(n,t){var e=this.pendingFetch;this.pendingFetch=[];var r=this.inflightFetch.shift();if(r&&e.push(r),e.length&&(r=function(i){Kr.callEach(e,i)}),n)return this._emitResponseError(n,r);this.ingestSnapshot(t,r),this._emitNothingPending()},Ft.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var r=this.pendingFetch;this.pendingFetch=[],e.callback&&r.push(e.callback);var i;if(r.length&&(i=function(o){Kr.callEach(r,o)}),n)return this._emitResponseError(n,i);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,i):i&&i(),this._emitNothingPending(),this._flushSubscribe()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Un.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&t.src===this.inflightOp.src&&t.seq===this.inflightOp.seq){this._opAcknowledged(t);return}if(this.version==null||t.v>this.version){this.fetch();return}if(!(t.v<this.version)){if(this.inflightOp){var e=Ph(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var r=0;r<this.pendingOps.length;r++){var e=Ph(this.pendingOps[r],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(i){return this._hardRollback(i)}}},Ft.prototype._onConnectionStateChanged=function(){this.connection.canSend?(this.flush(),this._resubscribe()):(this.inflightOp&&(this.pendingOps.unshift(this.inflightOp),this.inflightOp=null),this.subscribed=!1,this.inflightSubscribe&&(this.inflightSubscribe.wantSubscribe?(this.pendingSubscribe.unshift(this.inflightSubscribe),this.inflightSubscribe=null):this._handleSubscribe()),this.inflightFetch.length&&(this.pendingFetch=this.pendingFetch.concat(this.inflightFetch),this.inflightFetch.length=0))},Ft.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(t){return t.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},Ft.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);vO(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},Ft.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},Ft.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},Ft.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,r=e&&e.wantSubscribe===n;if(r){e.callback=BO([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},Ft.prototype._flushSubscribe=function(){if(!(this.inflightSubscribe||!this.pendingSubscribe.length)){if(this.connection.canSend){this.inflightSubscribe=this.pendingSubscribe.shift(),this.wantSubscribe=this.inflightSubscribe.wantSubscribe,this.wantSubscribe?this.connection.sendSubscribe(this):(this.subscribed=!1,this.connection.sendUnsubscribe(this));return}if(!this.pendingSubscribe[0].wantSubscribe){this.inflightSubscribe=this.pendingSubscribe.shift();var n=this;Kr.nextTick(function(){n._handleSubscribe()})}}};function vO(n,t,e){if(t){var r=n.pop();n.push(function(i){r&&r(i),e&&e(i)})}else n.push(e)}function BO(n){return n=n.filter(Kr.truthy),n.length?function(t){Kr.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function TO(n){delete n.op,delete n.create,delete n.del}function Ph(n,t){if(n.del)return TO(t);if(t.del)return new Yn(Un.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Yn(Un.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Yn(Un.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var e=n.type.transformX(n.op,t.op);n.op=e[0],t.op=e[1]}else{var r=n.type.transform(n.op,t.op,"left"),i=n.type.transform(t.op,n.op,"right");n.op=r,t.op=i}}}Ft.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Yn(Un.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,t),!t&&this.type===Nh.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,r=0;r<n.op.length;r++){var i=n.op[r],o={op:[i]};this.emit("before op",o.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Ph(this.applyStack[s],o);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,o.op)),this.emit("op",o.op,t,n.src)}this.emit("op batch",n.op,t),this._popApplyStack(e);return}this.emit("before op",n.op,t,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,t,n.src),this.emit("op batch",n.op,t);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",t);return}if(n.del){var c=this.data;this._setType(null),this.emit("del",c,t);return}},Ft.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var t=this.inflightOp;if(!t){var e=new Yn(Un.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",e)}if(t.sentAt=Date.now(),t.retries=t.retries==null?0:t.retries+1,t.seq==null){if(this.connection.seq>=Kr.MAX_SAFE_INTEGER)return this.emit("error",new Yn(Un.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));t.seq=this.connection.seq++}this.connection.sendOp(this,t),t.src==null&&(t.src=n)}},Ft.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var r=new Yn(Un.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(r):this.emit("error",r)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(o){return this._hardRollback(o)}var i=this;Kr.nextTick(function(){i.flush()})},Ft.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var r=this._tryCompose(n);if(r){r.callbacks.push(e);return}}n.type=this.type,n.callbacks=[e],this.pendingOps.push(n)},Ft.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var t=this.applyStack[0];if(this.applyStack=null,!!t){var e=this.pendingOps.indexOf(t);if(e!==-1)for(var r=this.pendingOps.splice(e),e=0;e<r.length;e++){var t=r[e],i=this._tryCompose(t);i?i.callbacks=i.callbacks.concat(t.callbacks):this.pendingOps.push(t)}}},Ft.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!xO(n.source,t.source))){if(t.create&&"op"in n)return t.create.data=this.type.apply(t.create.data,n.op),t;if("op"in t&&"op"in n&&this.type.compose)return t.op=this.type.compose(t.op,n.op),t}}},Ft.prototype.submitOp=function(n,t,e){typeof t=="function"&&(e=t,t=null);var r={op:n},i=t&&t.source;this._submit(r,i,e)},Ft.prototype.create=function(n,t,e,r){if(typeof t=="function"?(r=t,e=null,t=null):typeof e=="function"&&(r=e,e=null),t||(t=Nh.defaultType.uri),this.type){var i=new Yn(Un.ERR_DOC_ALREADY_CREATED,"Document already exists");return r?r(i):this.emit("error",i)}var o={create:{type:t,data:n}},s=e&&e.source;this._submit(o,s,r)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Yn(Un.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var r={del:!0},i=n&&n.source;this._submit(r,i,t)},Ft.prototype.pause=function(){this.paused=!0},Ft.prototype.resume=function(){this.paused=!1,this.flush()},Ft.prototype.toSnapshot=function(){return{v:this.version,data:AO(this.data),type:this.type.uri}},Ft.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return EO.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},Ft.prototype._rollback=function(n){var t=this.inflightOp;if("op"in t&&t.type.invert){try{t.op=t.type.invert(t.op)}catch{return this._hardRollback(n)}for(var e=0;e<this.pendingOps.length;e++){var r=Ph(this.pendingOps[e],t);if(r)return this._hardRollback(r)}try{this._otApply(t,!1)}catch(i){return this._hardRollback(i)}this._clearInflightOp(n);return}this._hardRollback(n)},Ft.prototype._hardRollback=function(n){var t=[];this.inflightOp&&t.push(this.inflightOp),t=t.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var e=this;this.fetch(function(){for(var r=!!t.length,i=0;i<t.length;i++)r=Kr.callEach(t[i].callbacks,n)&&r;if(n&&!r)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=Kr.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var nl={};nl.ACTIONS={initLegacy:"init",handshake:"hs",queryFetch:"qf",querySubscribe:"qs",queryUnsubscribe:"qu",queryUpdate:"q",bulkFetch:"bf",bulkSubscribe:"bs",bulkUnsubscribe:"bu",fetch:"f",subscribe:"s",unsubscribe:"u",op:"op",snapshotFetch:"nf",snapshotFetchByTimestamp:"nt",pingPong:"pp",presence:"p",presenceSubscribe:"ps",presenceUnsubscribe:"pu",presenceRequest:"pr"};var B2=qo,T2=nl.ACTIONS,yO=Fr,RO=On;function On(n,t,e,r,i,o,s){B2.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=r,this.query=i,this.results=null,o&&o.results&&(this.results=o.results,delete o.results),this.extra=void 0,this.options=o,this.callback=s,this.ready=!1,this.sent=!1}B2.mixin(On),On.prototype.hasPending=function(){return!this.ready},On.prototype.send=function(){if(!!this.connection.canSend){var n={a:this.action,id:this.id,c:this.collection,q:this.query};if(this.options&&(n.o=this.options),this.results){for(var t=[],e=0;e<this.results.length;e++){var r=this.results[e];t.push([r.id,r.version])}n.r=t}this.connection.send(n),this.sent=!0}},On.prototype.destroy=function(n){this.connection.canSend&&this.action===T2.querySubscribe&&this.connection.send({a:T2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&yO.nextTick(n)},On.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},On.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},On.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},On.prototype._handleResponse=function(n,t,e){var r=this.callback;if(this.callback=null,n)return this._finishResponse(n,r);if(!t)return this._finishResponse(null,r);var i=this,o=1,s=function(h){if(h)return i._finishResponse(h,r);--o||i._finishResponse(null,r)};if(Array.isArray(t))o+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){o++;var c=t[l],d=this.connection.get(c.c||this.collection,l);d.ingestSnapshot(c,s)}s()},On.prototype._ingestSnapshots=function(n,t){for(var e=[],r=0;r<n.length;r++){var i=n[r],o=this.connection.get(i.c||this.collection,i.d);o.ingestSnapshot(i,t),e.push(o)}return e},On.prototype._finishResponse=function(n,t){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),t?t(n):this.emit("error",n);t&&t(null,this.results,this.extra)},On.prototype._handleError=function(n){this.emit("error",n)},On.prototype._handleDiff=function(n){for(var t=0;t<n.length;t++){var e=n[t];e.type==="insert"&&(e.values=this._ingestSnapshots(e.values))}for(var t=0;t<n.length;t++){var e=n[t];switch(e.type){case"insert":var r=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(r)),this.emit("insert",r,e.index);break;case"remove":var o=e.howMany||1,i=this.results.splice(e.index,o);this.emit("remove",i,e.index);break;case"move":var o=e.howMany||1,s=this.results.splice(e.from,o);Array.prototype.splice.apply(this.results,[e.to,0].concat(s)),this.emit("move",s,e.from,e.to);break}}this.emit("changed",this.results)},On.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var y2=qo,kO=nl.ACTIONS,wO=Fr,R2=gi;function gi(n,t){if(y2.EventEmitter.call(this),!t||typeof t!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=t,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}y2.mixin(gi),gi.prototype.submit=function(n,t){this.value=n,this.send(t)},gi.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},gi.prototype.destroy=function(n){var t=this;this.submit(null,function(e){if(e)return t._callbackOrEmit(e,n);delete t.presence.localPresences[t.presenceId],n&&n()})},gi.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},gi.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},gi.prototype._message=function(){return{a:kO.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},gi.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},gi.prototype._callbackOrEmit=function(n,t){if(t)return wO.nextTick(t,n);n&&this.emit("error",n)};var SO=Fr,k2=xp;function xp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}xp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},xp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&SO.nextTick(n)};var bp={exports:{}};(function(n,t){(function(e,r){r(t)})(Dn,function(e){function r(y,S){S=S|0;for(var _=Math.max(y.length-S,0),N=Array(_),H=0;H<_;H++)N[H]=y[S+H];return N}var i=function(y){var S=r(arguments,1);return function(){var _=r(arguments);return y.apply(null,S.concat(_))}},o=function(y){return function(){var S=r(arguments),_=S.pop();y.call(this,S,_)}};function s(y){var S=typeof y;return y!=null&&(S=="object"||S=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function d(y){setTimeout(y,0)}function h(y){return function(S){var _=r(arguments,1);y(function(){S.apply(null,_)})}}var C;l?C=setImmediate:c?C=process.nextTick:C=d;var E=h(C);function x(y){return o(function(S,_){var N;try{N=y.apply(this,S)}catch(H){return _(H)}s(N)&&typeof N.then=="function"?N.then(function(H){v(_,null,H)},function(H){v(_,H.message?H:new Error(H))}):_(null,N)})}function v(y,S,_){try{y(S,_)}catch(N){E(k,N)}}function k(y){throw y}var L=typeof Symbol=="function";function M(y){return L&&y[Symbol.toStringTag]==="AsyncFunction"}function U(y){return M(y)?x(y):y}function F(y){return function(S){var _=r(arguments,1),N=o(function(H,$){var X=this;return y(S,function(J,ct){U(J).apply(X,H.concat(ct))},$)});return _.length?N.apply(this,_):N}}var G=typeof Dn=="object"&&Dn&&Dn.Object===Object&&Dn,W=typeof self=="object"&&self&&self.Object===Object&&self,rt=G||W||Function("return this")(),at=rt.Symbol,At=Object.prototype,Mt=At.hasOwnProperty,Bt=At.toString,se=at?at.toStringTag:void 0;function ne(y){var S=Mt.call(y,se),_=y[se];try{y[se]=void 0;var N=!0}catch{}var H=Bt.call(y);return N&&(S?y[se]=_:delete y[se]),H}var Tn=Object.prototype,xe=Tn.toString;function Pn(y){return xe.call(y)}var Si="[object Null]",yn="[object Undefined]",gn=at?at.toStringTag:void 0;function Li(y){return y==null?y===void 0?yn:Si:gn&&gn in Object(y)?ne(y):Pn(y)}var ho="[object AsyncFunction]",Ar="[object Function]",AA="[object GeneratorFunction]",xA="[object Proxy]";function bA(y){if(!s(y))return!1;var S=Li(y);return S==Ar||S==AA||S==ho||S==xA}var ds=9007199254740991;function El(y){return typeof y=="number"&&y>-1&&y%1==0&&y<=ds}function Al(y){return y!=null&&El(y.length)&&!bA(y)}var mo={};function Ht(){}function Ii(y){return function(){if(y!==null){var S=y;y=null,S.apply(this,arguments)}}}var hs=typeof Symbol=="function"&&Symbol.iterator,uc=function(y){return hs&&y[hs]&&y[hs]()};function am(y,S){for(var _=-1,N=Array(y);++_<y;)N[_]=S(_);return N}function pn(y){return y!=null&&typeof y=="object"}var xl="[object Arguments]";function cm(y){return pn(y)&&Li(y)==xl}var xr=Object.prototype,um=xr.hasOwnProperty,vA=xr.propertyIsEnumerable,bl=cm(function(){return arguments}())?cm:function(y){return pn(y)&&um.call(y,"callee")&&!vA.call(y,"callee")},ye=Array.isArray;function vl(){return!1}var Bl=typeof e=="object"&&e&&!e.nodeType&&e,fm=Bl&&!0&&n&&!n.nodeType&&n,Tl=fm&&fm.exports===Bl,dm=Tl?rt.Buffer:void 0,yl=dm?dm.isBuffer:void 0,ms=yl||vl,vf=9007199254740991,Bf=/^(?:0|[1-9]\d*)$/;function Tf(y,S){var _=typeof y;return S=S==null?vf:S,!!S&&(_=="number"||_!="symbol"&&Bf.test(y))&&y>-1&&y%1==0&&y<S}var yf="[object Arguments]",Rf="[object Array]",kf="[object Boolean]",wf="[object Date]",Sf="[object Error]",Lf="[object Function]",BA="[object Map]",TA="[object Number]",yA="[object Object]",hm="[object RegExp]",mm="[object Set]",RA="[object String]",kA="[object WeakMap]",wA="[object ArrayBuffer]",SA="[object DataView]",gm="[object Float32Array]",LA="[object Float64Array]",IA="[object Int8Array]",DA="[object Int16Array]",If="[object Int32Array]",_A="[object Uint8Array]",Df="[object Uint8ClampedArray]",MA="[object Uint16Array]",UA="[object Uint32Array]",fe={};fe[gm]=fe[LA]=fe[IA]=fe[DA]=fe[If]=fe[_A]=fe[Df]=fe[MA]=fe[UA]=!0,fe[yf]=fe[Rf]=fe[wA]=fe[kf]=fe[SA]=fe[wf]=fe[Sf]=fe[Lf]=fe[BA]=fe[TA]=fe[yA]=fe[hm]=fe[mm]=fe[RA]=fe[kA]=!1;function OA(y){return pn(y)&&El(y.length)&&!!fe[Li(y)]}function NA(y){return function(S){return y(S)}}var pm=typeof e=="object"&&e&&!e.nodeType&&e,Rl=pm&&!0&&n&&!n.nodeType&&n,PA=Rl&&Rl.exports===pm,fc=PA&&G.process,Cm=function(){try{var y=Rl&&Rl.require&&Rl.require("util").types;return y||fc&&fc.binding&&fc.binding("util")}catch{}}(),Em=Cm&&Cm.isTypedArray,FA=Em?NA(Em):OA,KA=Object.prototype,VA=KA.hasOwnProperty;function $A(y,S){var _=ye(y),N=!_&&bl(y),H=!_&&!N&&ms(y),$=!_&&!N&&!H&&FA(y),X=_||N||H||$,J=X?am(y.length,String):[],ct=J.length;for(var Ct in y)(S||VA.call(y,Ct))&&!(X&&(Ct=="length"||H&&(Ct=="offset"||Ct=="parent")||$&&(Ct=="buffer"||Ct=="byteLength"||Ct=="byteOffset")||Tf(Ct,ct)))&&J.push(Ct);return J}var dc=Object.prototype;function HA(y){var S=y&&y.constructor,_=typeof S=="function"&&S.prototype||dc;return y===_}function hc(y,S){return function(_){return y(S(_))}}var jA=hc(Object.keys,Object),zA=Object.prototype,GA=zA.hasOwnProperty;function Am(y){if(!HA(y))return jA(y);var S=[];for(var _ in Object(y))GA.call(y,_)&&_!="constructor"&&S.push(_);return S}function mc(y){return Al(y)?$A(y):Am(y)}function xm(y){var S=-1,_=y.length;return function(){return++S<_?{value:y[S],key:S}:null}}function WA(y){var S=-1;return function(){var N=y.next();return N.done?null:(S++,{value:N.value,key:S})}}function qA(y){var S=mc(y),_=-1,N=S.length;return function H(){var $=S[++_];return $==="__proto__"?H():_<N?{value:y[$],key:$}:null}}function XA(y){if(Al(y))return xm(y);var S=uc(y);return S?WA(S):qA(y)}function br(y){return function(){if(y===null)throw new Error("Callback was already called.");var S=y;y=null,S.apply(this,arguments)}}function kl(y){return function(S,_,N){if(N=Ii(N||Ht),y<=0||!S)return N(null);var H=XA(S),$=!1,X=0,J=!1;function ct(ut,xt){if(X-=1,ut)$=!0,N(ut);else{if(xt===mo||$&&X<=0)return $=!0,N(null);J||Ct()}}function Ct(){for(J=!0;X<y&&!$;){var ut=H();if(ut===null){$=!0,X<=0&&N(null);return}X+=1,_(ut.value,ut.key,br(ct))}J=!1}Ct()}}function Di(y,S,_,N){kl(S)(y,U(_),N)}function ze(y,S){return function(_,N,H){return y(_,S,N,H)}}function _f(y,S,_){_=Ii(_||Ht);var N=0,H=0,$=y.length;$===0&&_(null);function X(J,ct){J?_(J):(++H===$||ct===mo)&&_(null)}for(;N<$;N++)S(y[N],N,br(X))}var QA=ze(Di,1/0),Xr=function(y,S,_){var N=Al(y)?_f:QA;N(y,U(S),_)};function Qr(y){return function(S,_,N){return y(Xr,S,U(_),N)}}function Mf(y,S,_,N){N=N||Ht,S=S||[];var H=[],$=0,X=U(_);y(S,function(J,ct,Ct){var ut=$++;X(J,function(xt,Yt){H[ut]=Yt,Ct(xt)})},function(J){N(J,H)})}var gc=Qr(Mf),Uf=F(gc);function go(y){return function(S,_,N,H){return y(kl(_),S,U(N),H)}}var _i=go(Mf),Of=ze(_i,1),Nf=F(Of);function gs(y,S){for(var _=-1,N=y==null?0:y.length;++_<N&&S(y[_],_,y)!==!1;);return y}function Pf(y){return function(S,_,N){for(var H=-1,$=Object(S),X=N(S),J=X.length;J--;){var ct=X[y?J:++H];if(_($[ct],ct,$)===!1)break}return S}}var ps=Pf();function Cs(y,S){return y&&ps(y,S,mc)}function bm(y,S,_,N){for(var H=y.length,$=_+(N?1:-1);N?$--:++$<H;)if(S(y[$],$,y))return $;return-1}function YA(y){return y!==y}function vm(y,S,_){for(var N=_-1,H=y.length;++N<H;)if(y[N]===S)return N;return-1}function wl(y,S,_){return S===S?vm(y,S,_):bm(y,YA,_)}var pc=function(y,S,_){typeof S=="function"&&(_=S,S=null),_=Ii(_||Ht);var N=mc(y),H=N.length;if(!H)return _(null);S||(S=H);var $={},X=0,J=!1,ct=Object.create(null),Ct=[],ut=[],xt={};Cs(y,function(pe,ae){if(!ye(pe)){Yt(ae,[pe]),ut.push(ae);return}var be=pe.slice(0,pe.length-1),Br=be.length;if(Br===0){Yt(ae,pe),ut.push(ae);return}xt[ae]=Br,gs(be,function(R){if(!y[R])throw new Error("async.auto task `"+ae+"` has a non-existent dependency `"+R+"` in "+be.join(", "));on(R,function(){Br--,Br===0&&Yt(ae,pe)})})}),Ax(),Ne();function Yt(pe,ae){Ct.push(function(){vr(pe,ae)})}function Ne(){if(Ct.length===0&&X===0)return _(null,$);for(;Ct.length&&X<S;){var pe=Ct.shift();pe()}}function on(pe,ae){var be=ct[pe];be||(be=ct[pe]=[]),be.push(ae)}function Vn(pe){var ae=ct[pe]||[];gs(ae,function(be){be()}),Ne()}function vr(pe,ae){if(!J){var be=br(function(R,Oi){if(X--,arguments.length>2&&(Oi=r(arguments,1)),R){var bs={};Cs($,function($n,Vt){bs[Vt]=$n}),bs[pe]=Oi,J=!0,ct=Object.create(null),_(R,bs)}else $[pe]=Oi,Vn(pe)});X++;var Br=U(ae[ae.length-1]);ae.length>1?Br($,be):Br(be)}}function Ax(){for(var pe,ae=0;ut.length;)pe=ut.pop(),ae++,gs(xx(pe),function(be){--xt[be]===0&&ut.push(be)});if(ae!==H)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function xx(pe){var ae=[];return Cs(y,function(be,Br){ye(be)&&wl(be,pe,0)>=0&&ae.push(Br)}),ae}};function po(y,S){for(var _=-1,N=y==null?0:y.length,H=Array(N);++_<N;)H[_]=S(y[_],_,y);return H}var JA="[object Symbol]";function ZA(y){return typeof y=="symbol"||pn(y)&&Li(y)==JA}var tx=1/0,Ff=at?at.prototype:void 0,Bm=Ff?Ff.toString:void 0;function Kf(y){if(typeof y=="string")return y;if(ye(y))return po(y,Kf)+"";if(ZA(y))return Bm?Bm.call(y):"";var S=y+"";return S=="0"&&1/y==-tx?"-0":S}function ex(y,S,_){var N=-1,H=y.length;S<0&&(S=-S>H?0:H+S),_=_>H?H:_,_<0&&(_+=H),H=S>_?0:_-S>>>0,S>>>=0;for(var $=Array(H);++N<H;)$[N]=y[N+S];return $}function nx(y,S,_){var N=y.length;return _=_===void 0?N:_,!S&&_>=N?y:ex(y,S,_)}function Vf(y,S){for(var _=y.length;_--&&wl(S,y[_],0)>-1;);return _}function rx(y,S){for(var _=-1,N=y.length;++_<N&&wl(S,y[_],0)>-1;);return _}function ix(y){return y.split("")}var ox="\\ud800-\\udfff",sx="\\u0300-\\u036f",lx="\\ufe20-\\ufe2f",de="\\u20d0-\\u20ff",le=sx+lx+de,ax="\\ufe0e\\ufe0f",cx="\\u200d",ux=RegExp("["+cx+ox+le+ax+"]");function fx(y){return ux.test(y)}var Tm="\\ud800-\\udfff",dx="\\u0300-\\u036f",ym="\\ufe20-\\ufe2f",hx="\\u20d0-\\u20ff",Ye=dx+ym+hx,$f="\\ufe0e\\ufe0f",Co="["+Tm+"]",Cc="["+Ye+"]",Sl="\\ud83c[\\udffb-\\udfff]",Fn="(?:"+Cc+"|"+Sl+")",Hf="[^"+Tm+"]",jf="(?:\\ud83c[\\udde6-\\uddff]){2}",zf="[\\ud800-\\udbff][\\udc00-\\udfff]",Rm="\\u200d",Gf=Fn+"?",Wf="["+$f+"]?",Rn="(?:"+Rm+"(?:"+[Hf,jf,zf].join("|")+")"+Wf+Gf+")*",mx=Wf+Gf+Rn,Kn="(?:"+[Hf+Cc+"?",Cc,jf,zf,Co].join("|")+")",gx=RegExp(Sl+"(?="+Sl+")|"+Kn+mx,"g");function km(y){return y.match(gx)||[]}function Yr(y){return fx(y)?km(y):ix(y)}function Ec(y){return y==null?"":Kf(y)}var qf=/^\s+|\s+$/g;function ge(y,S,_){if(y=Ec(y),y&&(_||S===void 0))return y.replace(qf,"");if(!y||!(S=Kf(S)))return y;var N=Yr(y),H=Yr(S),$=rx(N,H),X=Vf(N,H)+1;return nx(N,$,X).join("")}var Mi=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,Xf=/,/,px=/(=.+)?(\s*)$/,Qf=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function Cx(y){return y=y.toString().replace(Qf,""),y=y.match(Mi)[2].replace(" ",""),y=y?y.split(Xf):[],y=y.map(function(S){return ge(S.replace(px,""))}),y}function wm(y,S){var _={};Cs(y,function(N,H){var $,X=M(N),J=!X&&N.length===1||X&&N.length===0;if(ye(N))$=N.slice(0,-1),N=N[N.length-1],_[H]=$.concat($.length>0?ct:N);else if(J)_[H]=N;else{if($=Cx(N),N.length===0&&!X&&$.length===0)throw new Error("autoInject task functions require explicit parameters.");X||$.pop(),_[H]=$.concat(ct)}function ct(Ct,ut){var xt=po($,function(Yt){return Ct[Yt]});xt.push(ut),U(N).apply(null,xt)}}),pc(_,S)}function nr(){this.head=this.tail=null,this.length=0}function Yf(y,S){y.length=1,y.head=y.tail=S}nr.prototype.removeLink=function(y){return y.prev?y.prev.next=y.next:this.head=y.next,y.next?y.next.prev=y.prev:this.tail=y.prev,y.prev=y.next=null,this.length-=1,y},nr.prototype.empty=function(){for(;this.head;)this.shift();return this},nr.prototype.insertAfter=function(y,S){S.prev=y,S.next=y.next,y.next?y.next.prev=S:this.tail=S,y.next=S,this.length+=1},nr.prototype.insertBefore=function(y,S){S.prev=y.prev,S.next=y,y.prev?y.prev.next=S:this.head=S,y.prev=S,this.length+=1},nr.prototype.unshift=function(y){this.head?this.insertBefore(this.head,y):Yf(this,y)},nr.prototype.push=function(y){this.tail?this.insertAfter(this.tail,y):Yf(this,y)},nr.prototype.shift=function(){return this.head&&this.removeLink(this.head)},nr.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},nr.prototype.toArray=function(){for(var y=Array(this.length),S=this.head,_=0;_<this.length;_++)y[_]=S.data,S=S.next;return y},nr.prototype.remove=function(y){for(var S=this.head;S;){var _=S.next;y(S)&&this.removeLink(S),S=_}return this};function Ll(y,S,_){if(S==null)S=1;else if(S===0)throw new Error("Concurrency must not be zero");var N=U(y),H=0,$=[],X=!1;function J(xt,Yt,Ne){if(Ne!=null&&typeof Ne!="function")throw new Error("task callback must be a function");if(ut.started=!0,ye(xt)||(xt=[xt]),xt.length===0&&ut.idle())return E(function(){ut.drain()});for(var on=0,Vn=xt.length;on<Vn;on++){var vr={data:xt[on],callback:Ne||Ht};Yt?ut._tasks.unshift(vr):ut._tasks.push(vr)}X||(X=!0,E(function(){X=!1,ut.process()}))}function ct(xt){return function(Yt){H-=1;for(var Ne=0,on=xt.length;Ne<on;Ne++){var Vn=xt[Ne],vr=wl($,Vn,0);vr===0?$.shift():vr>0&&$.splice(vr,1),Vn.callback.apply(Vn,arguments),Yt!=null&&ut.error(Yt,Vn.data)}H<=ut.concurrency-ut.buffer&&ut.unsaturated(),ut.idle()&&ut.drain(),ut.process()}}var Ct=!1,ut={_tasks:new nr,concurrency:S,payload:_,saturated:Ht,unsaturated:Ht,buffer:S/4,empty:Ht,drain:Ht,error:Ht,started:!1,paused:!1,push:function(xt,Yt){J(xt,!1,Yt)},kill:function(){ut.drain=Ht,ut._tasks.empty()},unshift:function(xt,Yt){J(xt,!0,Yt)},remove:function(xt){ut._tasks.remove(xt)},process:function(){if(!Ct){for(Ct=!0;!ut.paused&&H<ut.concurrency&&ut._tasks.length;){var xt=[],Yt=[],Ne=ut._tasks.length;ut.payload&&(Ne=Math.min(Ne,ut.payload));for(var on=0;on<Ne;on++){var Vn=ut._tasks.shift();xt.push(Vn),$.push(Vn),Yt.push(Vn.data)}H+=1,ut._tasks.length===0&&ut.empty(),H===ut.concurrency&&ut.saturated();var vr=br(ct(xt));N(Yt,vr)}Ct=!1}},length:function(){return ut._tasks.length},running:function(){return H},workersList:function(){return $},idle:function(){return ut._tasks.length+H===0},pause:function(){ut.paused=!0},resume:function(){ut.paused!==!1&&(ut.paused=!1,E(ut.process))}};return ut}function Eo(y,S){return Ll(y,1,S)}var Es=ze(Di,1);function Jr(y,S,_,N){N=Ii(N||Ht);var H=U(_);Es(y,function($,X,J){H(S,$,function(ct,Ct){S=Ct,J(ct)})},function($){N($,S)})}function Ac(){var y=po(arguments,U);return function(){var S=r(arguments),_=this,N=S[S.length-1];typeof N=="function"?S.pop():N=Ht,Jr(y,S,function(H,$,X){$.apply(_,H.concat(function(J){var ct=r(arguments,1);X(J,ct)}))},function(H,$){N.apply(_,[H].concat($))})}}var xc=function(){return Ac.apply(null,r(arguments).reverse())},Jf=Array.prototype.concat,Il=function(y,S,_,N){N=N||Ht;var H=U(_);_i(y,S,function($,X){H($,function(J){return J?X(J):X(null,r(arguments,1))})},function($,X){for(var J=[],ct=0;ct<X.length;ct++)X[ct]&&(J=Jf.apply(J,X[ct]));return N($,J)})},Sm=ze(Il,1/0),bc=ze(Il,1),vc=function(){var y=r(arguments),S=[null].concat(y);return function(){var _=arguments[arguments.length-1];return _.apply(this,S)}};function Dl(y){return y}function Ao(y,S){return function(_,N,H,$){$=$||Ht;var X=!1,J;_(N,function(ct,Ct,ut){H(ct,function(xt,Yt){xt?ut(xt):y(Yt)&&!J?(X=!0,J=S(!0,ct),ut(null,mo)):ut()})},function(ct){ct?$(ct):$(null,X?J:S(!1))})}}function Cn(y,S){return S}var As=Qr(Ao(Dl,Cn)),Zr=go(Ao(Dl,Cn)),_l=ze(Zr,1);function Zf(y){return function(S){var _=r(arguments,1);_.push(function(N){var H=r(arguments,1);typeof console=="object"&&(N?console.error&&console.error(N):console[y]&&gs(H,function($){console[y]($)}))}),U(S).apply(null,_)}}var Lm=Zf("dir");function Im(y,S,_){_=br(_||Ht);var N=U(y),H=U(S);function $(J){if(J)return _(J);var ct=r(arguments,1);ct.push(X),H.apply(this,ct)}function X(J,ct){if(J)return _(J);if(!ct)return _(null);N($)}X(null,!0)}function td(y,S,_){_=br(_||Ht);var N=U(y),H=function($){if($)return _($);var X=r(arguments,1);if(S.apply(this,X))return N(H);_.apply(null,[null].concat(X))};N(H)}function Dm(y,S,_){td(y,function(){return!S.apply(this,arguments)},_)}function _m(y,S,_){_=br(_||Ht);var N=U(S),H=U(y);function $(J){if(J)return _(J);H(X)}function X(J,ct){if(J)return _(J);if(!ct)return _(null);N($)}H(X)}function xo(y){return function(S,_,N){return y(S,N)}}function Bc(y,S,_){Xr(y,xo(U(S)),_)}function Ml(y,S,_,N){kl(S)(y,xo(U(_)),N)}var bo=ze(Ml,1);function Tc(y){return M(y)?y:o(function(S,_){var N=!0;S.push(function(){var H=arguments;N?E(function(){_.apply(null,H)}):_.apply(null,H)}),y.apply(this,S),N=!1})}function rr(y){return!y}var vo=Qr(Ao(rr,rr)),Ul=go(Ao(rr,rr)),yc=ze(Ul,1);function Mm(y){return function(S){return S==null?void 0:S[y]}}function xs(y,S,_,N){var H=new Array(S.length);y(S,function($,X,J){_($,function(ct,Ct){H[X]=!!Ct,J(ct)})},function($){if($)return N($);for(var X=[],J=0;J<S.length;J++)H[J]&&X.push(S[J]);N(null,X)})}function ir(y,S,_,N){var H=[];y(S,function($,X,J){_($,function(ct,Ct){ct?J(ct):(Ct&&H.push({index:X,value:$}),J())})},function($){$?N($):N(null,po(H.sort(function(X,J){return X.index-J.index}),Mm("value")))})}function Rc(y,S,_,N){var H=Al(S)?xs:ir;H(y,S,U(_),N||Ht)}var kc=Qr(Rc),Ol=go(Rc),wc=ze(Ol,1);function Um(y,S){var _=br(S||Ht),N=U(Tc(y));function H($){if($)return _($);N(H)}H()}var Sc=function(y,S,_,N){N=N||Ht;var H=U(_);_i(y,S,function($,X){H($,function(J,ct){return J?X(J):X(null,{key:ct,val:$})})},function($,X){for(var J={},ct=Object.prototype.hasOwnProperty,Ct=0;Ct<X.length;Ct++)if(X[Ct]){var ut=X[Ct].key,xt=X[Ct].val;ct.call(J,ut)?J[ut].push(xt):J[ut]=[xt]}return N($,J)})},Bo=ze(Sc,1/0),K=ze(Sc,1),q=Zf("log");function j(y,S,_,N){N=Ii(N||Ht);var H={},$=U(_);Di(y,S,function(X,J,ct){$(X,J,function(Ct,ut){if(Ct)return ct(Ct);H[J]=ut,ct()})},function(X){N(X,H)})}var mt=ze(j,1/0),wt=ze(j,1);function Wt(y,S){return S in y}function Le(y,S){var _=Object.create(null),N=Object.create(null);S=S||Dl;var H=U(y),$=o(function(J,ct){var Ct=S.apply(null,J);Wt(_,Ct)?E(function(){ct.apply(null,_[Ct])}):Wt(N,Ct)?N[Ct].push(ct):(N[Ct]=[ct],H.apply(null,J.concat(function(){var ut=r(arguments);_[Ct]=ut;var xt=N[Ct];delete N[Ct];for(var Yt=0,Ne=xt.length;Yt<Ne;Yt++)xt[Yt].apply(null,ut)})))});return $.memo=_,$.unmemoized=y,$}var Xt;c?Xt=process.nextTick:l?Xt=setImmediate:Xt=d;var Lc=h(Xt);function ed(y,S,_){_=_||Ht;var N=Al(S)?[]:{};y(S,function(H,$,X){U(H)(function(J,ct){arguments.length>2&&(ct=r(arguments,1)),N[$]=ct,X(J)})},function(H){_(H,N)})}function kn(y,S){ed(Xr,y,S)}function Nl(y,S,_){ed(kl(S),y,_)}var nd=function(y,S){var _=U(y);return Ll(function(N,H){_(N[0],H)},S,1)},To=function(y,S){var _=nd(y,S);return _.push=function(N,H,$){if($==null&&($=Ht),typeof $!="function")throw new Error("task callback must be a function");if(_.started=!0,ye(N)||(N=[N]),N.length===0)return E(function(){_.drain()});H=H||0;for(var X=_._tasks.head;X&&H>=X.priority;)X=X.next;for(var J=0,ct=N.length;J<ct;J++){var Ct={data:N[J],priority:H,callback:$};X?_._tasks.insertBefore(X,Ct):_._tasks.push(Ct)}E(_.process)},delete _.unshift,_};function Pl(y,S){if(S=Ii(S||Ht),!ye(y))return S(new TypeError("First argument to race must be an array of functions"));if(!y.length)return S();for(var _=0,N=y.length;_<N;_++)U(y[_])(S)}function yo(y,S,_,N){var H=r(y).reverse();Jr(H,S,_,N)}function qt(y){var S=U(y);return o(function(N,H){return N.push(function(X,J){if(X)H(null,{error:X});else{var ct;arguments.length<=2?ct=J:ct=r(arguments,1),H(null,{value:ct})}}),S.apply(this,N)})}function Om(y){var S;return ye(y)?S=po(y,qt):(S={},Cs(y,function(_,N){S[N]=qt.call(this,_)})),S}function rd(y,S,_,N){Rc(y,S,function(H,$){_(H,function(X,J){$(X,!J)})},N)}var Fl=Qr(rd),id=go(rd),Nm=ze(id,1);function Pm(y){return function(){return y}}function Ro(y,S,_){var N=5,H=0,$={times:N,intervalFunc:Pm(H)};function X(ut,xt){if(typeof xt=="object")ut.times=+xt.times||N,ut.intervalFunc=typeof xt.interval=="function"?xt.interval:Pm(+xt.interval||H),ut.errorFilter=xt.errorFilter;else if(typeof xt=="number"||typeof xt=="string")ut.times=+xt||N;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof y=="function"?(_=S||Ht,S=y):(X($,y),_=_||Ht),typeof S!="function")throw new Error("Invalid arguments for async.retry");var J=U(S),ct=1;function Ct(){J(function(ut){ut&&ct++<$.times&&(typeof $.errorFilter!="function"||$.errorFilter(ut))?setTimeout(Ct,$.intervalFunc(ct)):_.apply(null,arguments)})}Ct()}var ti=function(y,S){S||(S=y,y=null);var _=U(S);return o(function(N,H){function $(X){_.apply(null,N.concat(X))}y?Ro(y,$,H):Ro($,H)})};function Kl(y,S){ed(Es,y,S)}var Vl=Qr(Ao(Boolean,Dl)),Ui=go(Ao(Boolean,Dl)),$l=ze(Ui,1);function od(y,S,_){var N=U(S);gc(y,function($,X){N($,function(J,ct){if(J)return X(J);X(null,{value:$,criteria:ct})})},function($,X){if($)return _($);_(null,po(X.sort(H),Mm("value")))});function H($,X){var J=$.criteria,ct=X.criteria;return J<ct?-1:J>ct?1:0}}function Hl(y,S,_){var N=U(y);return o(function(H,$){var X=!1,J;function ct(){var Ct=y.name||"anonymous",ut=new Error('Callback function "'+Ct+'" timed out.');ut.code="ETIMEDOUT",_&&(ut.info=_),X=!0,$(ut)}H.push(function(){X||($.apply(null,arguments),clearTimeout(J))}),J=setTimeout(ct,S),N.apply(null,H)})}var Fm=Math.ceil,jl=Math.max;function ko(y,S,_,N){for(var H=-1,$=jl(Fm((S-y)/(_||1)),0),X=Array($);$--;)X[N?$:++H]=y,y+=_;return X}function wo(y,S,_,N){var H=U(_);_i(ko(0,y,1),S,H,N)}var Km=ze(wo,1/0),Vm=ze(wo,1);function $m(y,S,_,N){arguments.length<=3&&(N=_,_=S,S=ye(y)?[]:{}),N=Ii(N||Ht);var H=U(_);Xr(y,function($,X,J){H(S,$,X,J)},function($){N($,S)})}function zl(y,S){var _=null,N;S=S||Ht,bo(y,function(H,$){U(H)(function(X,J){arguments.length>2?N=r(arguments,1):N=J,_=X,$(!X)})},function(){S(_,N)})}function Gl(y){return function(){return(y.unmemoized||y).apply(null,arguments)}}function Wl(y,S,_){_=br(_||Ht);var N=U(S);if(!y())return _(null);var H=function($){if($)return _($);if(y())return N(H);var X=r(arguments,1);_.apply(null,[null].concat(X))};N(H)}function Hm(y,S,_){Wl(function(){return!y.apply(this,arguments)},S,_)}var sd=function(y,S){if(S=Ii(S||Ht),!ye(y))return S(new Error("First argument to waterfall must be an array of functions"));if(!y.length)return S();var _=0;function N($){var X=U(y[_++]);$.push(br(H)),X.apply(null,$)}function H($){if($||_===y.length)return S.apply(null,arguments);N(r(arguments,1))}N([])},Ex={apply:i,applyEach:Uf,applyEachSeries:Nf,asyncify:x,auto:pc,autoInject:wm,cargo:Eo,compose:xc,concat:Sm,concatLimit:Il,concatSeries:bc,constant:vc,detect:As,detectLimit:Zr,detectSeries:_l,dir:Lm,doDuring:Im,doUntil:Dm,doWhilst:td,during:_m,each:Bc,eachLimit:Ml,eachOf:Xr,eachOfLimit:Di,eachOfSeries:Es,eachSeries:bo,ensureAsync:Tc,every:vo,everyLimit:Ul,everySeries:yc,filter:kc,filterLimit:Ol,filterSeries:wc,forever:Um,groupBy:Bo,groupByLimit:Sc,groupBySeries:K,log:q,map:gc,mapLimit:_i,mapSeries:Of,mapValues:mt,mapValuesLimit:j,mapValuesSeries:wt,memoize:Le,nextTick:Lc,parallel:kn,parallelLimit:Nl,priorityQueue:To,queue:nd,race:Pl,reduce:Jr,reduceRight:yo,reflect:qt,reflectAll:Om,reject:Fl,rejectLimit:id,rejectSeries:Nm,retry:Ro,retryable:ti,seq:Ac,series:Kl,setImmediate:E,some:Vl,someLimit:Ui,someSeries:$l,sortBy:od,timeout:Hl,times:Km,timesLimit:wo,timesSeries:Vm,transform:$m,tryEach:zl,unmemoize:Gl,until:Hm,waterfall:sd,whilst:Wl,all:vo,allLimit:Ul,allSeries:yc,any:Vl,anyLimit:Ui,anySeries:$l,find:As,findLimit:Zr,findSeries:_l,forEach:Bc,forEachSeries:bo,forEachLimit:Ml,forEachOf:Xr,forEachOfSeries:Es,forEachOfLimit:Di,inject:Jr,foldl:Jr,foldr:yo,select:kc,selectLimit:Ol,selectSeries:wc,wrapSync:x};e.default=Ex,e.apply=i,e.applyEach=Uf,e.applyEachSeries=Nf,e.asyncify=x,e.auto=pc,e.autoInject=wm,e.cargo=Eo,e.compose=xc,e.concat=Sm,e.concatLimit=Il,e.concatSeries=bc,e.constant=vc,e.detect=As,e.detectLimit=Zr,e.detectSeries=_l,e.dir=Lm,e.doDuring=Im,e.doUntil=Dm,e.doWhilst=td,e.during=_m,e.each=Bc,e.eachLimit=Ml,e.eachOf=Xr,e.eachOfLimit=Di,e.eachOfSeries=Es,e.eachSeries=bo,e.ensureAsync=Tc,e.every=vo,e.everyLimit=Ul,e.everySeries=yc,e.filter=kc,e.filterLimit=Ol,e.filterSeries=wc,e.forever=Um,e.groupBy=Bo,e.groupByLimit=Sc,e.groupBySeries=K,e.log=q,e.map=gc,e.mapLimit=_i,e.mapSeries=Of,e.mapValues=mt,e.mapValuesLimit=j,e.mapValuesSeries=wt,e.memoize=Le,e.nextTick=Lc,e.parallel=kn,e.parallelLimit=Nl,e.priorityQueue=To,e.queue=nd,e.race=Pl,e.reduce=Jr,e.reduceRight=yo,e.reflect=qt,e.reflectAll=Om,e.reject=Fl,e.rejectLimit=id,e.rejectSeries=Nm,e.retry=Ro,e.retryable=ti,e.seq=Ac,e.series=Kl,e.setImmediate=E,e.some=Vl,e.someLimit=Ui,e.someSeries=$l,e.sortBy=od,e.timeout=Hl,e.times=Km,e.timesLimit=wo,e.timesSeries=Vm,e.transform=$m,e.tryEach=zl,e.unmemoize=Gl,e.until=Hm,e.waterfall=sd,e.whilst=Wl,e.all=vo,e.allLimit=Ul,e.allSeries=yc,e.any=Vl,e.anyLimit=Ui,e.anySeries=$l,e.find=As,e.findLimit=Zr,e.findSeries=_l,e.forEach=Bc,e.forEachSeries=bo,e.forEachLimit=Ml,e.forEachOf=Xr,e.forEachOfSeries=Es,e.forEachOfLimit=Di,e.inject=Jr,e.foldl=Jr,e.foldr=yo,e.select=kc,e.selectLimit=Ol,e.selectSeries=wc,e.wrapSync=x,Object.defineProperty(e,"__esModule",{value:!0})})})(bp,bp.exports);var w2={exports:{}},vp=w2.exports=function(n,t){if(t||(t=16),n===void 0&&(n=128),n<=0)return"0";for(var e=Math.log(Math.pow(2,n))/Math.log(t),r=2;e===1/0;r*=2)e=Math.log(Math.pow(2,n/r))/Math.log(t)*r;for(var i=e-Math.floor(e),o="",r=0;r<Math.floor(e);r++){var s=Math.floor(Math.random()*t).toString(t);o=s+o}if(i){var l=Math.pow(t,i),s=Math.floor(Math.random()*l).toString(t);o=s+o}var c=parseInt(o,t);return c!==1/0&&c>=Math.pow(2,n)?vp(n,t):o};vp.rack=function(n,t,e){var r=function(o){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=vp(n,t)}while(Object.hasOwnProperty.call(i,l));return i[l]=o,l},i=r.hats={};return r.get=function(o){return r.hats[o]},r.set=function(o,s){return r.hats[o]=s,r},r.bits=n||128,r.base=t||16,r};var S2=qo,LO=R2,IO=k2,Fh=Fr,Bp=bp.exports,DO=w2.exports,L2=nl.ACTIONS,I2=Ve;function Ve(n,t){if(S2.EventEmitter.call(this),!t||typeof t!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=t,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}S2.mixin(Ve),Ve.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Ve.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Ve.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||DO();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Ve.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(r){if(r)return t._callbackOrEmit(r,n);var i=Object.keys(t._remotePresenceInstances);Bp.parallel([function(o){Bp.each(e,function(s,l){t.localPresences[s].destroy(l)},o)},function(o){if(!t._wantsDestroy)return o();Bp.each(i,function(s,l){t._remotePresenceInstances[s].destroy(l)},o)}],function(o){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(o,n)})})},Ve.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?L2.presenceSubscribe:L2.presenceUnsubscribe,r=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[r]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,r,this)},Ve.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Ve.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Ve.prototype._receiveUpdate=function(n,t){var e=Fh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var r=this,i=Fh.digOrCreate(this._remotePresenceInstances,t.id,function(){return r._createRemotePresence(t.id)});i.receiveUpdate(t)},Ve.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Ve.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var t in this.localPresences){var e=this.localPresences[t];e.value!==null&&e.send()}},Ve.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Ve.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Ve.prototype._resubscribe=function(){var n=[];for(var t in this._subscriptionCallbacksBySeq){var e=this._subscriptionCallback(t);n.push(e)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var r=this;this.subscribe(function(i){r._callEachOrEmit(n,i)})},Ve.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Ve.prototype._callbackOrEmit=function(n,t){if(t)return Fh.nextTick(t,n);n&&this.emit("error",n)},Ve.prototype._createLocalPresence=function(n){return new LO(this,n)},Ve.prototype._createRemotePresence=function(n){return new IO(this,n)},Ve.prototype._callEachOrEmit=function(n,t){var e=Fh.callEach(n,t);!e&&t&&this.emit("error",t)};var Au=R2,D2=Mh,_O=Fr,_2=D2.CODES,MO=Vr;function Vr(n,t){Au.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this._doc=this.connection.get(this.collection,this.id),this._isSending=!1,this._docDataVersionByPresenceVersion={},this._opHandler=this._transformAgainstOp.bind(this),this._createOrDelHandler=this._handleCreateOrDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._destroyHandler=this.destroy.bind(this),this._registerWithDoc()}Vr.prototype=Object.create(Au.prototype),Vr.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:_2.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(e,t)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,Au.prototype.submit.call(this,n,t)},Vr.prototype.destroy=function(n){this._doc.removeListener("op",this._opHandler),this._doc.removeListener("create",this._createOrDelHandler),this._doc.removeListener("del",this._createOrDelHandler),this._doc.removeListener("load",this._loadHandler),this._doc.removeListener("destroy",this._destroyHandler),Au.prototype.destroy.call(this,n)},Vr.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(t){t.t=n._doc.type.uri,t.v=n._doc.version,n.connection.send(t)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},Vr.prototype._registerWithDoc=function(){this._doc.on("op",this._opHandler),this._doc.on("create",this._createOrDelHandler),this._doc.on("del",this._createOrDelHandler),this._doc.on("load",this._loadHandler),this._doc.on("destroy",this._destroyHandler)},Vr.prototype._transformAgainstOp=function(n,t){var e=this,r=this._doc._dataStateVersion;this._pendingMessages.forEach(function(i){var o=e._docDataVersionByPresenceVersion[i.pv];if(!(o>=r))try{i.p=e._transformPresence(i.p,n,t),e._docDataVersionByPresenceVersion[i.pv]=r}catch(l){var s=e._getCallback(i.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(i){this.emit("error",i)}},Vr.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Vr.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Vr.prototype._message=function(){var n=Au.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},Vr.prototype._transformPresence=function(n,t,e){var r=this._doc.type;if(!_O.supportsPresence(r))throw new D2(_2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+r.name);return r.transformPresence(n,t,e)};var M2={};(function(n){var t=pu,e=Mh,r=Fr,i=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new e(i.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[c];if(d==null||typeof d!="object")return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(i.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(i.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(i.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(i.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new e(i.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return t.map[l]&&t.map[l].uri},n.apply=function(l,c){if(typeof l!="object")return new e(i.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new e(i.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new e(i.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=c.create,h=t.map[d.type];if(!h)return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(E){return E}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var C=o(l,c.op);if(C)return C;l.v++}else l.v++};function o(l,c){if(!l.type)return new e(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new e(i.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,c)}catch(h){return new e(i.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,c,d){if(c.v!=null&&c.v!==d.v)return new e(i.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(c.create||"op"in c)return new e(i.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in c||c.create||c.del)||"op"in d&&c.create)return new e(i.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in c){if(!l)return new e(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,d.op,"left")}catch(h){return h}}}c.v!=null&&c.v++},n.applyOps=function(l,c,d){d=d||{};for(var h=0;h<c.length;h++){var C=c[h];if(d._normalizeLegacyJson0Ops)try{s(l,C)}catch{return new e(i.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=C.v;var E=n.apply(l,C);if(E)return E}},n.transformPresence=function(l,c,d){var h=this.checkOp(c);if(h)return h;var C=l.t;if(typeof C=="string"&&(C=t.map[C]),!C)return{code:i.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!r.supportsPresence(C))return{code:i.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:C.transformPresence(l.p,c.op,d)}catch(E){return{code:i.ERR_PRESENCE_TRANSFORM_FAILED,message:E.message||E}}l.v++};function s(l,c){if(l.type===t.defaultType.uri){var d=c.op;if(!!d){var h=l.data;d.length>1&&(h=r.clone(h));for(var C=0;C<d.length;C++){var E=d[C];typeof E.lm=="string"&&(E.lm=+E.lm);for(var x=E.p,v=h,k=0;k<x.length;k++){var L=x[k];Object.prototype.toString.call(v)=="[object Array]"?x[k]=+L:v.constructor===Object&&(x[k]=L.toString()),v=v[L]}C<d.length-1&&(h=t.defaultType.apply(h,[E]))}}}}})(M2);var xu=k2,UO=M2,OO=gr;function gr(n,t){xu.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this.src=null,this.presenceVersion=null,this._doc=this.connection.get(this.collection,this.id),this._pending=null,this._opCache=null,this._pendingSetPending=!1,this._opHandler=this._handleOp.bind(this),this._createDelHandler=this._handleCreateDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._registerWithDoc()}gr.prototype=Object.create(xu.prototype),gr.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},gr.prototype.destroy=function(n){this._doc.removeListener("op",this._opHandler),this._doc.removeListener("create",this._createDelHandler),this._doc.removeListener("del",this._createDelHandler),this._doc.removeListener("load",this._loadHandler),xu.prototype.destroy.call(this,n)},gr.prototype._registerWithDoc=function(){this._doc.on("op",this._opHandler),this._doc.on("create",this._createDelHandler),this._doc.on("del",this._createDelHandler),this._doc.on("load",this._loadHandler)},gr.prototype._setPendingPresence=function(){if(!this._pendingSetPending){this._pendingSetPending=!0;var n=this;this._doc.whenNothingPending(function(){if(n._pendingSetPending=!1,!!n._pending){if(n._pending.pv<n.presenceVersion)return n._pending=null;if(n._pending.v>n._doc.version)return n._doc.fetch();!n._catchUpStalePresence()||(n.value=n._pending.p,n.presenceVersion=n._pending.pv,n._pending=null,n.presence._updateRemotePresence(n))}})}},gr.prototype._handleOp=function(n,t,e){var r=e===this.src;this._transformAgainstOp(n,r),this._cacheOp(n,r),this._setPendingPresence()},xu.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},xu.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},gr.prototype._transformAgainstOp=function(n,t){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,t)}catch(e){return this.presence.emit("error",e)}this.presence._updateRemotePresence(this)}},gr.prototype._catchUpStalePresence=function(){if(this._pending.v>=this._doc.version)return!0;if(!this._opCache)return this._startCachingOps(),this._doc.fetch(),this.presence.subscribe(),!1;for(;this._opCache[this._pending.v];){var n=this._opCache[this._pending.v],t=n.op,e=n.isOwnOp;t===null?(this._pending.p=null,this._pending.v++):UO.transformPresence(this._pending,t,e)}var r=this._pending.v>=this._doc.version;return r&&this._stopCachingOps(),r},gr.prototype._startCachingOps=function(){this._opCache=[]},gr.prototype._stopCachingOps=function(){this._opCache=null},gr.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var U2=I2,NO=MO,PO=OO;function Ta(n,t,e){var r=Ta.channel(t,e);U2.call(this,n,r),this.collection=t,this.id=e}var FO=Ta;Ta.prototype=Object.create(U2.prototype),Ta.channel=function(n,t){return n+"."+t},Ta.prototype._createLocalPresence=function(n){return new NO(this,n)},Ta.prototype._createRemotePresence=function(n){return new PO(this,n)};var KO=VO;function VO(n,t,e,r,i){this.id=n,this.v=t,this.type=e,this.data=r,this.m=i}var $O=KO,O2=qo,N2=bu;function bu(n,t,e,r,i){if(O2.EventEmitter.call(this),typeof i!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=r,this.collection=e,this.callback=i,this.sent=!1}O2.mixin(bu),bu.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},bu.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},bu.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,r=new $O(this.id,t.v,t.type,t.data,e);this.callback(null,r)};var P2=N2,HO=Fr,jO=nl.ACTIONS,zO=Tp;function Tp(n,t,e,r,i,o){if(P2.call(this,n,t,e,r,o),!HO.isValidVersion(i))throw new Error("Snapshot version must be a positive integer or null");this.version=i}Tp.prototype=Object.create(P2.prototype),Tp.prototype._message=function(){return{a:jO.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var F2=N2,GO=Fr,WO=nl.ACTIONS,qO=yp;function yp(n,t,e,r,i,o){if(F2.call(this,n,t,e,r,o),!GO.isValidTimestamp(i))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=i}yp.prototype=Object.create(F2.prototype),yp.prototype._message=function(){return{a:WO.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var XO=bO,QO=RO,YO=I2,K2=FO,JO=zO,ZO=qO,V2=qo,ya=Mh,ie=nl.ACTIONS,$2=pu,$r=Fr,vu=C2,Bu=ya.CODES;function H2(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var tN=Rt;function Rt(n){V2.EventEmitter.call(this),this.collections={},this.nextQueryId=1,this.nextSnapshotRequestId=1,this.queries={},this._presences={},this._snapshotRequests={},this.seq=1,this._presenceSeq=1,this.id=null,this.agent=null,this.debug=!1,this.state=H2(n),this.bindToSocket(n)}V2.mixin(Rt),Rt.prototype.bindToSocket=function(n){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=n;var t=H2(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(r){try{var i=typeof r.data=="string"?JSON.parse(r.data):r.data}catch{vu.warn("Failed to parse message",r);return}e.debug&&vu.info("RECV",JSON.stringify(i));var o={data:i};if(e.emit("receive",o),!!o.data)try{e.handleMessage(o.data)}catch(s){$r.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(r){e.emit("connection error",r)},n.onclose=function(r){r==="closed"||r==="Closed"?e._setState("closed",r):r==="stopped"||r==="Stopped by server"?e._setState("stopped",r):e._setState("disconnected",r)}},Rt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=j2(n.error,n),delete n.error),n.a){case ie.initLegacy:return this._handleLegacyInit(n);case ie.handshake:return this._handleHandshake(t,n);case ie.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case ie.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case ie.queryUnsubscribe:return;case ie.queryUpdate:var e=this.queries[n.id];if(!e)return;if(t)return e._handleError(t);n.diff&&e._handleDiff(n.diff),n.hasOwnProperty("extra")&&e._handleExtra(n.extra);return;case ie.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case ie.bulkSubscribe:case ie.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case ie.snapshotFetch:case ie.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case ie.fetch:var r=this.getExisting(n.c,n.d);r&&r._handleFetch(t,n.data);return;case ie.subscribe:case ie.unsubscribe:var r=this.getExisting(n.c,n.d);r&&r._handleSubscribe(t,n.data);return;case ie.op:var r=this.getExisting(n.c,n.d);r&&r._handleOp(t,n);return;case ie.presence:return this._handlePresence(t,n);case ie.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case ie.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case ie.presenceRequest:return this._handlePresenceRequest(t,n);case ie.pingPong:return this._handlePingPong(t);default:vu.warn("Ignoring unrecognized message",n)}};function j2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}Rt.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var r in t.data){var i=t.data[r],o=this.getExisting(t.c,r);o&&(n?o[e](n):i.error?o[e](j2(i.error)):o[e](null,i))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var r=t.b[s],o=this.getExisting(t.c,r);o&&o[e](n)}else if(t.b)for(var r in t.b){var o=this.getExisting(t.c,r);o&&o[e](n)}else vu.error("Invalid bulk message",t)},Rt.prototype._reset=function(){this.agent=null},Rt.prototype._setState=function(n,t){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var e=new ya(Bu.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",e)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var r in this.queries){var i=this.queries[r];i._onConnectionStateChanged()}for(var o in this.collections){var s=this.collections[o];for(var r in s)s[r]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var r in this._snapshotRequests){var c=this._snapshotRequests[r];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},Rt.prototype.startBulk=function(){this.bulk||(this.bulk={})},Rt.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var t=this.bulk[n];this._sendBulk("f",n,t.f),this._sendBulk("s",n,t.s),this._sendBulk("u",n,t.u)}this.bulk=null},Rt.prototype._sendBulk=function(n,t,e){if(!!e){var r=[],i={},o=0,s;for(var l in e){var c=e[l];c==null?r.push(l):(i[l]=c,s=l,o++)}if(r.length===1){var l=r[0];this.send({a:n,c:t,d:l})}else r.length&&this.send({a:"b"+n,c:t,b:r});if(o===1){var d=i[s];this.send({a:n,c:t,d:s,v:d})}else o&&this.send({a:"b"+n,c:t,b:i})}},Rt.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var r=this.bulk[t.collection]||(this.bulk[t.collection]={}),i=r[n]||(r[n]={}),o=i.hasOwnProperty(t.id);return i[t.id]=e,o}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},Rt.prototype.sendFetch=function(n){return this._sendActions(ie.fetch,n,n.version)},Rt.prototype.sendSubscribe=function(n){return this._sendActions(ie.subscribe,n,n.version)},Rt.prototype.sendUnsubscribe=function(n){return this._sendActions(ie.unsubscribe,n)},Rt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:ie.op,c:n.collection,d:n.id,v:n.version,src:t.src,seq:t.seq,x:{}};"op"in t&&(e.op=t.op),t.create&&(e.create=t.create),t.del&&(e.del=t.del),n.submitSource&&(e.x.source=t.source),this.send(e)},Rt.prototype.send=function(n){this.debug&&vu.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},Rt.prototype.ping=function(){if(!this.canSend)throw new ya(Bu.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:ie.pingPong};this.send(n)},Rt.prototype.close=function(){this.socket.close()},Rt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},Rt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),r=e[t];return r||(r=e[t]=new XO(this,n,t),this.emit("doc",r)),r._wantsDestroy=!1,r},Rt.prototype._destroyDoc=function(n){!n._wantsDestroy||($r.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},Rt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},Rt.prototype._createQuery=function(n,t,e,r,i){var o=this.nextQueryId++,s=new QO(n,this,o,t,e,r,i);return this.queries[o]=s,s.send(),s},Rt.prototype._destroyQuery=function(n){delete this.queries[n.id]},Rt.prototype.createFetchQuery=function(n,t,e,r){return this._createQuery(ie.queryFetch,n,t,e,r)},Rt.prototype.createSubscribeQuery=function(n,t,e,r){return this._createQuery(ie.querySubscribe,n,t,e,r)},Rt.prototype.hasPending=function(){return!!(this._firstDoc(Kh)||this._firstQuery(Kh)||this._firstSnapshotRequest())};function Kh(n){return n.hasPending()}Rt.prototype.hasWritePending=function(){return!!this._firstDoc(eN)};function eN(n){return n.hasWritePending()}Rt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Kh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Kh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var r=this._firstSnapshotRequest();if(r){r.once("ready",this._nothingPendingRetry(n));return}$r.nextTick(n)},Rt.prototype._nothingPendingRetry=function(n){var t=this;return function(){$r.nextTick(function(){t.whenNothingPending(n)})}},Rt.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var r in e){var i=e[r];if(n(i))return i}}},Rt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},Rt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},Rt.prototype.fetchSnapshot=function(n,t,e,r){typeof e=="function"&&(r=e,e=null);var i=this.nextSnapshotRequestId++,o=new JO(this,i,n,t,e,r);this._snapshotRequests[o.requestId]=o,o.send()},Rt.prototype.fetchSnapshotByTimestamp=function(n,t,e,r){typeof e=="function"&&(r=e,e=null);var i=this.nextSnapshotRequestId++,o=new ZO(this,i,n,t,e,r);this._snapshotRequests[o.requestId]=o,o.send()},Rt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},Rt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},Rt.prototype._initializeHandshake=function(){this.send({a:ie.handshake,id:this.id})},Rt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},Rt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},Rt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new ya(Bu.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if($2.map[n.type]!==$2.defaultType)return this.emit("error",new ya(Bu.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new ya(Bu.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},Rt.prototype.getPresence=function(n){var t=this,e=$r.digOrCreate(this._presences,n,function(){return new YO(t,n)});return e._wantsDestroy=!1,e},Rt.prototype.getDocPresence=function(n,t){var e=K2.channel(n,t),r=this,i=$r.digOrCreate(this._presences,e,function(){return new K2(r,n,t)});return i._wantsDestroy=!1,i},Rt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var r={a:n,ch:e.channel,seq:t};return this.send(r),r.seq},Rt.prototype._addPresence=function(n){$r.digOrCreate(this._presences,n.channel,function(){return n})},Rt.prototype._handlePresenceSubscribe=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},Rt.prototype._handlePresenceUnsubscribe=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},Rt.prototype._handlePresence=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},Rt.prototype._handlePresenceRequest=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var z2=tN,nN=pu;const Tu={err:1001,msg:"user auth error",name:"AuthError"},Vh={err:1002,msg:"you don't have required permission",name:"PermissionError"},Rp={err:1003,msg:"Too many user connected",name:"MaxUserError"},yu={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},rN={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},iN={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},Ra="x-live-editor-token",Ru="x-live-editor-base-url",dn=I("auth-connection");function oN(n){try{n()}catch(t){dn.error(t)}}class sN{constructor(t,e){g(this,"enabled",!0);g(this,"connection");g(this,"ws");g(this,"retryCount");g(this,"events",new fb.EventEmitter);g(this,"token",null);g(this,"resourceToken",null);g(this,"reAuth",async()=>{if(this.connection&&this.reauthFunc){const t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}});this.url=t,this.reauthFunc=e,this.retryCount=0,window.addEventListener("offline",()=>{var r;this.token="fake",(r=this.connection)==null||r.close()})}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return Hi(this.getBaseURL())}async auth(t){p(dn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,r=await window.fetch(e,{method:"GET",headers:{[Ra]:t.token,[Ru]:this.getBase64BaseURL()},credentials:"include"});return r.status,this.enabled?(this.token=t.token,await r.json()):{read:"",user:""}}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[Ru]:Hi(this.getBaseURL())}})}async init(t){const e=await this.auth(t);if(!this.enabled)return;this.resourceToken=e.read,this.ws=new w6.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(z2.prototype),p(dn,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};const r=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=i=>{var s;const o=i;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in o||o.a==="pong")this.handleMessage(o);else{Object.prototype.hasOwnProperty.call(o,"a")&&o.a==="hs"&&this.retryCount>0&&(dn.info("retrying re-auth success"),this.emitAuthRecover()),Object.prototype.hasOwnProperty.call(o,"a")&&o.a!=="init"&&o.a!=="hs"&&(this.retryCount=0);try{r(o)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,o);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,o);return}throw l}}},z2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc){this.retryCount>=5&&(dn.warn("retry auth times exceed 5, broadcast auth error"),this.emitAuthError()),this.retryCount+=1,dn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();if(await this.auth(t),!this.enabled){this.retryCount=10,setTimeout(()=>this.handleAuthError(),0);return}this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){dn.error(t),setTimeout(()=>this.handleAuthError(),0)}}}emitPermissionError(){const t=new Error(Vh.msg);t.code=Vh.err,this.events.emit("error",t)}emitAuthRecover(){this.events.emit("authRecover")}emitAuthError(){const t=new Error(Tu.msg);t.code=Tu.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(yu.msg);t.code=yu.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t,e){t.orgMsg=e,this.events.emit("writeConflictError",t)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(t){const e=t;if(e.a==="pong")return;const r=e.err;if(r===Tu.err)dn.warn("auth error"),this.handleAuthError();else if(r===Rp.err)dn.warn(Rp.msg),this.emitMaxUsersError();else if(r===yu.err){dn.warn(yu.msg);try{this.emitRequestReloadError()}catch(i){dn.error(`error occurred while process reload error: ${JSON.stringify(i)}`)}finally{this.end(!1)}}else r===Vh.err?this.emitPermissionError():(dn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError())}get(t,e){return p(dn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(p(dn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onAuthError(t){this.events.addListener("error",t)}onAuthRecover(t){this.events.addListener("authRecover",t)}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){p(dn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){p(dn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.enabled=!1,this.reauthFunc=void 0,this.events.removeAllListeners(),oN(()=>{var r;return(r=this.connection)==null?void 0:r.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}I("utils/file");function lN(){function n(){return new Promise(t=>{const e=new FileReader;e.onload=()=>{t(e.result)},e.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}lN();async function aN(n){const e=n.size,r=Math.floor((e+102400-1)/102400),i=new S6.Hash;for(let s=0;s<r;s++){const l=s*102400;let c=l+102400;c>e&&(c=e);const h=await n.slice(l,c,n.type).arrayBuffer();i.update(new Uint8Array(h))}const o=i.digest();return Hi(o)}const pi=I("sharedb-doc/client"),cN=hb.default.create();class uN{constructor(t,e,r){g(this,"connection");g(this,"auth");g(this,"doc",null);g(this,"reauthFunc");g(this,"clientId",Z());g(this,"getDoc",async()=>{const t=r=>new Promise((i,o)=>{r.fetch(s=>{s?o(s):i()})});p(pi,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth),window.addEventListener("online",async()=>{await this.connection.init({...this.auth,token:"fake"})});const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),pi.debug(e),e});this.auth=t;const i=`${e}/${this.auth.appId}/${this.auth.docId}`;nN.register(Cd.type),this.connection=new sN(i,r),this.reauthFunc=r}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return p(pi,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}close(t){this.connection.end(t),this.doc=null}on(t,e){this.connection.addEventListener(t,r=>{(t==="error"||this.doc)&&e(r)})}onAuthError(t){this.connection.onAuthError(t)}onAuthRecover(t){this.connection.onAuthRecover(t)}onWriteConflictError(t){this.connection.onWriteConflictError(t)}onMaxUsersError(t){this.connection.onMaxUsersError(t)}onRequestReloadError(t){this.connection.onRequestReloadError(t)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const t=this.connection.url;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}async getFileUrlByHash(t,e,r,i,o){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...o},data:{name:r,size:i}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const r=`${this.apiServer()}/resources`;try{const i=`${r}/hash`,o=await this.request(i,{method:"post",headers:{[Ra]:this.connection.token},data:{resources:t}});return o.data&&Array.isArray(o.data)?o.data:[]}catch{return[]}}async uploadFile(t,e,r,i,o){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=x=>{pi.info(`on progress: ${x.loaded}`);let v=x.loaded*100/s;v>100&&(v=100),i(v)},c=await aN(e),d=await this.getFileUrlByHash(t,c,e.name,e.size,r);if(d)return i(-1),d;let h=t;o!=null&&o.thumbnail&&(h+="/thumbnail");const C=new FormData;C.append("file-size",`${e.size}`),C.append("file-hash",c),C.append("file",e,e.name);const E=await this.request(h,{method:"post",data:C,withCredentials:!0,headers:{...r},onUploadProgress:l});return pi.info(E),i(100),Array.isArray(E.data)?E.data[0]:E.data}async uploadResource(t,e=()=>{},r){const o=`${this.apiServer()}/resources`;p(pi,this.connection.token,"no connection token");const s=await this.uploadFile(o,t,{[Ra]:this.connection.token},e,r);return p(pi,s,"no result"),s}async request(t,e){var o,s;let r=this.connection.token,i;for(let l=0;l<2;l++){const c=e||{};c.url=t,c.headers||(c.headers={}),p(pi,r,"no token"),c.headers={...c.headers,[Ra]:r,[Ru]:this.connection.getBase64BaseURL()};try{return await cN(t,c)}catch(d){if(i=d,((o=d==null?void 0:d.response)==null?void 0:o.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;r=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw p(pi,i,"no error"),i}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,i=(await this.request(e)).data.versions;return i.forEach(o=>{o.extra&&(o.extra=JSON.parse(o.extra))}),i}async getVersion(t){const r=`${this.apiServer()}/versions/${t}`,i=await this.request(r);return JSON.parse(i.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,r=await this.request(e);return JSON.parse(r.data.data)}async getVersionOps(t,e){let i=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(i+=`&from=${e}`);const o=await this.request(i),s=o.data.ops,l=mb.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let d;return c?(p(pi,c.create,"no createDoc.create"),d=c.create.data):d=JSON.parse(o.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:o.data.ops}}async updateVersionExtra(t,e,r){const o=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(o,{method:"post",data:{extra:JSON.stringify(r)}})}async revertVersion(t){const r=`${this.apiServer()}/versions/revert/${t}`;await this.request(r,{method:"post",data:{}})}async createVersion(t,e){const i=`${this.apiServer()}/versions`;return(await this.request(i,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const r=`${this.apiServer()}/resources/external/${Hi(t)}`;return(await this.request(r)).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let i=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const o=[];if(e!=null&&e.withToken&&o.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&o.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),o.length>0){const s=o.join("&");i+=`?${s}`}return i}reAuth(){this.connection.reAuth()}}function fN(){return{blocks:[{id:Z(),type:"text",text:[]}],comments:{},meta:{}}}const kp=I("block-ids");class dN{constructor(){g(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((i,o)=>o-i);for(let i=0;i<e.length;i++){const o=e[i];if(o>=t){const s=this.ids.get(o);p(kp,s!==void 0,"old id is not exists"),this.ids.delete(o),this.ids.set(o+1,s)}}const r=Z();this.ids.set(t,r)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((r,i)=>r-i);for(let r=0;r<e.length;r++){const i=e[r];if(i>t){const o=this.ids.get(i);p(kp,o!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i-1,o)}}}getId(t){let e=this.ids.get(t);return e||(e=Z(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class hN{constructor(){g(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new dN,this.ids.set(t,e)),e}onInsertBlock(t,e){this.getContainerIds(t).onInsertBlock(e)}onDeleteBlock(t,e){this.getContainerIds(t).onDeleteBlock(e)}getBlockId(t,e){return this.getContainerIds(t).getId(e)}getBlockIndexById(t){const e=Array.from(this.ids.entries());for(let r=0;r<e.length;r++){const i=e[r],o=i[1].getById(t);if(o)return{containerId:i[0],blockIndex:o[0]}}return p(kp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class G2{constructor(t=new Set,e=new Map){this.deletedKeys=t,this.insertedValues=e}insert(t,e){this.insertedValues.set(t,e)}delete(t){this.deletedKeys.add(t)}toDocBlockDelta(){const t={};return this.insertedValues.forEach((e,r)=>{t[r]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const wp=I("op-parse-handler");class mN{constructor(t,e){g(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const r={...t,containerId:(i=>i==="blocks"?"root":i)(t.containerId)};this.actions.push(r)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,r){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:r})}onDeleteBlockData(t,e,r){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:r})}onInsertBlockData(t,e,r,i){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:r,value:i})}onUpdateBlockText(t,e,r){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:r})}onDeleteContainer(t){this.pushActions({type:"deleteContainer",containerId:t})}onCreateContainer(t,e){this.pushActions({type:"createContainer",containerId:t,data:e})}onDeleteComment(t){this.pushActions({type:"deleteComment",commentId:t})}onCreateComment(t){this.pushActions({type:"createComment",commentId:t})}onUpdateComment(t){this.pushActions({type:"updateComment",commentId:t})}end(){const t=this.actions,e=new Set,r=new Map,i=new hN,o=t.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of o)if(s.type==="deleteBlock"){const l=s,c=i.getBlockId(l.containerId,l.blockIndex);i.onDeleteBlock(l.containerId,l.blockIndex);const d=r.get(c);d&&(wp.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),r.delete(c));const h=`${l.containerId}-${l.blockIndex}`;e.add(h),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,c=`${l.containerId}-${l.blockIndex}`;if(e.has(c)){wp.warn("delete block data after delete block, ignore it");continue}const d=i.getBlockId(l.containerId,l.blockIndex);let h=r.get(d);h||(h=new G2,r.set(d,h)),h.delete(l.key)}else p(wp,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,c=i.getBlockId(l.containerId,l.blockIndex);let d=r.get(c);d||(d=new G2,r.set(c,d)),d.insert(l.key,l.value)}else if(s.type==="updateBlockText"){const l=s;this.outerHandler.onUpdateBlockText(l.containerId,l.blockIndex,l.richTextData,this.local)}else if(s.type==="createComment"){const l=s;this.outerHandler.onCreateComment(l.commentId,this.local)}else if(s.type==="updateComment"){const l=s;this.outerHandler.onUpdateComment(l.commentId,this.local)}}),Array.from(r.entries()).forEach(([s,l])=>{const{containerId:c,blockIndex:d}=i.getBlockIndexById(s);this.outerHandler.onUpdateBlockData(c,d,l.toDocBlockDelta(),this.local)})}}const $e=I("op-parser");class W2{}class Sp{constructor(t){g(this,"key");this.key=t}}function gN(n,t,e){const r=t.concat(),i=r[0];if(typeof i!="number"||(r.shift(),r.length===1))return!1;const o=r[0];if(typeof o!="object"||!o.i||Object.keys(o).length!==1)return!1;for(let l=1;l<r.length;l++){const c=r[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const h=c[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=o.i;p($e,s.id,"block id is required"),p($e,s.type,"block type is required");for(let l=1;l<r.length;l++){const c=r[l],d=c[0],h=c[1];s[d]=h.i}return e.onInsertBlock(n,i,s),!0}function Lp(n,t,e,r){if(e==="upsert"&&gN(n,t,r))return;p($e,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const i=t.concat(),o=i[0];i.shift();const s=[];for(;i.length>0;){const l=i[0];if(l==="text"){const c=i[1];if(p($e,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),p($e,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),i.splice(0,2),e==="upsert"){const h=c.e;r.onUpdateBlockText(n,o,h)}p($e,i.length===0,`invalid block ops.length !== 0, ${JSON.stringify(i)}`)}else if(Array.isArray(l)){p($e,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];p($e,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const d=l[1];if(c==="text"){if(p($e,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&r.onInsertBlockData(n,o,c,d.i),d.r&&e==="remove"&&r.onDeleteBlockData(n,o,c),d.et==="rich-text"&&e==="upsert"){const C=d.e;r.onUpdateBlockText(n,o,C)}}else e==="remove"&&d.r&&s.push(new Sp(c)),e==="upsert"&&d.i&&r.onInsertBlockData(n,o,c,d.i);i.shift()}else if(typeof l=="object"){const c=l;e==="remove"&&c.r&&s.push(new W2),e==="upsert"&&c.i&&r.onInsertBlock(n,o,c.i),i.shift()}else{p($e,typeof l=="string","data is not string"),p($e,l!=="text","data !== 'text'"),p($e,i.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(i)}`);const c=l,d=i[1];e==="remove"&&d.r&&s.push(new Sp(c)),e==="upsert"&&d.i&&r.onInsertBlockData(n,o,c,d.i),i.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof W2?r.onDeleteBlock(n,o):l instanceof Sp?r.onDeleteBlockData(n,o,l.key):p($e,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function pN(n,t,e){$e.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function CN(n,t,e){const r=n[1],i=n[2];p($e,r,`invalid comment op, no commentId: ${JSON.stringify(n)}`),p($e,i,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof i=="string"?$e.error(`unknown comment op, ${JSON.stringify(n)}`):i.i&&i.r?t==="upsert"&&e.onUpdateComment(r):i.i?t==="upsert"&&e.onCreateComment(r):i.r?t==="remove"&&e.onDeleteComment(r):$e.error(`unknown comment op, ${JSON.stringify(n)}`)}function Ip(n,t,e){const r=n[0];if(Array.isArray(r)){r.forEach(s=>{Ip(s,t,e)});return}const i=r;if(p($e,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){pN(n);return}if(i==="comments"){CN(n,t,e);return}const o=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{Lp(o,s,t,e)}):n.slice(1).forEach(s=>{Lp(o,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(o),s.i&&t==="upsert"&&e.onCreateContainer(o,s.i)}else p($e,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Lp(o,n.slice(1),t,e)}function Dp(n,t,e){const r=new mN(t,e);for(let i=0;i<2;i++){const o=i===0?"remove":"upsert",s=gt.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{Ip(c,o,r)}):Ip(s,o,r)}r.end()}const EN=I("sharedb-comments");function _p(n){const t=n.blocks;p(EN,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([r,i])=>{Array.isArray(i)&&(e.blocks[r]=i)}),gt.default(e)}function q2(n){const{id:t,groupId:e,userId:r,displayName:i,avatarUrl:o,abstract:s,created:l,modified:c}=n;return{id:t,groupId:e,userId:r,displayName:i,avatarUrl:o,abstract:s,created:l,modified:c}}function Mp(n,t){const e=nO(t),{comments:r,meta:i,blocks:o,...s}=e,l={...n,blocks:o,...s},c=gt.default(l);return delete c.children,c}const oe=I("sharedb-doc/doc-container"),X2="ot-json1";Cd.type.registerSubtype(rO.type),Cd.type.name=X2,Cd.type.invert=null;class ku extends ra{constructor(e,r,i=!0){super();g(this,"doc");g(this,"client");g(this,"localPresence");g(this,"remoteCaretHandler",new tO);g(this,"batching",0);g(this,"status","clean");g(this,"disableLogout");g(this,"destroyed",!1);g(this,"handleNothingPending",()=>{this.setStatus("clean")});g(this,"handleCreate",()=>{this.handleReload("doc created")});g(this,"handleDel",()=>{});g(this,"handleReload",e=>{this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)})});g(this,"handleReset",async e=>{const r=new Error(`reset doc: ${e}`);r.code="ResetDoc",this.callbacks.forEach(i=>{var o;return(o=i.onError)==null?void 0:o.call(i,r)}),this.destroy()});g(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});g(this,"insertObject",async(e,r,i)=>{const o=[e,r,{i}];return this.submitOp(o)});g(this,"deleteObject",async(e,r)=>{const i=[e,r,{r:!0}];return this.submitOp(i)});g(this,"replaceObject",async(e,r,i)=>{const o=[e,r,{r:!0,i}];return this.submitOp(o)});g(this,"updateObject",async(e,r,i)=>{const o=this.data()[e][r],s=[e,r];return Object.entries(i).forEach(([l,c])=>{if(!Nc.default(o[l],c))if(o[l]===void 0){if(c!=null){const d={i:c};s.push([l,d])}}else if(c==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:c};s.push([l,d])}}),Object.entries(o).forEach(([l,c])=>{if((i[l]===void 0||i[l]===null)&&c!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});g(this,"broadcastMessage",async e=>{const r={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(r)});g(this,"data",()=>this.doc.data);g(this,"submitOp",async e=>new Promise((r,i)=>{if(this.destroyed){oe.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},o=>{o?(oe.error(`invalid op, ${o.message}, ${JSON.stringify(e)}`),i(o),oe.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):r()}),this.doc.data||(oe.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));g(this,"createDoc",async e=>new Promise((r,i)=>{this.doc.create(e,X2,o=>{o?i(o):r()})}));g(this,"submitInsertChildContainers",async e=>{if(e.length===0)return Promise.resolve();const r=e.map(({containerId:i,blocks:o})=>[io(i),{i:o}]);return this.submitOp([r])});g(this,"submitDeleteChildContainer",async e=>{const r=[io(e),{r:!0}];return this.submitOp(r)});g(this,"submitInsertBlock",async(e,r,i)=>{const o=[io(e),r,{i}];return this.submitOp(o)});g(this,"submitDeleteBlock",async(e,r)=>{const i=[io(e),r,{r:!0}];return this.submitOp(i)});g(this,"submitUpdateBlockData",async(e,r,i)=>{if(i.delete.length===0&&Object.keys(i.insert).length===0)return Promise.resolve();const o=[io(e),r],s=new Set(i.delete);Object.entries(i.insert).forEach(([c,d])=>{if(s.has(c)){const h={r:!0,i:d};o.push([c,h])}});const l=new Set(Object.keys(i.insert));return i.delete.forEach(c=>{if(l.has(c))return;const d={r:!0};o.push([c,d])}),Object.entries(i.insert).forEach(([c,d])=>{if(s.has(c))return;const h={i:d};o.push([c,h])}),this.submitOp(o)});g(this,"submitUpdateRichText",async(e,r,i)=>{const o=[io(e),r,"text",{e:i,et:"rich-text"}];return this.submitOp(o)});g(this,"handleOp",(e,r,i)=>{if(this.destroyed){oe.warn("handleOp: destroyed");return}try{Dp(e,this,!!r)}catch(o){throw oe.error(o),o}});this.client=e,this.doc=r,this.doc.preventCompose=!0,this.disableLogout=i,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,p(oe,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const r=new uN(e.auth,e.serverUrl,e.reauthFunc),i=await r.getDoc(),o=new ku(r,i,e.disableLogout);if(i.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await o.createDoc(e.templateData||fN())}return await o.initPresence(),await o.subscribe(),o.initEvents(),o}catch(r){throw oe.error(r),oe.error(`failed to load doc: ${JSON.stringify(r)}`),r}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(r=>{var i;return(i=r.onStatusChanged)==null?void 0:i.call(r,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onAuthError(e=>{this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,e)})}),this.client.onAuthRecover(()=>{this.callbacks.forEach(e=>{var r;return(r=e.onAuthRecover)==null?void 0:r.call(e)})}),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((e,r)=>{if(this.localPresence)e();else{const i=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);i.on("receive",(o,s)=>{this.onCustomMessage(s)}),i.subscribe(o=>{o?r(o):(this.localPresence=i.create(Z()),e())})}})}subscribe(){return new Promise((e,r)=>{this.doc.subscribe(i=>{i?r(i):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return ro(this.data())}getContainerBlocks(e){const r=this.data();p(oe,r,"no doc data");const i=r[io(e)];return p(oe,i,`no container data: ${e}`),gt.default(i)}findContainerBlocks(e){const r=this.data();p(oe,r,"no doc data");const i=r[io(e)];return i!=null?i:null}getBlockData(e,r){const i=this.data();p(oe,i,"no doc data");const o=i[io(e)];p(oe,o,`no container data: ${e}`);const s=o[r];return p(oe,s,`no block data: ${r}`),gt.default(s)}localInsertBlock(e,r,i){return this.submitInsertBlock(e,r,i),this.getBlockData(e,r)}localDeleteBlock(e,r){const i=this.getBlockData(e,r);return this.submitDeleteBlock(e,r),i}localUpdateBlockText(e,r,i){const o=this.getBlockData(e,r);p(oe,o.text,"no block text");const s=gt.default(o.text);this.submitUpdateRichText(e,r,i);const l=fn.apply(s,i);return p(oe,l,"no block text"),l}localUpdateBlockData(e,r,i){const o=gt.default(this.getBlockData(e,r));return this.submitUpdateBlockData(e,r,i),o}localInsertChildContainers(e){this.submitInsertChildContainers(e)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(r=>{this.submitDeleteChildContainer(r)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(r=>q2(r))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const r=this.data().comments[e];return _p(r)}localCreateComment(e,r){const i=Mp(e,r),s=["comments",i.id,{i}];return this.submitOp(s)}localDeleteComment(e){const r=["comments",e,{r:!0}];return this.submitOp(r)}localUpdateComment(e,r){const i=Mp(e,r),o=["comments",e.id,{r:!0,i}];return this.submitOp(o)}destroy(){var e;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(e,r,i){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(o=>{var s;return(s=o.onDeleteBlock)==null?void 0:s.call(o,Ba(e),r,i)})}onInsertBlock(e,r,i,o){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Ba(e),r,i,o)})}onUpdateBlockData(e,r,i,o){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Ba(e),r,i,o)})}onUpdateBlockText(e,r,i,o){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Ba(e),r,i,o)})}onDeleteContainer(e,r){p(oe,this.callbacks.length>0,"no callbacks"),p(oe,e!=="root","should not delete root container in doc"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,Ba(e),r)})}onCreateContainer(e,r,i){p(oe,this.callbacks.length>0,"no callbacks"),p(oe,e!=="root","should not create root container in doc"),this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,Ba(e),r,i)})}onDeleteComment(e,r){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteComment)==null?void 0:o.call(i,e,r)})}onCreateComment(e,r){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onCreateComment)==null?void 0:o.call(i,e,r)})}onUpdateComment(e,r){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onUpdateComment)==null?void 0:o.call(i,e,r)})}onCustomMessage(e){const r=e;(r==null?void 0:r.type)==="custom"&&(r==null?void 0:r.clientId)!==this.client.clientId?this.callbacks.forEach(i=>{var o;return(o=i.onCustomMessage)==null?void 0:o.call(i,r.data)}):(r==null?void 0:r.type)==="onlineUsers"&&setTimeout(()=>{const i={type:"custom",data:e,clientId:"-"};this.onCustomMessage(i)})}onAuthRecover(){this.callbacks.forEach(e=>{var r;return(r=e.onAuthRecover)==null?void 0:r.call(e)})}async addResources(e){let r=[];return e.forEach(o=>{const s=o.split("|");r.push(...s)}),r=Array.from(new Set(r)),await this.client.getFileUrlsByHashes(r)}async uploadResource(e,r){var o;return{resourceId:await this.client.uploadResource(e,(o=r==null?void 0:r.onProgress)!=null?o:()=>{})}}buildResourceUrl(e,r){return this.client.buildResourceUrl(e,r)}request(e,r){return this.client.request(e,r)}getUser(){const e=this.client.clientId,{permission:r,userId:i,displayName:o,avatarUrl:s}=this.client.auth;return{permission:r,clientId:e,userId:i,displayName:o,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const r=await this.client.getVersion(e);return ro(r)}async getLatestVersion(){const e=await this.client.getLatestVersion();return ro(e)}async getHistoryData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r),s=o.map(l=>({user:l.meta.createdBy,data:l}));return{doc:ro(i),historyData:s}}async getVersionData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r);return{doc:ro(i),versionData:o}}async updateVersionExtra(e,r,i){await this.client.updateVersionExtra(e,r,i)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,r){return this.client.createVersion(e,r)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,r){Dp(e.data.op,r,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}triggerReAuth(){this.client.reAuth()}}I("remote-cursor");class Q2{constructor(t){g(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});g(this,"broadcastCaretPos",Ke.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));g(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const r=this.editor.findBlockById(e);r&&this.editor.reloadBlock(r)})});this.editor=t,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const Y2=I("remote-cursor-decorator");class Up{decorateText(t,e,r){const i=t.doc.getRemoteUsers();if(!i)return{};const o=new Map,{containerId:s,blockIndex:l}=e[e.length-1];p(Y2,typeof s=="string","invalid path containerId"),p(Y2,typeof l=="number","invalid path blockIndex");const c=t.doc.getBlockData(s,l),d=un(r);return i.getSimpleCursors(c.id).forEach((C,E)=>{E>d&&(E=d);const x=C.map(k=>({id:Z(),type:"remote-cursor",name:k.user.displayName,time:k.time,rainbowIndex:k.user.rainbowIndex})),v=o.get(E);v?v.push(...x):o.set(E,x)}),{insertions:o}}}const Op=I("sharedb-doc/share-db-server"),AN=hb.default.create();class xN{constructor(t,e){g(this,"auth");g(this,"clientId",Z());this.serverUrl=e,this.auth=t}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return p(Op,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}apiServer(){const t=`${this.serverUrl}/${this.auth.appId}/${this.auth.docId}`;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}getBaseURL(){const t=new URL(this.apiServer());return`${t.protocol}//${t.host}${t.pathname}`}getBase64BaseURL(){return Hi(this.getBaseURL())}async request(t,e){var o;const r=this.auth.token,i=e||{};i.url=t,i.headers||(i.headers={}),p(Op,r,"no token"),i.headers={...i.headers,[Ra]:r,[Ru]:this.getBase64BaseURL()};try{return await AN(t,i)}catch(s){throw(o=s.response)!=null&&o.data&&(s.responseData=s.response.data),s}}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,i=(await this.request(e)).data.versions;return i.forEach(o=>{o.extra&&(o.extra=JSON.parse(o.extra))}),i}async getVersion(t){const r=`${this.apiServer()}/versions/${t}`,i=await this.request(r);return JSON.parse(i.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,r=await this.request(e);return JSON.parse(r.data.data)}async getVersionOps(t,e){let i=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(i+=`&from=${e}`);const o=await this.request(i),s=o.data.ops,l=mb.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let d;return c?(p(Op,c.create,"no createDoc.create"),d=c.create.data):d=JSON.parse(o.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:o.data.ops}}async updateVersionExtra(t,e,r){const o=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(o,{method:"post",data:{extra:JSON.stringify(r)}})}async revertVersion(t){const r=`${this.apiServer()}/versions/revert/${t}`;await this.request(r,{method:"post",data:{}})}async createVersion(t,e){const i=`${this.apiServer()}/versions`;return(await this.request(i,{method:"post",data:{publish:e,tag:t}})).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let i=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const o=[];if(e!=null&&e.withToken,e!=null&&e.downloadFileName&&o.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),o.length>0){const s=o.join("&");i+=`?${s}`}return i}}I("sharedb-doc/share-db-server");class J2 extends ra{constructor(e){super();g(this,"remoteUsers",new gu);g(this,"client");this.options=e,this.client=new xN(e.auth,e.serverUrl)}destroy(){}buildResourceUrl(e,r){return this.client.buildResourceUrl(e,r)}getRemoteUsers(){return this.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const r=await this.client.getVersion(e);return ro(r)}async getLatestVersion(){const e=await this.client.getLatestVersion();return ro(e)}async getHistoryData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r),s=o.map(l=>({user:l.meta.createdBy,data:l}));return{doc:ro(i),historyData:s}}async getVersionData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r);return{doc:ro(i),versionData:o}}async updateVersionExtra(e,r,i){await this.client.updateVersionExtra(e,r,i)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,r){return this.client.createVersion(e,r)}parseHistoryData(e,r){Dp(e.data.op,r,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}class Z2 extends ve.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,r){if(Qt(li(this.editor,t)))return;const i=this.editor.getBlockByIndex(t,e),o=nt(this.editor.getContainerById(t));o&&this.emit("change",this.editor,o,i,r)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function bN(n,t){n.addCustom("child-block-tracker",()=>new Z2(n)).addListener("change",t)}function vN(n,t){n.addCustom("child-block-tracker",()=>new Z2(n)).removeListener("change",t)}const uat="",BN={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",name:"\u6587\u672C\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},TN={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},yN={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};D.mergeLang({"zh-CN":BN,"en-US":TN,"ja-JP":yN});const fat="";I("button");function pr(n,t,e,r,i){const o=B("button",["editor-button"],null);return o.setAttribute("data-button-id",n),i&&o.setAttribute(`data-editor-tooltip-${i}`,t),e?typeof e=="string"?e.startsWith("<")?o.innerHTML=e:o.innerText=e:o.appendChild(e):o.innerText=t,r&&(r.indexOf("checked")!==-1&&z(o,"checked"),r.indexOf("disabled")!==-1&&(o.disabled=!0),r.indexOf("primary")!==-1&&z(o,"primary")),o}const dat="",$h=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
28
28
  <path d="M8.00874 7.89952L12.9497 2.94975M8.00874 7.89952L12.9497 12.8492M8.00874 7.89952L3.05025 12.8492M8.00874 7.89952L3.05025 2.94975" stroke="currentColor" stroke-linejoin="round"/>
29
29
  </svg>
30
30
  `,tT=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
@@ -933,7 +933,7 @@ function print() { __p += __j.call(arguments, '') }
933
933
  <add as="fillColor" value="#ffffff"/>
934
934
  </add>
935
935
  </mxStylesheet>
936
- `,$4=0,NY=30*1e3,H4="editor-empty-drawio",j4="show-full-screen-iframe",je=I("embed-block-drawio");function oc(n){return n.options.componentsOptions.drawIO||{}}function PY(n){const e=oc(n).lang;return e?IY[e]:""}function FY(n){var i;const e=((i=(oc(n)||{}).cdn)==null?void 0:i.drawioIframe)||DY,r=PY(n);return Sg(e,{spin:1,proto:"json",configure:1,lang:r})}function KY(n){const t=()=>{p(je,n,"el does not exist");const r=document.body.clientWidth||document.documentElement.clientWidth,i=document.body.clientHeight||document.documentElement.clientHeight;n.setAttribute("width",`${r-2*$4}`),n.setAttribute("height",`${i-2*$4}`)},e=()=>{window.removeEventListener("resize",t)};return t(),window.addEventListener("resize",t),{disconnect:e}}async function VY(n,t){const r=(oc(n)||{}).callbacks||{},i=n.getCustom("iframe-embed-reauth-event-callback"),{onCreateDrawIoFrame:o,onCloseDrawIoFrame:s}=r;let l=null,c;if(o)l=await o(n),p(je,l,"iframe create failed"),c=()=>{p(je,l,"iframe does not exist"),p(je,s,"missing parameters: onCloseDrawIoFrame"),i.unRegister(),s(n,l)};else{const d=B("div",["editor-drawio-iframe-container","loading"],document.body);d.setAttribute("data-placeholder",D.t("drawio.loading")),l=B("iframe",["drawio-iframe-element"],d),l.setAttribute("frameborder","0"),z(d,j4);const{disconnect:h}=KY(l);c=()=>{p(je,l,"iframe does not exist"),i.unRegister(),h(),document.body.removeChild(d),ot(d,j4)}}return i.register(t,l,{onExit:()=>c()}),{drawioIframe:l,exit:c}}async function $Y(n,t,e,r){var i,o;try{r&&je.debug("auto saving drawio data");const s=new Blob([e]),l=new File([s],"drawio.svg",{type:"image/svg+xml"});try{const c=n.findBlockById(st(t));if(c){const d=await n.doc.uploadResource(l),{resourceId:h}=d,E=n.getBlockData(c).embedData,x={src:h,height:E==null?void 0:E.height};n.updateEmbedData(c,x)}else je.error("block has been deleted")}catch(c){const d=`failed to upload drawio data: ${c.message}`;je.error(d)}}catch(s){const l=`failed to save drawio data: ${s.message}`,c=oc(n);if((i=c.callbacks)!=null&&i.onError){const d=new Error(l);d.code="SaveDrawIo",(o=c.callbacks)==null||o.onError(n,d)}}}function HY(n,t,e,r,i,o,s){const l=()=>{window.removeEventListener("message",c),o()},c=async d=>{var h,C;if(p(je,r.contentWindow,"iframe.contentWindow does not exist"),d.data.length>0){const E=JSON.parse(d.data),x=e.xmlSvg||e.xml,v=document.querySelectorAll(".editor-drawio-iframe-container");switch(E.event){case"configure":r.contentWindow.postMessage(JSON.stringify({action:"configure",config:{defaultFonts:["Humor Sans","Helvetica","Times New Roman"]}}),"*");break;case"init":x!=null&&r.contentWindow.postMessage(JSON.stringify({action:"load",saveAndExit:1,noSaveBtn:1,noExitBtn:0,xml:x}),"*"),i(),v.forEach(L=>{ot(L,"loading")});break;case"export":const k=$c(E.data.substring(E.data.indexOf(",")+1));$Y(n,t,k,!!((h=E.message)!=null&&h.autoSave)),(C=E.message)!=null&&C.autoSave||l();break;case"save":r.contentWindow.postMessage(JSON.stringify({action:"export",format:"xmlsvg",spin:"Saving graph"}),"*");break;case"exit":l();break}}};window.addEventListener("message",c)}async function z4(n,t,e,r){if(r)return;r=!0;const i=oc(n)||{},{callbacks:o}=i;let s;o&&(o==null?void 0:o.onBeginInitDrawIo)&&o.onBeginInitDrawIo(n,t);const{drawioIframe:l,exit:c}=await VY(n,t);if(AE(n,t),e.src){const E=await V4(n,n.doc.buildResourceUrl(e.src));E&&(e.xmlSvg=E)}HY(n,t,e,l,()=>{s=setInterval(()=>{!l||!l.contentWindow||l.contentWindow.postMessage(JSON.stringify({action:"export",format:"xmlsvg",spin:"Saving graph",autoSave:!0}),"*")},NY)},()=>{c(),s&&clearInterval(s);const E=n.findBlockById(st(t));E&&xE(n,E)});const C=FY(n);l.setAttribute("src",C)}async function jY(n){var i,o;const t=oc(n),e=((i=t.cdn)==null?void 0:i.drawio)||_Y,r=((o=t.cdn)==null?void 0:o.pako)||MY;await Ds(r,"editor-pako"),await Ds(e,"editor-drawio"),await new Promise(s=>{setTimeout(s,100)})}function zY(n){ot(n,H4)}function sA(n){z(n,H4);const t=B("div",["drawio-empty-content"],n);t.innerHTML=UY,B("span",["drawio-empty-title"],t,D.t("drawio.empty"))}function GY(n,t,e){const r=nt(t);if(!r)return;const i=Ot(r);t.innerHTML="",t.style.height="100%",z(r,"drawio-load-error");const o=B("div",["drawio-error-content"],t),s=B("div",["drawio-error-brand-icon"],o);s.innerHTML=e0,B("div",["drawio-error-title"],o,D.t("drawio.errorTips"));const l=B("div",["drawio-error-sub-title"],o);B("span",[],l,D.t("drawio.errorSubTips"));const c=B("span",["drawio-error-retry-button"],l,D.t("drawio.retry"));c.onclick=()=>{t.innerHTML="",ot(r,"drawio-load-error"),e.src?G4(e.src,t,n):e.xml?W4(e.xml,t,n):e.xmlSvg&&q4(e.xmlSvg,t),e.height&&(i.style.height=`${e.height}px`,t.style.height=`${e.height-20}px`)}}function lA(n,t){if(p(je,t,"Required data is missing in setGraph"),"src"in t){n.setAttribute("data-src",t.src);return}if("xmlSvg"in t){n.setAttribute("data-xmlsvg",t.xmlSvg);return}if("graph"in t){const{xml:e,graph:r}=t;n.graph=r,n.setAttribute("data-mxfile",e)}}function WY(n){return{src:n.getAttribute("data-src")||"",xmlSvg:n.getAttribute("data-xmlsvg")||"",xml:n.getAttribute("data-mxfile")||""}}function G4(n,t,e){p(je,n,"params error: src"),p(je,e,"params error: editor");const r=t,i=e.doc.buildResourceUrl(n),o=document.createElement("img");r.innerHTML="",r.appendChild(o),o.src=i,o.draggable=!1,lA(r,{src:n}),o.onload=s=>{const l=r.querySelector("img");s.target!==l||!l||(wY(l)?sA(t):(l.style.width="100%",l.style.height="100%",zY(t)))},o.onerror=s=>{const l=r.querySelector("img");s.target===l&&GY(e,t,{src:n})}}function W4(n,t,e){p(je,e,"parameter missing"),jY(e).then(()=>{const{mxUtils:r,mxGraph:i,mxCodec:o}=window;p(je,r,"External resource loading exception: mxUtils"),p(je,i,"External resource loading exception: MxGraph"),p(je,o,"External resource loading exception: MxCodec");const s=r.parseXml(n);t.innerHTML="";const l=s.documentElement;p(je,l,"Resource parsing exception"),p(je,l.nodeName==="mxfile","Resource parsing exception");const c=l.getElementsByTagName("diagram");p(je,c.length>0,"Resource parsing exception");let d;const h=c[0];if(h.text||h.textContent){const k=LY(h),L=atob(k),M=window.pako;p(je,M,"External resource loading exception: pako");const U=M.inflateRaw(Uint8Array.from(L,G=>G.charCodeAt(0)),{to:"string"}),F=decodeURIComponent(U);d=r.parseXml(F)}else{const k=new XMLSerializer().serializeToString(h.firstChild);d=r.parseXml(k)}const C=new i(t);C.resetViewOnRootChange=!1,C.foldingEnabled=!1,C.setTooltips(!1),C.setEnabled(!1),C.setHtmlLabels(!0);const E=r.parseXml(OY);new o(E).decode(E.documentElement,C.getStylesheet());const v=new o(d);v.decode(v.document.documentElement,C.getModel()),C.maxFitScale=1,C.fit(),C.center(!0,!1),lA(t,{graph:C,xml:n})})}function q4(n,t){t.innerHTML=n,lA(t,{xmlSvg:n});const e=t.querySelectorAll("svg");for(let r=0;r<e.length;r++){const i=e[r];if(!SY(i))return}sA(t)}function qY(n,t){return{...qE(n,t,{handleExecuteCommand:(r,i,o)=>{if(o.id==="edit"){const s=r.getBlockData(i).embedData;return z4(r,i,s,!1),!0}return!1}}),abstract:D.t("drawio.abstract")}}const XY={"en-US":{drawio:{title:"Flowchart/UML",empty:"Empty graph",loading:"Loading",abstract:"Flowchart/UML",errorTips:"Flowchart/UML loading failed",errorSubTips:"The network service is abnormal, you can",retry:"Try again"},authError:{tips:'<div>\u670D\u52A1\u5DF2\u65AD\u5F00\uFF0C\u4E3A\u4E86\u907F\u514D\u5185\u5BB9\u4E22\u5931\uFF0C\u6211\u4EEC\u6682\u65F6\u7981\u7528\u7F16\u8F91\u529F\u80FD\uFF0C\u4F60\u53EF\u4EE5 <span id="retry">\u91CD\u8FDE\u670D\u52A1</span> \u6216 <span id="exit">\u9000\u51FA\u7F16\u8F91</span></div>'}},"zh-CN":{drawio:{title:"\u6D41\u7A0B\u56FE/UML",empty:"\u7A7A\u56FE\u8868",loading:"\u52A0\u8F7D\u4E2D",abstract:"\u6D41\u7A0B\u56FE/UML",errorTips:"\u6D41\u7A0B\u56FE/UML\u52A0\u8F7D\u5931\u8D25",errorSubTips:"\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38\uFF0C\u4F60\u53EF\u4EE5",retry:"\u91CD\u8BD5"},authError:{tips:'<div>\u670D\u52A1\u5DF2\u65AD\u5F00\uFF0C\u4E3A\u4E86\u907F\u514D\u5185\u5BB9\u4E22\u5931\uFF0C\u6211\u4EEC\u6682\u65F6\u7981\u7528\u7F16\u8F91\u529F\u80FD\uFF0C\u4F60\u53EF\u4EE5 <span id="retry">\u91CD\u8FDE\u670D\u52A1</span> \u6216 <span id="exit">\u9000\u51FA\u7F16\u8F91</span></div>'}},"ja-JP":{drawio:{title:"\u30D5\u30ED\u30FC\u30C1\u30E3\u30FC\u30C8/UML",empty:"\u30B0\u30E9\u30D5\u30C7\u30FC\u30BF\u306A\u3057",loading:"\u8AAD\u8FBC\u4E2D",abstract:"\u30D5\u30ED\u30FC\u30C1\u30E3\u30FC\u30C8/UML",errorTips:"\u30D5\u30ED\u30FC\u30C1\u30E3\u30FC\u30C8/UML \u306E\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u306B\u5931\u6557\u3057\u307E\u3057\u305F",errorSubTips:"\u304A\u4F7F\u3044\u306E\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u6B21\u306E\u64CD\u4F5C\u3092\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002 ",retry:"\u518D\u8A66\u884C"},authError:{tips:'<div>\u670D\u52A1\u5DF2\u65AD\u5F00\uFF0C\u4E3A\u4E86\u907F\u514D\u5185\u5BB9\u4E22\u5931\uFF0C\u6211\u4EEC\u6682\u65F6\u7981\u7528\u7F16\u8F91\u529F\u80FD\uFF0C\u4F60\u53EF\u4EE5 <span id="retry">\u91CD\u8FDE\u670D\u52A1</span> \u6216 <span id="exit">\u9000\u51FA\u7F16\u8F91</span></div>'}}};D.mergeLang(XY);const om=I("embed-block-drawio"),QY=!1;function YY(n,t,e,r){p(om,e,`parameter missing: ${e}`),p(om,n,`parameter missing: ${n}`),z4(n,t,r,QY)}function X4(n,t,e){const{src:r,xml:i,xmlSvg:o}=e;r?G4(r,t,n):i?W4(i,t,n):o?q4(o,t):sA(t)}function JY(n,t,e){const r=B("div",["editor-drawio-content","editor-embed"],null);t.appendChild(r),X4(n,r,e),e.height&&(t.style.height=`${e.height}px`,r.style.height=`${e.height-20}px`)}function ZY(n,t,e){const{src:r,xml:i,xmlSvg:o}=e,s=WY(t);if(r!==s.src||(i||"")!==s.xml||(o||"")!==s.xmlSvg){X4(n,t,e);return}const l=t.parentElement,c=nt(l);e.height&&e.height!==Number.parseInt(l.style.height,10)&&(l.style.height=`${e.height}px`,c&&!c.classList.contains("drawio-load-error")?t.style.height=`${e.height-20}px`:t.style.height="100%")}function tJ(n,t,e,r,i,o){const s=e.embedData;JY(n,t,s),Cf.register(n,o)}function eJ(n,t,e){const r=e.embedData,o=Ot(t).querySelector(":scope > .editor-drawio-content");return p(om,o,"embed should not be null"),ZY(n,o,r),!0}function nJ(){return{name:"UML",insertEmbedCommandItems:[{id:"insert-drawio",name:D.t("drawio.title"),icon:kT,group:"common",order:600,subText:vn("insert-drawio")}],handleInsertEmptyEmbed:async(n,t)=>{const e={src:"",xml:"",xmlSvg:""},r=n.insertEmbed(t.containerId,t.blockIndex,"drawio",e);return setTimeout(()=>{const o=Ot(r).querySelector(":scope > .editor-drawio-content");p(om,o,"embed should not be null");const s=n.getBlockData(r);YY(n,r,o,s.embedData)},100),r}}}function rJ(n,t,e,r){const{embedData:i}=t,o=i;return r==="html"?o.src?`<img src="${n.doc.buildResourceUrl(o.src,{withToken:!0})}" />`:o.xmlSvg?o.xmlSvg:"<p>[drawio]</p>":r==="markdown"?o.src?`![drawio](${n.doc.buildResourceUrl(o.src,{withToken:!0})})`:o.xmlSvg?o.xmlSvg:"[drawio]":""}const Q4={embedType:"drawio",getOptions:nJ,createEmbedContent:tJ,handleUpdateBlock:eJ,getBlockProperties:qY,convertTo:rJ},dct="";class aA extends ve.TypedEmitter{constructor(e){super();g(this,"currentBlock");g(this,"currentIframe");g(this,"onReAuthErrorWhenIframeEditing");g(this,"onIframeExitEdit");g(this,"destroy",()=>{this.editor.doc.externalDoc.unregisterCallback(this)});g(this,"onError",e=>{e.code===Tu.err&&this.currentIframe&&this.onConnectReAuthError()});g(this,"onAuthRecover",()=>{this.currentBlock&&Ld(this.currentBlock.id)});g(this,"unregisterCallbacks",()=>{this.editor.doc.unregisterCallback(this)});g(this,"register",(e,r,i)=>{this.currentBlock=e,this.currentIframe=r,this.onReAuthErrorWhenIframeEditing=i.onError,this.onIframeExitEdit=i.onExit});g(this,"unRegister",()=>{this.currentBlock=void 0,this.currentIframe=void 0,this.onReAuthErrorWhenIframeEditing=void 0});g(this,"onConnectReAuthError",()=>{var e;if(this.currentBlock&&this.currentIframe){(e=this.onReAuthErrorWhenIframeEditing)==null||e.call(this,this.currentBlock,this.currentIframe);const r=Dg(this.currentBlock.id),i=B("div",["iframe-embed-auth-error-tips"],r);i.innerHTML=D.t("authError.tips"),i.addEventListener("click",o=>{var l,c;const s=o.target;if(s instanceof HTMLSpanElement)switch(s.id){case"retry":(c=(l=this.editor.doc).triggerReAuth)==null||c.call(l);break;case"exit":this.exit();break}})}});this.editor=e,this.editor.doc.externalDoc.registerCallback(this)}exit(){var e;this.currentBlock&&Ld(this.currentBlock.id),this.unRegister(),(e=this.onIframeExitEdit)==null||e.call(this)}}const iJ=`<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
936
+ `,$4=0,NY=30*1e3,H4="editor-empty-drawio",j4="show-full-screen-iframe",je=I("embed-block-drawio");function oc(n){return n.options.componentsOptions.drawIO||{}}function PY(n){const e=oc(n).lang;return e?IY[e]:""}function FY(n){var i;const e=((i=(oc(n)||{}).cdn)==null?void 0:i.drawioIframe)||DY,r=PY(n);return Sg(e,{spin:1,proto:"json",configure:1,lang:r})}function KY(n){const t=()=>{p(je,n,"el does not exist");const r=document.body.clientWidth||document.documentElement.clientWidth,i=document.body.clientHeight||document.documentElement.clientHeight;n.setAttribute("width",`${r-2*$4}`),n.setAttribute("height",`${i-2*$4}`)},e=()=>{window.removeEventListener("resize",t)};return t(),window.addEventListener("resize",t),{disconnect:e}}async function VY(n,t){const r=(oc(n)||{}).callbacks||{},i=n.getCustom("iframe-embed-reauth-event-callback"),{onCreateDrawIoFrame:o,onCloseDrawIoFrame:s}=r;let l=null,c;if(o)l=await o(n),p(je,l,"iframe create failed"),c=()=>{p(je,l,"iframe does not exist"),p(je,s,"missing parameters: onCloseDrawIoFrame"),i.unRegister(),s(n,l)};else{const d=B("div",["editor-drawio-iframe-container","loading"],document.body);d.setAttribute("data-placeholder",D.t("drawio.loading")),l=B("iframe",["drawio-iframe-element"],d),l.setAttribute("frameborder","0"),z(d,j4);const{disconnect:h}=KY(l);c=()=>{p(je,l,"iframe does not exist"),i.unRegister(),h(),document.body.removeChild(d),ot(d,j4)}}return i.register(t,l,{onExit:()=>c()}),{drawioIframe:l,exit:c}}async function $Y(n,t,e,r){var i,o;try{r&&je.debug("auto saving drawio data");const s=new Blob([e]),l=new File([s],"drawio.svg",{type:"image/svg+xml"});try{const c=n.findBlockById(st(t));if(c){const d=await n.doc.uploadResource(l),{resourceId:h}=d,E=n.getBlockData(c).embedData,x={src:h,height:E==null?void 0:E.height};n.updateEmbedData(c,x)}else je.error("block has been deleted")}catch(c){const d=`failed to upload drawio data: ${c.message}`;je.error(d)}}catch(s){const l=`failed to save drawio data: ${s.message}`,c=oc(n);if((i=c.callbacks)!=null&&i.onError){const d=new Error(l);d.code="SaveDrawIo",(o=c.callbacks)==null||o.onError(n,d)}}}function HY(n,t,e,r,i,o,s){const l=()=>{window.removeEventListener("message",c),o()},c=async d=>{var h,C;if(p(je,r.contentWindow,"iframe.contentWindow does not exist"),d.data.length>0){const E=JSON.parse(d.data),x=e.xmlSvg||e.xml,v=document.querySelectorAll(".editor-drawio-iframe-container");switch(E.event){case"configure":r.contentWindow.postMessage(JSON.stringify({action:"configure",config:{defaultFonts:["Humor Sans","Helvetica","Times New Roman"]}}),"*");break;case"init":x!=null&&r.contentWindow.postMessage(JSON.stringify({action:"load",saveAndExit:1,noSaveBtn:1,noExitBtn:0,xml:x}),"*"),i(),v.forEach(L=>{ot(L,"loading")});break;case"export":const k=$c(E.data.substring(E.data.indexOf(",")+1));$Y(n,t,k,!!((h=E.message)!=null&&h.autoSave)),(C=E.message)!=null&&C.autoSave||l();break;case"save":r.contentWindow.postMessage(JSON.stringify({action:"export",format:"xmlsvg",spin:"Saving graph"}),"*");break;case"exit":l();break}}};window.addEventListener("message",c)}async function z4(n,t,e,r){if(r)return;r=!0;const i=oc(n)||{},{callbacks:o}=i;let s;o&&(o==null?void 0:o.onBeginInitDrawIo)&&o.onBeginInitDrawIo(n,t);const{drawioIframe:l,exit:c}=await VY(n,t);if(AE(n,t),e.src){const E=await V4(n,n.doc.buildResourceUrl(e.src));E&&(e.xmlSvg=E)}HY(n,t,e,l,()=>{s=setInterval(()=>{!l||!l.contentWindow||l.contentWindow.postMessage(JSON.stringify({action:"export",format:"xmlsvg",spin:"Saving graph",autoSave:!0}),"*")},NY)},()=>{c(),s&&clearInterval(s);const E=n.findBlockById(st(t));E&&xE(n,E)});const C=FY(n);l.setAttribute("src",C)}async function jY(n){var i,o;const t=oc(n),e=((i=t.cdn)==null?void 0:i.drawio)||_Y,r=((o=t.cdn)==null?void 0:o.pako)||MY;await Ds(r,"editor-pako"),await Ds(e,"editor-drawio"),await new Promise(s=>{setTimeout(s,100)})}function zY(n){ot(n,H4)}function sA(n){z(n,H4);const t=B("div",["drawio-empty-content"],n);t.innerHTML=UY,B("span",["drawio-empty-title"],t,D.t("drawio.empty"))}function GY(n,t,e){const r=nt(t);if(!r)return;const i=Ot(r);t.innerHTML="",t.style.height="100%",z(r,"drawio-load-error");const o=B("div",["drawio-error-content"],t),s=B("div",["drawio-error-brand-icon"],o);s.innerHTML=e0,B("div",["drawio-error-title"],o,D.t("drawio.errorTips"));const l=B("div",["drawio-error-sub-title"],o);B("span",[],l,D.t("drawio.errorSubTips"));const c=B("span",["drawio-error-retry-button"],l,D.t("drawio.retry"));c.onclick=()=>{t.innerHTML="",ot(r,"drawio-load-error"),e.src?G4(e.src,t,n):e.xml?W4(e.xml,t,n):e.xmlSvg&&q4(e.xmlSvg,t),e.height&&(i.style.height=`${e.height}px`,t.style.height=`${e.height-20}px`)}}function lA(n,t){if(p(je,t,"Required data is missing in setGraph"),"src"in t){n.setAttribute("data-src",t.src);return}if("xmlSvg"in t){n.setAttribute("data-xmlsvg",t.xmlSvg);return}if("graph"in t){const{xml:e,graph:r}=t;n.graph=r,n.setAttribute("data-mxfile",e)}}function WY(n){return{src:n.getAttribute("data-src")||"",xmlSvg:n.getAttribute("data-xmlsvg")||"",xml:n.getAttribute("data-mxfile")||""}}function G4(n,t,e){p(je,n,"params error: src"),p(je,e,"params error: editor");const r=t,i=e.doc.buildResourceUrl(n),o=document.createElement("img");r.innerHTML="",r.appendChild(o),o.src=i,o.draggable=!1,lA(r,{src:n}),o.onload=s=>{const l=r.querySelector("img");s.target!==l||!l||(wY(l)?sA(t):(l.style.width="100%",l.style.height="100%",zY(t)))},o.onerror=s=>{const l=r.querySelector("img");s.target===l&&GY(e,t,{src:n})}}function W4(n,t,e){p(je,e,"parameter missing"),jY(e).then(()=>{const{mxUtils:r,mxGraph:i,mxCodec:o}=window;p(je,r,"External resource loading exception: mxUtils"),p(je,i,"External resource loading exception: MxGraph"),p(je,o,"External resource loading exception: MxCodec");const s=r.parseXml(n);t.innerHTML="";const l=s.documentElement;p(je,l,"Resource parsing exception"),p(je,l.nodeName==="mxfile","Resource parsing exception");const c=l.getElementsByTagName("diagram");p(je,c.length>0,"Resource parsing exception");let d;const h=c[0];if(h.text||h.textContent){const k=LY(h),L=atob(k),M=window.pako;p(je,M,"External resource loading exception: pako");const U=M.inflateRaw(Uint8Array.from(L,G=>G.charCodeAt(0)),{to:"string"}),F=decodeURIComponent(U);d=r.parseXml(F)}else{const k=new XMLSerializer().serializeToString(h.firstChild);d=r.parseXml(k)}const C=new i(t);C.resetViewOnRootChange=!1,C.foldingEnabled=!1,C.setTooltips(!1),C.setEnabled(!1),C.setHtmlLabels(!0);const E=r.parseXml(OY);new o(E).decode(E.documentElement,C.getStylesheet());const v=new o(d);v.decode(v.document.documentElement,C.getModel()),C.maxFitScale=1,C.fit(),C.center(!0,!1),lA(t,{graph:C,xml:n})})}function q4(n,t){t.innerHTML=n,lA(t,{xmlSvg:n});const e=t.querySelectorAll("svg");for(let r=0;r<e.length;r++){const i=e[r];if(!SY(i))return}sA(t)}function qY(n,t){return{...qE(n,t,{handleExecuteCommand:(r,i,o)=>{if(o.id==="edit"){const s=r.getBlockData(i).embedData;return z4(r,i,s,!1),!0}return!1}}),abstract:D.t("drawio.abstract")}}const XY={"en-US":{drawio:{title:"Flowchart/UML",empty:"Empty graph",loading:"Loading",abstract:"Flowchart/UML",errorTips:"Flowchart/UML loading failed",errorSubTips:"The network service is abnormal, you can",retry:"Try again"},authError:{tips:'<div>\u670D\u52A1\u5DF2\u65AD\u5F00\uFF0C\u4E3A\u4E86\u907F\u514D\u5185\u5BB9\u4E22\u5931\uFF0C\u6211\u4EEC\u6682\u65F6\u7981\u7528\u7F16\u8F91\u529F\u80FD\uFF0C\u4F60\u53EF\u4EE5 <span id="retry">\u91CD\u8FDE\u670D\u52A1</span> \u6216 <span id="exit">\u9000\u51FA\u7F16\u8F91</span></div>'}},"zh-CN":{drawio:{title:"\u6D41\u7A0B\u56FE/UML",empty:"\u7A7A\u56FE\u8868",loading:"\u52A0\u8F7D\u4E2D",abstract:"\u6D41\u7A0B\u56FE/UML",errorTips:"\u6D41\u7A0B\u56FE/UML\u52A0\u8F7D\u5931\u8D25",errorSubTips:"\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38\uFF0C\u4F60\u53EF\u4EE5",retry:"\u91CD\u8BD5"},authError:{tips:'<div>\u670D\u52A1\u5DF2\u65AD\u5F00\uFF0C\u4E3A\u4E86\u907F\u514D\u5185\u5BB9\u4E22\u5931\uFF0C\u6211\u4EEC\u6682\u65F6\u7981\u7528\u7F16\u8F91\u529F\u80FD\uFF0C\u4F60\u53EF\u4EE5 <span id="retry">\u91CD\u8FDE\u670D\u52A1</span> \u6216 <span id="exit">\u9000\u51FA\u7F16\u8F91</span></div>'}},"ja-JP":{drawio:{title:"\u30D5\u30ED\u30FC\u30C1\u30E3\u30FC\u30C8/UML",empty:"\u30B0\u30E9\u30D5\u30C7\u30FC\u30BF\u306A\u3057",loading:"\u8AAD\u8FBC\u4E2D",abstract:"\u30D5\u30ED\u30FC\u30C1\u30E3\u30FC\u30C8/UML",errorTips:"\u30D5\u30ED\u30FC\u30C1\u30E3\u30FC\u30C8/UML \u306E\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u306B\u5931\u6557\u3057\u307E\u3057\u305F",errorSubTips:"\u304A\u4F7F\u3044\u306E\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u6B21\u306E\u64CD\u4F5C\u3092\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002 ",retry:"\u518D\u8A66\u884C"},authError:{tips:'<div>\u670D\u52A1\u5DF2\u65AD\u5F00\uFF0C\u4E3A\u4E86\u907F\u514D\u5185\u5BB9\u4E22\u5931\uFF0C\u6211\u4EEC\u6682\u65F6\u7981\u7528\u7F16\u8F91\u529F\u80FD\uFF0C\u4F60\u53EF\u4EE5 <span id="retry">\u91CD\u8FDE\u670D\u52A1</span> \u6216 <span id="exit">\u9000\u51FA\u7F16\u8F91</span></div>'}}};D.mergeLang(XY);const om=I("embed-block-drawio"),QY=!1;function YY(n,t,e,r){p(om,e,`parameter missing: ${e}`),p(om,n,`parameter missing: ${n}`),z4(n,t,r,QY)}function X4(n,t,e){const{src:r,xml:i,xmlSvg:o}=e;r?G4(r,t,n):i?W4(i,t,n):o?q4(o,t):sA(t)}function JY(n,t,e){const r=B("div",["editor-drawio-content","editor-embed"],null);t.appendChild(r),X4(n,r,e),e.height&&(t.style.height=`${e.height}px`,r.style.height=`${e.height-20}px`)}function ZY(n,t,e){const{src:r,xml:i,xmlSvg:o}=e,s=WY(t);if(r!==s.src||(i||"")!==s.xml||(o||"")!==s.xmlSvg){X4(n,t,e);return}const l=t.parentElement,c=nt(l);e.height&&e.height!==Number.parseInt(l.style.height,10)&&(l.style.height=`${e.height}px`,c&&!c.classList.contains("drawio-load-error")?t.style.height=`${e.height-20}px`:t.style.height="100%")}function tJ(n,t,e,r,i,o){const s=e.embedData;JY(n,t,s),Cf.register(n,o)}function eJ(n,t,e){const r=e.embedData,o=Ot(t).querySelector(":scope > .editor-drawio-content");return p(om,o,"embed should not be null"),ZY(n,o,r),!0}function nJ(){return{name:"UML",insertEmbedCommandItems:[{id:"insert-drawio",name:D.t("drawio.title"),icon:kT,group:"common",order:600,subText:vn("insert-drawio")}],handleInsertEmptyEmbed:async(n,t)=>{const e={src:"",xml:"",xmlSvg:""},r=n.insertEmbed(t.containerId,t.blockIndex,"drawio",e);return setTimeout(()=>{const o=Ot(r).querySelector(":scope > .editor-drawio-content");p(om,o,"embed should not be null");const s=n.getBlockData(r);YY(n,r,o,s.embedData)},100),r}}}function rJ(n,t,e,r){const{embedData:i}=t,o=i;return r==="html"?o.src?`<img src="${n.doc.buildResourceUrl(o.src,{withToken:!0})}" />`:o.xmlSvg?o.xmlSvg:"<p>[drawio]</p>":r==="markdown"?o.src?`![drawio](${n.doc.buildResourceUrl(o.src,{withToken:!0})})`:o.xmlSvg?o.xmlSvg:"[drawio]":""}const Q4={embedType:"drawio",getOptions:nJ,createEmbedContent:tJ,handleUpdateBlock:eJ,getBlockProperties:qY,convertTo:rJ},dct="";class aA extends ve.TypedEmitter{constructor(e){super();g(this,"currentBlock");g(this,"currentIframe");g(this,"onReAuthErrorWhenIframeEditing");g(this,"onIframeExitEdit");g(this,"onRecover");g(this,"destroy",()=>{this.editor.doc.externalDoc.unregisterCallback(this)});g(this,"onError",e=>{e.code===Tu.err&&this.currentIframe&&this.onConnectReAuthError()});g(this,"onAuthRecover",()=>{var e;this.currentBlock&&(Ld(this.currentBlock.id),(e=this.onRecover)==null||e.call(this))});g(this,"unregisterCallbacks",()=>{this.editor.doc.unregisterCallback(this)});g(this,"register",(e,r,i)=>{this.currentBlock=e,this.currentIframe=r,this.onReAuthErrorWhenIframeEditing=i.onError,this.onIframeExitEdit=i.onExit});g(this,"unRegister",()=>{this.currentBlock=void 0,this.currentIframe=void 0,this.onReAuthErrorWhenIframeEditing=void 0});g(this,"onConnectReAuthError",()=>{var e;if(this.currentBlock&&this.currentIframe){(e=this.onReAuthErrorWhenIframeEditing)==null||e.call(this,this.currentBlock,this.currentIframe);const r=Dg(this.currentBlock.id),i=B("div",["iframe-embed-auth-error-tips"],r);i.innerHTML=D.t("authError.tips"),i.addEventListener("click",o=>{var l,c;const s=o.target;if(s instanceof HTMLSpanElement)switch(s.id){case"retry":(c=(l=this.editor.doc).triggerReAuth)==null||c.call(l);break;case"exit":this.exit();break}})}});this.editor=e,this.editor.doc.externalDoc.registerCallback(this)}exit(){var e;this.currentBlock&&Ld(this.currentBlock.id),this.unRegister(),(e=this.onIframeExitEdit)==null||e.call(this)}}const iJ=`<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
937
937
  <g>
938
938
  <path fill-rule="evenodd" clip-rule="evenodd" d="M12 7.61719C11.4477 7.61719 11 7.16947 11 6.61719V3.61719C11 3.0649 11.4477 2.61719 12 2.61719C12.5523 2.61719 13 3.0649 13 3.61719V6.61719C13 7.16947 12.5523 7.61719 12 7.61719ZM4.92893 5.54612C5.31946 5.15559 5.95262 5.1556 6.34315 5.54612L8.46447 7.66744C8.85499 8.05796 8.85499 8.69113 8.46447 9.08165C8.07394 9.47218 7.44078 9.47218 7.05025 9.08165L4.92893 6.96033C4.53841 6.56981 4.53841 5.93664 4.92893 5.54612ZM15.5355 9.08165C15.145 8.69113 15.145 8.05796 15.5355 7.66744L17.6569 5.54612C18.0474 5.1556 18.6805 5.1556 19.0711 5.54612C19.4616 5.93664 19.4616 6.56981 19.0711 6.96033L16.9497 9.08165C16.5592 9.47218 15.9261 9.47218 15.5355 9.08165ZM2 12.6172C2 12.0649 2.44772 11.6172 3 11.6172L6 11.6172C6.55229 11.6172 7 12.0649 7 12.6172C7 13.1695 6.55228 13.6172 6 13.6172L3 13.6172C2.44772 13.6172 2 13.1695 2 12.6172ZM17 12.6172C17 12.0649 17.4477 11.6172 18 11.6172L21 11.6172C21.5523 11.6172 22 12.0649 22 12.6172C22 13.1695 21.5523 13.6172 21 13.6172L18 13.6172C17.4477 13.6172 17 13.1695 17 12.6172ZM15.5355 16.1527C15.9261 15.7622 16.5592 15.7622 16.9497 16.1527L19.0711 18.274C19.4616 18.6646 19.4616 19.2977 19.0711 19.6883C18.6805 20.0788 18.0474 20.0788 17.6569 19.6883L15.5355 17.5669C15.145 17.1764 15.145 16.5432 15.5355 16.1527ZM4.92893 19.6883C4.53841 19.2977 4.53841 18.6646 4.92893 18.274L7.05025 16.1527C7.44078 15.7622 8.07394 15.7622 8.46447 16.1527C8.85499 16.5432 8.85499 17.1764 8.46447 17.5669L6.34315 19.6883C5.95262 20.0788 5.31946 20.0788 4.92893 19.6883ZM12 22.6172C11.4477 22.6172 11 22.1695 11 21.6172V18.6172C11 18.0649 11.4477 17.6172 12 17.6172C12.5523 17.6172 13 18.0649 13 18.6172V21.6172C13 22.1695 12.5523 22.6172 12 22.6172Z" fill="#5587F0"/>
939
939
  <animateTransform attributeType="xml" attributeName="transform" type="rotate" values="0 12 12.5;360 12 12.5" dur="2s" repeatCount="indefinite" />