@ones-editor/editor 0.0.3-beta.214 → 0.0.3-beta.215

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 p6={boxType:"br",updateBoxContent:PI,convertTo:NI},C6=S("editor-boxes");class A6{constructor(t){m(this,"boxes",new Map);this.editor=t}registerBoxClass(t){const e=t.boxType,o=this.boxes.get(e);g(C6,!o,`duplicated box type: ${e}`),this.boxes.set(e,t)}getBoxClass(t){const e=this.boxes.get(t);return g(C6,e,`unknown box type: ${t}`),e}createBox(t,e){const o=Z5(e),r=Y5(o);return this.getBoxClass(e.type).updateBoxContent(this.editor,o,r,e),o}forEach(t){this.boxes.forEach(t)}}function $I(n,t,e,o){const r=o,{width:i,height:s,src:l}=r,a=["editor-box-image"];r.link&&a.push("editor-box-image-link");const d=k("img",a,e);i&&(d.style.width=`${i}px`),s&&(d.style.height=`${s}px`),d.src=n.doc.buildResourceUrl(l)}const b6={boxType:"image",updateBoxContent:$I},HI="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIGZpbGw9InJnYigxNzgsIDE4OCwgMjA1KSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0ibTE3IDE1IDEuNTUgMS41NWMtLjk2IDEuNjktMy4zMyAzLjA0LTUuNTUgMy4zN1YxMWgzVjloLTNWNy44MkMxNC4xNiA3LjQgMTUgNi4zIDE1IDVjMC0xLjY1LTEuMzUtMy0zLTNTOSAzLjM1IDkgNWMwIDEuMy44NCAyLjQgMiAyLjgyVjlIOHYyaDN2OC45MmMtMi4yMi0uMzMtNC41OS0xLjY4LTUuNTUtMy4zN0w3IDE1bC00LTN2M2MwIDMuODggNC45MiA3IDkgN3M5LTMuMTIgOS03di0zbC00IDN6TTEyIDRjLjU1IDAgMSAuNDUgMSAxcy0uNDUgMS0xIDEtMS0uNDUtMS0xIC40NS0xIDEtMXoiPjwvcGF0aD4KPC9zdmc+Cg==";function jI(n,t,e){W(e,"editor-box-anchor"),vm(HI,[],e)}const v6={boxType:"anchor",updateBoxContent:jI};function UI(n,t,e,o){k("span",[],e,o.text)}const y6={insertionType:"inputting",updateInsertionContent:UI},k6=S("editor-insertion");class w6{constructor(t){m(this,"insertions",new Map);this.editor=t}registerInsertionClass(t){const e=t.insertionType,o=this.insertions.get(e);g(k6,!o,`duplicated insertion type: ${e}`),this.insertions.set(e,t)}getInsertionClass(t){const e=this.insertions.get(t);return g(k6,e,`unknown insertion type: ${t}`),e}createInsertion(t,e){const o=J5(e.type,e.id),r=X5(o);return this.getInsertionClass(e.type).updateInsertionContent(this.editor,o,r,e),o}}class zI{constructor(t){m(this,"cursors",new Map);m(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,o])=>{if(t-o>3e3){const r=K5(this.editor,e);r&&rt(r,"active"),this.cursors.delete(e)}})},1e3)}destroy(){clearInterval(this.timer)}}function VI(n,t,e,o){var l;const r=o;Date.now()-r.time<5*1e3&&(n.addCustom("active-cursors",d=>new zI(d)).add(r.id,r.time),W(t,"active")),k("span",[],e,"|").setAttribute("data-cursor-name",r.name),t.style.setProperty("--cursor-color",n.getColor((l=r.rainbowIndex)!=null?l:0))}const kg={insertionType:"remote-cursor",updateInsertionContent:VI};class B6{constructor(t){m(this,"decorators",[]);this.editor=t}registerDecorator(t){this.decorators.push(t)}decorateBlock(t,e){let o=e;return this.decorators.forEach(r=>{if(r.decorateBlock){const i=r.decorateBlock(this.editor,t,e);i&&(o=mt.default(i))}}),o}decorateText(t,e){let o=e;const r=new Map;return this.decorators.forEach(i=>{if(i.decorateText){const s=i.decorateText(this.editor,t,e);if(s){const{insertions:l,text:a}=s;l&&Array.from(l.entries()).forEach(([d,h])=>{const p=r.get(d);p?p.push(...h):r.set(d,h)}),a&&(o=mt.default(a))}}}),{insertions:r,text:o}}}const wg=S("editor-input");class WI{constructor(t,e){m(this,"editor");m(this,"composing",!1);m(this,"callbacks");m(this,"inputElement");m(this,"handleDocumentClick",t=>{const e=this.editor.rootContainer,o=t.target;if(o&&e.contains(o)&&!Ds(o)){this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus();return}this.editor.emit("blur",this.editor),this.callbacks.onBlur()});m(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var e;const t=(e=document.getSelection())==null?void 0:e.focusNode;t&&this.editor.contains(t)&&!Ds(t)||(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});m(this,"handleEditorSelectionChanged",()=>{const e=!this.editor.isWritable();this.inputElement.readOnly=e});m(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});m(this,"handleCompositionstart",t=>{!this.editor.isWritable()||(this.composing=!0,this.callbacks.onCompositionStart(t))});m(this,"handleCompositionend",t=>{this.composing=!1,this.callbacks.onUpdateCompositionText(t,this.inputElement.value,!0),this.inputElement.value=""});m(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="")}});m(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="")})}});m(this,"handleCopy",t=>{this.callbacks.onCopy(t)});m(this,"handleCut",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onCut(t),wg.debug("on cut")});m(this,"handlePaste",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onPaste(t)});m(this,"handlePasteText",(t,e)=>{this.callbacks.onPasteText(t,e)});this.editor=t,this.callbacks=e;const o=k("input",["editor-input"],t.contentElement);o.type="text",o.name="editor-input",o.onkeydown=this.handleKeyDown,o.oninput=this.handleInput,o.oncopy=this.handleCopy,o.onpaste=this.handlePaste,o.oncut=this.handleCut,o.addEventListener("compositionstart",this.handleCompositionstart),o.addEventListener("compositionend",this.handleCompositionend),this.inputElement=o,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,t.onpaste=null,t.oncut=null}getInput(){return this.inputElement}focus(){this.editor.selection.caret.visible()||this.editor.selection.caret.update(),Ze.isMobileSafari?this.inputElement.focus():setTimeout(()=>{this.inputElement.focus()})}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,o,r,i){g(wg,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,o,r,i)}defaultHandleKeydown(t,e){return g(wg,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}}function E6(n){const t=n.rootElement,e=t.getBoundingClientRect(),o=ro(t),r=window.innerWidth,i=window.innerHeight,s=e.left<0?0:e.left,l=e.top<0?0:e.top,a=e.right>r?r:e.right,d=e.bottom>i?i:e.bottom,h=(s+a)/2,p=(l+d)/2,C=0-e.left+h,v=0-e.top+p,B=n.input.inputElement;B.style.left=`${C/o}px`,B.style.top=`${v/o}px`}const Bg=S("editor-caret");class qI{constructor(t){m(this,"editor");m(this,"caretElem");m(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=t,this.caretElem=k("div",["editor-cursor"],this.editor.contentElement),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 Ue))return!1;const e=this.editor.getBlockById(t.blockId);return!!nt(this.editor,e)}update(){if(i5(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",E6(this.editor);return}const{range:e}=this.editor.selection;g(Bg,e.isCollapsed,"range is not collapsed");const o=e.start;g(Bg,o instanceof Ue,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);g(Bg,nt(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=bs(s),i=new DOMRect(i.right,i.top,1,i.height)):i=Vn(r,o);const l=this.editor.contentElement.getBoundingClientRect(),a=i.left-l.left,d=i.top-l.top;t.style.left=`${a}px`,t.style.top=`${d}px`,t.style.height=`${i.height}px`;const h=this.editor.input.inputElement;h.style.left=`${a}px`,h.style.top=`${d+i.height-24}px`,Ze.isMobileSafari&&(h.style.left=`${a-4}px`,h.style.height=`${i.height}px`);const C=so(r,{horizontal:!0}).getBoundingClientRect(),v=C.left-l.left,B=v+C.width;a<v||a>B?(E6(this.editor),t.style.display="none"):t.style.display=""}}function GI(n){r4(n),n.selection.range.getSelectedBlocks().forEach(t=>i4(n,t.block,t.start,t.end))}const ZI=S("editor-dom");function x6(n){return so(n.rootContainer).clientHeight}function QI(n){return n.getFirstBlock().getBoundingClientRect().top}function YI(n){return n.getLastBlock().getBoundingClientRect().bottom}function Eg(n){const e=so(n.rootContainer).getBoundingClientRect(),o=e.x<0?0:e.x,r=e.y<0?0:e.y,i=e.right>window.innerWidth?window.innerWidth:e.right,s=e.bottom>window.innerHeight?window.innerHeight:e.bottom;return new DOMRect(o,r,i-o,s-r)}function JI(n,t){const e=Eg(n),o=n.getBlockById(t.blockId),i=Lo(n,o,t);return ys(e,i.x,i.y)&&ys(e,i.right,i.bottom)}function I6(n,t){const e=Eg(n),o=t.getBoundingClientRect();return o.top>=e.top&&o.top<=e.bottom||o.bottom<=e.bottom&&o.bottom>=e.top}function KI(n,t){const e=Eg(n),o=t.getBoundingClientRect();return ys(e,o.x,o.y)||ys(e,o.right,o.bottom)}function XI(n){if(!Bm(n.rootContainer)){ZI.warn("editorScrollIntoView: editor is not visible");return}const t=n.rootContainer.getBoundingClientRect();if(t.height<1&&t.width<1)return;const e=n.selection,o=e.range.focus;if(!o.isSimple()){const p=o,C=n.getContainerById(p.childContainerId);KI(n,C)||C.scrollIntoView();return}if(e.range.start.blockId===e.range.end.blockId){const p=n.getBlockById(e.range.start.blockId);if(Ie(p)&&I6(n,p)||Mt(n,p)&&I6(n,p))return}const r=o,i=n.getBlockById(r.blockId);if(JI(n,r))return;const s=Lo(n,i,r),l=i.getBoundingClientRect(),a=ee(i),d=k("div",["editor-block-anchor"],a),h=ro(i);d.style.top=`${(s.top-l.top)/h}px`,Gd(d,{elementToScroll:so(n.rootContainer)}),setTimeout(()=>{d.remove()},200)}function tT(n,t){if(t.isCollapsed())return!1;const e=ye(n.rootContainer),o=Qe(n.rootContainer),{start:r,end:i}=t;return r.blockId===it(e)&&r.offset===0&&i.blockId===it(o)&&i.offset===ut(n,o)}const T6=S("range-in-block");function D6(n,t){const e=t.getEditor(),o=e.getBlockById(t.start.blockId),r=e.getBlockById(t.end.blockId),i=o===n||Qt(n,o),s=r===n||Qt(n,r);return!!(i||s)}function S6(n,t){const e=n.doc.toJSON(),o=new Set(Object.values(e.blocks).map(s=>s.map(l=>l.id)).flat());let r,i=ae(t);if(i){for(;i&&!o.has(it(i));)i=ae(i);g(T6,i,"no prev block while deleting a block"),r=ke(n,i,ut(n,i))}else{const s=Yt(t);g(T6,s,"no prev and next block while deleting a block"),r=ke(n,s,0)}return r}const eT=S("block-to-html");function xg(n,t,e,o){const r=Ss(n,t.type);if(r.convertTo)return r.convertTo(n,t,e,"html",o);if(r.blockKind!=="text")return`[${t.type}]`;g(eT,t.text,"no text");const i=ie(t.text);return`<div>${a5(i)}</div>`}const L6=S("block-to-text");function nT(n,t,e){let o="";return t.forEach(r=>{if(g(L6,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const i=r.attributes,s=n.editorBoxes.getBoxClass(i.type);if(s!=null&&s.convertTo){o+=s.convertTo(n,i,e,"text");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${i.type}]`}o+=r.insert}),o}function Eh(n,t,e,o){const r=Ss(n,t.type);return r.convertTo?r.convertTo(n,t,e,"text",o):r.blockKind!=="text"?`[${t.type}]`:(g(L6,t.text,"no text"),nT(n,t.text,e))}function Ig(n,t,e,o){const r=Ss(n,t.type);return r.convertTo?r.convertTo(n,t,e,"markdown",o):Eh(n,t,e,o)}function xh(n,t){return t.blocks.root.map((r,i)=>xg(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
25
25
  `)}function M6(n,t){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${xh(n,t)}</body></html>`}function Oa(n,t){return t.blocks.root.map((r,i)=>Eh(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
26
26
  `)}function _a(n,t){const e=t.blocks.root.map((r,i)=>Ig(n,r,t,[{containerId:"root",blockIndex:i}]));return e[e.length-1]=e[e.length-1].trimEnd(),e.join(`
27
- `)}const oT=S("get-text-position");function ql(n,t){const e=t!=null?t:n.selection.range.start;e instanceof Ue||g(oT,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=bt(r),s=ot(r),l=ct(s),{offset:a}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const Gl=S("insert-text");function Tg(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(g(Gl,r,"no block data"),g(Gl,r.text,"no block text"),rn(r.text)===0)return g(Gl,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Ve(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function rT(n,t,e){const o=ot(t),r=ct(o),i=bt(t);return Tg(n,r,i,e)}function R6(n,t,e,o,r){const i=ot(t),s=ct(i),l=bt(t),a=rT(n,t,e),d=gh(e,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),pn(n,t)}function O6(n,t,e,o){const r=ot(t),i=ct(r),s=bt(t),l=gh(e," ",o);return n.doc.localUpdateBlockText(i,s,l),pn(n,t)}function iT(n,t){let e=0;if(t===0)return!1;for(let o=0;o<n.length;o++){const r=n[o];g(Gl,typeof r.insert=="string","invalid text op, no insert");const i=e+ph(r);if(i===t)return!1;if(i>t)return!0;e=i}return!1}function Dg(n,t,e,o,r){const i=n.doc.getBlockData(e,o);g(Gl,i,"no block data"),g(Gl,i.text,"no block text");const s=Tg(n,e,o,r);s&&Object.keys(s).includes("link")&&(iT(i.text,r)||delete s.link);const l=gh(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),pn(n,n.getBlockById(i.id))}function Sg(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=ql(n);Dg(n,t,e,o,r)}const Ih=S("update-composition-text");function _6(n){const t=n.selection.range.start;t instanceof Ue||g(Ih,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);g(Ih,nt(n,o),"not a text kind block");const r=ot(o),i=ct(r),s=bt(o),l=n.doc.getBlockData(i,s);g(Ih,l,"no block data in doc"),g(Ih,l.text,"no text data in text block");const a=Lt(o);dh(n,Ri(o),e,a,l.text)}function F6(n){Fx(n)}function Zl(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Fa=S("delete-block-text");function Lg(n,t,e,o,r){if(!n.isBlockWritable(t))return Fa.error("block is not writable"),0;g(Fa,nt(n,t),"block is not a text kind block");const i=ot(t),s=ct(i),l=bt(t),a=n.doc.getBlockData(s,l);g(Fa,a,"no block data in doc"),g(Fa,a.text,"no text data in text block");let d=e;sn(t,e)||(d=_i(t,d));let h=e+o;g(Fa,h<=ut(n,t),`invalid offset and count: ${e}, ${o}`),sn(t,h)||(h=_s(t,h));const p=h-d,C=q4(d,p);return n.doc.localUpdateBlockText(s,l,C,r),p}const Mg=S("break-text-block");function P6(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Ql(n,t,e,o){g(Mg,nt(n,t),`block is not a text kind block: ${Dt(t)}`),g(Mg,e>=0&&e<=ut(n,t),`invalid offset: ${e}`);const r=ot(t),i=ct(r),s=bt(t),l=o!=null&&o.copyBlockAttributes?P6(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===ut(n,t))){const v=e===0?s:s+1,B={...ar(""),...l,...o==null?void 0:o.newBlockData},D=ke(n,t.id,0),x=Zl(n,i,v,B,D);return{block:t,newBlock:x}}g(Mg,sn(t,e),"not a valid offset");const a=pn(n,t),{right:d}=Tn(a,e),h=rn(d);h>0&&Lg(n,t,e,h);const p={...ar(d),...l,...o==null?void 0:o.newBlockData},C=Zl(n,i,s+1,p,ke(n,p.id,0));return{block:t,newBlock:C}}const sT=S("prepare-insert-new-block");function lT(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=me(d);return g(sT,e>=0&&e<=h.length,`invalid blockIndex: ${e}`),{containerId:t,blockIndex:e}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(t=ct(ot(r)),e=bt(r),!nt(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===ut(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const a=Ql(n,r,s).newBlock;return{containerId:t,blockIndex:bt(a)}}const cT=S("auto-insert-block");function N6(n,t,e,o,r,i){const s=lT(n,e,o);g(cT,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},a={anchor:l,focus:l};return Zl(n,s.containerId,s.blockIndex,t,r!=null?r:a,i)}const aT=S("delete-block");function Th(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{Th(n,i,e)})}))}function Dh(n,t,e){const o=ot(t),r=ct(o),i=bt(t),s=n.doc.getBlockData(r,i);return g(aT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,ze(n,{anchor:e.start,focus:e.end})),s}function Rg(n,t,e){return n.undoManager.runInGroup(()=>{const o=ot(t);To(o)===1&&n.insertTextBlock("",ct(o),0);let r=e?Oi(n,e):null;if(!r){const l=n.selection.range;D6(t,l)?r=S6(n,t):r=l}const i=Dh(n,t,r),s=[];return Th(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function uT(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{Th(n,r,e)}),n.doc.localDeleteChildContainers(e)}function $6(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{Th(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const Og=S("merge-text-block");function H6(n,t,e){g(Og,nt(n,t),"only text block can be merged"),g(Og,nt(n,e),"only text block can be merged");const o=Pi(n,t),r=Pi(n,e),i=o.text,s=r.text;g(Og,i&&s,"block data has no text");const l=ot(t),a=ct(l),d=bt(t),h=ut(n,t),p=Dg(n,s,a,d,h),C=ke(n,t,rn(i));return Rg(n,e,C),p}const ur=S("clear-selected-contents");function Sh(n,t){g(ur,nt(n,t.block),"not a text kind block");const{start:e,end:o}=t;g(ur,e.isSimple(),"not a simple block position"),g(ur,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;g(ur,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function j6(n,t,e){const o=ct(t),r=me(t),i=e.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});e.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function dT(n,t){const{block:e,start:o,end:r}=t;if(nt(n,e)){Sh(n,t);return}if(Ie(e)||o.isSimple()){g(ur,r.isSimple(),"invalid range");const s=ot(e),l=bt(e),a=n.insertTextBlock("",ct(s),l);n.selection.selectBlock(a,0),n.deleteBlock(e);return}g(ur,Mt(n,e),"invalid block kind"),g(ur,!o.isSimple()&&!r.isSimple(),"invalid range"),Ms(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{j6(n,s,{focus:l===0})})}function hT(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(g(ur,e.length>0,"no selected block"),e.length===1){dT(n,e[0]);return}const o=e[0],r=o.block,i=ot(r);g(ur,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(nt(n,r)){Sh(n,o);const h=ke(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(C=>n.deleteBlock(C.block)),nt(n,l)){Sh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(nt(n,l)){Sh(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===To(i)){j6(n,i,{focus:!0});return}const a=ae(r),d=Yt(l);g(ur,a||d,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function _g(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),hT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const fT=S("core");function U6(n,t,e){const o=ot(t),r=ct(o),i=bt(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),pn(n,t)}function z6(n,t,e){if(!n.isBlockWritable(t)){fT.error("block is not writable");return}const o=n.getBlockText(t),r=ln.diff(o,e);U6(n,t,r)}function Lh(n,t,e){const o=pn(n,t),r=typeof e=="string"?Fi(e):e,i=ln.diff(o,r);return U6(n,t,i)}const Pa=S("update-block-data");function Mh(n,t,e,o){const r=ot(t),i=ct(r),s=bt(t),l=n.doc.getBlockData(i,s),a={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(e));return d.forEach(C=>{if(!h.has(C)){if(C==="id"||C==="type"||C==="text")return;Pa.debug(`delete key: ${C}`),a.delete.push(C)}}),Object.entries(e).forEach(([C,v])=>{g(Pa,C!=="id"&&C!=="type",`invalid block data delta, ${C}`);const B=l[C];if(v==null){B!=null&&(Pa.debug(`delete key: ${C}`),a.delete.push(C));return}B!==v&&(aa.default(B,v)||C==="text"&&ln.diff(B,v).length===0||(d.has(C)?(Pa.debug(`replace key: ${C}`),a.delete.push(C)):Pa.debug(`insert key: ${C}`),a.insert[C]=v))}),n.doc.localUpdateBlockData(i,s,a,o),Pi(n,t)}function V6(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function Fg(n,t,e){if(!Mt(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=zn(n,t).getChildContainers(n,t)[0],i=ye(r);Fg(n,i,e)}function Ns(n){const t=[];let e={};return n.forEach(o=>{t.push(...o.blocks.root);const{root:r,...i}=o.blocks;e={...e,...i}}),{blocks:{...e,root:t},meta:{},comments:{}}}const Na=S("clone-block");function Ni(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(h,p)=>(g(Na,e!==p,"invalid child block"),Ni(n,h,e,o)));let i={};const s=new Map,l=mt.default(e);l.children&&(l.children=l.children.map(h=>{const p=K(),C=t.blocks[h];g(Na,Array.isArray(C),"invalid child blocks");const v=C.map(_=>Ni(n,t,_,o)),B=Ns(v),{root:D,...x}=B.blocks;return i={...i,...x},i[p]=B.blocks.root,s.set(h,p),p}));const a=Array.from(s.entries()),d=h=>{for(const p of a){const[C,v]=p;{const B=`${C}/`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}/${D}`;return Na.debug(`replace key: ${h} -> ${x}`),x}}{const B=`${C}_`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}_${D}`;return Na.debug(`replace key: ${h} -> ${x}`),x}}}return h};return Array.from(Object.entries(l)).forEach(([h,p])=>{const C=d(h);C!==h&&delete l.key,l[C]=p}),l.id=K(),o&&(o.blockIdMap.set(e.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Pg(n,t,e,o){const r=t.blocks[e];g(Na,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Ni(n,t,l,o));return Ns(i)}function Ng(n,t,e){const o=t.blocks.root.map(r=>Ni(n.editorBlocks,t,r,e));return mt.default(Ns(o))}const W6=S("insert-doc");function q6(n,t,e,o,r){if(Mt(n,t)){W6.warn("failed to insert doc into a complex block");return}const i=Ng(n,o,r),s=ot(t),l=bt(t),a=ct(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var H,z,Z;const d=[];Object.entries(i.blocks).forEach(([tt,ft])=>{tt!=="root"&&d.push({containerId:tt,blocks:ft})}),d.length>0&&n.doc.localInsertChildContainers(d);const h=i.blocks.root;if(Ie(t)){n.deleteBlock(t);let tt;h.reverse().forEach(ft=>{const vt=n.insertBlock(a,l,ft,void 0,{noFocus:!0});tt||(tt=vt)}),tt&&n.selection.selectBlock(tt,ut(n,tt));return}if(g(W6,nt(n,t),"not a text block"),ue(n,t)){const tt=a==="root"&&n.getBlockByIndex(a,0)===t,ft=bt(t);let vt;h.forEach((zt,Ht)=>{const Xt=n.insertBlock(a,ft+Ht,zt,void 0,{noFocus:!0});Ht===h.length-1&&(vt=Xt)}),vt&&n.selection.selectBlock(vt,ut(n,vt)),tt&&n.deleteBlock(t);return}if(h.length===1){const tt=h[0];if(ka(n,tt.type)){n.insertTextToBlock(t,e,(H=tt.text)!=null?H:[]);return}n.breakTextBlock(t,e),n.insertBlock(a,l+1,tt);return}const p=e===ut(n,t),C=e===0,v=h[0],B=h[h.length-1];let D;!p&&!C?D=n.breakTextBlock(t,e,{forceInsertAfter:!0}):D=t;const x=C?l:l+1;p?(D=n.insertBlock(a,l+1,B),n.selection.selectBlock(D,ut(n,D))):(n.selection.selectBlock(D,0),ka(n,B.type)?n.insertTextToBlock(D,0,(z=B.text)!=null?z:[]):n.insertBlock(a,x,B));const _=n.selection.range;let R=x;ka(n,v.type)?C?(n.insertBlock(a,x,v),R+=1):n.insertTextToBlock(t,e,(Z=v.text)!=null?Z:[]):(n.insertBlock(a,x,v),R+=1),h.slice(1,h.length-1).reverse().forEach(tt=>{n.insertBlock(a,R,tt)}),n.selection.setRange(_)}),n.doc.endBatchUpdate()}function $g(n,t,e,o,r){const i=Ng(n,o,r),s=ct(t),l=[];return n.undoManager.runInGroup(()=>{const a=[];Object.entries(i.blocks).forEach(([h,p])=>{h!=="root"&&a.push({containerId:h,blocks:p})}),n.doc.localInsertChildContainers(a),i.blocks.root.reverse().forEach(h=>{const p=n.insertBlock(s,e,h);l.push(p)})}),l}function G6(n,t,e){const o=To(t);$g(n,t,o,e);for(let r=0;r<o;r++){const i=ye(t);n.deleteBlock(i)}}const $a=S("add-text-attribute");function mT(n,t,e,o){const{start:r,end:i}=e;g($a,r.blockId===i.blockId&&r.blockId===it(t),"invalid range"),g($a,o,"invalid attribute name");const s=n.getBlockText(t),l=Wl(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function Z6(n,t,e,o,r){const{start:i,end:s}=e;g($a,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g($a,o,"invalid attribute name");const l=n.getBlockText(t),a=Sa(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Yl(n,t,e,o,r){const{start:i,end:s}=e;g($a,i.blockId===s.blockId&&i.blockId===it(t),"invalid range");const l=n.getBlockText(t),a=e6(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Q6(n,t,e,o){const r=Oo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!nt(n,s))return;if(ue(n,s)){o(n,it(s),t,e);return}const d=ze(n,{anchor:l,focus:a});t==="color"||t==="backgroundColor"?Yl(n,s,d,t,e):(Yl(n,s,d,"color",null),Yl(n,s,d,"backgroundColor",null))})})}function Y6(n,t,e){const o=Oo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!nt(n,i))return;if(ue(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,it(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,it(i),"backgroundColor",null);return}const a=ze(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Yl(n,i,a,"color",null),(t==="clearBackground"||t==="clearAll")&&Yl(n,i,a,"backgroundColor",null)})})}function Hg(n,t){const e=Oo(n,{simpleBlockOnly:!0}).filter(s=>nt(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(ut(n,s.block)===0)return t(n,it(s.block));const l=s.start,a=s.end,d=n.getBlockText(s.block);return r6(l.offset,a.offset-l.offset,d)};let[r,i]=o(e[0]);return r===null&&i===null?[r,i]:(e.forEach(s=>{const[l,a]=o(s);l===null||r===null?r=null:r=l===r?r:null,a===null||i===null?i=null:i=a===i?i:null}),[r,i])}const Wn=S("adjust-selection-pos");function J6(n){const t=[];for(;n;){const e=ot(n);if(t.unshift(e),Gt(e))return t;const o=et(e);g(Wn,o,"child container has not parent container"),n=o}g(Wn,!1,"should not come here: getParentContainers")}function K6(n,t){for(;t;){const e=ot(t);if(e===n)return t;const o=et(e);g(Wn,o,"could not find parent block for a child container"),t=o}g(Wn,!1,"no parent block in specified container")}function gT(n,t){const e=J6(n),o=J6(t);g(Wn,e.length>0&&o.length>0,"block has not parent container"),g(Wn,e[0]===o[0],"root container does not equal");let r=e[0];for(let l=1;l<e.length||o.length;l++)if(e[l]!==o[l]){r=e[l-1];break}const i=K6(r,n),s=K6(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function X6(n,t){let e=et(t);for(g(Wn,e,"element is not in a block");e;){const o=ot(e);g(Wn,Mo(o),"not a child container");const r=et(o);if(g(Wn,r,"child container has not parent block"),r===n)return o;e=r}g(Wn,!1,"failed to find parent container in complex block")}function Rh(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof Ue&&e instanceof Ue?{anchor:t,focus:e}:t instanceof Ro&&e instanceof Ro?ah(n,o,t,e):null;const i=ot(o),s=ot(r);if(i===s)return t instanceof Ro&&(t=st(o,0,"home")),e instanceof Ro&&(e=st(r,ut(n,r),"end")),g(Wn,t instanceof Ue,"not valid position type"),g(Wn,e instanceof Ue,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof Ue&&e instanceof Ro){const B=n.getContainerById(e.childContainerId);if(B===i)return{anchor:e,focus:e};const D=et(i);if(D&&D===et(B)){const x=fe(D,ct(i)),_=fe(D,ct(B));return ah(n,D,x,_)}}return null}const l=Wd(o,r)>0,{newBlock1:a,newBlock2:d}=gT(o,r);if(a===d){const B=a,D=X6(B,o),x=X6(B,r);return t=fe(a,ct(D)),e=fe(a,ct(x)),Wn.debug(`select in complex block: ${D.id}, ${x.id}`),ah(n,B,t,e)}let h=l?ut(n,a):0;a===o&&t instanceof Ue&&(h=t.offset);let C=l?0:ut(n,d);return d===r&&e instanceof Ue&&(C=e.offset),t=st(a,h,l?"end":"home"),e=st(d,C,l?"home":"end"),{anchor:t,focus:e}}const pT=S("move-complex-block-position");function CT(n,t,e){const o=n.getBlockById(t.blockId);g(pT,Mt(n,o),"is not a complex block");const r=zn(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?fe(o,ct(s)):null}const Ha=S("move-simple-block-position");function tA(n,t){const e=gn(n,t,{visibleOnly:!0});g(Ha,e.length>0,"complex block has not any child container");const o=e[0];return ye(o)}function eA(n,t){const e=gn(n,t,{visibleOnly:!0});g(Ha,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Qe(o)}function nA(n,t,e){const o=e?tA(n,t):eA(n,t);return Mt(n,o)?nA(n,o,e):o}function AT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===0?tA(n,e):Ts(e)}function bT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===1?eA(n,e):Is(e)}function jg(n){return n==="ArrowLeft"||n==="ArrowUp"}function Ug(n,t,e){const o=ot(t);if(Gt(o))return null;const r=et(o);g(Ha,r,"child container has not parent block"),g(Ha,Mt(n,r),"is not a complex block");const i=zn(n,r).getNextContainer(n,r,o,e);return i?jg(e)?Qe(i):ye(i):Ug(n,r,e)}function vT(n,t,e){const o=ot(t);if(Gt(o))return null;const r=et(o);if(g(Ha,r,"child container has not parent block"),jg(e)){const l=ae(r);if(l)return l}else{const l=Yt(r);if(l)return l}const i=Ug(n,r,e);if(i)return i;let s=r;for(;!Gt(ot(s));)s=et(ot(s));return jg(e)?ae(s):Yt(s)}function yT(n,t,e){return!Mt(n,t)||zn(n,t).enableKeyboardSelect?t:nA(n,t,e==="ArrowDown"||e==="ArrowRight")}function kT(n,t,e){const o=n.getBlockById(t.blockId),i=Jt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?AT(n,t):bT(n,t);if(s||(s=Ug(n,o,e),s||(s=vT(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Gt(ot(o)))return null;const l=n.insertTextBlock("",ct(n.rootContainer),To(n.rootContainer));return st(l,0,"home")}return null}if(s=yT(n,s,e),nt(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return Zx(n,s,o,t,l);if(e==="ArrowUp")return Gx(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?st(s,ut(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?st(s,0,"home"):null}function wT(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(nt(n,r))return o;const i=Yt(r);if(i)return st(i,0,"home");if(!Gt(ot(r))||n.readonly)return o;const s=n.insertTextBlock("",ct(n.rootContainer),To(n.rootContainer));return st(s,0,"home")}function BT(n,t,e){const o=n.selection.range;let r;if(o instanceof Ye)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=wT(n,t,o):r=kT(n,o.getFocusedPos(),t);else if(r=CT(n,o.focus,t),e==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(t==="ArrowLeft"||t==="ArrowUp"){const l=Qe(s);r=st(l,0,"home")}else{const l=ye(s);r=st(l,ut(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:Rh(n,o.anchor,r):null}function $i(n,t,e){const o=BT(n,t,e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(t==="ArrowLeft"||t==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function oA(n){return $i(n,"ArrowLeft","move"),!0}function rA(n){return $i(n,"ArrowRight","move"),!0}function iA(n){return $i(n,"ArrowUp","move"),!0}function sA(n){if($i(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=ot(t);if(Gt(e)||Qe(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",ct(o),To(o)),!0}function lA(n){return $i(n,"ArrowDown","select"),!0}function cA(n){return $i(n,"ArrowLeft","select"),!0}function aA(n){return $i(n,"ArrowRight","select"),!0}function uA(n){return $i(n,"ArrowUp","select"),!0}const dA=S("word-offset");function zg(n,t){const e=n.selection.range.focus;g(dA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(ue(n,o))return st(o,0,"home");if(e.offset===0||!nt(n,o)){const s=ae(o);if(!s)return null;const l=st(s,ut(n,s),"end");if(t==="select"&&nt(n,s)){const a=vg(n,s,l.offset);return st(s,a,"normal")}return l}const r=vg(n,o,e.offset);return st(o,r,"normal")}function Vg(n,t){const e=n.selection.range.focus;g(dA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(ue(n,o))return st(o,0,"end");if(e.offset===ut(n,o)||!nt(n,o)){const s=Yt(o);if(!s)return null;const l=st(s,0,"home");if(t==="select"&&nt(n,s)){const a=yg(n,s,l.offset);return st(s,a,"end")}return l}const r=yg(n,o,e.offset);return st(o,r,"normal")}function hA(n){if(!n.selection.range.focus.isSimple())return!1;const e=zg(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function fA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vg(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function mA(n){if(!n.selection.range.focus.isSimple())return!1;const e=zg(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function gA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vg(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}S("find-block");function Wg(n,t){if(!Mt(n,t))return t;const o=zn(n,t).getChildContainers(n,t)[0],i=me(o)[0];return Wg(n,i)}function qg(n,t){if(!Mt(n,t))return t;const e=zn(n,t).getChildContainers(n,t),o=e[e.length-1],r=me(o),i=r[r.length-1];return qg(n,i)}function Gg(n){const t=qg(n,Qe(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(e),!0}function pA(n){const t=Wg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(e),!0}function CA(n){const t=Wg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function Zg(n){const t=qg(n,Qe(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const AA=S("line-offset");function bA(n){const t=n.selection.range.focus;g(AA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!nt(n,e))return st(e,0,"home");let r=j4(e,t).start;const{next:i}=ih(e,r);return i&&co(i)&&ya(i)==="br"&&(r+=1),st(e,r,"home")}function vA(n){const t=n.selection.range.focus;g(AA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===ut(n,e)||!nt(n,e))return st(e,ut(n,e),"end");const o=j4(e,t);return st(e,o.end,"end")}function yA(n){if(!n.selection.range.focus.isSimple())return!1;const e=bA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function kA(n){if(!n.selection.range.focus.isSimple())return!1;const e=vA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function wA(n){if(!n.selection.range.focus.isSimple())return!1;const e=bA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function BA(n){if(!n.selection.range.focus.isSimple())return!1;const e=vA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const EA=S("find-block-position");function ET(n,t,e,o){g(EA,Mt(n,t),"is not a complex block");const r=zn(n,t).getChildContainers(n,t);g(EA,r.length>0,"complex block has not any child container");const i=Lo(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,a=S4(n,t,s,l);return Qg(n,a,e,o)}function Qg(n,t,e,o){if(Mt(n,t))return ET(n,t,e,o);const r=it(t);let i=Number.MAX_SAFE_INTEGER;const s=Lo(n,e,o),l=s.left+s.width/2,a=s.top+s.height/2;let d=st(r,0,"home");const h=ut(n,t);for(let p=0;p<=h;p++){const C=st(r,p,"normal"),v=Lo(n,t,C),B=or(v,l,a);B<i&&(i=B,d=C)}return d}const xA=S("page-offset");function xT(n,t){const e=x6(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<QI(n))return n.getFirstBlock();const i=ae(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ae(s)}return n.getFirstBlock()}function IT(n,t){const e=x6(n)*.9,o=t.getBoundingClientRect(),r=YI(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=Yt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Yt(l)}return n.getLastBlock()}function IA(n){const t=n.selection.range.focus;g(xA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=xT(n,e);let r;return o===n.getFirstBlock()?r=st(o,0,"home"):r=Qg(n,o,e,t),r}function TA(n){const t=n.selection.range.focus;g(xA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=IT(n,e);let r;return o===n.getLastBlock()?r=st(o,ut(n,o),"end"):r=Qg(n,o,e,t),r}function DA(n){if(!n.selection.range.focus.isSimple())return!1;const e=IA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function SA(n){if(!n.selection.range.focus.isSimple())return!1;const e=TA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function LA(n){if(!n.selection.range.focus.isSimple())return!1;const e=IA(n);if(!e)return!1;const o=Rh(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function MA(n){if(!n.selection.range.focus.isSimple())return!1;const e=TA(n);if(!e)return!1;const o=Rh(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const ja=S("select-all");function RA(n,t){const e=ye(n),o=Qe(n);return t.start.offset===0&&t.start.blockId===it(e)&&t.end.offset===ut(t.getEditor(),o)&&t.end.blockId===it(o)}function TT(n,t){const e=t.getEditor(),o=zn(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=it(n);return t.start.blockId===s&&t.start.childContainerId===ct(r)&&t.end.blockId===s&&t.end.childContainerId===ct(i)}function DT(n,t){g(ja,t,"no parent block"),g(ja,Mt(n,t),"not a complex block");const e=zn(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(ze(n,{anchor:fe(t,ct(o)),focus:fe(t,ct(r))}))}function OA(n,t){const e=ot(t);Yg(n,e)}function _A(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&nt(n,t)){const r=e.start,i=e.end,s=ut(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return W(n.rootContainer,"select-all"),OA(n,ye(n.rootContainer)),!1}return g(ja,!e.isSimple(),"invalid range type"),TT(t,e)?(OA(n,t),!1):(g(ja,t,"no parent block"),g(ja,Mt(n,t),"not a complex block"),DT(n,t),!0)}function Yg(n,t){const e=me(t),o=e[0],r=e[e.length-1],i=st(o,0,"home"),s=st(r,ut(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function ST(n){Zg(n),n.focus()}const Jg=S("selected-block-to-doc");function FA(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{FA(n,i,e)}),e.blocks[o]=mt.default(r)})}function Oh(n,t){const e=Jt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const o=mt.default(Pi(n,t.block));if(nt(n,t.block)){const i=t.start,s=t.end;if(g(Jg,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=Ve(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Ie(t.block))return{blocks:{root:[o]},meta:{},comments:{}};g(Jg,Mt(n,t.block),"not complex block"),g(Jg,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return FA(n,o,r),r}function Kg(n,t){const e=st(t,0,"normal"),o=st(t,ut(n,t),"end");return Oh(n,{block:t,start:e,end:o})}const LT=S("block-to-doc");function MT(n,t){g(LT,t.length>0,"invalid params, no blocks");const e=t.map(o=>Kg(n,o));return Ns(e)}function _h(n){const e=n.selection.range.getSelectedBlocks().map(o=>Oh(n,o));return Ns(e)}function PA(n,t){const e=n.getContainerById(t),i=me(e).map(s=>({start:st(s,0,"home"),end:st(s,ut(n,s),"end"),block:s})).map(s=>Oh(n,s));return Ns(i)}const Fh=S("editor-selection");class RT{constructor(t){m(this,"editor");m(this,"caret");m(this,"_range");m(this,"lastCaretRect");m(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(D6(e,i)){Fh.debug("adjust selection because remote deleted current block");const s=S6(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=it(e);this.caret=new qI(t);const r=st(o,0,"normal");this._range=ze(t,{anchor:r,focus:r}),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,o){const r=st(t,e,"normal");let i;o&&(i=st(t,o,"normal")),this.setSelection(r,i)}setSelection(t,e,o){if(e||(e=t),this.verifyPos(t),this.verifyPos(e),!this.selectionChanging(t,e))return this.range;const r=ze(this.editor,{anchor:t,focus:e});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),xt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!tT(this.editor,r))&&rt(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(t,e){return this.setSelection(t.anchor,t.focus,e)}updateSelection(){this.caret.update(),GI(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(!Vr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Lo(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){XI(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=ut(this.editor,e)||g(Fh,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||g(Fh,!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 o;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(o=this.editor.getBlockById(this.range.start.blockId));let r=!1;e&&xt(e,"focused")&&(rt(e,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(t){const e=_h(this.editor);return t==="text"?Oa(this.editor,e):t==="markdown"?_a(this.editor,e):M6(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{rt(t,"focused"),rt(t,"child-focused")})}setBlockFocused(t){if(xt(t,"focused"))return!1;W(t,"focused");let e=ot(t);for(;Mo(e);){const o=et(e);g(Fh,o,"parent block not found"),W(o,"child-focused"),e=ot(o)}return!0}}function OT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);!e||n.selection.selectBlock(e,0,ut(n,e))}function _T(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!nt(n,e))return;let o=zg(n,"select"),r=Vg(n,"select");if(!o||!r)return;const i=t.blockId;o.blockId!==i&&(o=st(e,0,"home")),r.blockId!==i&&(r=st(e,ut(n,e),"end")),n.selection.setSelection(o,r)}class FT{constructor(t){m(this,"editor");m(this,"startPos",null);m(this,"lastCaretRect");m(this,"mouseDownEvent",null);m(this,"autoScroll",null);m(this,"handleMouseDown",(t,e)=>{var r;this.mouseDownEvent=t;const o=R4(this.editor,t.x,t.y);if(o){if(o instanceof sr)return;if(!this.autoScroll&&e.autoScroll){const s=o.getSelectedBlocks(),l=so(s[0].block);this.autoScroll=new Xd({scrollElement:l,edge:{top:50,bottom:50}})}const i=this.editor.selection.range;if(t.shiftKey&&i.isSimple()){const s=i.anchor;this.editor.selection.setSelection(s,o.focus),this.startPos=o.start}else this.editor.selection.setSelection(o.anchor,o.focus),this.startPos=o.start;this.editor.selection.updateLastCaretRect(),e.autoScroll&&((r=this.autoScroll)==null||r.active())}});m(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=uh(this.editor,t.x,t.y);if(!e)return;const o=Rh(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});m(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){_T(this.editor)}handleTripleClick(t){OT(this.editor)}}function PT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function NT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const NA=S("delete-text");function $A(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof Ue||g(NA,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(NA,nt(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!sn(s,l-e)){const a=_i(s,l);e=l-a}}else if(t==="forward"&&l+e>ut(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function HA(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const $T=S("handle-backspace");function Xg(n,t){if(!ue(n,t))return;const e=ot(t);To(e)!==1&&n.deleteBlock(t)}function HT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(nt(n,o))if(e.offset===0){if(HA(n,o))return;const r=ae(o);if(r){if(!n.isBlockWritable(r))return;if(nt(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Mt(n,r)){Xg(n,o);const i=zl(n,r);i?n.selection.selectBlock(i,ut(n,i)):n.selection.selectBlock(r,0,ut(n,r))}else Xg(n,o),g($T,Ie(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=ot(o);if(Mo(i)){const s=I4(n,i);if(s){if(!n.isBlockWritable(s))return;Xg(n,o),n.selection.selectBlock(s,ut(n,s))}}}}else $A(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=bt(o),i=ot(o);n.insertTextBlock("",ct(i),r),n.deleteBlock(o)}}function jT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(nt(n,o))if(e.offset===ut(n,o)){const r=Yt(o);if(r){if(!n.isBlockWritable(r))return;nt(n,r)?n.mergeTextBlock(o,r,{focus:!0}):ue(n,o)?n.deleteBlock(o,ke(n,r,0)):n.deleteBlock(r)}}else $A(n,"forward",1,null);else{const r=bt(o),i=ot(o);n.insertTextBlock("",ct(i),r),n.deleteBlock(o)}}function UT(n){const{range:t}=n.selection,{start:e,end:o}=t,r=n.getBlockById(e.blockId),i=n.getBlockById(o.blockId);if(r!==i||!Mt(n,r))return!1;if(Vr(e))return!0;const s=Ms(n,r,e,o),l=gn(n,r);return s.length===l.length}function zT(n,t){if(UT(n)){const s=n.getFocusedBlock(),l=bt(s),a=ct(ot(s));n.insertTextBlock("",a,l+1);return}const e=n.getFocusedBlock(),{start:o,end:r}=n.selection.range,i=o.blockId===r.blockId&&Ie(e);if(!n.selection.range.isCollapsed()&&!i&&n.clearSelectedContents(),nt(n,e)){if(ue(n,e)&&HA(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 VT(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!nt(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:K(),box:!0,created:Date.now()}),!0}const WT=S("input-handler-actions");function qT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(zT(n),!0))}function GT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(jT(n),!0))}function ZT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(HT(n),!0))}function QT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(VT(n),!0))}function YT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{WT.error(t)}),!0)}const Ph={ArrowDown:sA,ArrowUp:iA,ArrowLeft:oA,ArrowRight:rA,"Shift+ArrowDown":lA,"Shift+ArrowUp":uA,"Shift+ArrowLeft":cA,"Shift+ArrowRight":aA,"CtrlOrCmd+ArrowLeft":hA,"CtrlOrCmd+ArrowRight":fA,"CtrlOrCmd+Shift+ArrowLeft":mA,"CtrlOrCmd+Shift+ArrowRight":gA,"CtrlOrCmd+ArrowUp":pA,"CtrlOrCmd+ArrowDown":Gg,"CtrlOrCmd+Shift+ArrowUp":CA,"CtrlOrCmd+Shift+ArrowDown":Zg,"CtrlOrCmd+A":_A,Home:wA,End:BA,"Shift+Home":yA,"Shift+End":kA,PageUp:DA,PageDown:SA,"Shift+PageUp":LA,"Shift+PageDown":MA,"CtrlOrCmd+Z":PT,"CtrlOrCmd+Shift+Z":NT,Enter:qT,Delete:GT,Backspace:ZT,"Shift+Enter":QT,"CtrlOrCmd+Shift+V":YT};function jA(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function UA(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){let l="";s.split("|").forEach(d=>{const h=e.get(d);l+=l?`|${h}`:`${h}`}),i.src=l}return}const o=t.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=e.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{UA(n,l,e)})})}function zA(n,t,e){if(e.size===0)return;t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,e):UA(t,r,e)})}async function JT(n,t){const e=t.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(e),r=new Map;if(e.length!==o.length)return r;for(let i=0;i<e.length;i++)r.set(e[i],o[i]);return r}function KT(n,t){var i,s;const o=t.meta.serverId;if(!o||typeof o!="string")return!1;const r=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i);return!(!r||r.serverId!==o)}async function XT(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(KT(n,t)){const s=Array.from(Object.keys(o));r=await JT(n,s),zA(n,t,r)}const i=new Map;Object.entries(o).forEach(([s,l])=>{r.get(s)===void 0&&s!==l&&i.set(s,l)}),i.size!==0&&zA(n,t,i)}async function tD(n,t,e){await XT(n,t),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Ie(i)){const s=ot(i),l=n.getBlockIndex(i),[a]=n.insertDocAt(s,l+1,t,e);a&&n.selection.selectBlock(a,ut(n,a))}else{n.clearSelectedContents();const{block:s,offset:l}=ql(n);n.insertDoc(s,l,t,e)}})}const eD=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function nD(n){let t;for(const e of eD)if(t=n[e],t)break;return t||null}function VA(n,t,e){if(t.type==="embed"){const s=t.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))e.add(l);return}const o=t.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&e.add(i.attributes.src)});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{VA(n,l,e)})})}function oD(n,t){const e=new Set;return t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{e.add(s)}):VA(t,r,e)}),Array.from(e)}function Nh(n,t){return Ze.isFirefox?`<!doctype html><html><head><meta charset="utf8" /></head><body><canvas data-editor-doc="${Mi(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::${Mi(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function $h(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=oD(n,t),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),t.meta={...e,resources:r}}function rD(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=_h(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),$h(n,o);const i=xh(n,o),s=_a(n,o),l=Nh(i,o);t.clipboardData.setData("text/html",l),t.clipboardData.setData("text/plain",s),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Hh(n,t){const e=Kg(n,t);$h(n,e);const o=xh(n,e),r=_a(n,e),i=Nh(o,e);return Rm([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class iD{constructor(t){m(this,"editor");m(this,"handlers",[]);m(this,"onPasteText",async(t,e)=>{const o=new DataTransfer;o.setData("text/plain",t);const r=await this.editor.dataConverter.fromData(this.editor,o,e);r&&this.pasteDocs(r,null)});this.editor=t}onInsertText(t,e){if(!nt(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=ql(this.editor);this.handleBeforeInsertText(o,r,i,e)||(this.defaultInsertText(this.editor,o,r,i,e),this.handleAfterInsertText(o,r,i,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 o=this.handlers[e];o.handleChanged&&o.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:o,offset:r}=ql(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,o,r)}}onUpdateCompositionText(t,e,o){this.editor.updateCompositionText(e,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=ql(this.editor);for(let l=0;l<this.handlers.length;l++){const a=this.handlers[l];a.handleUpdateCompositionText&&a.handleUpdateCompositionText(this.editor,r,i,s,o)}this.editor.selection.updateLastCaretRect()}onCopy(t){rD(this.editor,t,(e,o,r)=>{for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,o,r);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onCut(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;Ie(o)&&this.editor.deleteBlock(o)}else _g(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{o&&this.pasteDocs(o,t)})}onFocus(){W(this.editor.rootElement,"active")}onBlur(){rt(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,o)=>{var s,l;const r=(s=e.order)!=null?s:1;return((l=o.order)!=null?l:1)-r})}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,o,r))return!0}return!1}handleAfterInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,o,r))return!0}return!1}handleBeforeKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,o,r,i){Sg(this.editor,i)}defaultHandleKeydown(t,e){return jA(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await tD(this.editor,t,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,e,t))return}const o=nD(t);if(!!o){await this.pasteDoc(o);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPaste&&await i.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function sD(n,t,e){const o=Nr(t,e);return o.remove(),o}S("copy-dom-attributes");const WA=["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 lD(n,t){for(let l=0;l<WA.length;l++){const a=WA[l];t[a]=n[a]}const e=n.attributes,o=t.attributes,r=[],i=[];for(let l=0;l<e.length;l++){const a=e[l],d=o.getNamedItem(a.name);d?d.value!==a.value&&(d.value=a.value,i.push(a)):r.push(a)}const s=[];for(let l=0;l<o.length;l++){const a=o[l];e.getNamedItem(a.name)||s.push(a)}r.forEach(l=>{t.setAttribute(l.name,l.value)}),i.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function qA(n){const t=Array.from(n.childNodes).filter(e=>!z5(e));return t.forEach(e=>{e.remove()}),t}function GA(n,t,e){var d;const o=n.getContainerById(t),r=Nr(o,e),i=Ri(r),s=n.doc.getBlockData(t,e),l=Jt(n,r);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const h=n.editorBlocks.createBlock(i,o,s),p=qA(h);qA(r),p.forEach(v=>{r.appendChild(v)});const C=oh(h);if(C){const v=oh(r);v&&v.remove(),r.appendChild(C)}lD(h,r)}l4(n,r,s),n.blockHooks.forEach(h=>{var p;(p=h.update)==null||p.call(h,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const cD=S("transform-selection");function ZA(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;g(cD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const d=ln.transformCursor(i.offset,e,o);l=st(t,d,"normal")}let a=s;if(s.blockId===t){const d=ln.transformCursor(s.offset,e,o);a=st(t,d,"normal")}return ze(n,{anchor:l,focus:a})}const aD=S("handle-block-text-changed");function uD(n,t,e,o,r){const i=n.getContainerById(t),s=Nr(i,e),l=n.doc.getBlockData(t,e);if(g(aD,l.text,"no block text"),e4(n,s).setBlockText(n,s,l.text),!r){const a=ZA(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function dD(n,t){const e=mt.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function QA(n,t,e,o){const r=Jt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function hD(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{QA(n,i,o,{child:!0})}),QA(n,r,o,{child:!1})}const Fo=S("editor-doc");class fD extends ha{constructor(e,o,r){super();m(this,"localEvents",[]);this.editor=e,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}getBlockData(e,o){return this.externalDoc.getBlockData(e,o)}verifyBlockWritable(e,o){const r=this.editor.getBlockByIndex(e,o);g(Fo,this.editor.isBlockWritable(r),`block is not writable, ${e}, ${o}`)}localUpdateBlockText(e,o,r,i){g(Fo,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const s=this.getBlockData(e,o),l=s.text;g(Fo,l,`no text, ${e}, ${o}`);const a=ZA(this.editor,s.id,r,!0),d=ln.apply(l,r);this.localEvents.forEach(p=>p.onBeforeUpdateBlockText(e,s.id,l,d,a.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(a,i),h}localUpdateBlockData(e,o,r,i){g(Fo,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,o);if(!this.editor.isBlockWritable(s)){const h=Array.from(r.delete).filter(C=>C!=="comments"),p=Object.keys(r.insert).filter(C=>C!=="comments");(h.length>0||p.length>0)&&g(Fo,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=mt.default(this.getBlockData(e,o)),a=mt.default(dD(l,r));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,a,i));const d=this.externalDoc.localUpdateBlockData(e,o,r,i);return this.editor.selection.setRange(Oi(this.editor,i)),d}localInsertBlock(e,o,r,i,s){g(Fo,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(a=>a.onBeforeInsertBlock(e,o,r,i));const l=this.externalDoc.localInsertBlock(e,o,r,i);return s!=null&&s.noFocus||this.editor.selection.setRange(Oi(this.editor,i),s),l}localDeleteBlock(e,o,r){g(Fo,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const i=mt.default(this.getBlockData(e,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,o,i,r));const s=this.externalDoc.localDeleteBlock(e,o,r);return this.editor.selection.setRange(Oi(this.editor,r)),s}localDeleteChildContainers(e){return g(Fo,!this.editor.readonly,"editor is readonly"),e.forEach(o=>{const r=mt.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainers(e){g(Fo,!this.editor.readonly,"editor is readonly");const o=mt.default(e);o.forEach(r=>{this.localEvents.forEach(i=>i.onBeforeInsertChildContainer(r.containerId,r.blocks))}),this.externalDoc.localInsertChildContainers(o)}onRequestReload(e){Fo.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,o,r,i)}),uD(this.editor,e,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,i)}),GA(this.editor,e,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(e,o,r,i){this.callbacks.forEach(l=>{var a;return(a=l.onInsertBlock)==null?void 0:a.call(l,e,o,r,i)});const s=this.editor.getContainerById(e);XE(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){hD(this.editor,e,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,r)});const i=this.editor.getContainerById(e);sD(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(e,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,r)})}onDeleteChildContainer(e,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,e)})}onStatusChanged(e){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)})}onError(e){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,e)})}uploadResource(e,o){return this.externalDoc.uploadResource(e,o)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,o){return this.externalDoc.buildResourceUrl(e,o)}request(e,o){return this.externalDoc.request(e,o)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,o,r;return(r=(o=(e=this.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}reset(e){Fo.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function YA(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 tp=S("undo-action");class Jl{constructor(t,e,o){m(this,"beforeRange");m(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=o}undo(t){return!1}redo(t){return!1}combinable(t){return g(tp,t,"no other action"),!1}combine(t){g(tp,!1,"no other")}setAfterRange(t){this.afterRange&&tp.warn("after range has already set"),this.afterRange=t}}const mD=S("block-action");class JA extends Jl{constructor(e,o,r,i,s){super(e,o,s);m(this,"blockData");m(this,"blockIndex");this.blockData=mt.default(i),this.blockIndex=r}deleteBlock(e,o){if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);return i?(g(mD,this.blockIndex===bt(i),"invalid block index"),Dh(e,i,Oi(e,o)),!0):!1}insertBlock(e,o){return Zl(e,this.containerId,this.blockIndex,mt.default(this.blockData),o),!0}}const gD=S("insert-block-action");class pD extends JA{undo(t){return t.findBlockById(this.blockData.id)?this.deleteBlock(t,this.beforeRange):(gD.warn(`block (${this.blockData.blockId}) not found, deleted by others?`),!1)}redo(t){return this.insertBlock(t,this.afterRange)}}class CD extends JA{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class AD extends Jl{constructor(e){super(e,ct(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){YA(this.actions,e),this.afterRange=e.afterRange}undo(e){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(e)&&(o=!0)}),o}redo(e){let o=!1;return this.actions.forEach(r=>{r.redo(e)&&(o=!0)}),o}setAfterRange(e){this.afterRange=e;const o=this.actions[this.actions.length-1];!o||o instanceof Jl&&(o.afterRange||o.setAfterRange(e))}}const Hi=S("update-block-data-action");class jh extends Jl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeBlockData");m(this,"afterBlockData");m(this,"blockId");this.blockId=r,g(Hi,this.blockId===i.id,"invalid block id"),g(Hi,this.blockId===s.id,"invalid block id"),this.beforeBlockData=mt.default(i),this.afterBlockData=mt.default(s),g(Hi,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){if(!e.findBlockById(this.blockId))return Hi.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hi,r,"no container"),Mh(e,o,jh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){if(!e.findBlockById(this.blockId))return Hi.warn(`block (${this.blockId}) not found, deleted by others?`),!1;g(Hi,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hi,r,"no container"),Mh(e,o,jh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=mt.default(e);return delete o.id,delete o.type,o}}const ep=S("update-block-text-action");class Ua extends Jl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeRichTextData");m(this,"afterRichTextData");m(this,"blockId");m(this,"type");this.blockId=r,this.beforeRichTextData=mt.default(i),this.afterRichTextData=mt.default(s),this.type=Ua.calType(i,s)}static calType(e,o){g(ep,e,"no old data"),g(ep,o,"no new data");const i=ln.diff(e,o),s=new Set;let l=!1;const a=h=>A5(h)?`cjk_${h}`:p5(h)?"number":Zd(h)?"space":C5(h)?"letter":"unknown";let d=!1;return i.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_${a(h.insert.substr(1))}`)):s.add(`insert_${a(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Lh(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Lh(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof Ua)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const o=e.beforeRange,r=o.anchor;if(!r.isSimple())return!1;const i=this.afterRange;if(!i)return!1;const s=i.anchor;return!(!s.isSimple()||s.blockId!==o.anchor.blockId||s.offset!==r.offset)}combine(e){g(ep,e instanceof Ua,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class KA extends Jl{constructor(t,e,o){super(t,e,t.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(t){return t.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(t){return t.doc.localInsertChildContainers([{containerId:this.containerId,blocks:mt.default(this.blocks)}]),!0}}class bD extends KA{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class vD extends KA{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Po=S("undo");class yD{constructor(t){m(this,"editor");m(this,"actions",[]);m(this,"undoCursor");m(this,"currentGroup",null);m(this,"groupCounter",0);m(this,"undoRedoing",!1);m(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):(YA(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(g(Po,!this.currentGroup,"current group already exists"),this.currentGroup=new AD(this.editor),this.groupCounter=1):(g(Po,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Po,this.currentGroup,"current group not exists"),g(Po,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Po.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 Po.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(Oi(this.editor,t.beforeRange))}catch(e){Po.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(Oi(this.editor,e)):Po.warn("no after range")}catch(e){Po.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,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),ln.diff(o,r).length!==0&&this.addAction(new Ua(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new jh(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Po,e>=0,"invalid block index"),g(Po,o,"no block data"),this.addAction(new pD(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new CD(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new bD(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new vD(this.editor,t,e)))}}class kD{async fromData(t,e){const o=e.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class wD{constructor(){m(this,"converters",[]);m(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new kD)}prepareData(t){const e=new DataTransfer;for(let o=0;o<this.converterTypes.length;o++)e.setData(this.converterTypes[o],t.getData(this.converterTypes[o]));return e}async fromData(t,e,o){let r={};const i=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,i,o);l&&(r={...r,...l})}return r}addConverter(t){this.converters.push(t)}}class BD{constructor(t){m(this,"renders",[]);this.editor=t}registerRender(t){this.renders.push(t)}renderText(t,e){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,t,e);i.classes&&o.classes.push(...i.classes),i.attributes&&(o.attributes={...o.attributes,...i.attributes}),i.styles&&(o.styles={...o.styles,...i.styles})}}),o}renderBlock(t,e,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,e,o);s.classes&&r.classes.push(...s.classes),s.attributes&&(r.attributes={...r.attributes,...s.attributes}),s.styles&&(r.styles={...r.styles,...s.styles})}}),r}updateBlock(t,e,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,t,e,o,r)})}}class Ce extends ve.TypedEmitter{constructor(e){super();m(this,"hoveringBlock",null);m(this,"hoveringTextChild",null);m(this,"filters",[]);m(this,"finders",[]);m(this,"handleDocumentMouseMove",e=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,e))return}const o=document.elementFromPoint(e.x,e.y);if(!o){this.setHoveringBlock(null,e,null);return}let r=et(o);if((!r||!Qt(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(e),!r)){this.setHoveringBlock(null,e,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,e,i)});this.editor=e,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(e=>e.destroy()),this.filters=[],this.finders.forEach(e=>e.destroy()),this.finders=[]}addFilter(e){this.filters.push(e)}addFinder(e){this.finders.push(e)}hoveringBlockId(){return this.hoveringBlock?it(this.hoveringBlock):""}findBlockByFinders(e){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,e);if(i)return i}return null}setHoveringBlock(e,o,r){if(this.hoveringBlock===e&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==e){const s=this.hoveringBlock&&Qt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&rt(s,"hover"),e&&W(e,"hover"),this.hoveringBlock=e,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(e){return e.addCustom("standard-hovering-block",()=>new Ce(e))}getParentTextContentChild(e,o){if(!nt(this.editor,e))return null;const r=Lt(e);return o.parentElement===r?o:Hm(o)}}const XA="style-color-",tb="style-bg-color-";class ED{renderText(t,e,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(XA)?i["data-style-color"]=l.substring(XA.length):l.startsWith(tb)?i["data-style-bg-color"]=l.substring(tb.length):l.startsWith("style")&&r.push(l):typeof a=="string"&&(l==="link"&&(r.push("link"),i.link=a),l==="inline-style-color"&&(s.color=a))}),{classes:r,attributes:i,styles:s}}renderBlock(t,e,o){var l,a;const r={};Object.entries(o).filter(d=>d[0].startsWith("style-")).forEach(([d,h])=>{r[`data-${d}`]=`${h}`});const s=[];return((a=(l=t.selection)==null?void 0:l.range)==null?void 0:a.start.blockId)===o.id&&s.push("focused"),typeof o.align=="string"&&o.align&&(r["data-style-align"]=o.align),o.heading&&(r["data-style-heading"]=String(o.heading)),o.quoted&&(r["data-style-quoted"]="true"),Ce.get(t).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(t,e,o,r){var s,l;Array.from(o.attributes).forEach(a=>{a.name.startsWith("data-style-")&&o.removeAttribute(a.name)}),Object.entries(r).filter(a=>a[0].startsWith("style-")||a[0]==="align").forEach(([a,d])=>{a==="align"&&o.setAttribute(a.startsWith("style-")?`data-${a}`:`data-style-${a}`,`${d}`)}),((l=(s=t.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&W(o,"focused"),Ce.get(t).hoveringBlockId()===r.id&&W(o,"hover")}}function xD(n){n.editorBlocks.registerBlockClass(Dn),n.editorBlocks.registerBlockClass(x4),n.editorBoxes.registerBoxClass(g6),n.editorBoxes.registerBoxClass(p6),n.editorBoxes.registerBoxClass(b6),n.editorBoxes.registerBoxClass(v6),n.editorInsertions.registerInsertionClass(y6),n.editorBlockRenders.registerRender(new ED)}function ID(n,t){xD(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 eb=S("range-commands");function nb(n,t){n.forEach(e=>{e.source=t,e.children&&nb(e.children,t)})}function ob(n,t,e){const o=it(t);g(eb,o===e.start.blockId,"invalid start range"),g(eb,o===e.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,t,e);nb(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),Mt(n,t)&&Ms(n,t,e.start,e.end).forEach(l=>{me(l).forEach(d=>{const h=ut(n,d),p=ze(n,{anchor:st(d,0,"home"),focus:st(d,h,"end")}),C=ob(n,d,p);i.push(...C)})}),i}function rb(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=ze(t,{anchor:r.start,focus:r.end});ob(t,r.block,i).forEach(l=>{o.push(l)})}),o}function ib(n,t,e,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const C=s[p];if(C.beforeExecuteCommand&&C.beforeExecuteCommand(n,t,e,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),a={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,o,r,{}))return i[it(t)]=a,!0;let d=!1;return Mt(n,t)&&Ms(n,t,e.start,e.end).forEach(C=>{me(C).forEach(B=>{const D=ut(n,B),x=ze(n,{anchor:st(B,0,"home"),focus:st(B,D,"end")});ib(n,B,x,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,t,e,o,r,i)}),d}function sb(n,t,e){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(t.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,t,e,r)||n.getSelectedBlocks().forEach(l=>{const a=ze(o,{anchor:l.start,focus:l.end});ib(o,l.block,a,t,e,r)}),r}const TD=S("command-providers");class lb{constructor(t){m(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(o=>o.id===t);return g(TD,e,`no command provider, id=${t}`),e}getCommands(t){return rb(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>sb(t,e,o))}getEmptyBlockTextAttributes(t,e){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,t,e);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function DD(n,t){const e=ot(t),o=ct(e),r=bt(t);GA(n,o,r)}const SD=S("table-scroll");class cb{constructor(t,e,o,r,i){m(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=o,this.handler=r,this.data=i,e.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class LD{constructor(t){m(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(o=>o.destroy()),this.handlers.delete(t)})}addEventListener(t,e,o,r){const i=this.handlers.get(t);if(i){if(i.find(s=>s.handler===o&&s.name===e)){SD.warn(`event has already registered: ${e}`);return}i.push(new cb(this.editor,t,e,o,r))}else{const s=new cb(this.editor,t,e,o,r);this.handlers.set(t,[s])}}removeEventListener(t,e,o){if(!t){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const a=s[l];if(e)e===a.name&&o===a.handler&&s.splice(l,1);else if(o===a.handler){s.splice(l,1),a.destroy(),s.length===0&&this.handlers.delete(i);continue}}return}const r=this.handlers.get(t);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===e);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const o=this.handlers.get(t);if(o)if(e)for(let r=0;r<o.length;r++){const i=o[r];i.name===e&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(t)}}const ab=S("update-block-text");function MD(n,t){const e=n.getBoxById(t.id),o=et(e);g(ab,o,"no parent block"),g(ab,nt(n,o),"not a text block");const r=n.getBlockText(o),i=s6(r,"id",t.id,t);z6(n,o,i)}function RD(n,t){for(const e of n.blockHooks)if(e.writable){const o=e.writable(n,t);if(typeof o=="boolean")return o}return!0}function OD(n){if(n.readonly)return!1;const t=Oo(n);return!!n.isBlockWritable(t.map(e=>e.block))}class _D{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 FD{constructor(){m(this,"shortcuts",[])}handleKeyboardEvents(t,e){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(rr(e,s)){const a=l(t,e);if(a!==void 0)return a}}}}const Qr=S("editor");class PD extends ve.TypedEmitter{constructor(e,o,r){var i,s,l,a,d,h,p;super();m(this,"parent");m(this,"rootElement");m(this,"contentElement");m(this,"rootContainerObject");m(this,"rootContainer");m(this,"input");m(this,"selection");m(this,"selectionHandler");m(this,"doc");m(this,"id");m(this,"clientId");m(this,"compositingText","");m(this,"undoManager");m(this,"shortcuts",new FD);m(this,"dataConverter",new wD);m(this,"editorBlocks",new k4(this));m(this,"editorBoxes",new A6(this));m(this,"editorInsertions",new w6(this));m(this,"editorEmbeds",new B4(this));m(this,"editorDecorators",new B6(this));m(this,"editorCommandProviders",new lb(this));m(this,"editorBlockRenders",new BD(this));m(this,"blockHooks",[]);m(this,"domEvents",new LD(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new iD(this));m(this,"settingsProvider");m(this,"_readonly",!1);Qr.debug("create editor"),this.setMaxListeners(100),this.options={colors:(i=r==null?void 0:r.colors)!=null?i:["#9923E9","#4587C2","#8BDB7A","#FB28D3","#CBC619","#10FEEB","#812A1A","#8A3F25","#22D742","#A53E74","#555C87","#57E0AA"],componentsOptions:(l=(s=r==null?void 0:r.components)==null?void 0:s.options)!=null?l:{},scrollContainer:r==null?void 0:r.scrollContainer},this.settingsProvider=(a=r==null?void 0:r.settingsProvider)!=null?a:new _D(this),ID(this,r==null?void 0:r.components),this.blockHooks.push(...(h=(d=r==null?void 0:r.components)==null?void 0:d.blockHooks)!=null?h:[]),this.id=(p=r==null?void 0:r.id)!=null?p:K(),this.clientId=K(),this.undoManager=new yD(this),this.doc=new fD(this,o,this.undoManager),this.parent=e,this.rootElement=k("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=k("div",["editor-content"],this.rootElement),this.rootContainerObject=b4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new WI(this,this.inputHandlers),this.selection=new RT(this),this.selectionHandler=new FT(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),Ze.isMobile&&W(this.rootElement,"mobile"),Ze.isSafari&&W(this.rootElement,"safari"),this._readonly&&W(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?W(this.rootElement,"readonly"):rt(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:so(this.rootContainer)}addCustom(e,o){const r=this.customs.get(e);if(r)return r;const i=o(this);return this.customs.set(e,i),i}getCustom(e){const o=this.customs.get(e);return g(Qr,o,`${e} does not exists`),o}replaceCustom(e,o){const r=this.customs.get(e);return r&&r.destroy(),this.customs.set(e,o),o}findCustom(e){return this.customs.get(e)}findCustomByType(e){const o=this.customs.values();for(const r of o)if(r instanceof e)return r;return null}destroyCustom(e){const o=this.customs.get(e);o&&(this.customs.delete(e),o.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,o,r){return this.editorBlocks.createBlock(e,o,r)}createBox(e,o){return this.editorBoxes.createBox(e,o)}createInsertion(e,o){return this.editorInsertions.createInsertion(e,o)}destroy(){Qr.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(),setTimeout(()=>{W(this.rootElement,"active")})}focusToBlock(e,o){Fg(this,e,o)}isWritable(){return OD(this)}isBlockWritable(e){return RD(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return(!o||!Array.isArray(o))&&(g(Qr,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),g(Qr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`)),o}createChildContainer(e,o,r){return v4(this,e,o,r)}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 o=this.rootContainer.querySelector(`#${e}`);return o&&g(Qr,Bs(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(Qr,$m(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return g(Qr,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return g(Qr,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return Nr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return bt(o)}return bt(e)}getContainerById(e){return zr(this,e)}getParentContainer(e){return ot(e)}reloadBlock(e){DD(this,e)}contains(e){const o=e instanceof Element?e:e.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,o,r,i,s){const l={blockId:r.id,offset:0},a={anchor:l,focus:l};return Zl(this,e,o,r,i!=null?i:a,s)}insertEmbed(e,o,r,i,s){const l={id:K(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){Rg(this,e,o)}mergeTextBlock(e,o){return H6(this,e,o)}breakTextBlock(e,o,r){return Ql(this,e,o,r).newBlock}getTextPosition(){return ql(this)}getBlockString(e,o){const r=this.getBlockText(e);return ie(r,o)}getBlockData(e){return Pi(this,e)}getBoxData(e){return f6(this,e)}getBlockText(e){return pn(this,e)}setBlockText(e,o){z6(this,e,o)}deleteTextFromBlock(e,o,r,i){return Lg(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return R6(this,e,o,r,i)}insertBoxToBlock(e,o,r){return O6(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){q6(this,e,o,r,i)}insertDocAt(e,o,r,i){return $g(this,e,o,r,i)}deleteChildContainers(e){$6(this,e)}replaceBlockText(e,o){return Lh(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...a}=i;return Mh(this,e,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return V6(this,e,o,r)}updateBoxData(e){MD(this,e)}getSelectedText(){const e=_h(this);return Oa(this,e)}clearSelectedContents(){_g(this)}insertTextBlock(e,o,r,i){const s=ar(e!=null?e:"");return N6(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(e,o){if(e&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!o){F6(this);return}o?(this.compositingText="",pa()||Sg(this,e)):(this.compositingText=e,_6(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function za(n,t,e){return new PD(n,t,e)}function ND(n){const t=(o,r)=>{const i=o.findIndex(l=>l.id===r.id);if(i===-1){o.push(r);return}const s=o[i];if(s.value!==r.value){o.splice(i,1);return}if(!!s.states){if(!r.states){s.states=[];return}s.states=Cm.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const $D=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class Uh extends ve.TypedEmitter{constructor(e){super();m(this,"users",new Map);m(this,"cursors",new Map);m(this,"addingUser",!1);m(this,"colors");this.colors=e&&e.length>0?e:$D}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&aa.default(o,e))return;this.cursors.set(e.user.userId,e);const r=new Set([e.range.anchor.blockId,e.range.focus.blockId]),i=new Set(r);o&&new Set([o.range.anchor.blockId,o.range.focus.blockId]).forEach(l=>{r.has(l)||i.add(l)}),this.emit("remote-carets-change",[...i])}addUsers(e){this.addingUser=!0,e.forEach(o=>this.addUser(o)),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 o;return(o=this.users.get(e))!=null?o:null}removeUser(e){this.users.delete(e),this.cursors.delete(e),this.emit("change",Array.from(this.users.values()))}updateUsers(e){this.users.clear(),this.addingUser=!0;try{e.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e&&vh(r.range)).forEach(r=>{const i=r.range.focus.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(e){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===e||o.range.focus.blockId===e)}onUpdateBlockText(e,o,r){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(vh(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===e.id&&(a.offset=ln.transformCursor(a.offset,o,r)),d.blockId===e.id&&(d.offset=ln.transformCursor(d.offset,o,r))}})}getFixedUserColor(e,o){let r=0;Array.from(e).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const Xe=S("local-doc");class np extends ha{constructor(e,o){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[ar("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return mt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`);const i=r[o];return g(Xe,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(Xe,i.text,"no text for data");const s=ln.apply(i.text,r);return i.text=s,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockText)==null?void 0:a.call(l,e,o,r,!0)}),s}localUpdateBlockData(e,o,r){const i=this.getBlockData(e,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,!0)}),i}localInsertBlock(e,o,r){const i=this.getContainerBlocks(e);return g(Xe,i,`no container data: ${e}`),g(Xe,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,o,r,!0)}),r}localDeleteBlock(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`),g(Xe,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,!0)}),i}localInsertChildContainers(e){e.forEach(({containerId:o,blocks:r})=>{this.doc.blocks[o]=r,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,o,r,!0)})})}localDeleteChildContainers(e){Xe.debug(`delete child containers: ${e}`),e.forEach(o=>{g(Xe,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,o,!0)})})}uploadResource(e,o){g(Xe,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){g(Xe,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Uh}setDoc(e){this.doc=mt.default(e),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class HD{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function op(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new HD(o)})}const ub=S("find-block");function db(n,t){const e=Is(t);if(!e){if(lo(t))return null;const o=Es(t);return g(ub,o,"no parent block"),db(n,o)}return Mt(n,e)?zl(n,e,{visibleOnly:!0}):e}function hb(n,t){const e=Ts(t);if(!e){if(lo(t))return null;const o=Es(t);return g(ub,o,"no parent block"),hb(n,o)}return Mt(n,e)?tg(n,e,{visibleOnly:!0}):e}const jD=S("remote-cursor");class UD{constructor(){m(this,"remoteUsers",new Uh)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):jD.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 zD(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function VD(n){const{blocks:t,meta:e,comments:o}=n,{root:r,...i}=t;return{blocks:r,meta:e,comments:o,...i}}function Va(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=zD(mt.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function ji(n){return n==="root"?"blocks":n}function Kl(n){return n==="blocks"?"root":n}const WD={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new on.default(n)},apply(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},compose(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},diff(n,t){const e=new on.default(n),o=new on.default(t);return e.diff(o).ops},transform(n,t,e){const o=new on.default(n);return new on.default(t).transform(o,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 o=new on.default(t),r=this.transformCursor(n.index,o,e),i=this.transformCursor(n.index+n.length,o,e);return{...n,index:r,length:i-r}}}};var dr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ui={},rp=Q3.default.EventEmitter;Ui.EventEmitter=rp,Ui.mixin=qD;function qD(n){for(var t in rp.prototype)n.prototype[t]=rp.prototype[t]}var fb=["info","warn","error"];function mb(){var n={};fb.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var GD=mb;mb.prototype.setMethods=function(n){n=n||{};var t=this;fb.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var ZD=GD,QD=new ZD,gb=QD;function $s(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,$s):this.stack=new Error().stack}$s.prototype=Object.create(Error.prototype),$s.prototype.constructor=$s,$s.prototype.name="ShareDBError",$s.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 zh=$s,Wa={},pb=YD;function YD(n,t,e,o){var r=function(s,l,a,d){t(a,s,l,"left"),t(d,l,s,"right")},i=n.transformX=function(s,l){e(s),e(l);for(var a=[],d=0;d<l.length;d++){for(var h=l[d],p=[],C=0;C<s.length;){var v=[];if(r(s[C],h,p,v),C++,v.length===1)h=v[0];else if(v.length===0){for(var B=C;B<s.length;B++)o(p,s[B]);h=null;break}else{for(var D=i(s.slice(C),v),x=0;x<D[0].length;x++)o(p,D[0][x]);for(var _=0;_<D[1].length;_++)o(a,D[1][_]);h=null;break}}h!=null&&o(a,h),s=p}return[s,a]};n.transform=function(s,l,a){if(!(a==="left"||a==="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],a):a==="left"?i(s,l)[0]:i(l,s)[1]}}var Cb={exports:{}},zi=Cb.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||""}},ip=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},sp=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")},Vh=function(n){for(var t=0;t<n.length;t++)sp(n[t])};zi.apply=function(n,t){var e;Vh(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=ip(n,r.p,r.i);else{if(e=n.slice(r.p,r.p+r.d.length),r.d!==e)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+e+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var Yr=zi._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:ip(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:ip(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};zi.compose=function(n,t){Vh(n),Vh(t);for(var e=n.slice(),o=0;o<t.length;o++)Yr(e,t[o]);return e},zi.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=0),Yr(t,o)}return t};var lp=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};zi.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=lp(n,t[r],o);return n};var JD=zi._tc=function(n,t,e,o){if(sp(t),sp(e),t.i!=null)Yr(n,{i:t.i,p:lp(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(Yr(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&Yr(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)Yr(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)Yr(n,t);else{var i={d:"",p:t.p};t.p<e.p&&(i.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(i.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),a=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(a!==d)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=lp(i.p,e),Yr(n,i))}return n},KD=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};zi.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=KD(n[t]);return n},pb(zi,JD,Vh,Yr);var Wh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},XD=function(n){return!!n&&n.constructor===Object},No=function(n){return JSON.parse(JSON.stringify(n))},It={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Jr={};It.registerSubtype=function(n){Jr[n.name]=n},It.create=function(n){return n===void 0?null:No(n)},It.invertComponent=function(n){var t={p:n.p};return n.t&&Jr[n.t]&&(t.t=n.t,t.o=Jr[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},It.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(It.invertComponent(t[o]));return e},It.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Wh(n[t].p))throw new Error("Missing path")},It.checkList=function(n){if(!Wh(n))throw new Error("Referenced element not a list")},It.checkObj=function(n){if(!XD(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function qa(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 Ga(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}It.apply=function(n,t){It.checkValidOp(t),t=No(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&qa(r);for(var i=null,s=e,l="data",a=0;a<r.p.length;a++){var d=r.p[a];if(i=s,s=s[l],l=d,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Jr[r.t])s[l]=Jr[r.t].apply(s[l],r.o);else if(r.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=r.na}else if(r.li!==void 0&&r.ld!==void 0)It.checkList(s),s[l]=r.li;else if(r.li!==void 0)It.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)It.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(It.checkList(s),r.lm!=l){var h=s[l];s.splice(l,1),s.splice(r.lm,0,h)}}else if(r.oi!==void 0)It.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)It.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},It.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},It.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=It.apply(n,r),e(r,n)}return n};var tS=It.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==t[o]&&(!e||o!==n.length-1))return!1;return!0};It.append=function(n,t){if(t=No(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)&&(qa(t),qa(e)),tS(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Jr[t.t]){if(e.o=Jr[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var o=t.p,r=0;r<e.o.length-1;r++)t.o=[e.o.pop()],t.p=o.slice(),Ga(t),n.push(t);Ga(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)&&(Ga(t),Ga(e)),n.push(t)},It.compose=function(n,t){It.checkValidOp(n),It.checkValidOp(t);for(var e=No(n),o=0;o<t.length;o++)It.append(e,t[o]);return e},It.normalize=function(n){var t=[];n=Wh(n)?n:[n];for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=[]),It.append(t,o)}return t},It.commonLengthForOps=function(n,t){var e=n.p.length,o=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&o++,e===0)return-1;if(o===0)return null;e--,o--;for(var r=0;r<e;r++){var i=n.p[r];if(r>=o||i!==t.p[r])return null}return e},It.canOpAffectPath=function(n,t){return It.commonLengthForOps({p:t},n)!=null},It.transformComponent=function(n,t,e,o){t=No(t);var r=It.commonLengthForOps(e,t),i=It.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,i!=null&&l>s&&t.p[i]==e.p[i]){if(t.ld!==void 0){var a=No(e);a.p=a.p.slice(s),t.ld=It.apply(No(t.ld),[a])}else if(t.od!==void 0){var a=No(e);a.p=a.p.slice(s),t.od=It.apply(No(t.od),[a])}}if(r!=null){var d=s==l,a=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(qa(t),a=No(e),qa(a)),a.t&&Jr[a.t]){if(t.t&&t.t===a.t){var h=Jr[t.t].transform(t.o,a.o,o);if(t.si!=null||t.sd!=null)for(var p=t.p,C=0;C<h.length;C++)t.o=[h[C]],t.p=p.slice(),Ga(t),It.append(n,t);else(!Wh(h)||h.length>0)&&(t.o=h,It.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[r]===t.p[r])if(d){if(t.ld!==void 0)if(t.li!==void 0&&o==="left")t.ld=No(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[r]===e.p[r]?o==="right"&&t.p[r]++:e.p[r]<=t.p[r]&&t.p[r]++,t.lm!==void 0&&d&&e.p[r]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[r]===t.p[r])return n;var p=e.p[r],v=t.p[r],B=t.lm;(p<B||p===B&&v<B)&&t.lm--}if(e.p[r]<t.p[r])t.p[r]--;else if(e.p[r]===t.p[r]){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 v=t.p[r],B=t.lm,D=e.p[r],x=e.lm;if(D!==x)if(v===D)if(o==="left")t.p[r]=x,v===B&&(t.lm=x);else return n;else v>D&&t.p[r]--,v>x?t.p[r]++:v===x&&D>x&&(t.p[r]++,v===B&&t.lm++),(B>D||B===D&&B>v)&&t.lm--,B>x?t.lm++:B===x&&(x>D&&B>v||x<D&&B<v?o==="right"&&t.lm++:B>v?t.lm++:B===D&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var v=e.p[r],B=e.lm;p=t.p[r],p>v&&t.p[r]--,p>B&&t.p[r]++}else{var v=e.p[r],B=e.lm;p=t.p[r],p===v?t.p[r]=B:(p>v&&t.p[r]--,(p>B||p===B&&v>B)&&t.p[r]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[r]===e.p[r])if(t.oi!==void 0&&d){if(o==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[r]===e.p[r])if(o==="left")It.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[r]==e.p[r]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return It.append(n,t),n},pb(It,It.transformComponent,It.checkValidOp,It.append);var eS=Cb.exports;It.registerSubtype(eS);var nS=It,oS={type:nS};(function(n){n.defaultType=oS.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)})(Wa);var $o={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var o 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],o=1;o<arguments.length;o++){var r=arguments[o];e=e[r]||(o===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];e=e[i]||(e[i]=r===arguments.length-2?o():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],o=[e],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!e.hasOwnProperty(i))break;e=e[i],o.push(e)}for(var r=o.length-1;r>=0;r--){var s=o[r],i=arguments[r+1],l=s[i];(r===o.length-1||!n.hasKeys(l))&&delete s[i]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,o){var r=!1;return e.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];setTimeout(function(){e.apply(null,o)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})($o);var Ab=Array.isArray,bb=Object.keys,rS=Object.prototype.hasOwnProperty,iS=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=Ab(t),r=Ab(e),i,s,l;if(o&&r){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!n(t[i],e[i]))return!1;return!0}if(o!=r)return!1;var a=t instanceof Date,d=e instanceof Date;if(a!=d)return!1;if(a&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,p=e instanceof RegExp;if(h!=p)return!1;if(h&&p)return t.toString()==e.toString();var C=bb(t);if(s=C.length,s!==bb(e).length)return!1;for(i=s;i--!==0;)if(!rS.call(e,C[i]))return!1;for(i=s;i--!==0;)if(l=C[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},vb=Ui,sS=gb,qn=zh,qh=Wa,Ho=$o,lS=Ho.clone,cS=iS,Sn=qn.CODES,aS=Ft;function Ft(n,t,e){vb.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}vb.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=qh.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new qn(Sn.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 qn(Sn.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 qn(Sn.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 o=n.type===void 0?qh.defaultType:n.type;this._setType(o),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;Ho.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===Sn.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 o=this.inflightFetch.shift();if(o&&e.push(o),e.length&&(o=function(r){Ho.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},Ft.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],e.callback&&o.push(e.callback);var r;if(o.length&&(r=function(i){Ho.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Sn.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=Gh(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Gh(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},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);uS(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,o=e&&e.wantSubscribe===n;if(o){e.callback=dS([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;Ho.nextTick(function(){n._handleSubscribe()})}}};function uS(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function dS(n){return n=n.filter(Ho.truthy),n.length?function(t){Ho.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function hS(n){delete n.op,delete n.create,delete n.del}function Gh(n,t){if(n.del)return hS(t);if(t.del)return new qn(Sn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new qn(Sn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new qn(Sn.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 o=n.type.transform(n.op,t.op,"left"),r=n.type.transform(t.op,n.op,"right");n.op=o,t.op=r}}}Ft.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new qn(Sn.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===qh.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Gh(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.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 a=this.data;this._setType(null),this.emit("del",a,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 qn(Sn.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>=Ho.MAX_SAFE_INTEGER)return this.emit("error",new qn(Sn.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 o=new qn(Sn.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(i){return this._hardRollback(i)}var r=this;Ho.nextTick(function(){r.flush()})},Ft.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.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 o=this.pendingOps.splice(e),e=0;e<o.length;e++){var t=o[e],r=this._tryCompose(t);r?r.callbacks=r.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&&!cS(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 o={op:n},r=t&&t.source;this._submit(o,r,e)},Ft.prototype.create=function(n,t,e,o){if(typeof t=="function"?(o=t,e=null,t=null):typeof e=="function"&&(o=e,e=null),t||(t=qh.defaultType.uri),this.type){var r=new qn(Sn.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:t,data:n}},s=e&&e.source;this._submit(i,s,o)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new qn(Sn.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var o={del:!0},r=n&&n.source;this._submit(o,r,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:lS(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 sS.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 o=Gh(this.pendingOps[e],t);if(o)return this._hardRollback(o)}try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}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 o=!!t.length,r=0;r<t.length;r++)o=Ho.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=Ho.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var Hs={};Hs.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 yb=Ui,kb=Hs.ACTIONS,fS=$o,mS=Ln;function Ln(n,t,e,o,r,i,s){yb.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=o,this.query=r,this.results=null,i&&i.results&&(this.results=i.results,delete i.results),this.extra=void 0,this.options=i,this.callback=s,this.ready=!1,this.sent=!1}yb.mixin(Ln),Ln.prototype.hasPending=function(){return!this.ready},Ln.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 o=this.results[e];t.push([o.id,o.version])}n.r=t}this.connection.send(n),this.sent=!0}},Ln.prototype.destroy=function(n){this.connection.canSend&&this.action===kb.querySubscribe&&this.connection.send({a:kb.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&fS.nextTick(n)},Ln.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Ln.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Ln.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Ln.prototype._handleResponse=function(n,t,e){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!t)return this._finishResponse(null,o);var r=this,i=1,s=function(h){if(h)return r._finishResponse(h,o);--i||r._finishResponse(null,o)};if(Array.isArray(t))i+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){i++;var a=t[l],d=this.connection.get(a.c||this.collection,l);d.ingestSnapshot(a,s)}s()},Ln.prototype._ingestSnapshots=function(n,t){for(var e=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,t),e.push(i)}return e},Ln.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)},Ln.prototype._handleError=function(n){this.emit("error",n)},Ln.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 o=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(o)),this.emit("insert",o,e.index);break;case"remove":var i=e.howMany||1,r=this.results.splice(e.index,i);this.emit("remove",r,e.index);break;case"move":var i=e.howMany||1,s=this.results.splice(e.from,i);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)},Ln.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var wb=Ui,gS=Hs.ACTIONS,pS=$o,Bb=hr;function hr(n,t){if(wb.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={}}wb.mixin(hr),hr.prototype.submit=function(n,t){this.value=n,this.send(t)},hr.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},hr.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()})},hr.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},hr.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},hr.prototype._message=function(){return{a:gS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},hr.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},hr.prototype._callbackOrEmit=function(n,t){if(t)return pS.nextTick(t,n);n&&this.emit("error",n)};var CS=$o,Eb=cp;function cp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}cp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},cp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&CS.nextTick(n)};var ap={exports:{}};(function(n,t){(function(e,o){o(t)})(dr,function(e){function o(w,T){T=T|0;for(var M=Math.max(w.length-T,0),F=Array(M),U=0;U<M;U++)F[U]=w[T+U];return F}var r=function(w){var T=o(arguments,1);return function(){var M=o(arguments);return w.apply(null,T.concat(M))}},i=function(w){return function(){var T=o(arguments),M=T.pop();w.call(this,T,M)}};function s(w){var T=typeof w;return w!=null&&(T=="object"||T=="function")}var l=typeof setImmediate=="function"&&setImmediate,a=typeof process=="object"&&typeof process.nextTick=="function";function d(w){setTimeout(w,0)}function h(w){return function(T){var M=o(arguments,1);w(function(){T.apply(null,M)})}}var p;l?p=setImmediate:a?p=process.nextTick:p=d;var C=h(p);function v(w){return i(function(T,M){var F;try{F=w.apply(this,T)}catch(U){return M(U)}s(F)&&typeof F.then=="function"?F.then(function(U){B(M,null,U)},function(U){B(M,U.message?U:new Error(U))}):M(null,F)})}function B(w,T,M){try{w(T,M)}catch(F){C(D,F)}}function D(w){throw w}var x=typeof Symbol=="function";function _(w){return x&&w[Symbol.toStringTag]==="AsyncFunction"}function R(w){return _(w)?v(w):w}function H(w){return function(T){var M=o(arguments,1),F=i(function(U,j){var G=this;return w(T,function(J,lt){R(J).apply(G,U.concat(lt))},j)});return M.length?F.apply(this,M):F}}var z=typeof dr=="object"&&dr&&dr.Object===Object&&dr,Z=typeof self=="object"&&self&&self.Object===Object&&self,tt=z||Z||Function("return this")(),ft=tt.Symbol,vt=Object.prototype,zt=vt.hasOwnProperty,Ht=vt.toString,Xt=ft?ft.toStringTag:void 0;function qe(w){var T=zt.call(w,Xt),M=w[Xt];try{w[Xt]=void 0;var F=!0}catch{}var U=Ht.call(w);return F&&(T?w[Xt]=M:delete w[Xt]),U}var Yn=Object.prototype,He=Yn.toString;function Rn(w){return He.call(w)}var Er="[object Null]",kn="[object Undefined]",an=ft?ft.toStringTag:void 0;function xr(w){return w==null?w===void 0?kn:Er:an&&an in Object(w)?qe(w):Rn(w)}var ii="[object AsyncFunction]",Ao="[object Function]",eC="[object GeneratorFunction]",nC="[object Proxy]";function oC(w){if(!s(w))return!1;var T=xr(w);return T==Ao||T==eC||T==ii||T==nC}var ns=9007199254740991;function nl(w){return typeof w=="number"&&w>-1&&w%1==0&&w<=ns}function ol(w){return w!=null&&nl(w.length)&&!oC(w)}var si={};function Nt(){}function Ir(w){return function(){if(w!==null){var T=w;w=null,T.apply(this,arguments)}}}var os=typeof Symbol=="function"&&Symbol.iterator,Fc=function(w){return os&&w[os]&&w[os]()};function u1(w,T){for(var M=-1,F=Array(w);++M<w;)F[M]=T(M);return F}function un(w){return w!=null&&typeof w=="object"}var rl="[object Arguments]";function d1(w){return un(w)&&xr(w)==rl}var bo=Object.prototype,h1=bo.hasOwnProperty,rC=bo.propertyIsEnumerable,il=d1(function(){return arguments}())?d1:function(w){return un(w)&&h1.call(w,"callee")&&!rC.call(w,"callee")},Ae=Array.isArray;function sl(){return!1}var ll=typeof e=="object"&&e&&!e.nodeType&&e,f1=ll&&!0&&n&&!n.nodeType&&n,cl=f1&&f1.exports===ll,m1=cl?tt.Buffer:void 0,al=m1?m1.isBuffer:void 0,rs=al||sl,Wu=9007199254740991,qu=/^(?:0|[1-9]\d*)$/;function Gu(w,T){var M=typeof w;return T=T==null?Wu:T,!!T&&(M=="number"||M!="symbol"&&qu.test(w))&&w>-1&&w%1==0&&w<T}var Zu="[object Arguments]",Qu="[object Array]",Yu="[object Boolean]",Ju="[object Date]",Ku="[object Error]",Xu="[object Function]",iC="[object Map]",sC="[object Number]",lC="[object Object]",g1="[object RegExp]",p1="[object Set]",cC="[object String]",aC="[object WeakMap]",uC="[object ArrayBuffer]",dC="[object DataView]",C1="[object Float32Array]",hC="[object Float64Array]",fC="[object Int8Array]",mC="[object Int16Array]",td="[object Int32Array]",gC="[object Uint8Array]",ed="[object Uint8ClampedArray]",pC="[object Uint16Array]",CC="[object Uint32Array]",le={};le[C1]=le[hC]=le[fC]=le[mC]=le[td]=le[gC]=le[ed]=le[pC]=le[CC]=!0,le[Zu]=le[Qu]=le[uC]=le[Yu]=le[dC]=le[Ju]=le[Ku]=le[Xu]=le[iC]=le[sC]=le[lC]=le[g1]=le[p1]=le[cC]=le[aC]=!1;function AC(w){return un(w)&&nl(w.length)&&!!le[xr(w)]}function bC(w){return function(T){return w(T)}}var A1=typeof e=="object"&&e&&!e.nodeType&&e,ul=A1&&!0&&n&&!n.nodeType&&n,vC=ul&&ul.exports===A1,Pc=vC&&z.process,b1=function(){try{var w=ul&&ul.require&&ul.require("util").types;return w||Pc&&Pc.binding&&Pc.binding("util")}catch{}}(),v1=b1&&b1.isTypedArray,yC=v1?bC(v1):AC,kC=Object.prototype,wC=kC.hasOwnProperty;function BC(w,T){var M=Ae(w),F=!M&&il(w),U=!M&&!F&&rs(w),j=!M&&!F&&!U&&yC(w),G=M||F||U||j,J=G?u1(w.length,String):[],lt=J.length;for(var pt in w)(T||wC.call(w,pt))&&!(G&&(pt=="length"||U&&(pt=="offset"||pt=="parent")||j&&(pt=="buffer"||pt=="byteLength"||pt=="byteOffset")||Gu(pt,lt)))&&J.push(pt);return J}var Nc=Object.prototype;function EC(w){var T=w&&w.constructor,M=typeof T=="function"&&T.prototype||Nc;return w===M}function $c(w,T){return function(M){return w(T(M))}}var xC=$c(Object.keys,Object),IC=Object.prototype,TC=IC.hasOwnProperty;function y1(w){if(!EC(w))return xC(w);var T=[];for(var M in Object(w))TC.call(w,M)&&M!="constructor"&&T.push(M);return T}function Hc(w){return ol(w)?BC(w):y1(w)}function k1(w){var T=-1,M=w.length;return function(){return++T<M?{value:w[T],key:T}:null}}function DC(w){var T=-1;return function(){var F=w.next();return F.done?null:(T++,{value:F.value,key:T})}}function SC(w){var T=Hc(w),M=-1,F=T.length;return function U(){var j=T[++M];return j==="__proto__"?U():M<F?{value:w[j],key:j}:null}}function LC(w){if(ol(w))return k1(w);var T=Fc(w);return T?DC(T):SC(w)}function vo(w){return function(){if(w===null)throw new Error("Callback was already called.");var T=w;w=null,T.apply(this,arguments)}}function dl(w){return function(T,M,F){if(F=Ir(F||Nt),w<=0||!T)return F(null);var U=LC(T),j=!1,G=0,J=!1;function lt(at,At){if(G-=1,at)j=!0,F(at);else{if(At===si||j&&G<=0)return j=!0,F(null);J||pt()}}function pt(){for(J=!0;G<w&&!j;){var at=U();if(at===null){j=!0,G<=0&&F(null);return}G+=1,M(at.value,at.key,vo(lt))}J=!1}pt()}}function Tr(w,T,M,F){dl(T)(w,R(M),F)}function je(w,T){return function(M,F,U){return w(M,T,F,U)}}function nd(w,T,M){M=Ir(M||Nt);var F=0,U=0,j=w.length;j===0&&M(null);function G(J,lt){J?M(J):(++U===j||lt===si)&&M(null)}for(;F<j;F++)T(w[F],F,vo(G))}var MC=je(Tr,1/0),Zo=function(w,T,M){var F=ol(w)?nd:MC;F(w,R(T),M)};function Qo(w){return function(T,M,F){return w(Zo,T,R(M),F)}}function od(w,T,M,F){F=F||Nt,T=T||[];var U=[],j=0,G=R(M);w(T,function(J,lt,pt){var at=j++;G(J,function(At,Zt){U[at]=Zt,pt(At)})},function(J){F(J,U)})}var jc=Qo(od),rd=H(jc);function li(w){return function(T,M,F,U){return w(dl(M),T,R(F),U)}}var Dr=li(od),id=je(Dr,1),sd=H(id);function is(w,T){for(var M=-1,F=w==null?0:w.length;++M<F&&T(w[M],M,w)!==!1;);return w}function ld(w){return function(T,M,F){for(var U=-1,j=Object(T),G=F(T),J=G.length;J--;){var lt=G[w?J:++U];if(M(j[lt],lt,j)===!1)break}return T}}var ss=ld();function ls(w,T){return w&&ss(w,T,Hc)}function w1(w,T,M,F){for(var U=w.length,j=M+(F?1:-1);F?j--:++j<U;)if(T(w[j],j,w))return j;return-1}function RC(w){return w!==w}function B1(w,T,M){for(var F=M-1,U=w.length;++F<U;)if(w[F]===T)return F;return-1}function hl(w,T,M){return T===T?B1(w,T,M):w1(w,RC,M)}var Uc=function(w,T,M){typeof T=="function"&&(M=T,T=null),M=Ir(M||Nt);var F=Hc(w),U=F.length;if(!U)return M(null);T||(T=U);var j={},G=0,J=!1,lt=Object.create(null),pt=[],at=[],At={};ls(w,function(he,re){if(!Ae(he)){Zt(re,[he]),at.push(re);return}var pe=he.slice(0,he.length-1),ko=pe.length;if(ko===0){Zt(re,he),at.push(re);return}At[re]=ko,is(pe,function(E){if(!w[E])throw new Error("async.auto task `"+re+"` has a non-existent dependency `"+E+"` in "+pe.join(", "));en(E,function(){ko--,ko===0&&Zt(re,he)})})}),e3(),De();function Zt(he,re){pt.push(function(){yo(he,re)})}function De(){if(pt.length===0&&G===0)return M(null,j);for(;pt.length&&G<T;){var he=pt.shift();he()}}function en(he,re){var pe=lt[he];pe||(pe=lt[he]=[]),pe.push(re)}function Fn(he){var re=lt[he]||[];is(re,function(pe){pe()}),De()}function yo(he,re){if(!J){var pe=vo(function(E,Mr){if(G--,arguments.length>2&&(Mr=o(arguments,1)),E){var ds={};ls(j,function(Pn,Pt){ds[Pt]=Pn}),ds[he]=Mr,J=!0,lt=Object.create(null),M(E,ds)}else j[he]=Mr,Fn(he)});G++;var ko=R(re[re.length-1]);re.length>1?ko(j,pe):ko(pe)}}function e3(){for(var he,re=0;at.length;)he=at.pop(),re++,is(n3(he),function(pe){--At[pe]===0&&at.push(pe)});if(re!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function n3(he){var re=[];return ls(w,function(pe,ko){Ae(pe)&&hl(pe,he,0)>=0&&re.push(ko)}),re}};function ci(w,T){for(var M=-1,F=w==null?0:w.length,U=Array(F);++M<F;)U[M]=T(w[M],M,w);return U}var OC="[object Symbol]";function _C(w){return typeof w=="symbol"||un(w)&&xr(w)==OC}var FC=1/0,cd=ft?ft.prototype:void 0,E1=cd?cd.toString:void 0;function ad(w){if(typeof w=="string")return w;if(Ae(w))return ci(w,ad)+"";if(_C(w))return E1?E1.call(w):"";var T=w+"";return T=="0"&&1/w==-FC?"-0":T}function PC(w,T,M){var F=-1,U=w.length;T<0&&(T=-T>U?0:U+T),M=M>U?U:M,M<0&&(M+=U),U=T>M?0:M-T>>>0,T>>>=0;for(var j=Array(U);++F<U;)j[F]=w[F+T];return j}function NC(w,T,M){var F=w.length;return M=M===void 0?F:M,!T&&M>=F?w:PC(w,T,M)}function ud(w,T){for(var M=w.length;M--&&hl(T,w[M],0)>-1;);return M}function $C(w,T){for(var M=-1,F=w.length;++M<F&&hl(T,w[M],0)>-1;);return M}function HC(w){return w.split("")}var jC="\\ud800-\\udfff",UC="\\u0300-\\u036f",zC="\\ufe20-\\ufe2f",ce="\\u20d0-\\u20ff",oe=UC+zC+ce,VC="\\ufe0e\\ufe0f",WC="\\u200d",qC=RegExp("["+WC+jC+oe+VC+"]");function GC(w){return qC.test(w)}var x1="\\ud800-\\udfff",ZC="\\u0300-\\u036f",I1="\\ufe20-\\ufe2f",QC="\\u20d0-\\u20ff",Ge=ZC+I1+QC,dd="\\ufe0e\\ufe0f",ai="["+x1+"]",zc="["+Ge+"]",fl="\\ud83c[\\udffb-\\udfff]",On="(?:"+zc+"|"+fl+")",hd="[^"+x1+"]",fd="(?:\\ud83c[\\udde6-\\uddff]){2}",md="[\\ud800-\\udbff][\\udc00-\\udfff]",T1="\\u200d",gd=On+"?",pd="["+dd+"]?",wn="(?:"+T1+"(?:"+[hd,fd,md].join("|")+")"+pd+gd+")*",YC=pd+gd+wn,_n="(?:"+[hd+zc+"?",zc,fd,md,ai].join("|")+")",JC=RegExp(fl+"(?="+fl+")|"+_n+YC,"g");function D1(w){return w.match(JC)||[]}function Yo(w){return GC(w)?D1(w):HC(w)}function Vc(w){return w==null?"":ad(w)}var Cd=/^\s+|\s+$/g;function de(w,T,M){if(w=Vc(w),w&&(M||T===void 0))return w.replace(Cd,"");if(!w||!(T=ad(T)))return w;var F=Yo(w),U=Yo(T),j=$C(F,U),G=ud(F,U)+1;return NC(F,j,G).join("")}var Sr=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,Ad=/,/,KC=/(=.+)?(\s*)$/,bd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function XC(w){return w=w.toString().replace(bd,""),w=w.match(Sr)[2].replace(" ",""),w=w?w.split(Ad):[],w=w.map(function(T){return de(T.replace(KC,""))}),w}function S1(w,T){var M={};ls(w,function(F,U){var j,G=_(F),J=!G&&F.length===1||G&&F.length===0;if(Ae(F))j=F.slice(0,-1),F=F[F.length-1],M[U]=j.concat(j.length>0?lt:F);else if(J)M[U]=F;else{if(j=XC(F),F.length===0&&!G&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");G||j.pop(),M[U]=j.concat(lt)}function lt(pt,at){var At=ci(j,function(Zt){return pt[Zt]});At.push(at),R(F).apply(null,At)}}),Uc(M,T)}function Jn(){this.head=this.tail=null,this.length=0}function vd(w,T){w.length=1,w.head=w.tail=T}Jn.prototype.removeLink=function(w){return w.prev?w.prev.next=w.next:this.head=w.next,w.next?w.next.prev=w.prev:this.tail=w.prev,w.prev=w.next=null,this.length-=1,w},Jn.prototype.empty=function(){for(;this.head;)this.shift();return this},Jn.prototype.insertAfter=function(w,T){T.prev=w,T.next=w.next,w.next?w.next.prev=T:this.tail=T,w.next=T,this.length+=1},Jn.prototype.insertBefore=function(w,T){T.prev=w.prev,T.next=w,w.prev?w.prev.next=T:this.head=T,w.prev=T,this.length+=1},Jn.prototype.unshift=function(w){this.head?this.insertBefore(this.head,w):vd(this,w)},Jn.prototype.push=function(w){this.tail?this.insertAfter(this.tail,w):vd(this,w)},Jn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},Jn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},Jn.prototype.toArray=function(){for(var w=Array(this.length),T=this.head,M=0;M<this.length;M++)w[M]=T.data,T=T.next;return w},Jn.prototype.remove=function(w){for(var T=this.head;T;){var M=T.next;w(T)&&this.removeLink(T),T=M}return this};function ml(w,T,M){if(T==null)T=1;else if(T===0)throw new Error("Concurrency must not be zero");var F=R(w),U=0,j=[],G=!1;function J(At,Zt,De){if(De!=null&&typeof De!="function")throw new Error("task callback must be a function");if(at.started=!0,Ae(At)||(At=[At]),At.length===0&&at.idle())return C(function(){at.drain()});for(var en=0,Fn=At.length;en<Fn;en++){var yo={data:At[en],callback:De||Nt};Zt?at._tasks.unshift(yo):at._tasks.push(yo)}G||(G=!0,C(function(){G=!1,at.process()}))}function lt(At){return function(Zt){U-=1;for(var De=0,en=At.length;De<en;De++){var Fn=At[De],yo=hl(j,Fn,0);yo===0?j.shift():yo>0&&j.splice(yo,1),Fn.callback.apply(Fn,arguments),Zt!=null&&at.error(Zt,Fn.data)}U<=at.concurrency-at.buffer&&at.unsaturated(),at.idle()&&at.drain(),at.process()}}var pt=!1,at={_tasks:new Jn,concurrency:T,payload:M,saturated:Nt,unsaturated:Nt,buffer:T/4,empty:Nt,drain:Nt,error:Nt,started:!1,paused:!1,push:function(At,Zt){J(At,!1,Zt)},kill:function(){at.drain=Nt,at._tasks.empty()},unshift:function(At,Zt){J(At,!0,Zt)},remove:function(At){at._tasks.remove(At)},process:function(){if(!pt){for(pt=!0;!at.paused&&U<at.concurrency&&at._tasks.length;){var At=[],Zt=[],De=at._tasks.length;at.payload&&(De=Math.min(De,at.payload));for(var en=0;en<De;en++){var Fn=at._tasks.shift();At.push(Fn),j.push(Fn),Zt.push(Fn.data)}U+=1,at._tasks.length===0&&at.empty(),U===at.concurrency&&at.saturated();var yo=vo(lt(At));F(Zt,yo)}pt=!1}},length:function(){return at._tasks.length},running:function(){return U},workersList:function(){return j},idle:function(){return at._tasks.length+U===0},pause:function(){at.paused=!0},resume:function(){at.paused!==!1&&(at.paused=!1,C(at.process))}};return at}function ui(w,T){return ml(w,1,T)}var cs=je(Tr,1);function Jo(w,T,M,F){F=Ir(F||Nt);var U=R(M);cs(w,function(j,G,J){U(T,j,function(lt,pt){T=pt,J(lt)})},function(j){F(j,T)})}function Wc(){var w=ci(arguments,R);return function(){var T=o(arguments),M=this,F=T[T.length-1];typeof F=="function"?T.pop():F=Nt,Jo(w,T,function(U,j,G){j.apply(M,U.concat(function(J){var lt=o(arguments,1);G(J,lt)}))},function(U,j){F.apply(M,[U].concat(j))})}}var qc=function(){return Wc.apply(null,o(arguments).reverse())},yd=Array.prototype.concat,gl=function(w,T,M,F){F=F||Nt;var U=R(M);Dr(w,T,function(j,G){U(j,function(J){return J?G(J):G(null,o(arguments,1))})},function(j,G){for(var J=[],lt=0;lt<G.length;lt++)G[lt]&&(J=yd.apply(J,G[lt]));return F(j,J)})},L1=je(gl,1/0),Gc=je(gl,1),Zc=function(){var w=o(arguments),T=[null].concat(w);return function(){var M=arguments[arguments.length-1];return M.apply(this,T)}};function pl(w){return w}function di(w,T){return function(M,F,U,j){j=j||Nt;var G=!1,J;M(F,function(lt,pt,at){U(lt,function(At,Zt){At?at(At):w(Zt)&&!J?(G=!0,J=T(!0,lt),at(null,si)):at()})},function(lt){lt?j(lt):j(null,G?J:T(!1))})}}function dn(w,T){return T}var as=Qo(di(pl,dn)),Ko=li(di(pl,dn)),Cl=je(Ko,1);function kd(w){return function(T){var M=o(arguments,1);M.push(function(F){var U=o(arguments,1);typeof console=="object"&&(F?console.error&&console.error(F):console[w]&&is(U,function(j){console[w](j)}))}),R(T).apply(null,M)}}var M1=kd("dir");function R1(w,T,M){M=vo(M||Nt);var F=R(w),U=R(T);function j(J){if(J)return M(J);var lt=o(arguments,1);lt.push(G),U.apply(this,lt)}function G(J,lt){if(J)return M(J);if(!lt)return M(null);F(j)}G(null,!0)}function wd(w,T,M){M=vo(M||Nt);var F=R(w),U=function(j){if(j)return M(j);var G=o(arguments,1);if(T.apply(this,G))return F(U);M.apply(null,[null].concat(G))};F(U)}function O1(w,T,M){wd(w,function(){return!T.apply(this,arguments)},M)}function _1(w,T,M){M=vo(M||Nt);var F=R(T),U=R(w);function j(J){if(J)return M(J);U(G)}function G(J,lt){if(J)return M(J);if(!lt)return M(null);F(j)}U(G)}function hi(w){return function(T,M,F){return w(T,F)}}function Qc(w,T,M){Zo(w,hi(R(T)),M)}function Al(w,T,M,F){dl(T)(w,hi(R(M)),F)}var fi=je(Al,1);function Yc(w){return _(w)?w:i(function(T,M){var F=!0;T.push(function(){var U=arguments;F?C(function(){M.apply(null,U)}):M.apply(null,U)}),w.apply(this,T),F=!1})}function Kn(w){return!w}var mi=Qo(di(Kn,Kn)),bl=li(di(Kn,Kn)),Jc=je(bl,1);function F1(w){return function(T){return T==null?void 0:T[w]}}function us(w,T,M,F){var U=new Array(T.length);w(T,function(j,G,J){M(j,function(lt,pt){U[G]=!!pt,J(lt)})},function(j){if(j)return F(j);for(var G=[],J=0;J<T.length;J++)U[J]&&G.push(T[J]);F(null,G)})}function Xn(w,T,M,F){var U=[];w(T,function(j,G,J){M(j,function(lt,pt){lt?J(lt):(pt&&U.push({index:G,value:j}),J())})},function(j){j?F(j):F(null,ci(U.sort(function(G,J){return G.index-J.index}),F1("value")))})}function Kc(w,T,M,F){var U=ol(T)?us:Xn;U(w,T,R(M),F||Nt)}var Xc=Qo(Kc),vl=li(Kc),ta=je(vl,1);function P1(w,T){var M=vo(T||Nt),F=R(Yc(w));function U(j){if(j)return M(j);F(U)}U()}var ea=function(w,T,M,F){F=F||Nt;var U=R(M);Dr(w,T,function(j,G){U(j,function(J,lt){return J?G(J):G(null,{key:lt,val:j})})},function(j,G){for(var J={},lt=Object.prototype.hasOwnProperty,pt=0;pt<G.length;pt++)if(G[pt]){var at=G[pt].key,At=G[pt].val;lt.call(J,at)?J[at].push(At):J[at]=[At]}return F(j,J)})},gi=je(ea,1/0),N=je(ea,1),q=kd("log");function V(w,T,M,F){F=Ir(F||Nt);var U={},j=R(M);Tr(w,T,function(G,J,lt){j(G,J,function(pt,at){if(pt)return lt(pt);U[J]=at,lt()})},function(G){F(G,U)})}var ht=je(V,1/0),Et=je(V,1);function Vt(w,T){return T in w}function Be(w,T){var M=Object.create(null),F=Object.create(null);T=T||pl;var U=R(w),j=i(function(J,lt){var pt=T.apply(null,J);Vt(M,pt)?C(function(){lt.apply(null,M[pt])}):Vt(F,pt)?F[pt].push(lt):(F[pt]=[lt],U.apply(null,J.concat(function(){var at=o(arguments);M[pt]=at;var At=F[pt];delete F[pt];for(var Zt=0,De=At.length;Zt<De;Zt++)At[Zt].apply(null,at)})))});return j.memo=M,j.unmemoized=w,j}var qt;a?qt=process.nextTick:l?qt=setImmediate:qt=d;var na=h(qt);function Bd(w,T,M){M=M||Nt;var F=ol(T)?[]:{};w(T,function(U,j,G){R(U)(function(J,lt){arguments.length>2&&(lt=o(arguments,1)),F[j]=lt,G(J)})},function(U){M(U,F)})}function Bn(w,T){Bd(Zo,w,T)}function yl(w,T,M){Bd(dl(T),w,M)}var Ed=function(w,T){var M=R(w);return ml(function(F,U){M(F[0],U)},T,1)},pi=function(w,T){var M=Ed(w,T);return M.push=function(F,U,j){if(j==null&&(j=Nt),typeof j!="function")throw new Error("task callback must be a function");if(M.started=!0,Ae(F)||(F=[F]),F.length===0)return C(function(){M.drain()});U=U||0;for(var G=M._tasks.head;G&&U>=G.priority;)G=G.next;for(var J=0,lt=F.length;J<lt;J++){var pt={data:F[J],priority:U,callback:j};G?M._tasks.insertBefore(G,pt):M._tasks.push(pt)}C(M.process)},delete M.unshift,M};function kl(w,T){if(T=Ir(T||Nt),!Ae(w))return T(new TypeError("First argument to race must be an array of functions"));if(!w.length)return T();for(var M=0,F=w.length;M<F;M++)R(w[M])(T)}function Ci(w,T,M,F){var U=o(w).reverse();Jo(U,T,M,F)}function Wt(w){var T=R(w);return i(function(F,U){return F.push(function(G,J){if(G)U(null,{error:G});else{var lt;arguments.length<=2?lt=J:lt=o(arguments,1),U(null,{value:lt})}}),T.apply(this,F)})}function N1(w){var T;return Ae(w)?T=ci(w,Wt):(T={},ls(w,function(M,F){T[F]=Wt.call(this,M)})),T}function xd(w,T,M,F){Kc(w,T,function(U,j){M(U,function(G,J){j(G,!J)})},F)}var wl=Qo(xd),Id=li(xd),$1=je(Id,1);function H1(w){return function(){return w}}function Ai(w,T,M){var F=5,U=0,j={times:F,intervalFunc:H1(U)};function G(at,At){if(typeof At=="object")at.times=+At.times||F,at.intervalFunc=typeof At.interval=="function"?At.interval:H1(+At.interval||U),at.errorFilter=At.errorFilter;else if(typeof At=="number"||typeof At=="string")at.times=+At||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof w=="function"?(M=T||Nt,T=w):(G(j,w),M=M||Nt),typeof T!="function")throw new Error("Invalid arguments for async.retry");var J=R(T),lt=1;function pt(){J(function(at){at&&lt++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(at))?setTimeout(pt,j.intervalFunc(lt)):M.apply(null,arguments)})}pt()}var Xo=function(w,T){T||(T=w,w=null);var M=R(T);return i(function(F,U){function j(G){M.apply(null,F.concat(G))}w?Ai(w,j,U):Ai(j,U)})};function Bl(w,T){Bd(cs,w,T)}var El=Qo(di(Boolean,pl)),Lr=li(di(Boolean,pl)),xl=je(Lr,1);function Td(w,T,M){var F=R(T);jc(w,function(j,G){F(j,function(J,lt){if(J)return G(J);G(null,{value:j,criteria:lt})})},function(j,G){if(j)return M(j);M(null,ci(G.sort(U),F1("value")))});function U(j,G){var J=j.criteria,lt=G.criteria;return J<lt?-1:J>lt?1:0}}function Il(w,T,M){var F=R(w);return i(function(U,j){var G=!1,J;function lt(){var pt=w.name||"anonymous",at=new Error('Callback function "'+pt+'" timed out.');at.code="ETIMEDOUT",M&&(at.info=M),G=!0,j(at)}U.push(function(){G||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(lt,T),F.apply(null,U)})}var j1=Math.ceil,Tl=Math.max;function bi(w,T,M,F){for(var U=-1,j=Tl(j1((T-w)/(M||1)),0),G=Array(j);j--;)G[F?j:++U]=w,w+=M;return G}function vi(w,T,M,F){var U=R(M);Dr(bi(0,w,1),T,U,F)}var U1=je(vi,1/0),z1=je(vi,1);function V1(w,T,M,F){arguments.length<=3&&(F=M,M=T,T=Ae(w)?[]:{}),F=Ir(F||Nt);var U=R(M);Zo(w,function(j,G,J){U(T,j,G,J)},function(j){F(j,T)})}function Dl(w,T){var M=null,F;T=T||Nt,fi(w,function(U,j){R(U)(function(G,J){arguments.length>2?F=o(arguments,1):F=J,M=G,j(!G)})},function(){T(M,F)})}function Sl(w){return function(){return(w.unmemoized||w).apply(null,arguments)}}function Ll(w,T,M){M=vo(M||Nt);var F=R(T);if(!w())return M(null);var U=function(j){if(j)return M(j);if(w())return F(U);var G=o(arguments,1);M.apply(null,[null].concat(G))};F(U)}function W1(w,T,M){Ll(function(){return!w.apply(this,arguments)},T,M)}var Dd=function(w,T){if(T=Ir(T||Nt),!Ae(w))return T(new Error("First argument to waterfall must be an array of functions"));if(!w.length)return T();var M=0;function F(j){var G=R(w[M++]);j.push(vo(U)),G.apply(null,j)}function U(j){if(j||M===w.length)return T.apply(null,arguments);F(o(arguments,1))}F([])},t3={apply:r,applyEach:rd,applyEachSeries:sd,asyncify:v,auto:Uc,autoInject:S1,cargo:ui,compose:qc,concat:L1,concatLimit:gl,concatSeries:Gc,constant:Zc,detect:as,detectLimit:Ko,detectSeries:Cl,dir:M1,doDuring:R1,doUntil:O1,doWhilst:wd,during:_1,each:Qc,eachLimit:Al,eachOf:Zo,eachOfLimit:Tr,eachOfSeries:cs,eachSeries:fi,ensureAsync:Yc,every:mi,everyLimit:bl,everySeries:Jc,filter:Xc,filterLimit:vl,filterSeries:ta,forever:P1,groupBy:gi,groupByLimit:ea,groupBySeries:N,log:q,map:jc,mapLimit:Dr,mapSeries:id,mapValues:ht,mapValuesLimit:V,mapValuesSeries:Et,memoize:Be,nextTick:na,parallel:Bn,parallelLimit:yl,priorityQueue:pi,queue:Ed,race:kl,reduce:Jo,reduceRight:Ci,reflect:Wt,reflectAll:N1,reject:wl,rejectLimit:Id,rejectSeries:$1,retry:Ai,retryable:Xo,seq:Wc,series:Bl,setImmediate:C,some:El,someLimit:Lr,someSeries:xl,sortBy:Td,timeout:Il,times:U1,timesLimit:vi,timesSeries:z1,transform:V1,tryEach:Dl,unmemoize:Sl,until:W1,waterfall:Dd,whilst:Ll,all:mi,allLimit:bl,allSeries:Jc,any:El,anyLimit:Lr,anySeries:xl,find:as,findLimit:Ko,findSeries:Cl,forEach:Qc,forEachSeries:fi,forEachLimit:Al,forEachOf:Zo,forEachOfSeries:cs,forEachOfLimit:Tr,inject:Jo,foldl:Jo,foldr:Ci,select:Xc,selectLimit:vl,selectSeries:ta,wrapSync:v};e.default=t3,e.apply=r,e.applyEach=rd,e.applyEachSeries=sd,e.asyncify=v,e.auto=Uc,e.autoInject=S1,e.cargo=ui,e.compose=qc,e.concat=L1,e.concatLimit=gl,e.concatSeries=Gc,e.constant=Zc,e.detect=as,e.detectLimit=Ko,e.detectSeries=Cl,e.dir=M1,e.doDuring=R1,e.doUntil=O1,e.doWhilst=wd,e.during=_1,e.each=Qc,e.eachLimit=Al,e.eachOf=Zo,e.eachOfLimit=Tr,e.eachOfSeries=cs,e.eachSeries=fi,e.ensureAsync=Yc,e.every=mi,e.everyLimit=bl,e.everySeries=Jc,e.filter=Xc,e.filterLimit=vl,e.filterSeries=ta,e.forever=P1,e.groupBy=gi,e.groupByLimit=ea,e.groupBySeries=N,e.log=q,e.map=jc,e.mapLimit=Dr,e.mapSeries=id,e.mapValues=ht,e.mapValuesLimit=V,e.mapValuesSeries=Et,e.memoize=Be,e.nextTick=na,e.parallel=Bn,e.parallelLimit=yl,e.priorityQueue=pi,e.queue=Ed,e.race=kl,e.reduce=Jo,e.reduceRight=Ci,e.reflect=Wt,e.reflectAll=N1,e.reject=wl,e.rejectLimit=Id,e.rejectSeries=$1,e.retry=Ai,e.retryable=Xo,e.seq=Wc,e.series=Bl,e.setImmediate=C,e.some=El,e.someLimit=Lr,e.someSeries=xl,e.sortBy=Td,e.timeout=Il,e.times=U1,e.timesLimit=vi,e.timesSeries=z1,e.transform=V1,e.tryEach=Dl,e.unmemoize=Sl,e.until=W1,e.waterfall=Dd,e.whilst=Ll,e.all=mi,e.allLimit=bl,e.allSeries=Jc,e.any=El,e.anyLimit=Lr,e.anySeries=xl,e.find=as,e.findLimit=Ko,e.findSeries=Cl,e.forEach=Qc,e.forEachSeries=fi,e.forEachLimit=Al,e.forEachOf=Zo,e.forEachOfSeries=cs,e.forEachOfLimit=Tr,e.inject=Jo,e.foldl=Jo,e.foldr=Ci,e.select=Xc,e.selectLimit=vl,e.selectSeries=ta,e.wrapSync=v,Object.defineProperty(e,"__esModule",{value:!0})})})(ap,ap.exports);var xb={exports:{}},up=xb.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),o=2;e===1/0;o*=2)e=Math.log(Math.pow(2,n/o))/Math.log(t)*o;for(var r=e-Math.floor(e),i="",o=0;o<Math.floor(e);o++){var s=Math.floor(Math.random()*t).toString(t);i=s+i}if(r){var l=Math.pow(t,r),s=Math.floor(Math.random()*l).toString(t);i=s+i}var a=parseInt(i,t);return a!==1/0&&a>=Math.pow(2,n)?up(n,t):i};up.rack=function(n,t,e){var o=function(i){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=up(n,t)}while(Object.hasOwnProperty.call(r,l));return r[l]=i,l},r=o.hats={};return o.get=function(i){return o.hats[i]},o.set=function(i,s){return o.hats[i]=s,o},o.bits=n||128,o.base=t||16,o};var Ib=Ui,AS=Bb,bS=Eb,Zh=$o,dp=ap.exports,vS=xb.exports,Tb=Hs.ACTIONS,Db=Re;function Re(n,t){if(Ib.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}Ib.mixin(Re),Re.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Re.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Re.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||vS();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Re.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(o){if(o)return t._callbackOrEmit(o,n);var r=Object.keys(t._remotePresenceInstances);dp.parallel([function(i){dp.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();dp.each(r,function(s,l){t._remotePresenceInstances[s].destroy(l)},i)}],function(i){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(i,n)})})},Re.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?Tb.presenceSubscribe:Tb.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Re.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Re.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Re.prototype._receiveUpdate=function(n,t){var e=Zh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=Zh.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Re.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Re.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()}},Re.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Re.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Re.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 o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},Re.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Re.prototype._callbackOrEmit=function(n,t){if(t)return Zh.nextTick(t,n);n&&this.emit("error",n)},Re.prototype._createLocalPresence=function(n){return new AS(this,n)},Re.prototype._createRemotePresence=function(n){return new bS(this,n)},Re.prototype._callEachOrEmit=function(n,t){var e=Zh.callEach(n,t);!e&&t&&this.emit("error",t)};var Za=Bb,Sb=zh,yS=$o,Lb=Sb.CODES,kS=jo;function jo(n,t){Za.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()}jo.prototype=Object.create(Za.prototype),jo.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:Lb.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,Za.prototype.submit.call(this,n,t)},jo.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),Za.prototype.destroy.call(this,n)},jo.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={})})}},jo.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)},jo.prototype._transformAgainstOp=function(n,t){var e=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=e._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=e._transformPresence(r.p,n,t),e._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=e._getCallback(r.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(r){this.emit("error",r)}},jo.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},jo.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},jo.prototype._message=function(){var n=Za.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},jo.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!yS.supportsPresence(o))throw new Sb(Lb.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var Mb={};(function(n){var t=Wa,e=zh,o=$o,r=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var a=l.create.type;if(typeof a!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[a];if(d==null||typeof d!="object")return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(r.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(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(r.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,a){if(typeof l!="object")return new e(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&a.v!=null&&l.v!==a.v)return new e(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(a.create){if(l.type)return new e(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=a.create,h=t.map[d.type];if(!h)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(C){return C}}else if(a.del)l.data=void 0,l.type=null,l.v++;else if("op"in a){var p=i(l,a.op);if(p)return p;l.v++}else l.v++};function i(l,a){if(!l.type)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(a===void 0)return new e(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,a)}catch(h){return new e(r.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,a,d){if(a.v!=null&&a.v!==d.v)return new e(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(a.create||"op"in a)return new e(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in a||a.create||a.del)||"op"in d&&a.create)return new e(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in a){if(!l)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{a.op=l.transform(a.op,d.op,"left")}catch(h){return h}}}a.v!=null&&a.v++},n.applyOps=function(l,a,d){d=d||{};for(var h=0;h<a.length;h++){var p=a[h];if(d._normalizeLegacyJson0Ops)try{s(l,p)}catch{return new e(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=p.v;var C=n.apply(l,p);if(C)return C}},n.transformPresence=function(l,a,d){var h=this.checkOp(a);if(h)return h;var p=l.t;if(typeof p=="string"&&(p=t.map[p]),!p)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(p))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(a.create||a.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:p.transformPresence(l.p,a.op,d)}catch(C){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:C.message||C}}l.v++};function s(l,a){if(l.type===t.defaultType.uri){var d=a.op;if(!!d){var h=l.data;d.length>1&&(h=o.clone(h));for(var p=0;p<d.length;p++){var C=d[p];typeof C.lm=="string"&&(C.lm=+C.lm);for(var v=C.p,B=h,D=0;D<v.length;D++){var x=v[D];Object.prototype.toString.call(B)=="[object Array]"?v[D]=+x:B.constructor===Object&&(v[D]=x.toString()),B=B[x]}p<d.length-1&&(h=t.defaultType.apply(h,[C]))}}}}})(Mb);var Qa=Eb,wS=Mb,BS=ho;function ho(n,t){Qa.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()}ho.prototype=Object.create(Qa.prototype),ho.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},ho.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),Qa.prototype.destroy.call(this,n)},ho.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)},ho.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))}})}},ho.prototype._handleOp=function(n,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},Qa.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Qa.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},ho.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)}},ho.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++):wS.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},ho.prototype._startCachingOps=function(){this._opCache=[]},ho.prototype._stopCachingOps=function(){this._opCache=null},ho.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var Rb=Db,ES=kS,xS=BS;function Xl(n,t,e){var o=Xl.channel(t,e);Rb.call(this,n,o),this.collection=t,this.id=e}var IS=Xl;Xl.prototype=Object.create(Rb.prototype),Xl.channel=function(n,t){return n+"."+t},Xl.prototype._createLocalPresence=function(n){return new ES(this,n)},Xl.prototype._createRemotePresence=function(n){return new xS(this,n)};var TS=DS;function DS(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var SS=TS,Ob=Ui,_b=Ya;function Ya(n,t,e,o,r){if(Ob.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=o,this.collection=e,this.callback=r,this.sent=!1}Ob.mixin(Ya),Ya.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Ya.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Ya.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new SS(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var Fb=_b,LS=$o,MS=Hs.ACTIONS,RS=hp;function hp(n,t,e,o,r,i){if(Fb.call(this,n,t,e,o,i),!LS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}hp.prototype=Object.create(Fb.prototype),hp.prototype._message=function(){return{a:MS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var Pb=_b,OS=$o,_S=Hs.ACTIONS,FS=fp;function fp(n,t,e,o,r,i){if(Pb.call(this,n,t,e,o,i),!OS.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}fp.prototype=Object.create(Pb.prototype),fp.prototype._message=function(){return{a:_S.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var PS=aS,NS=mS,$S=Db,Nb=IS,HS=RS,jS=FS,$b=Ui,tc=zh,ne=Hs.ACTIONS,Hb=Wa,Uo=$o,Ja=gb,Ka=tc.CODES;function jb(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var US=Bt;function Bt(n){$b.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=jb(n),this.bindToSocket(n)}$b.mixin(Bt),Bt.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=jb(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Ja.warn("Failed to parse message",o);return}e.debug&&Ja.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){Uo.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(o){e.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?e._setState("closed",o):o==="stopped"||o==="Stopped by server"?e._setState("stopped",o):e._setState("disconnected",o)}},Bt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=Ub(n.error,n),delete n.error),n.a){case ne.initLegacy:return this._handleLegacyInit(n);case ne.handshake:return this._handleHandshake(t,n);case ne.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case ne.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case ne.queryUnsubscribe:return;case ne.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 ne.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case ne.bulkSubscribe:case ne.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case ne.snapshotFetch:case ne.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case ne.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case ne.subscribe:case ne.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case ne.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case ne.presence:return this._handlePresence(t,n);case ne.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case ne.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case ne.presenceRequest:return this._handlePresenceRequest(t,n);case ne.pingPong:return this._handlePingPong(t);default:Ja.warn("Ignoring unrecognized message",n)}};function Ub(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}Bt.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var o in t.data){var r=t.data[o],i=this.getExisting(t.c,o);i&&(n?i[e](n):r.error?i[e](Ub(r.error)):i[e](null,r))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var o=t.b[s],i=this.getExisting(t.c,o);i&&i[e](n)}else if(t.b)for(var o in t.b){var i=this.getExisting(t.c,o);i&&i[e](n)}else Ja.error("Invalid bulk message",t)},Bt.prototype._reset=function(){this.agent=null},Bt.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 tc(Ka.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 o in this.queries){var r=this.queries[o];r._onConnectionStateChanged()}for(var i in this.collections){var s=this.collections[i];for(var o in s)s[o]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var o in this._snapshotRequests){var a=this._snapshotRequests[o];a._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},Bt.prototype.startBulk=function(){this.bulk||(this.bulk={})},Bt.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},Bt.prototype._sendBulk=function(n,t,e){if(!!e){var o=[],r={},i=0,s;for(var l in e){var a=e[l];a==null?o.push(l):(r[l]=a,s=l,i++)}if(o.length===1){var l=o[0];this.send({a:n,c:t,d:l})}else o.length&&this.send({a:"b"+n,c:t,b:o});if(i===1){var d=r[s];this.send({a:n,c:t,d:s,v:d})}else i&&this.send({a:"b"+n,c:t,b:r})}},Bt.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var o=this.bulk[t.collection]||(this.bulk[t.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(t.id);return r[t.id]=e,i}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},Bt.prototype.sendFetch=function(n){return this._sendActions(ne.fetch,n,n.version)},Bt.prototype.sendSubscribe=function(n){return this._sendActions(ne.subscribe,n,n.version)},Bt.prototype.sendUnsubscribe=function(n){return this._sendActions(ne.unsubscribe,n)},Bt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:ne.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)},Bt.prototype.send=function(n){this.debug&&Ja.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},Bt.prototype.ping=function(){if(!this.canSend)throw new tc(Ka.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:ne.pingPong};this.send(n)},Bt.prototype.close=function(){this.socket.close()},Bt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},Bt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new PS(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},Bt.prototype._destroyDoc=function(n){!n._wantsDestroy||(Uo.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},Bt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},Bt.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new NS(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},Bt.prototype._destroyQuery=function(n){delete this.queries[n.id]},Bt.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(ne.queryFetch,n,t,e,o)},Bt.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(ne.querySubscribe,n,t,e,o)},Bt.prototype.hasPending=function(){return!!(this._firstDoc(Qh)||this._firstQuery(Qh)||this._firstSnapshotRequest())};function Qh(n){return n.hasPending()}Bt.prototype.hasWritePending=function(){return!!this._firstDoc(zS)};function zS(n){return n.hasWritePending()}Bt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Qh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Qh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}Uo.nextTick(n)},Bt.prototype._nothingPendingRetry=function(n){var t=this;return function(){Uo.nextTick(function(){t.whenNothingPending(n)})}},Bt.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var o in e){var r=e[o];if(n(r))return r}}},Bt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},Bt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},Bt.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new HS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},Bt.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new jS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},Bt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},Bt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},Bt.prototype._initializeHandshake=function(){this.send({a:ne.handshake,id:this.id})},Bt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},Bt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},Bt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new tc(Ka.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(Hb.map[n.type]!==Hb.defaultType)return this.emit("error",new tc(Ka.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new tc(Ka.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},Bt.prototype.getPresence=function(n){var t=this,e=Uo.digOrCreate(this._presences,n,function(){return new $S(t,n)});return e._wantsDestroy=!1,e},Bt.prototype.getDocPresence=function(n,t){var e=Nb.channel(n,t),o=this,r=Uo.digOrCreate(this._presences,e,function(){return new Nb(o,n,t)});return r._wantsDestroy=!1,r},Bt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},Bt.prototype._addPresence=function(n){Uo.digOrCreate(this._presences,n.channel,function(){return n})},Bt.prototype._handlePresenceSubscribe=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},Bt.prototype._handlePresenceUnsubscribe=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},Bt.prototype._handlePresence=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},Bt.prototype._handlePresenceRequest=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var zb=US,VS=Wa;const Yh={err:1001,msg:"user auth error",name:"AuthError"},WS={err:1002,msg:"you don't have required permission",name:"PermissionError"},mp={err:1003,msg:"Too many user connected",name:"MaxUserError"},Xa={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},qS={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},GS={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},tu="x-live-editor-token",Jh="x-live-editor-base-url",Cn=S("auth-connection");function ZS(n){try{n()}catch(t){Cn.error(t)}}class QS{constructor(t,e){m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new G3.EventEmitter);m(this,"token",null);m(this,"resourceToken",null);this.url=t,this.reauthFunc=e,this.retryCount=0}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return Mi(this.getBaseURL())}async auth(t){g(Cn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[tu]:t.token,[Jh]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=t.token,await o.json()}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[Jh]:Mi(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new HB.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(zb.prototype),g(Cn,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};const o=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=r=>{var s;const i=r;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in i||i.a==="pong")this.handleMessage(i);else{Object.prototype.hasOwnProperty.call(i,"a")&&i.a!=="init"&&i.a!=="hs"&&(this.retryCount=0);try{o(i)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,i);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,i);return}throw l}}},zb.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,Cn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){Cn.error(t),setTimeout(()=>this.handleAuthError(),0)}}else Cn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(Yh.msg);t.code=Yh.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Xa.msg);t.code=Xa.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 o=e.err;if(o===Yh.err)Cn.warn("auth error"),this.handleAuthError();else if(o===mp.err)Cn.warn(mp.msg),this.emitMaxUsersError();else if(o===Xa.err){Cn.warn(Xa.msg);try{this.emitRequestReloadError()}catch(r){Cn.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else Cn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return g(Cn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(g(Cn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){g(Cn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){g(Cn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.reauthFunc=void 0,this.events.removeAllListeners(),ZS(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}S("utils/file");function YS(){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}YS();async function JS(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new jB.Hash;for(let s=0;s<o;s++){const l=s*102400;let a=l+102400;a>e&&(a=e);const h=await n.slice(l,a,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return Mi(i)}const fr=S("sharedb-doc/client");class KS{constructor(t,e,o){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",K());m(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});g(fr,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),fr.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;VS.register(Hd.type),this.connection=new QS(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return g(fr,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,o=>{(t==="error"||this.doc)&&e(o)})}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,o,r,i){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...i},data:{name:o,size:r}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const o=`${this.apiServer()}/resources`;let r=[];t.forEach(l=>{const a=l.split("|");r.push(...a)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[tu]:this.connection.token}));return await Promise.all(i)}async uploadFile(t,e,o,r,i){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=v=>{fr.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await JS(e),d=await this.getFileUrlByHash(t,a,e.name,e.size,o);if(d)return r(-1),d;let h=t;i!=null&&i.thumbnail&&(h+="/thumbnail");const p=new FormData;p.append("file-size",`${e.size}`),p.append("file-hash",a),p.append("file",e,e.name);const C=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return fr.info(C),r(100),Array.isArray(C.data)?C.data[0]:C.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;g(fr,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[tu]:this.connection.token},e,o);return g(fr,s,"no result"),s}async request(t,e){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const a=e||{};a.url=t,a.headers||(a.headers={}),g(fr,o,"no token"),a.headers={...a.headers,[tu]:o,[Jh]:this.connection.getBase64BaseURL()};try{return await NB.default(t,a)}catch(d){if(r=d,((i=d==null?void 0:d.response)==null?void 0:i.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;o=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw g(fr,r,"no error"),r}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,r=(await this.request(e)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),r}async getVersion(t){const o=`${this.apiServer()}/versions/${t}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,o=await this.request(e);return JSON.parse(o.data.data)}async getVersionOps(t,e){let r=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(r+=`&from=${e}`);const i=await this.request(r),s=i.data.ops,l=$B.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(fr,a.create,"no createDoc.create"),d=a.create.data):d=JSON.parse(i.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:i.data.ops}}async updateVersionExtra(t,e,o){const i=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}async revertVersion(t){const o=`${this.apiServer()}/versions/revert/${t}`;await this.request(o,{method:"post",data:{}})}async createVersion(t,e){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const o=`${this.apiServer()}/resources/external/${Mi(t)}`;return(await this.request(o)).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 r=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const i=[];if(e!=null&&e.withToken&&i.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&i.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function XS(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const gp=S("block-ids");class tL{constructor(){m(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<e.length;r++){const i=e[r];if(i>=t){const s=this.ids.get(i);g(gp,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=K();this.ids.set(t,o)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<e.length;o++){const r=e[o];if(r>t){const i=this.ids.get(r);g(gp,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(t){let e=this.ids.get(t);return e||(e=K(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class eL{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new tL,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 o=0;o<e.length;o++){const r=e[o],i=r[1].getById(t);if(i)return{containerId:r[0],blockIndex:i[0]}}return g(gp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class Vb{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,o)=>{t[o]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const Kh=S("op-parse-handler");class nL{constructor(t,e){m(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const o={...t,containerId:(r=>r==="blocks"?"root":r)(t.containerId)};this.actions.push(o)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,o){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:o})}onDeleteBlockData(t,e,o){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:o})}onInsertBlockData(t,e,o,r){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:o,value:r})}onUpdateBlockText(t,e,o){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:o})}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,o=new Map,r=new eL,i=t.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of i)if(s.type==="deleteBlock"){const l=s,a=r.getBlockId(l.containerId,l.blockIndex);r.onDeleteBlock(l.containerId,l.blockIndex);const d=o.get(a);d&&(Kh.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),o.delete(a));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,a=`${l.containerId}-${l.blockIndex}`;if(e.has(a)){Kh.warn("delete block data after delete block, ignore it");continue}const d=r.getBlockId(l.containerId,l.blockIndex);let h=o.get(d);h||(h=new Vb,o.set(d,h)),h.delete(l.key)}else g(Kh,!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,a=r.getBlockId(l.containerId,l.blockIndex);let d=o.get(a);d||(d=new Vb,o.set(a,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(o.entries()).forEach(([s,l])=>{const{containerId:a,blockIndex:d}=r.getBlockIndexById(s);Kh.debug(`update block data: ${a}, ${d}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Oe=S("op-parser");class Wb{}class pp{constructor(t){m(this,"key");this.key=t}}function oL(n,t,e){const o=t.concat(),r=o[0];if(typeof r!="number"||(o.shift(),o.length===1))return!1;const i=o[0];if(typeof i!="object"||!i.i||Object.keys(i).length!==1)return!1;for(let l=1;l<o.length;l++){const a=o[l];if(!Array.isArray(a)||a.length!==2||typeof a[0]!="string")return!1;const h=a[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=i.i;g(Oe,s.id,"block id is required"),g(Oe,s.type,"block type is required");for(let l=1;l<o.length;l++){const a=o[l],d=a[0],h=a[1];s[d]=h.i}return e.onInsertBlock(n,r,s),!0}function Cp(n,t,e,o){if(e==="upsert"&&oL(n,t,o))return;g(Oe,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const r=t.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const a=r[1];if(g(Oe,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),g(Oe,a.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const h=a.e;o.onUpdateBlockText(n,i,h)}g(Oe,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){g(Oe,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];g(Oe,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(g(Oe,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&o.onInsertBlockData(n,i,a,d.i),d.r&&e==="remove"&&o.onDeleteBlockData(n,i,a),d.et==="rich-text"&&e==="upsert"){const p=d.e;o.onUpdateBlockText(n,i,p)}}else e==="remove"&&d.r&&s.push(new pp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i);r.shift()}else if(typeof l=="object"){const a=l;e==="remove"&&a.r&&s.push(new Wb),e==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{g(Oe,typeof l=="string","data is not string"),g(Oe,l!=="text","data !== 'text'"),g(Oe,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const a=l,d=r[1];e==="remove"&&d.r&&s.push(new pp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Wb?o.onDeleteBlock(n,i):l instanceof pp?o.onDeleteBlockData(n,i,l.key):g(Oe,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function rL(n,t,e){Oe.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function iL(n,t,e){const o=n[1],r=n[2];g(Oe,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),g(Oe,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Oe.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?t==="upsert"&&e.onUpdateComment(o):r.i?t==="upsert"&&e.onCreateComment(o):r.r?t==="remove"&&e.onDeleteComment(o):Oe.error(`unknown comment op, ${JSON.stringify(n)}`)}function Ap(n,t,e){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{Ap(s,t,e)});return}const r=o;if(g(Oe,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){rL(n);return}if(r==="comments"){iL(n,t,e);return}const i=r;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{Cp(i,s,t,e)}):n.slice(1).forEach(s=>{Cp(i,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(i),s.i&&t==="upsert"&&e.onCreateContainer(i,s.i)}else g(Oe,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Cp(i,n.slice(1),t,e)}function qb(n,t,e){const o=new nL(t,e);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=mt.default(n),l=s[0];Array.isArray(l)?s.forEach(a=>{Ap(a,i,o)}):Ap(s,i,o)}o.end()}const sL=S("sharedb-comments");function bp(n){const t=n.blocks;g(sL,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(e.blocks[o]=r)}),mt.default(e)}function Gb(n){const{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}=n;return{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}}function vp(n,t){const e=VD(t),{comments:o,meta:r,blocks:i,...s}=e,l={...n,blocks:i,...s},a=mt.default(l);return delete a.children,a}const se=S("sharedb-doc/doc-container"),Zb="ot-json1";Hd.type.registerSubtype(WD.type),Hd.type.name=Zb,Hd.type.invert=null;class eu extends ha{constructor(e,o,r=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new UD);m(this,"batching",0);m(this,"status","clean");m(this,"disableLogout");m(this,"destroyed",!1);m(this,"handleNothingPending",()=>{this.setStatus("clean")});m(this,"handleCreate",()=>{this.handleReload("doc created")});m(this,"handleDel",()=>{});m(this,"handleReload",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});m(this,"handleReset",async e=>{const o=new Error(`reset doc: ${e}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});m(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});m(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});m(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});m(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});m(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,a])=>{if(!aa.default(i[l],a))if(i[l]===void 0){if(a!=null){const d={i:a};s.push([l,d])}}else if(a==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:a};s.push([l,d])}}),Object.entries(i).forEach(([l,a])=>{if((r[l]===void 0||r[l]===null)&&a!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});m(this,"broadcastMessage",async e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});m(this,"data",()=>this.doc.data);m(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){se.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(se.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),se.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(se.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));m(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,Zb,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainers",async e=>{const o=e.map(({containerId:r,blocks:i})=>[ji(r),{i}]);return this.submitOp([o])});m(this,"submitDeleteChildContainer",async e=>{const o=[ji(e),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(e,o,r)=>{const i=[ji(e),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(e,o)=>{const r=[ji(e),o,{r:!0}];return this.submitOp(r)});m(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[ji(e),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a)){const h={r:!0,i:d};i.push([a,h])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(a=>{if(l.has(a))return;const d={r:!0};i.push([a,d])}),Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a))return;const h={i:d};i.push([a,h])}),this.submitOp(i)});m(this,"submitUpdateRichText",async(e,o,r)=>{const i=[ji(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(e,o,r)=>{if(this.destroyed){se.warn("handleOp: destroyed");return}try{qb(e,this,!!o)}catch(i){throw se.error(i),i}});this.client=e,this.doc=o,this.doc.preventCompose=!0,this.disableLogout=r,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,g(se,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new KS(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new eu(o,r,e.disableLogout);if(r.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(e.templateData||XS())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw se.error(o),se.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),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,o)=>{if(this.localPresence)e();else{const r=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);r.on("receive",(i,s)=>{this.onCustomMessage(s)}),r.subscribe(i=>{i?o(i):(this.localPresence=r.create(K()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return Va(this.data())}getContainerBlocks(e){const o=this.data();g(se,o,"no doc data");const r=o[ji(e)];return g(se,r,`no container data: ${e}`),mt.default(r)}getBlockData(e,o){const r=this.data();g(se,r,"no doc data");const i=r[ji(e)];g(se,i,`no container data: ${e}`);const s=i[o];return g(se,s,`no block data: ${o}`),mt.default(s)}localInsertBlock(e,o,r){return this.submitInsertBlock(e,o,r),this.getBlockData(e,o)}localDeleteBlock(e,o){const r=this.getBlockData(e,o);return this.submitDeleteBlock(e,o),r}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(se,i.text,"no block text");const s=mt.default(i.text);this.submitUpdateRichText(e,o,r);const l=ln.apply(s,r);return g(se,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=mt.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainers(e){this.submitInsertChildContainers(e)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>Gb(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return bp(o)}localCreateComment(e,o){const r=vp(e,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(e){const o=["comments",e,{r:!0}];return this.submitOp(o)}localUpdateComment(e,o){const r=vp(e,o),i=["comments",e.id,{r:!0,i:r}];return this.submitOp(i)}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,o,r){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Kl(e),o,r)})}onInsertBlock(e,o,r,i){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Kl(e),o,r,i)})}onUpdateBlockData(e,o,r,i){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Kl(e),o,r,i)})}onUpdateBlockText(e,o,r,i){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Kl(e),o,r,i)})}onDeleteContainer(e,o){g(se,this.callbacks.length>0,"no callbacks"),g(se,e!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Kl(e),o)})}onCreateContainer(e,o,r){g(se,this.callbacks.length>0,"no callbacks"),g(se,e!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Kl(e),o,r)})}onDeleteComment(e,o){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,e,o)})}onCreateComment(e,o){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,e,o)})}onUpdateComment(e,o){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){const o=e;(o==null?void 0:o.type)==="custom"&&(o==null?void 0:o.clientId)!==this.client.clientId?this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,o.data)}):(o==null?void 0:o.type)==="onlineUsers"&&setTimeout(()=>{const r={type:"custom",data:e,clientId:"-"};this.onCustomMessage(r)})}async addResources(e){return await this.client.getFileUrlsByHashes(e)}async uploadResource(e,o){var i;return{resourceId:await this.client.uploadResource(e,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(e,o){return this.client.buildResourceUrl(e,o)}request(e,o){return this.client.request(e,o)}getUser(){const e=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:e,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const o=await this.client.getVersion(e);return Va(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return Va(e)}async getHistoryData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:Va(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:Va(r),versionData:i}}async updateVersionExtra(e,o,r){await this.client.updateVersionExtra(e,o,r)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,o){return this.client.createVersion(e,o)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,o){qb(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}S("remote-cursor");class Qb{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Me.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));m(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const o=this.editor.findBlockById(e);o&&this.editor.reloadBlock(o)})});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 Yb=S("remote-cursor-decorator");class yp{decorateText(t,e,o){const r=t.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=e[e.length-1];g(Yb,typeof s=="string","invalid path containerId"),g(Yb,typeof l=="number","invalid path blockIndex");const a=t.doc.getBlockData(s,l),d=rn(o);return r.getSimpleCursors(a.id).forEach((p,C)=>{C>d&&(C=d);const v=p.map(D=>({id:K(),type:"remote-cursor",name:D.user.displayName,time:D.time,rainbowIndex:D.user.rainbowIndex})),B=i.get(C);B?B.push(...v):i.set(C,v)}),{insertions:i}}}class Jb extends ve.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Gt(zr(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=et(this.editor.getContainerById(t));i&&this.emit("change",this.editor,i,r,o)}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 lL(n,t){n.addCustom("child-block-tracker",()=>new Jb(n)).addListener("change",t)}function cL(n,t){n.addCustom("child-block-tracker",()=>new Jb(n)).removeListener("change",t)}const Ent="",aL={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"}},uL={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},dL={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"}};L.mergeLang({"zh-CN":aL,"en-US":uL,"js-JP":dL});const xnt="";S("button");function fo(n,t,e,o,r){const i=k("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,t),e?typeof e=="string"?e.startsWith("<")?i.innerHTML=e:i.innerText=e:i.appendChild(e):i.innerText=t,o&&(o.indexOf("checked")!==-1&&W(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0),o.indexOf("primary")!==-1&&W(i,"primary")),i}function Kb(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const Int="",Xb=`<?xml version="1.0" ?>
27
+ `)}const oT=S("get-text-position");function ql(n,t){const e=t!=null?t:n.selection.range.start;e instanceof Ue||g(oT,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=bt(r),s=ot(r),l=ct(s),{offset:a}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const Gl=S("insert-text");function Tg(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(g(Gl,r,"no block data"),g(Gl,r.text,"no block text"),rn(r.text)===0)return g(Gl,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Ve(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function rT(n,t,e){const o=ot(t),r=ct(o),i=bt(t);return Tg(n,r,i,e)}function R6(n,t,e,o,r){const i=ot(t),s=ct(i),l=bt(t),a=rT(n,t,e),d=gh(e,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),pn(n,t)}function O6(n,t,e,o){const r=ot(t),i=ct(r),s=bt(t),l=gh(e," ",o);return n.doc.localUpdateBlockText(i,s,l),pn(n,t)}function iT(n,t){let e=0;if(t===0)return!1;for(let o=0;o<n.length;o++){const r=n[o];g(Gl,typeof r.insert=="string","invalid text op, no insert");const i=e+ph(r);if(i===t)return!1;if(i>t)return!0;e=i}return!1}function Dg(n,t,e,o,r){const i=n.doc.getBlockData(e,o);g(Gl,i,"no block data"),g(Gl,i.text,"no block text");const s=Tg(n,e,o,r);s&&Object.keys(s).includes("link")&&(iT(i.text,r)||delete s.link);const l=gh(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),pn(n,n.getBlockById(i.id))}function Sg(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=ql(n);Dg(n,t,e,o,r)}const Ih=S("update-composition-text");function _6(n){const t=n.selection.range.start;t instanceof Ue||g(Ih,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);g(Ih,nt(n,o),"not a text kind block");const r=ot(o),i=ct(r),s=bt(o),l=n.doc.getBlockData(i,s);g(Ih,l,"no block data in doc"),g(Ih,l.text,"no text data in text block");const a=Lt(o);dh(n,Ri(o),e,a,l.text)}function F6(n){Fx(n)}function Zl(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Fa=S("delete-block-text");function Lg(n,t,e,o,r){if(!n.isBlockWritable(t))return Fa.error("block is not writable"),0;g(Fa,nt(n,t),"block is not a text kind block");const i=ot(t),s=ct(i),l=bt(t),a=n.doc.getBlockData(s,l);g(Fa,a,"no block data in doc"),g(Fa,a.text,"no text data in text block");let d=e;sn(t,e)||(d=_i(t,d));let h=e+o;g(Fa,h<=ut(n,t),`invalid offset and count: ${e}, ${o}`),sn(t,h)||(h=_s(t,h));const p=h-d,C=q4(d,p);return n.doc.localUpdateBlockText(s,l,C,r),p}const Mg=S("break-text-block");function P6(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Ql(n,t,e,o){g(Mg,nt(n,t),`block is not a text kind block: ${Dt(t)}`),g(Mg,e>=0&&e<=ut(n,t),`invalid offset: ${e}`);const r=ot(t),i=ct(r),s=bt(t),l=o!=null&&o.copyBlockAttributes?P6(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===ut(n,t))){const v=e===0?s:s+1,B={...ar(""),...l,...o==null?void 0:o.newBlockData},D=ke(n,t.id,0),x=Zl(n,i,v,B,D);return{block:t,newBlock:x}}g(Mg,sn(t,e),"not a valid offset");const a=pn(n,t),{right:d}=Tn(a,e),h=rn(d);h>0&&Lg(n,t,e,h);const p={...ar(d),...l,...o==null?void 0:o.newBlockData},C=Zl(n,i,s+1,p,ke(n,p.id,0));return{block:t,newBlock:C}}const sT=S("prepare-insert-new-block");function lT(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=me(d);return g(sT,e>=0&&e<=h.length,`invalid blockIndex: ${e}`),{containerId:t,blockIndex:e}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(t=ct(ot(r)),e=bt(r),!nt(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===ut(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const a=Ql(n,r,s).newBlock;return{containerId:t,blockIndex:bt(a)}}const cT=S("auto-insert-block");function N6(n,t,e,o,r,i){const s=lT(n,e,o);g(cT,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},a={anchor:l,focus:l};return Zl(n,s.containerId,s.blockIndex,t,r!=null?r:a,i)}const aT=S("delete-block");function Th(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{Th(n,i,e)})}))}function Dh(n,t,e){const o=ot(t),r=ct(o),i=bt(t),s=n.doc.getBlockData(r,i);return g(aT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,ze(n,{anchor:e.start,focus:e.end})),s}function Rg(n,t,e){return n.undoManager.runInGroup(()=>{const o=ot(t);To(o)===1&&n.insertTextBlock("",ct(o),0);let r=e?Oi(n,e):null;if(!r){const l=n.selection.range;D6(t,l)?r=S6(n,t):r=l}const i=Dh(n,t,r),s=[];return Th(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function uT(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{Th(n,r,e)}),n.doc.localDeleteChildContainers(e)}function $6(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{Th(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const Og=S("merge-text-block");function H6(n,t,e){g(Og,nt(n,t),"only text block can be merged"),g(Og,nt(n,e),"only text block can be merged");const o=Pi(n,t),r=Pi(n,e),i=o.text,s=r.text;g(Og,i&&s,"block data has no text");const l=ot(t),a=ct(l),d=bt(t),h=ut(n,t),p=Dg(n,s,a,d,h),C=ke(n,t,rn(i));return Rg(n,e,C),p}const ur=S("clear-selected-contents");function Sh(n,t){g(ur,nt(n,t.block),"not a text kind block");const{start:e,end:o}=t;g(ur,e.isSimple(),"not a simple block position"),g(ur,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;g(ur,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function j6(n,t,e){const o=ct(t),r=me(t),i=e.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});e.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function dT(n,t){const{block:e,start:o,end:r}=t;if(nt(n,e)){Sh(n,t);return}if(Ie(e)||o.isSimple()){g(ur,r.isSimple(),"invalid range");const s=ot(e),l=bt(e),a=n.insertTextBlock("",ct(s),l);n.selection.selectBlock(a,0),n.deleteBlock(e);return}g(ur,Mt(n,e),"invalid block kind"),g(ur,!o.isSimple()&&!r.isSimple(),"invalid range"),Ms(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{j6(n,s,{focus:l===0})})}function hT(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(g(ur,e.length>0,"no selected block"),e.length===1){dT(n,e[0]);return}const o=e[0],r=o.block,i=ot(r);g(ur,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(nt(n,r)){Sh(n,o);const h=ke(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(C=>n.deleteBlock(C.block)),nt(n,l)){Sh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(nt(n,l)){Sh(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===To(i)){j6(n,i,{focus:!0});return}const a=ae(r),d=Yt(l);g(ur,a||d,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function _g(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),hT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const fT=S("core");function U6(n,t,e){const o=ot(t),r=ct(o),i=bt(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),pn(n,t)}function z6(n,t,e){if(!n.isBlockWritable(t)){fT.error("block is not writable");return}const o=n.getBlockText(t),r=ln.diff(o,e);U6(n,t,r)}function Lh(n,t,e){const o=pn(n,t),r=typeof e=="string"?Fi(e):e,i=ln.diff(o,r);return U6(n,t,i)}const Pa=S("update-block-data");function Mh(n,t,e,o){const r=ot(t),i=ct(r),s=bt(t),l=n.doc.getBlockData(i,s),a={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(e));return d.forEach(C=>{if(!h.has(C)){if(C==="id"||C==="type"||C==="text")return;Pa.debug(`delete key: ${C}`),a.delete.push(C)}}),Object.entries(e).forEach(([C,v])=>{g(Pa,C!=="id"&&C!=="type",`invalid block data delta, ${C}`);const B=l[C];if(v==null){B!=null&&(Pa.debug(`delete key: ${C}`),a.delete.push(C));return}B!==v&&(aa.default(B,v)||C==="text"&&ln.diff(B,v).length===0||(d.has(C)?(Pa.debug(`replace key: ${C}`),a.delete.push(C)):Pa.debug(`insert key: ${C}`),a.insert[C]=v))}),n.doc.localUpdateBlockData(i,s,a,o),Pi(n,t)}function V6(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function Fg(n,t,e){if(!Mt(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=zn(n,t).getChildContainers(n,t)[0],i=ye(r);Fg(n,i,e)}function Ns(n){const t=[];let e={};return n.forEach(o=>{t.push(...o.blocks.root);const{root:r,...i}=o.blocks;e={...e,...i}}),{blocks:{...e,root:t},meta:{},comments:{}}}const Na=S("clone-block");function Ni(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(h,p)=>(g(Na,e!==p,"invalid child block"),Ni(n,h,e,o)));let i={};const s=new Map,l=mt.default(e);l.children&&(l.children=l.children.map(h=>{const p=K(),C=t.blocks[h];g(Na,Array.isArray(C),"invalid child blocks");const v=C.map(_=>Ni(n,t,_,o)),B=Ns(v),{root:D,...x}=B.blocks;return i={...i,...x},i[p]=B.blocks.root,s.set(h,p),p}));const a=Array.from(s.entries()),d=h=>{for(const p of a){const[C,v]=p;{const B=`${C}/`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}/${D}`;return Na.debug(`replace key: ${h} -> ${x}`),x}}{const B=`${C}_`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}_${D}`;return Na.debug(`replace key: ${h} -> ${x}`),x}}}return h};return Array.from(Object.entries(l)).forEach(([h,p])=>{const C=d(h);C!==h&&delete l.key,l[C]=p}),l.id=K(),o&&(o.blockIdMap.set(e.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Pg(n,t,e,o){const r=t.blocks[e];g(Na,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Ni(n,t,l,o));return Ns(i)}function Ng(n,t,e){const o=t.blocks.root.map(r=>Ni(n.editorBlocks,t,r,e));return mt.default(Ns(o))}const W6=S("insert-doc");function q6(n,t,e,o,r){if(Mt(n,t)){W6.warn("failed to insert doc into a complex block");return}const i=Ng(n,o,r),s=ot(t),l=bt(t),a=ct(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var H,z,Z;const d=[];Object.entries(i.blocks).forEach(([tt,ft])=>{tt!=="root"&&d.push({containerId:tt,blocks:ft})}),d.length>0&&n.doc.localInsertChildContainers(d);const h=i.blocks.root;if(Ie(t)){n.deleteBlock(t);let tt;h.reverse().forEach(ft=>{const vt=n.insertBlock(a,l,ft,void 0,{noFocus:!0});tt||(tt=vt)}),tt&&n.selection.selectBlock(tt,ut(n,tt));return}if(g(W6,nt(n,t),"not a text block"),ue(n,t)){const tt=a==="root"&&n.getBlockByIndex(a,0)===t,ft=bt(t);let vt;h.forEach((zt,Ht)=>{const Xt=n.insertBlock(a,ft+Ht,zt,void 0,{noFocus:!0});Ht===h.length-1&&(vt=Xt)}),vt&&n.selection.selectBlock(vt,ut(n,vt)),tt&&n.deleteBlock(t);return}if(h.length===1){const tt=h[0];if(ka(n,tt.type)){n.insertTextToBlock(t,e,(H=tt.text)!=null?H:[]);return}n.breakTextBlock(t,e),n.insertBlock(a,l+1,tt);return}const p=e===ut(n,t),C=e===0,v=h[0],B=h[h.length-1];let D;!p&&!C?D=n.breakTextBlock(t,e,{forceInsertAfter:!0}):D=t;const x=C?l:l+1;p?(D=n.insertBlock(a,l+1,B),n.selection.selectBlock(D,ut(n,D))):(n.selection.selectBlock(D,0),ka(n,B.type)?n.insertTextToBlock(D,0,(z=B.text)!=null?z:[]):n.insertBlock(a,x,B));const _=n.selection.range;let R=x;ka(n,v.type)?C?(n.insertBlock(a,x,v),R+=1):n.insertTextToBlock(t,e,(Z=v.text)!=null?Z:[]):(n.insertBlock(a,x,v),R+=1),h.slice(1,h.length-1).reverse().forEach(tt=>{n.insertBlock(a,R,tt)}),n.selection.setRange(_)}),n.doc.endBatchUpdate()}function $g(n,t,e,o,r){const i=Ng(n,o,r),s=ct(t),l=[];return n.undoManager.runInGroup(()=>{const a=[];Object.entries(i.blocks).forEach(([h,p])=>{h!=="root"&&a.push({containerId:h,blocks:p})}),n.doc.localInsertChildContainers(a),i.blocks.root.reverse().forEach(h=>{const p=n.insertBlock(s,e,h);l.push(p)})}),l}function G6(n,t,e){const o=To(t);$g(n,t,o,e);for(let r=0;r<o;r++){const i=ye(t);n.deleteBlock(i)}}const $a=S("add-text-attribute");function mT(n,t,e,o){const{start:r,end:i}=e;g($a,r.blockId===i.blockId&&r.blockId===it(t),"invalid range"),g($a,o,"invalid attribute name");const s=n.getBlockText(t),l=Wl(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function Z6(n,t,e,o,r){const{start:i,end:s}=e;g($a,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g($a,o,"invalid attribute name");const l=n.getBlockText(t),a=Sa(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Yl(n,t,e,o,r){const{start:i,end:s}=e;g($a,i.blockId===s.blockId&&i.blockId===it(t),"invalid range");const l=n.getBlockText(t),a=e6(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Q6(n,t,e,o){const r=Oo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!nt(n,s))return;if(ue(n,s)){o(n,it(s),t,e);return}const d=ze(n,{anchor:l,focus:a});t==="color"||t==="backgroundColor"?Yl(n,s,d,t,e):(Yl(n,s,d,"color",null),Yl(n,s,d,"backgroundColor",null))})})}function Y6(n,t,e){const o=Oo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!nt(n,i))return;if(ue(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,it(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,it(i),"backgroundColor",null);return}const a=ze(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Yl(n,i,a,"color",null),(t==="clearBackground"||t==="clearAll")&&Yl(n,i,a,"backgroundColor",null)})})}function Hg(n,t){const e=Oo(n,{simpleBlockOnly:!0}).filter(s=>nt(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(ut(n,s.block)===0)return t(n,it(s.block));const l=s.start,a=s.end,d=n.getBlockText(s.block);return r6(l.offset,a.offset-l.offset,d)};let[r,i]=o(e[0]);return r===null&&i===null?[r,i]:(e.forEach(s=>{const[l,a]=o(s);l===null||r===null?r=null:r=l===r?r:null,a===null||i===null?i=null:i=a===i?i:null}),[r,i])}const Wn=S("adjust-selection-pos");function J6(n){const t=[];for(;n;){const e=ot(n);if(t.unshift(e),Gt(e))return t;const o=et(e);g(Wn,o,"child container has not parent container"),n=o}g(Wn,!1,"should not come here: getParentContainers")}function K6(n,t){for(;t;){const e=ot(t);if(e===n)return t;const o=et(e);g(Wn,o,"could not find parent block for a child container"),t=o}g(Wn,!1,"no parent block in specified container")}function gT(n,t){const e=J6(n),o=J6(t);g(Wn,e.length>0&&o.length>0,"block has not parent container"),g(Wn,e[0]===o[0],"root container does not equal");let r=e[0];for(let l=1;l<e.length||o.length;l++)if(e[l]!==o[l]){r=e[l-1];break}const i=K6(r,n),s=K6(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function X6(n,t){let e=et(t);for(g(Wn,e,"element is not in a block");e;){const o=ot(e);g(Wn,Mo(o),"not a child container");const r=et(o);if(g(Wn,r,"child container has not parent block"),r===n)return o;e=r}g(Wn,!1,"failed to find parent container in complex block")}function Rh(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof Ue&&e instanceof Ue?{anchor:t,focus:e}:t instanceof Ro&&e instanceof Ro?ah(n,o,t,e):null;const i=ot(o),s=ot(r);if(i===s)return t instanceof Ro&&(t=st(o,0,"home")),e instanceof Ro&&(e=st(r,ut(n,r),"end")),g(Wn,t instanceof Ue,"not valid position type"),g(Wn,e instanceof Ue,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof Ue&&e instanceof Ro){const B=n.getContainerById(e.childContainerId);if(B===i)return{anchor:e,focus:e};const D=et(i);if(D&&D===et(B)){const x=fe(D,ct(i)),_=fe(D,ct(B));return ah(n,D,x,_)}}return null}const l=Wd(o,r)>0,{newBlock1:a,newBlock2:d}=gT(o,r);if(a===d){const B=a,D=X6(B,o),x=X6(B,r);return t=fe(a,ct(D)),e=fe(a,ct(x)),Wn.debug(`select in complex block: ${D.id}, ${x.id}`),ah(n,B,t,e)}let h=l?ut(n,a):0;a===o&&t instanceof Ue&&(h=t.offset);let C=l?0:ut(n,d);return d===r&&e instanceof Ue&&(C=e.offset),t=st(a,h,l?"end":"home"),e=st(d,C,l?"home":"end"),{anchor:t,focus:e}}const pT=S("move-complex-block-position");function CT(n,t,e){const o=n.getBlockById(t.blockId);g(pT,Mt(n,o),"is not a complex block");const r=zn(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?fe(o,ct(s)):null}const Ha=S("move-simple-block-position");function tA(n,t){const e=gn(n,t,{visibleOnly:!0});g(Ha,e.length>0,"complex block has not any child container");const o=e[0];return ye(o)}function eA(n,t){const e=gn(n,t,{visibleOnly:!0});g(Ha,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Qe(o)}function nA(n,t,e){const o=e?tA(n,t):eA(n,t);return Mt(n,o)?nA(n,o,e):o}function AT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===0?tA(n,e):Ts(e)}function bT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===1?eA(n,e):Is(e)}function jg(n){return n==="ArrowLeft"||n==="ArrowUp"}function Ug(n,t,e){const o=ot(t);if(Gt(o))return null;const r=et(o);g(Ha,r,"child container has not parent block"),g(Ha,Mt(n,r),"is not a complex block");const i=zn(n,r).getNextContainer(n,r,o,e);return i?jg(e)?Qe(i):ye(i):Ug(n,r,e)}function vT(n,t,e){const o=ot(t);if(Gt(o))return null;const r=et(o);if(g(Ha,r,"child container has not parent block"),jg(e)){const l=ae(r);if(l)return l}else{const l=Yt(r);if(l)return l}const i=Ug(n,r,e);if(i)return i;let s=r;for(;!Gt(ot(s));)s=et(ot(s));return jg(e)?ae(s):Yt(s)}function yT(n,t,e){return!Mt(n,t)||zn(n,t).enableKeyboardSelect?t:nA(n,t,e==="ArrowDown"||e==="ArrowRight")}function kT(n,t,e){const o=n.getBlockById(t.blockId),i=Jt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?AT(n,t):bT(n,t);if(s||(s=Ug(n,o,e),s||(s=vT(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Gt(ot(o)))return null;const l=n.insertTextBlock("",ct(n.rootContainer),To(n.rootContainer));return st(l,0,"home")}return null}if(s=yT(n,s,e),nt(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return Zx(n,s,o,t,l);if(e==="ArrowUp")return Gx(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?st(s,ut(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?st(s,0,"home"):null}function wT(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(nt(n,r))return o;const i=Yt(r);if(i)return st(i,0,"home");if(!Gt(ot(r))||n.readonly)return o;const s=n.insertTextBlock("",ct(n.rootContainer),To(n.rootContainer));return st(s,0,"home")}function BT(n,t,e){const o=n.selection.range;let r;if(o instanceof Ye)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=wT(n,t,o):r=kT(n,o.getFocusedPos(),t);else if(r=CT(n,o.focus,t),e==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(t==="ArrowLeft"||t==="ArrowUp"){const l=Qe(s);r=st(l,0,"home")}else{const l=ye(s);r=st(l,ut(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:Rh(n,o.anchor,r):null}function $i(n,t,e){const o=BT(n,t,e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(t==="ArrowLeft"||t==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function oA(n){return $i(n,"ArrowLeft","move"),!0}function rA(n){return $i(n,"ArrowRight","move"),!0}function iA(n){return $i(n,"ArrowUp","move"),!0}function sA(n){if($i(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=ot(t);if(Gt(e)||Qe(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",ct(o),To(o)),!0}function lA(n){return $i(n,"ArrowDown","select"),!0}function cA(n){return $i(n,"ArrowLeft","select"),!0}function aA(n){return $i(n,"ArrowRight","select"),!0}function uA(n){return $i(n,"ArrowUp","select"),!0}const dA=S("word-offset");function zg(n,t){const e=n.selection.range.focus;g(dA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(ue(n,o))return st(o,0,"home");if(e.offset===0||!nt(n,o)){const s=ae(o);if(!s)return null;const l=st(s,ut(n,s),"end");if(t==="select"&&nt(n,s)){const a=vg(n,s,l.offset);return st(s,a,"normal")}return l}const r=vg(n,o,e.offset);return st(o,r,"normal")}function Vg(n,t){const e=n.selection.range.focus;g(dA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(ue(n,o))return st(o,0,"end");if(e.offset===ut(n,o)||!nt(n,o)){const s=Yt(o);if(!s)return null;const l=st(s,0,"home");if(t==="select"&&nt(n,s)){const a=yg(n,s,l.offset);return st(s,a,"end")}return l}const r=yg(n,o,e.offset);return st(o,r,"normal")}function hA(n){if(!n.selection.range.focus.isSimple())return!1;const e=zg(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function fA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vg(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function mA(n){if(!n.selection.range.focus.isSimple())return!1;const e=zg(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function gA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vg(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}S("find-block");function Wg(n,t){if(!Mt(n,t))return t;const o=zn(n,t).getChildContainers(n,t)[0],i=me(o)[0];return Wg(n,i)}function qg(n,t){if(!Mt(n,t))return t;const e=zn(n,t).getChildContainers(n,t),o=e[e.length-1],r=me(o),i=r[r.length-1];return qg(n,i)}function Gg(n){const t=qg(n,Qe(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(e),!0}function pA(n){const t=Wg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(e),!0}function CA(n){const t=Wg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function Zg(n){const t=qg(n,Qe(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const AA=S("line-offset");function bA(n){const t=n.selection.range.focus;g(AA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!nt(n,e))return st(e,0,"home");let r=j4(e,t).start;const{next:i}=ih(e,r);return i&&co(i)&&ya(i)==="br"&&(r+=1),st(e,r,"home")}function vA(n){const t=n.selection.range.focus;g(AA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===ut(n,e)||!nt(n,e))return st(e,ut(n,e),"end");const o=j4(e,t);return st(e,o.end,"end")}function yA(n){if(!n.selection.range.focus.isSimple())return!1;const e=bA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function kA(n){if(!n.selection.range.focus.isSimple())return!1;const e=vA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function wA(n){if(!n.selection.range.focus.isSimple())return!1;const e=bA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function BA(n){if(!n.selection.range.focus.isSimple())return!1;const e=vA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const EA=S("find-block-position");function ET(n,t,e,o){g(EA,Mt(n,t),"is not a complex block");const r=zn(n,t).getChildContainers(n,t);g(EA,r.length>0,"complex block has not any child container");const i=Lo(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,a=S4(n,t,s,l);return Qg(n,a,e,o)}function Qg(n,t,e,o){if(Mt(n,t))return ET(n,t,e,o);const r=it(t);let i=Number.MAX_SAFE_INTEGER;const s=Lo(n,e,o),l=s.left+s.width/2,a=s.top+s.height/2;let d=st(r,0,"home");const h=ut(n,t);for(let p=0;p<=h;p++){const C=st(r,p,"normal"),v=Lo(n,t,C),B=or(v,l,a);B<i&&(i=B,d=C)}return d}const xA=S("page-offset");function xT(n,t){const e=x6(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<QI(n))return n.getFirstBlock();const i=ae(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ae(s)}return n.getFirstBlock()}function IT(n,t){const e=x6(n)*.9,o=t.getBoundingClientRect(),r=YI(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=Yt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Yt(l)}return n.getLastBlock()}function IA(n){const t=n.selection.range.focus;g(xA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=xT(n,e);let r;return o===n.getFirstBlock()?r=st(o,0,"home"):r=Qg(n,o,e,t),r}function TA(n){const t=n.selection.range.focus;g(xA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=IT(n,e);let r;return o===n.getLastBlock()?r=st(o,ut(n,o),"end"):r=Qg(n,o,e,t),r}function DA(n){if(!n.selection.range.focus.isSimple())return!1;const e=IA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function SA(n){if(!n.selection.range.focus.isSimple())return!1;const e=TA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function LA(n){if(!n.selection.range.focus.isSimple())return!1;const e=IA(n);if(!e)return!1;const o=Rh(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function MA(n){if(!n.selection.range.focus.isSimple())return!1;const e=TA(n);if(!e)return!1;const o=Rh(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const ja=S("select-all");function RA(n,t){const e=ye(n),o=Qe(n);return t.start.offset===0&&t.start.blockId===it(e)&&t.end.offset===ut(t.getEditor(),o)&&t.end.blockId===it(o)}function TT(n,t){const e=t.getEditor(),o=zn(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=it(n);return t.start.blockId===s&&t.start.childContainerId===ct(r)&&t.end.blockId===s&&t.end.childContainerId===ct(i)}function DT(n,t){g(ja,t,"no parent block"),g(ja,Mt(n,t),"not a complex block");const e=zn(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(ze(n,{anchor:fe(t,ct(o)),focus:fe(t,ct(r))}))}function OA(n,t){const e=ot(t);Yg(n,e)}function _A(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&nt(n,t)){const r=e.start,i=e.end,s=ut(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return W(n.rootContainer,"select-all"),OA(n,ye(n.rootContainer)),!1}return g(ja,!e.isSimple(),"invalid range type"),TT(t,e)?(OA(n,t),!1):(g(ja,t,"no parent block"),g(ja,Mt(n,t),"not a complex block"),DT(n,t),!0)}function Yg(n,t){const e=me(t),o=e[0],r=e[e.length-1],i=st(o,0,"home"),s=st(r,ut(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function ST(n){Zg(n),n.focus()}const Jg=S("selected-block-to-doc");function FA(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{FA(n,i,e)}),e.blocks[o]=mt.default(r)})}function Oh(n,t){const e=Jt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const o=mt.default(Pi(n,t.block));if(nt(n,t.block)){const i=t.start,s=t.end;if(g(Jg,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=Ve(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Ie(t.block))return{blocks:{root:[o]},meta:{},comments:{}};g(Jg,Mt(n,t.block),"not complex block"),g(Jg,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return FA(n,o,r),r}function Kg(n,t){const e=st(t,0,"normal"),o=st(t,ut(n,t),"end");return Oh(n,{block:t,start:e,end:o})}const LT=S("block-to-doc");function MT(n,t){g(LT,t.length>0,"invalid params, no blocks");const e=t.map(o=>Kg(n,o));return Ns(e)}function _h(n){const e=n.selection.range.getSelectedBlocks().map(o=>Oh(n,o));return Ns(e)}function PA(n,t){const e=n.getContainerById(t),i=me(e).map(s=>({start:st(s,0,"home"),end:st(s,ut(n,s),"end"),block:s})).map(s=>Oh(n,s));return Ns(i)}const Fh=S("editor-selection");class RT{constructor(t){m(this,"editor");m(this,"caret");m(this,"_range");m(this,"lastCaretRect");m(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(D6(e,i)){Fh.debug("adjust selection because remote deleted current block");const s=S6(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=it(e);this.caret=new qI(t);const r=st(o,0,"normal");this._range=ze(t,{anchor:r,focus:r}),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,o){const r=st(t,e,"normal");let i;o&&(i=st(t,o,"normal")),this.setSelection(r,i)}setSelection(t,e,o){if(e||(e=t),this.verifyPos(t),this.verifyPos(e),!this.selectionChanging(t,e))return this.range;const r=ze(this.editor,{anchor:t,focus:e});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),xt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!tT(this.editor,r))&&rt(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(t,e){return this.setSelection(t.anchor,t.focus,e)}updateSelection(){this.caret.update(),GI(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(!Vr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Lo(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){XI(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=ut(this.editor,e)||g(Fh,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||g(Fh,!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 o;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(o=this.editor.getBlockById(this.range.start.blockId));let r=!1;e&&xt(e,"focused")&&(rt(e,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(t){const e=_h(this.editor);return t==="text"?Oa(this.editor,e):t==="markdown"?_a(this.editor,e):M6(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{rt(t,"focused"),rt(t,"child-focused")})}setBlockFocused(t){if(xt(t,"focused"))return!1;W(t,"focused");let e=ot(t);for(;Mo(e);){const o=et(e);g(Fh,o,"parent block not found"),W(o,"child-focused"),e=ot(o)}return!0}}function OT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);!e||n.selection.selectBlock(e,0,ut(n,e))}function _T(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!nt(n,e))return;let o=zg(n,"select"),r=Vg(n,"select");if(!o||!r)return;const i=t.blockId;o.blockId!==i&&(o=st(e,0,"home")),r.blockId!==i&&(r=st(e,ut(n,e),"end")),n.selection.setSelection(o,r)}class FT{constructor(t){m(this,"editor");m(this,"startPos",null);m(this,"lastCaretRect");m(this,"mouseDownEvent",null);m(this,"autoScroll",null);m(this,"handleMouseDown",(t,e)=>{var r;this.mouseDownEvent=t;const o=R4(this.editor,t.x,t.y);if(o){if(o instanceof sr)return;if(!this.autoScroll&&e.autoScroll){const s=o.getSelectedBlocks(),l=so(s[0].block);this.autoScroll=new Xd({scrollElement:l,edge:{top:50,bottom:50}})}const i=this.editor.selection.range;if(t.shiftKey&&i.isSimple()){const s=i.anchor;this.editor.selection.setSelection(s,o.focus),this.startPos=o.start}else this.editor.selection.setSelection(o.anchor,o.focus),this.startPos=o.start;this.editor.selection.updateLastCaretRect(),e.autoScroll&&((r=this.autoScroll)==null||r.active())}});m(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=uh(this.editor,t.x,t.y);if(!e)return;const o=Rh(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});m(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){_T(this.editor)}handleTripleClick(t){OT(this.editor)}}function PT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function NT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const NA=S("delete-text");function $A(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof Ue||g(NA,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(NA,nt(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!sn(s,l-e)){const a=_i(s,l);e=l-a}}else if(t==="forward"&&l+e>ut(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function HA(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const $T=S("handle-backspace");function Xg(n,t){if(!ue(n,t))return;const e=ot(t);To(e)!==1&&n.deleteBlock(t)}function HT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(nt(n,o))if(e.offset===0){if(HA(n,o))return;const r=ae(o);if(r){if(!n.isBlockWritable(r))return;if(nt(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Mt(n,r)){Xg(n,o);const i=zl(n,r);i?n.selection.selectBlock(i,ut(n,i)):n.selection.selectBlock(r,0,ut(n,r))}else Xg(n,o),g($T,Ie(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=ot(o);if(Mo(i)){const s=I4(n,i);if(s){if(!n.isBlockWritable(s))return;Xg(n,o),n.selection.selectBlock(s,ut(n,s))}}}}else $A(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=bt(o),i=ot(o);n.insertTextBlock("",ct(i),r),n.deleteBlock(o)}}function jT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(nt(n,o))if(e.offset===ut(n,o)){const r=Yt(o);if(r){if(!n.isBlockWritable(r))return;nt(n,r)?n.mergeTextBlock(o,r,{focus:!0}):ue(n,o)?n.deleteBlock(o,ke(n,r,0)):n.deleteBlock(r)}}else $A(n,"forward",1,null);else{const r=bt(o),i=ot(o);n.insertTextBlock("",ct(i),r),n.deleteBlock(o)}}function UT(n){const{range:t}=n.selection,{start:e,end:o}=t,r=n.getBlockById(e.blockId),i=n.getBlockById(o.blockId);if(r!==i||!Mt(n,r))return!1;if(Vr(e))return!0;const s=Ms(n,r,e,o),l=gn(n,r);return s.length===l.length}function zT(n,t){if(UT(n)){const s=n.getFocusedBlock(),l=bt(s),a=ct(ot(s));n.insertTextBlock("",a,l+1);return}const e=n.getFocusedBlock(),{start:o,end:r}=n.selection.range,i=o.blockId===r.blockId&&Ie(e);if(!n.selection.range.isCollapsed()&&!i&&n.clearSelectedContents(),nt(n,e)){if(ue(n,e)&&HA(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 VT(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!nt(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:K(),box:!0,created:Date.now()}),!0}const WT=S("input-handler-actions");function qT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(zT(n),!0))}function GT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(jT(n),!0))}function ZT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(HT(n),!0))}function QT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(VT(n),!0))}function YT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{WT.error(t)}),!0)}const Ph={ArrowDown:sA,ArrowUp:iA,ArrowLeft:oA,ArrowRight:rA,"Shift+ArrowDown":lA,"Shift+ArrowUp":uA,"Shift+ArrowLeft":cA,"Shift+ArrowRight":aA,"CtrlOrCmd+ArrowLeft":hA,"CtrlOrCmd+ArrowRight":fA,"CtrlOrCmd+Shift+ArrowLeft":mA,"CtrlOrCmd+Shift+ArrowRight":gA,"CtrlOrCmd+ArrowUp":pA,"CtrlOrCmd+ArrowDown":Gg,"CtrlOrCmd+Shift+ArrowUp":CA,"CtrlOrCmd+Shift+ArrowDown":Zg,"CtrlOrCmd+A":_A,Home:wA,End:BA,"Shift+Home":yA,"Shift+End":kA,PageUp:DA,PageDown:SA,"Shift+PageUp":LA,"Shift+PageDown":MA,"CtrlOrCmd+Z":PT,"CtrlOrCmd+Shift+Z":NT,Enter:qT,Delete:GT,Backspace:ZT,"Shift+Enter":QT,"CtrlOrCmd+Shift+V":YT};function jA(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function UA(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){let l="";s.split("|").forEach(d=>{const h=e.get(d);l+=l?`|${h}`:`${h}`}),i.src=l}return}const o=t.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=e.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{UA(n,l,e)})})}function zA(n,t,e){if(e.size===0)return;t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,e):UA(t,r,e)})}async function JT(n,t){const e=t.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(e),r=new Map;if(e.length!==o.length)return r;for(let i=0;i<e.length;i++)r.set(e[i],o[i]);return r}function KT(n,t){var i,s;const o=t.meta.serverId;if(!o||typeof o!="string")return!1;const r=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i);return!(!r||r.serverId!==o)}async function XT(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(KT(n,t)){const s=Array.from(Object.keys(o));r=await JT(n,s),zA(n,t,r)}const i=new Map;Object.entries(o).forEach(([s,l])=>{r.get(s)===void 0&&s!==l&&i.set(s,l)}),i.size!==0&&zA(n,t,i)}async function tD(n,t,e){await XT(n,t),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Ie(i)){const s=ot(i),l=n.getBlockIndex(i),[a]=n.insertDocAt(s,l+1,t,e);a&&n.selection.selectBlock(a,ut(n,a))}else{n.clearSelectedContents();const{block:s,offset:l}=ql(n);n.insertDoc(s,l,t,e)}})}const eD=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function nD(n){let t;for(const e of eD)if(t=n[e],t)break;return t||null}function VA(n,t,e){if(t.type==="embed"){const s=t.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))e.add(l);return}const o=t.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&e.add(i.attributes.src)});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{VA(n,l,e)})})}function oD(n,t){const e=new Set;return t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{e.add(s)}):VA(t,r,e)}),Array.from(e)}function Nh(n,t){return Ze.isFirefox?`<!doctype html><html><head><meta charset="utf8" /></head><body><canvas data-editor-doc="${Mi(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::${Mi(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function $h(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=oD(n,t),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),t.meta={...e,resources:r}}function rD(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=_h(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),$h(n,o);const i=xh(n,o),s=_a(n,o),l=Nh(i,o);t.clipboardData.setData("text/html",l),t.clipboardData.setData("text/plain",s),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Hh(n,t){const e=Kg(n,t);$h(n,e);const o=xh(n,e),r=_a(n,e),i=Nh(o,e);return Rm([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class iD{constructor(t){m(this,"editor");m(this,"handlers",[]);m(this,"onPasteText",async(t,e)=>{const o=new DataTransfer;o.setData("text/plain",t);const r=await this.editor.dataConverter.fromData(this.editor,o,e);r&&this.pasteDocs(r,null)});this.editor=t}onInsertText(t,e){if(!nt(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=ql(this.editor);this.handleBeforeInsertText(o,r,i,e)||(this.defaultInsertText(this.editor,o,r,i,e),this.handleAfterInsertText(o,r,i,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 o=this.handlers[e];o.handleChanged&&o.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:o,offset:r}=ql(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,o,r)}}onUpdateCompositionText(t,e,o){this.editor.updateCompositionText(e,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=ql(this.editor);for(let l=0;l<this.handlers.length;l++){const a=this.handlers[l];a.handleUpdateCompositionText&&a.handleUpdateCompositionText(this.editor,r,i,s,o)}this.editor.selection.updateLastCaretRect()}onCopy(t){rD(this.editor,t,(e,o,r)=>{for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,o,r);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onCut(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;Ie(o)&&this.editor.deleteBlock(o)}else _g(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{o&&this.pasteDocs(o,t)})}onFocus(){W(this.editor.rootElement,"active")}onBlur(){rt(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,o)=>{var s,l;const r=(s=e.order)!=null?s:1;return((l=o.order)!=null?l:1)-r})}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,o,r))return!0}return!1}handleAfterInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,o,r))return!0}return!1}handleBeforeKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,o,r,i){Sg(this.editor,i)}defaultHandleKeydown(t,e){return jA(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await tD(this.editor,t,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,e,t))return}const o=nD(t);if(!!o){await this.pasteDoc(o);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPaste&&await i.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function sD(n,t,e){const o=Nr(t,e);return o.remove(),o}S("copy-dom-attributes");const WA=["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 lD(n,t){for(let l=0;l<WA.length;l++){const a=WA[l];t[a]=n[a]}const e=n.attributes,o=t.attributes,r=[],i=[];for(let l=0;l<e.length;l++){const a=e[l],d=o.getNamedItem(a.name);d?d.value!==a.value&&(d.value=a.value,i.push(a)):r.push(a)}const s=[];for(let l=0;l<o.length;l++){const a=o[l];e.getNamedItem(a.name)||s.push(a)}r.forEach(l=>{t.setAttribute(l.name,l.value)}),i.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function qA(n){const t=Array.from(n.childNodes).filter(e=>!z5(e));return t.forEach(e=>{e.remove()}),t}function GA(n,t,e){var d;const o=n.getContainerById(t),r=Nr(o,e),i=Ri(r),s=n.doc.getBlockData(t,e),l=Jt(n,r);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const h=n.editorBlocks.createBlock(i,o,s),p=qA(h);qA(r),p.forEach(v=>{r.appendChild(v)});const C=oh(h);if(C){const v=oh(r);v&&v.remove(),r.appendChild(C)}lD(h,r)}l4(n,r,s),n.blockHooks.forEach(h=>{var p;(p=h.update)==null||p.call(h,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const cD=S("transform-selection");function ZA(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;g(cD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const d=ln.transformCursor(i.offset,e,o);l=st(t,d,"normal")}let a=s;if(s.blockId===t){const d=ln.transformCursor(s.offset,e,o);a=st(t,d,"normal")}return ze(n,{anchor:l,focus:a})}const aD=S("handle-block-text-changed");function uD(n,t,e,o,r){const i=n.getContainerById(t),s=Nr(i,e),l=n.doc.getBlockData(t,e);if(g(aD,l.text,"no block text"),e4(n,s).setBlockText(n,s,l.text),!r){const a=ZA(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function dD(n,t){const e=mt.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function QA(n,t,e,o){const r=Jt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function hD(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{QA(n,i,o,{child:!0})}),QA(n,r,o,{child:!1})}const Fo=S("editor-doc");class fD extends ha{constructor(e,o,r){super();m(this,"localEvents",[]);this.editor=e,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}getBlockData(e,o){return this.externalDoc.getBlockData(e,o)}verifyBlockWritable(e,o){const r=this.editor.getBlockByIndex(e,o);g(Fo,this.editor.isBlockWritable(r),`block is not writable, ${e}, ${o}`)}localUpdateBlockText(e,o,r,i){g(Fo,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const s=this.getBlockData(e,o),l=s.text;g(Fo,l,`no text, ${e}, ${o}`);const a=ZA(this.editor,s.id,r,!0),d=ln.apply(l,r);this.localEvents.forEach(p=>p.onBeforeUpdateBlockText(e,s.id,l,d,a.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(a,i),h}localUpdateBlockData(e,o,r,i){g(Fo,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,o);if(!this.editor.isBlockWritable(s)){const h=Array.from(r.delete).filter(C=>C!=="comments"),p=Object.keys(r.insert).filter(C=>C!=="comments");(h.length>0||p.length>0)&&g(Fo,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=mt.default(this.getBlockData(e,o)),a=mt.default(dD(l,r));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,a,i));const d=this.externalDoc.localUpdateBlockData(e,o,r,i);return this.editor.selection.setRange(Oi(this.editor,i)),d}localInsertBlock(e,o,r,i,s){g(Fo,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(a=>a.onBeforeInsertBlock(e,o,r,i));const l=this.externalDoc.localInsertBlock(e,o,r,i);return s!=null&&s.noFocus||this.editor.selection.setRange(Oi(this.editor,i),s),l}localDeleteBlock(e,o,r){g(Fo,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const i=mt.default(this.getBlockData(e,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,o,i,r));const s=this.externalDoc.localDeleteBlock(e,o,r);return this.editor.selection.setRange(Oi(this.editor,r)),s}localDeleteChildContainers(e){return g(Fo,!this.editor.readonly,"editor is readonly"),e.forEach(o=>{const r=mt.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainers(e){g(Fo,!this.editor.readonly,"editor is readonly");const o=mt.default(e);o.forEach(r=>{this.localEvents.forEach(i=>i.onBeforeInsertChildContainer(r.containerId,r.blocks))}),this.externalDoc.localInsertChildContainers(o)}onRequestReload(e){Fo.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,o,r,i)}),uD(this.editor,e,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,i)}),GA(this.editor,e,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(e,o,r,i){this.callbacks.forEach(l=>{var a;return(a=l.onInsertBlock)==null?void 0:a.call(l,e,o,r,i)});const s=this.editor.getContainerById(e);XE(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){hD(this.editor,e,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,r)});const i=this.editor.getContainerById(e);sD(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(e,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,r)})}onDeleteChildContainer(e,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,e)})}onStatusChanged(e){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)})}onError(e){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,e)})}uploadResource(e,o){return this.externalDoc.uploadResource(e,o)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,o){return this.externalDoc.buildResourceUrl(e,o)}request(e,o){return this.externalDoc.request(e,o)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,o,r;return(r=(o=(e=this.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}reset(e){Fo.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function YA(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 tp=S("undo-action");class Jl{constructor(t,e,o){m(this,"beforeRange");m(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=o}undo(t){return!1}redo(t){return!1}combinable(t){return g(tp,t,"no other action"),!1}combine(t){g(tp,!1,"no other")}setAfterRange(t){this.afterRange&&tp.warn("after range has already set"),this.afterRange=t}}const mD=S("block-action");class JA extends Jl{constructor(e,o,r,i,s){super(e,o,s);m(this,"blockData");m(this,"blockIndex");this.blockData=mt.default(i),this.blockIndex=r}deleteBlock(e,o){if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);return i?(g(mD,this.blockIndex===bt(i),"invalid block index"),Dh(e,i,Oi(e,o)),!0):!1}insertBlock(e,o){return Zl(e,this.containerId,this.blockIndex,mt.default(this.blockData),o),!0}}const gD=S("insert-block-action");class pD extends JA{undo(t){return t.findBlockById(this.blockData.id)?this.deleteBlock(t,this.beforeRange):(gD.warn(`block (${this.blockData.blockId}) not found, deleted by others?`),!1)}redo(t){return this.insertBlock(t,this.afterRange)}}class CD extends JA{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class AD extends Jl{constructor(e){super(e,ct(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){YA(this.actions,e),this.afterRange=e.afterRange}undo(e){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(e)&&(o=!0)}),o}redo(e){let o=!1;return this.actions.forEach(r=>{r.redo(e)&&(o=!0)}),o}setAfterRange(e){this.afterRange=e;const o=this.actions[this.actions.length-1];!o||o instanceof Jl&&(o.afterRange||o.setAfterRange(e))}}const Hi=S("update-block-data-action");class jh extends Jl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeBlockData");m(this,"afterBlockData");m(this,"blockId");this.blockId=r,g(Hi,this.blockId===i.id,"invalid block id"),g(Hi,this.blockId===s.id,"invalid block id"),this.beforeBlockData=mt.default(i),this.afterBlockData=mt.default(s),g(Hi,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){if(!e.findBlockById(this.blockId))return Hi.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hi,r,"no container"),Mh(e,o,jh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){if(!e.findBlockById(this.blockId))return Hi.warn(`block (${this.blockId}) not found, deleted by others?`),!1;g(Hi,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hi,r,"no container"),Mh(e,o,jh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=mt.default(e);return delete o.id,delete o.type,o}}const ep=S("update-block-text-action");class Ua extends Jl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeRichTextData");m(this,"afterRichTextData");m(this,"blockId");m(this,"type");this.blockId=r,this.beforeRichTextData=mt.default(i),this.afterRichTextData=mt.default(s),this.type=Ua.calType(i,s)}static calType(e,o){g(ep,e,"no old data"),g(ep,o,"no new data");const i=ln.diff(e,o),s=new Set;let l=!1;const a=h=>A5(h)?`cjk_${h}`:p5(h)?"number":Zd(h)?"space":C5(h)?"letter":"unknown";let d=!1;return i.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_${a(h.insert.substr(1))}`)):s.add(`insert_${a(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Lh(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Lh(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof Ua)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const o=e.beforeRange,r=o.anchor;if(!r.isSimple())return!1;const i=this.afterRange;if(!i)return!1;const s=i.anchor;return!(!s.isSimple()||s.blockId!==o.anchor.blockId||s.offset!==r.offset)}combine(e){g(ep,e instanceof Ua,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class KA extends Jl{constructor(t,e,o){super(t,e,t.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(t){return t.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(t){return t.doc.localInsertChildContainers([{containerId:this.containerId,blocks:mt.default(this.blocks)}]),!0}}class bD extends KA{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class vD extends KA{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Po=S("undo");class yD{constructor(t){m(this,"editor");m(this,"actions",[]);m(this,"undoCursor");m(this,"currentGroup",null);m(this,"groupCounter",0);m(this,"undoRedoing",!1);m(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):(YA(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(g(Po,!this.currentGroup,"current group already exists"),this.currentGroup=new AD(this.editor),this.groupCounter=1):(g(Po,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Po,this.currentGroup,"current group not exists"),g(Po,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Po.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 Po.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(Oi(this.editor,t.beforeRange))}catch(e){Po.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(Oi(this.editor,e)):Po.warn("no after range")}catch(e){Po.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,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),ln.diff(o,r).length!==0&&this.addAction(new Ua(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new jh(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Po,e>=0,"invalid block index"),g(Po,o,"no block data"),this.addAction(new pD(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new CD(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new bD(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new vD(this.editor,t,e)))}}class kD{async fromData(t,e){const o=e.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class wD{constructor(){m(this,"converters",[]);m(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new kD)}prepareData(t){const e=new DataTransfer;for(let o=0;o<this.converterTypes.length;o++)e.setData(this.converterTypes[o],t.getData(this.converterTypes[o]));return e}async fromData(t,e,o){let r={};const i=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,i,o);l&&(r={...r,...l})}return r}addConverter(t){this.converters.push(t)}}class BD{constructor(t){m(this,"renders",[]);this.editor=t}registerRender(t){this.renders.push(t)}renderText(t,e){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,t,e);i.classes&&o.classes.push(...i.classes),i.attributes&&(o.attributes={...o.attributes,...i.attributes}),i.styles&&(o.styles={...o.styles,...i.styles})}}),o}renderBlock(t,e,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,e,o);s.classes&&r.classes.push(...s.classes),s.attributes&&(r.attributes={...r.attributes,...s.attributes}),s.styles&&(r.styles={...r.styles,...s.styles})}}),r}updateBlock(t,e,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,t,e,o,r)})}}class Ce extends ve.TypedEmitter{constructor(e){super();m(this,"hoveringBlock",null);m(this,"hoveringTextChild",null);m(this,"filters",[]);m(this,"finders",[]);m(this,"handleDocumentMouseMove",e=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,e))return}const o=document.elementFromPoint(e.x,e.y);if(!o){this.setHoveringBlock(null,e,null);return}let r=et(o);if((!r||!Qt(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(e),!r)){this.setHoveringBlock(null,e,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,e,i)});this.editor=e,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(e=>e.destroy()),this.filters=[],this.finders.forEach(e=>e.destroy()),this.finders=[]}addFilter(e){this.filters.push(e)}addFinder(e){this.finders.push(e)}hoveringBlockId(){return this.hoveringBlock?it(this.hoveringBlock):""}findBlockByFinders(e){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,e);if(i)return i}return null}setHoveringBlock(e,o,r){if(this.hoveringBlock===e&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==e){const s=this.hoveringBlock&&Qt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&rt(s,"hover"),e&&W(e,"hover"),this.hoveringBlock=e,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(e){return e.addCustom("standard-hovering-block",()=>new Ce(e))}getParentTextContentChild(e,o){if(!nt(this.editor,e))return null;const r=Lt(e);return o.parentElement===r?o:Hm(o)}}const XA="style-color-",tb="style-bg-color-";class ED{renderText(t,e,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(XA)?i["data-style-color"]=l.substring(XA.length):l.startsWith(tb)?i["data-style-bg-color"]=l.substring(tb.length):l.startsWith("style")&&r.push(l):typeof a=="string"&&(l==="link"&&(r.push("link"),i.link=a),l==="inline-style-color"&&(s.color=a))}),{classes:r,attributes:i,styles:s}}renderBlock(t,e,o){var l,a;const r={};Object.entries(o).filter(d=>d[0].startsWith("style-")).forEach(([d,h])=>{r[`data-${d}`]=`${h}`});const s=[];return((a=(l=t.selection)==null?void 0:l.range)==null?void 0:a.start.blockId)===o.id&&s.push("focused"),typeof o.align=="string"&&o.align&&(r["data-style-align"]=o.align),o.heading&&(r["data-style-heading"]=String(o.heading)),o.quoted&&(r["data-style-quoted"]="true"),Ce.get(t).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(t,e,o,r){var s,l;Array.from(o.attributes).forEach(a=>{a.name.startsWith("data-style-")&&o.removeAttribute(a.name)}),Object.entries(r).filter(a=>a[0].startsWith("style-")||a[0]==="align").forEach(([a,d])=>{a==="align"&&o.setAttribute(a.startsWith("style-")?`data-${a}`:`data-style-${a}`,`${d}`)}),((l=(s=t.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&W(o,"focused"),Ce.get(t).hoveringBlockId()===r.id&&W(o,"hover")}}function xD(n){n.editorBlocks.registerBlockClass(Dn),n.editorBlocks.registerBlockClass(x4),n.editorBoxes.registerBoxClass(g6),n.editorBoxes.registerBoxClass(p6),n.editorBoxes.registerBoxClass(b6),n.editorBoxes.registerBoxClass(v6),n.editorInsertions.registerInsertionClass(y6),n.editorBlockRenders.registerRender(new ED)}function ID(n,t){xD(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 eb=S("range-commands");function nb(n,t){n.forEach(e=>{e.source=t,e.children&&nb(e.children,t)})}function ob(n,t,e){const o=it(t);g(eb,o===e.start.blockId,"invalid start range"),g(eb,o===e.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,t,e);nb(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),Mt(n,t)&&Ms(n,t,e.start,e.end).forEach(l=>{me(l).forEach(d=>{const h=ut(n,d),p=ze(n,{anchor:st(d,0,"home"),focus:st(d,h,"end")}),C=ob(n,d,p);i.push(...C)})}),i}function rb(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=ze(t,{anchor:r.start,focus:r.end});ob(t,r.block,i).forEach(l=>{o.push(l)})}),o}function ib(n,t,e,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const C=s[p];if(C.beforeExecuteCommand&&C.beforeExecuteCommand(n,t,e,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),a={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,o,r,{}))return i[it(t)]=a,!0;let d=!1;return Mt(n,t)&&Ms(n,t,e.start,e.end).forEach(C=>{me(C).forEach(B=>{const D=ut(n,B),x=ze(n,{anchor:st(B,0,"home"),focus:st(B,D,"end")});ib(n,B,x,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,t,e,o,r,i)}),d}function sb(n,t,e){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(t.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,t,e,r)||n.getSelectedBlocks().forEach(l=>{const a=ze(o,{anchor:l.start,focus:l.end});ib(o,l.block,a,t,e,r)}),r}const TD=S("command-providers");class lb{constructor(t){m(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(o=>o.id===t);return g(TD,e,`no command provider, id=${t}`),e}getCommands(t){return rb(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>sb(t,e,o))}getEmptyBlockTextAttributes(t,e){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,t,e);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function DD(n,t){const e=ot(t),o=ct(e),r=bt(t);GA(n,o,r)}const SD=S("table-scroll");class cb{constructor(t,e,o,r,i){m(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=o,this.handler=r,this.data=i,e.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class LD{constructor(t){m(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(o=>o.destroy()),this.handlers.delete(t)})}addEventListener(t,e,o,r){const i=this.handlers.get(t);if(i){if(i.find(s=>s.handler===o&&s.name===e)){SD.warn(`event has already registered: ${e}`);return}i.push(new cb(this.editor,t,e,o,r))}else{const s=new cb(this.editor,t,e,o,r);this.handlers.set(t,[s])}}removeEventListener(t,e,o){if(!t){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const a=s[l];if(e)e===a.name&&o===a.handler&&s.splice(l,1);else if(o===a.handler){s.splice(l,1),a.destroy(),s.length===0&&this.handlers.delete(i);continue}}return}const r=this.handlers.get(t);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===e);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const o=this.handlers.get(t);if(o)if(e)for(let r=0;r<o.length;r++){const i=o[r];i.name===e&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(t)}}const ab=S("update-block-text");function MD(n,t){const e=n.getBoxById(t.id),o=et(e);g(ab,o,"no parent block"),g(ab,nt(n,o),"not a text block");const r=n.getBlockText(o),i=s6(r,"id",t.id,t);z6(n,o,i)}function RD(n,t){for(const e of n.blockHooks)if(e.writable){const o=e.writable(n,t);if(typeof o=="boolean")return o}return!0}function OD(n){if(n.readonly)return!1;const t=Oo(n);return!!n.isBlockWritable(t.map(e=>e.block))}class _D{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 FD{constructor(){m(this,"shortcuts",[])}handleKeyboardEvents(t,e){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(rr(e,s)){const a=l(t,e);if(a!==void 0)return a}}}}const Qr=S("editor");class PD extends ve.TypedEmitter{constructor(e,o,r){var i,s,l,a,d,h,p;super();m(this,"parent");m(this,"rootElement");m(this,"contentElement");m(this,"rootContainerObject");m(this,"rootContainer");m(this,"input");m(this,"selection");m(this,"selectionHandler");m(this,"doc");m(this,"id");m(this,"clientId");m(this,"compositingText","");m(this,"undoManager");m(this,"shortcuts",new FD);m(this,"dataConverter",new wD);m(this,"editorBlocks",new k4(this));m(this,"editorBoxes",new A6(this));m(this,"editorInsertions",new w6(this));m(this,"editorEmbeds",new B4(this));m(this,"editorDecorators",new B6(this));m(this,"editorCommandProviders",new lb(this));m(this,"editorBlockRenders",new BD(this));m(this,"blockHooks",[]);m(this,"domEvents",new LD(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new iD(this));m(this,"settingsProvider");m(this,"_readonly",!1);Qr.debug("create editor"),this.setMaxListeners(100),this.options={colors:(i=r==null?void 0:r.colors)!=null?i:["#9923E9","#4587C2","#8BDB7A","#FB28D3","#CBC619","#10FEEB","#812A1A","#8A3F25","#22D742","#A53E74","#555C87","#57E0AA"],componentsOptions:(l=(s=r==null?void 0:r.components)==null?void 0:s.options)!=null?l:{},scrollContainer:r==null?void 0:r.scrollContainer},this.settingsProvider=(a=r==null?void 0:r.settingsProvider)!=null?a:new _D(this),ID(this,r==null?void 0:r.components),this.blockHooks.push(...(h=(d=r==null?void 0:r.components)==null?void 0:d.blockHooks)!=null?h:[]),this.id=(p=r==null?void 0:r.id)!=null?p:K(),this.clientId=K(),this.undoManager=new yD(this),this.doc=new fD(this,o,this.undoManager),this.parent=e,this.rootElement=k("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=k("div",["editor-content"],this.rootElement),this.rootContainerObject=b4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new WI(this,this.inputHandlers),this.selection=new RT(this),this.selectionHandler=new FT(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),Ze.isMobile&&W(this.rootElement,"mobile"),Ze.isSafari&&W(this.rootElement,"safari"),this._readonly&&W(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?W(this.rootElement,"readonly"):rt(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:so(this.rootContainer)}addCustom(e,o){const r=this.customs.get(e);if(r)return r;const i=o(this);return this.customs.set(e,i),i}getCustom(e){const o=this.customs.get(e);return g(Qr,o,`${e} does not exists`),o}replaceCustom(e,o){const r=this.customs.get(e);return r&&r.destroy(),this.customs.set(e,o),o}findCustom(e){return this.customs.get(e)}findCustomByType(e){const o=this.customs.values();for(const r of o)if(r instanceof e)return r;return null}destroyCustom(e){const o=this.customs.get(e);o&&(this.customs.delete(e),o.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,o,r){return this.editorBlocks.createBlock(e,o,r)}createBox(e,o){return this.editorBoxes.createBox(e,o)}createInsertion(e,o){return this.editorInsertions.createInsertion(e,o)}destroy(){Qr.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(),setTimeout(()=>{W(this.rootElement,"active")})}focusToBlock(e,o){Fg(this,e,o)}isWritable(){return OD(this)}isBlockWritable(e){return RD(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return(!o||!Array.isArray(o))&&(g(Qr,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),g(Qr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`)),o}createChildContainer(e,o,r){return v4(this,e,o,r)}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 o=this.rootContainer.querySelector(`#${e}`);return o&&g(Qr,Bs(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(Qr,$m(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return g(Qr,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return g(Qr,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return Nr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return bt(o)}return bt(e)}getContainerById(e){return zr(this,e)}getParentContainer(e){return ot(e)}reloadBlock(e){DD(this,e)}contains(e){const o=e instanceof Element?e:e.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,o,r,i,s){const l={blockId:r.id,offset:0},a={anchor:l,focus:l};return Zl(this,e,o,r,i!=null?i:a,s)}insertEmbed(e,o,r,i,s){const l={id:K(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){Rg(this,e,o)}mergeTextBlock(e,o){return H6(this,e,o)}breakTextBlock(e,o,r){return Ql(this,e,o,r).newBlock}getTextPosition(){return ql(this)}getBlockString(e,o){const r=this.getBlockText(e);return ie(r,o)}getBlockData(e){return Pi(this,e)}getBoxData(e){return f6(this,e)}getBlockText(e){return pn(this,e)}setBlockText(e,o){z6(this,e,o)}deleteTextFromBlock(e,o,r,i){return Lg(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return R6(this,e,o,r,i)}insertBoxToBlock(e,o,r){return O6(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){q6(this,e,o,r,i)}insertDocAt(e,o,r,i){return $g(this,e,o,r,i)}deleteChildContainers(e){$6(this,e)}replaceBlockText(e,o){return Lh(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...a}=i;return Mh(this,e,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return V6(this,e,o,r)}updateBoxData(e){MD(this,e)}getSelectedText(){const e=_h(this);return Oa(this,e)}clearSelectedContents(){_g(this)}insertTextBlock(e,o,r,i){const s=ar(e!=null?e:"");return N6(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(e,o){if(e&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!o){F6(this);return}o?(this.compositingText="",pa()||Sg(this,e)):(this.compositingText=e,_6(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function za(n,t,e){return new PD(n,t,e)}function ND(n){const t=(o,r)=>{const i=o.findIndex(l=>l.id===r.id);if(i===-1){o.push(r);return}const s=o[i];if(s.value!==r.value){o.splice(i,1);return}if(!!s.states){if(!r.states){s.states=[];return}s.states=Cm.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const $D=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class Uh extends ve.TypedEmitter{constructor(e){super();m(this,"users",new Map);m(this,"cursors",new Map);m(this,"addingUser",!1);m(this,"colors");this.colors=e&&e.length>0?e:$D}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&aa.default(o,e))return;this.cursors.set(e.user.userId,e);const r=new Set([e.range.anchor.blockId,e.range.focus.blockId]),i=new Set(r);o&&new Set([o.range.anchor.blockId,o.range.focus.blockId]).forEach(l=>{r.has(l)||i.add(l)}),this.emit("remote-carets-change",[...i])}addUsers(e){this.addingUser=!0,e.forEach(o=>this.addUser(o)),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 o;return(o=this.users.get(e))!=null?o:null}removeUser(e){this.users.delete(e),this.emit("change",Array.from(this.users.values()));const o=this.cursors.get(e);if(o){const r=new Set(new Set([o==null?void 0:o.range.anchor.blockId,o==null?void 0:o.range.focus.blockId]));this.cursors.delete(e),this.emit("remote-carets-change",[...r])}}updateUsers(e){this.users.forEach(o=>{e.find(r=>r.userId===o.userId)||this.removeUser(o.userId)}),this.users.clear(),this.addingUser=!0;try{e.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e&&vh(r.range)).forEach(r=>{const i=r.range.focus.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(e){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===e||o.range.focus.blockId===e)}onUpdateBlockText(e,o,r){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(vh(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===e.id&&(a.offset=ln.transformCursor(a.offset,o,r)),d.blockId===e.id&&(d.offset=ln.transformCursor(d.offset,o,r))}})}getFixedUserColor(e,o){let r=0;Array.from(e).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const Xe=S("local-doc");class np extends ha{constructor(e,o){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[ar("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return mt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`);const i=r[o];return g(Xe,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(Xe,i.text,"no text for data");const s=ln.apply(i.text,r);return i.text=s,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockText)==null?void 0:a.call(l,e,o,r,!0)}),s}localUpdateBlockData(e,o,r){const i=this.getBlockData(e,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,!0)}),i}localInsertBlock(e,o,r){const i=this.getContainerBlocks(e);return g(Xe,i,`no container data: ${e}`),g(Xe,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,o,r,!0)}),r}localDeleteBlock(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`),g(Xe,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,!0)}),i}localInsertChildContainers(e){e.forEach(({containerId:o,blocks:r})=>{this.doc.blocks[o]=r,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,o,r,!0)})})}localDeleteChildContainers(e){Xe.debug(`delete child containers: ${e}`),e.forEach(o=>{g(Xe,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,o,!0)})})}uploadResource(e,o){g(Xe,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){g(Xe,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Uh}setDoc(e){this.doc=mt.default(e),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class HD{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function op(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new HD(o)})}const ub=S("find-block");function db(n,t){const e=Is(t);if(!e){if(lo(t))return null;const o=Es(t);return g(ub,o,"no parent block"),db(n,o)}return Mt(n,e)?zl(n,e,{visibleOnly:!0}):e}function hb(n,t){const e=Ts(t);if(!e){if(lo(t))return null;const o=Es(t);return g(ub,o,"no parent block"),hb(n,o)}return Mt(n,e)?tg(n,e,{visibleOnly:!0}):e}const jD=S("remote-cursor");class UD{constructor(){m(this,"remoteUsers",new Uh)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):jD.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 zD(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function VD(n){const{blocks:t,meta:e,comments:o}=n,{root:r,...i}=t;return{blocks:r,meta:e,comments:o,...i}}function Va(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=zD(mt.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function ji(n){return n==="root"?"blocks":n}function Kl(n){return n==="blocks"?"root":n}const WD={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new on.default(n)},apply(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},compose(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},diff(n,t){const e=new on.default(n),o=new on.default(t);return e.diff(o).ops},transform(n,t,e){const o=new on.default(n);return new on.default(t).transform(o,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 o=new on.default(t),r=this.transformCursor(n.index,o,e),i=this.transformCursor(n.index+n.length,o,e);return{...n,index:r,length:i-r}}}};var dr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ui={},rp=Q3.default.EventEmitter;Ui.EventEmitter=rp,Ui.mixin=qD;function qD(n){for(var t in rp.prototype)n.prototype[t]=rp.prototype[t]}var fb=["info","warn","error"];function mb(){var n={};fb.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var GD=mb;mb.prototype.setMethods=function(n){n=n||{};var t=this;fb.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var ZD=GD,QD=new ZD,gb=QD;function $s(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,$s):this.stack=new Error().stack}$s.prototype=Object.create(Error.prototype),$s.prototype.constructor=$s,$s.prototype.name="ShareDBError",$s.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 zh=$s,Wa={},pb=YD;function YD(n,t,e,o){var r=function(s,l,a,d){t(a,s,l,"left"),t(d,l,s,"right")},i=n.transformX=function(s,l){e(s),e(l);for(var a=[],d=0;d<l.length;d++){for(var h=l[d],p=[],C=0;C<s.length;){var v=[];if(r(s[C],h,p,v),C++,v.length===1)h=v[0];else if(v.length===0){for(var B=C;B<s.length;B++)o(p,s[B]);h=null;break}else{for(var D=i(s.slice(C),v),x=0;x<D[0].length;x++)o(p,D[0][x]);for(var _=0;_<D[1].length;_++)o(a,D[1][_]);h=null;break}}h!=null&&o(a,h),s=p}return[s,a]};n.transform=function(s,l,a){if(!(a==="left"||a==="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],a):a==="left"?i(s,l)[0]:i(l,s)[1]}}var Cb={exports:{}},zi=Cb.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||""}},ip=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},sp=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")},Vh=function(n){for(var t=0;t<n.length;t++)sp(n[t])};zi.apply=function(n,t){var e;Vh(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=ip(n,r.p,r.i);else{if(e=n.slice(r.p,r.p+r.d.length),r.d!==e)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+e+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var Yr=zi._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:ip(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:ip(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};zi.compose=function(n,t){Vh(n),Vh(t);for(var e=n.slice(),o=0;o<t.length;o++)Yr(e,t[o]);return e},zi.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=0),Yr(t,o)}return t};var lp=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};zi.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=lp(n,t[r],o);return n};var JD=zi._tc=function(n,t,e,o){if(sp(t),sp(e),t.i!=null)Yr(n,{i:t.i,p:lp(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(Yr(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&Yr(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)Yr(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)Yr(n,t);else{var i={d:"",p:t.p};t.p<e.p&&(i.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(i.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),a=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(a!==d)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=lp(i.p,e),Yr(n,i))}return n},KD=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};zi.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=KD(n[t]);return n},pb(zi,JD,Vh,Yr);var Wh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},XD=function(n){return!!n&&n.constructor===Object},No=function(n){return JSON.parse(JSON.stringify(n))},It={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Jr={};It.registerSubtype=function(n){Jr[n.name]=n},It.create=function(n){return n===void 0?null:No(n)},It.invertComponent=function(n){var t={p:n.p};return n.t&&Jr[n.t]&&(t.t=n.t,t.o=Jr[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},It.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(It.invertComponent(t[o]));return e},It.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Wh(n[t].p))throw new Error("Missing path")},It.checkList=function(n){if(!Wh(n))throw new Error("Referenced element not a list")},It.checkObj=function(n){if(!XD(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function qa(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 Ga(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}It.apply=function(n,t){It.checkValidOp(t),t=No(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&qa(r);for(var i=null,s=e,l="data",a=0;a<r.p.length;a++){var d=r.p[a];if(i=s,s=s[l],l=d,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Jr[r.t])s[l]=Jr[r.t].apply(s[l],r.o);else if(r.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=r.na}else if(r.li!==void 0&&r.ld!==void 0)It.checkList(s),s[l]=r.li;else if(r.li!==void 0)It.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)It.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(It.checkList(s),r.lm!=l){var h=s[l];s.splice(l,1),s.splice(r.lm,0,h)}}else if(r.oi!==void 0)It.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)It.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},It.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},It.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=It.apply(n,r),e(r,n)}return n};var tS=It.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==t[o]&&(!e||o!==n.length-1))return!1;return!0};It.append=function(n,t){if(t=No(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)&&(qa(t),qa(e)),tS(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Jr[t.t]){if(e.o=Jr[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var o=t.p,r=0;r<e.o.length-1;r++)t.o=[e.o.pop()],t.p=o.slice(),Ga(t),n.push(t);Ga(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)&&(Ga(t),Ga(e)),n.push(t)},It.compose=function(n,t){It.checkValidOp(n),It.checkValidOp(t);for(var e=No(n),o=0;o<t.length;o++)It.append(e,t[o]);return e},It.normalize=function(n){var t=[];n=Wh(n)?n:[n];for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=[]),It.append(t,o)}return t},It.commonLengthForOps=function(n,t){var e=n.p.length,o=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&o++,e===0)return-1;if(o===0)return null;e--,o--;for(var r=0;r<e;r++){var i=n.p[r];if(r>=o||i!==t.p[r])return null}return e},It.canOpAffectPath=function(n,t){return It.commonLengthForOps({p:t},n)!=null},It.transformComponent=function(n,t,e,o){t=No(t);var r=It.commonLengthForOps(e,t),i=It.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,i!=null&&l>s&&t.p[i]==e.p[i]){if(t.ld!==void 0){var a=No(e);a.p=a.p.slice(s),t.ld=It.apply(No(t.ld),[a])}else if(t.od!==void 0){var a=No(e);a.p=a.p.slice(s),t.od=It.apply(No(t.od),[a])}}if(r!=null){var d=s==l,a=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(qa(t),a=No(e),qa(a)),a.t&&Jr[a.t]){if(t.t&&t.t===a.t){var h=Jr[t.t].transform(t.o,a.o,o);if(t.si!=null||t.sd!=null)for(var p=t.p,C=0;C<h.length;C++)t.o=[h[C]],t.p=p.slice(),Ga(t),It.append(n,t);else(!Wh(h)||h.length>0)&&(t.o=h,It.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[r]===t.p[r])if(d){if(t.ld!==void 0)if(t.li!==void 0&&o==="left")t.ld=No(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[r]===e.p[r]?o==="right"&&t.p[r]++:e.p[r]<=t.p[r]&&t.p[r]++,t.lm!==void 0&&d&&e.p[r]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[r]===t.p[r])return n;var p=e.p[r],v=t.p[r],B=t.lm;(p<B||p===B&&v<B)&&t.lm--}if(e.p[r]<t.p[r])t.p[r]--;else if(e.p[r]===t.p[r]){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 v=t.p[r],B=t.lm,D=e.p[r],x=e.lm;if(D!==x)if(v===D)if(o==="left")t.p[r]=x,v===B&&(t.lm=x);else return n;else v>D&&t.p[r]--,v>x?t.p[r]++:v===x&&D>x&&(t.p[r]++,v===B&&t.lm++),(B>D||B===D&&B>v)&&t.lm--,B>x?t.lm++:B===x&&(x>D&&B>v||x<D&&B<v?o==="right"&&t.lm++:B>v?t.lm++:B===D&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var v=e.p[r],B=e.lm;p=t.p[r],p>v&&t.p[r]--,p>B&&t.p[r]++}else{var v=e.p[r],B=e.lm;p=t.p[r],p===v?t.p[r]=B:(p>v&&t.p[r]--,(p>B||p===B&&v>B)&&t.p[r]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[r]===e.p[r])if(t.oi!==void 0&&d){if(o==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[r]===e.p[r])if(o==="left")It.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[r]==e.p[r]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return It.append(n,t),n},pb(It,It.transformComponent,It.checkValidOp,It.append);var eS=Cb.exports;It.registerSubtype(eS);var nS=It,oS={type:nS};(function(n){n.defaultType=oS.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)})(Wa);var $o={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var o 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],o=1;o<arguments.length;o++){var r=arguments[o];e=e[r]||(o===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];e=e[i]||(e[i]=r===arguments.length-2?o():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],o=[e],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!e.hasOwnProperty(i))break;e=e[i],o.push(e)}for(var r=o.length-1;r>=0;r--){var s=o[r],i=arguments[r+1],l=s[i];(r===o.length-1||!n.hasKeys(l))&&delete s[i]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,o){var r=!1;return e.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];setTimeout(function(){e.apply(null,o)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})($o);var Ab=Array.isArray,bb=Object.keys,rS=Object.prototype.hasOwnProperty,iS=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=Ab(t),r=Ab(e),i,s,l;if(o&&r){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!n(t[i],e[i]))return!1;return!0}if(o!=r)return!1;var a=t instanceof Date,d=e instanceof Date;if(a!=d)return!1;if(a&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,p=e instanceof RegExp;if(h!=p)return!1;if(h&&p)return t.toString()==e.toString();var C=bb(t);if(s=C.length,s!==bb(e).length)return!1;for(i=s;i--!==0;)if(!rS.call(e,C[i]))return!1;for(i=s;i--!==0;)if(l=C[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},vb=Ui,sS=gb,qn=zh,qh=Wa,Ho=$o,lS=Ho.clone,cS=iS,Sn=qn.CODES,aS=Ft;function Ft(n,t,e){vb.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}vb.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=qh.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new qn(Sn.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 qn(Sn.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 qn(Sn.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 o=n.type===void 0?qh.defaultType:n.type;this._setType(o),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;Ho.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===Sn.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 o=this.inflightFetch.shift();if(o&&e.push(o),e.length&&(o=function(r){Ho.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},Ft.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],e.callback&&o.push(e.callback);var r;if(o.length&&(r=function(i){Ho.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Sn.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=Gh(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Gh(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},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);uS(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,o=e&&e.wantSubscribe===n;if(o){e.callback=dS([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;Ho.nextTick(function(){n._handleSubscribe()})}}};function uS(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function dS(n){return n=n.filter(Ho.truthy),n.length?function(t){Ho.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function hS(n){delete n.op,delete n.create,delete n.del}function Gh(n,t){if(n.del)return hS(t);if(t.del)return new qn(Sn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new qn(Sn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new qn(Sn.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 o=n.type.transform(n.op,t.op,"left"),r=n.type.transform(t.op,n.op,"right");n.op=o,t.op=r}}}Ft.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new qn(Sn.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===qh.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Gh(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.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 a=this.data;this._setType(null),this.emit("del",a,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 qn(Sn.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>=Ho.MAX_SAFE_INTEGER)return this.emit("error",new qn(Sn.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 o=new qn(Sn.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(i){return this._hardRollback(i)}var r=this;Ho.nextTick(function(){r.flush()})},Ft.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.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 o=this.pendingOps.splice(e),e=0;e<o.length;e++){var t=o[e],r=this._tryCompose(t);r?r.callbacks=r.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&&!cS(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 o={op:n},r=t&&t.source;this._submit(o,r,e)},Ft.prototype.create=function(n,t,e,o){if(typeof t=="function"?(o=t,e=null,t=null):typeof e=="function"&&(o=e,e=null),t||(t=qh.defaultType.uri),this.type){var r=new qn(Sn.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:t,data:n}},s=e&&e.source;this._submit(i,s,o)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new qn(Sn.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var o={del:!0},r=n&&n.source;this._submit(o,r,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:lS(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 sS.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 o=Gh(this.pendingOps[e],t);if(o)return this._hardRollback(o)}try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}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 o=!!t.length,r=0;r<t.length;r++)o=Ho.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=Ho.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var Hs={};Hs.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 yb=Ui,kb=Hs.ACTIONS,fS=$o,mS=Ln;function Ln(n,t,e,o,r,i,s){yb.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=o,this.query=r,this.results=null,i&&i.results&&(this.results=i.results,delete i.results),this.extra=void 0,this.options=i,this.callback=s,this.ready=!1,this.sent=!1}yb.mixin(Ln),Ln.prototype.hasPending=function(){return!this.ready},Ln.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 o=this.results[e];t.push([o.id,o.version])}n.r=t}this.connection.send(n),this.sent=!0}},Ln.prototype.destroy=function(n){this.connection.canSend&&this.action===kb.querySubscribe&&this.connection.send({a:kb.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&fS.nextTick(n)},Ln.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Ln.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Ln.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Ln.prototype._handleResponse=function(n,t,e){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!t)return this._finishResponse(null,o);var r=this,i=1,s=function(h){if(h)return r._finishResponse(h,o);--i||r._finishResponse(null,o)};if(Array.isArray(t))i+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){i++;var a=t[l],d=this.connection.get(a.c||this.collection,l);d.ingestSnapshot(a,s)}s()},Ln.prototype._ingestSnapshots=function(n,t){for(var e=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,t),e.push(i)}return e},Ln.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)},Ln.prototype._handleError=function(n){this.emit("error",n)},Ln.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 o=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(o)),this.emit("insert",o,e.index);break;case"remove":var i=e.howMany||1,r=this.results.splice(e.index,i);this.emit("remove",r,e.index);break;case"move":var i=e.howMany||1,s=this.results.splice(e.from,i);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)},Ln.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var wb=Ui,gS=Hs.ACTIONS,pS=$o,Bb=hr;function hr(n,t){if(wb.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={}}wb.mixin(hr),hr.prototype.submit=function(n,t){this.value=n,this.send(t)},hr.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},hr.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()})},hr.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},hr.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},hr.prototype._message=function(){return{a:gS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},hr.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},hr.prototype._callbackOrEmit=function(n,t){if(t)return pS.nextTick(t,n);n&&this.emit("error",n)};var CS=$o,Eb=cp;function cp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}cp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},cp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&CS.nextTick(n)};var ap={exports:{}};(function(n,t){(function(e,o){o(t)})(dr,function(e){function o(w,T){T=T|0;for(var M=Math.max(w.length-T,0),F=Array(M),U=0;U<M;U++)F[U]=w[T+U];return F}var r=function(w){var T=o(arguments,1);return function(){var M=o(arguments);return w.apply(null,T.concat(M))}},i=function(w){return function(){var T=o(arguments),M=T.pop();w.call(this,T,M)}};function s(w){var T=typeof w;return w!=null&&(T=="object"||T=="function")}var l=typeof setImmediate=="function"&&setImmediate,a=typeof process=="object"&&typeof process.nextTick=="function";function d(w){setTimeout(w,0)}function h(w){return function(T){var M=o(arguments,1);w(function(){T.apply(null,M)})}}var p;l?p=setImmediate:a?p=process.nextTick:p=d;var C=h(p);function v(w){return i(function(T,M){var F;try{F=w.apply(this,T)}catch(U){return M(U)}s(F)&&typeof F.then=="function"?F.then(function(U){B(M,null,U)},function(U){B(M,U.message?U:new Error(U))}):M(null,F)})}function B(w,T,M){try{w(T,M)}catch(F){C(D,F)}}function D(w){throw w}var x=typeof Symbol=="function";function _(w){return x&&w[Symbol.toStringTag]==="AsyncFunction"}function R(w){return _(w)?v(w):w}function H(w){return function(T){var M=o(arguments,1),F=i(function(U,j){var G=this;return w(T,function(J,lt){R(J).apply(G,U.concat(lt))},j)});return M.length?F.apply(this,M):F}}var z=typeof dr=="object"&&dr&&dr.Object===Object&&dr,Z=typeof self=="object"&&self&&self.Object===Object&&self,tt=z||Z||Function("return this")(),ft=tt.Symbol,vt=Object.prototype,zt=vt.hasOwnProperty,Ht=vt.toString,Xt=ft?ft.toStringTag:void 0;function qe(w){var T=zt.call(w,Xt),M=w[Xt];try{w[Xt]=void 0;var F=!0}catch{}var U=Ht.call(w);return F&&(T?w[Xt]=M:delete w[Xt]),U}var Yn=Object.prototype,He=Yn.toString;function Rn(w){return He.call(w)}var Er="[object Null]",kn="[object Undefined]",an=ft?ft.toStringTag:void 0;function xr(w){return w==null?w===void 0?kn:Er:an&&an in Object(w)?qe(w):Rn(w)}var ii="[object AsyncFunction]",Ao="[object Function]",eC="[object GeneratorFunction]",nC="[object Proxy]";function oC(w){if(!s(w))return!1;var T=xr(w);return T==Ao||T==eC||T==ii||T==nC}var ns=9007199254740991;function nl(w){return typeof w=="number"&&w>-1&&w%1==0&&w<=ns}function ol(w){return w!=null&&nl(w.length)&&!oC(w)}var si={};function Nt(){}function Ir(w){return function(){if(w!==null){var T=w;w=null,T.apply(this,arguments)}}}var os=typeof Symbol=="function"&&Symbol.iterator,Fc=function(w){return os&&w[os]&&w[os]()};function u1(w,T){for(var M=-1,F=Array(w);++M<w;)F[M]=T(M);return F}function un(w){return w!=null&&typeof w=="object"}var rl="[object Arguments]";function d1(w){return un(w)&&xr(w)==rl}var bo=Object.prototype,h1=bo.hasOwnProperty,rC=bo.propertyIsEnumerable,il=d1(function(){return arguments}())?d1:function(w){return un(w)&&h1.call(w,"callee")&&!rC.call(w,"callee")},Ae=Array.isArray;function sl(){return!1}var ll=typeof e=="object"&&e&&!e.nodeType&&e,f1=ll&&!0&&n&&!n.nodeType&&n,cl=f1&&f1.exports===ll,m1=cl?tt.Buffer:void 0,al=m1?m1.isBuffer:void 0,rs=al||sl,Wu=9007199254740991,qu=/^(?:0|[1-9]\d*)$/;function Gu(w,T){var M=typeof w;return T=T==null?Wu:T,!!T&&(M=="number"||M!="symbol"&&qu.test(w))&&w>-1&&w%1==0&&w<T}var Zu="[object Arguments]",Qu="[object Array]",Yu="[object Boolean]",Ju="[object Date]",Ku="[object Error]",Xu="[object Function]",iC="[object Map]",sC="[object Number]",lC="[object Object]",g1="[object RegExp]",p1="[object Set]",cC="[object String]",aC="[object WeakMap]",uC="[object ArrayBuffer]",dC="[object DataView]",C1="[object Float32Array]",hC="[object Float64Array]",fC="[object Int8Array]",mC="[object Int16Array]",td="[object Int32Array]",gC="[object Uint8Array]",ed="[object Uint8ClampedArray]",pC="[object Uint16Array]",CC="[object Uint32Array]",le={};le[C1]=le[hC]=le[fC]=le[mC]=le[td]=le[gC]=le[ed]=le[pC]=le[CC]=!0,le[Zu]=le[Qu]=le[uC]=le[Yu]=le[dC]=le[Ju]=le[Ku]=le[Xu]=le[iC]=le[sC]=le[lC]=le[g1]=le[p1]=le[cC]=le[aC]=!1;function AC(w){return un(w)&&nl(w.length)&&!!le[xr(w)]}function bC(w){return function(T){return w(T)}}var A1=typeof e=="object"&&e&&!e.nodeType&&e,ul=A1&&!0&&n&&!n.nodeType&&n,vC=ul&&ul.exports===A1,Pc=vC&&z.process,b1=function(){try{var w=ul&&ul.require&&ul.require("util").types;return w||Pc&&Pc.binding&&Pc.binding("util")}catch{}}(),v1=b1&&b1.isTypedArray,yC=v1?bC(v1):AC,kC=Object.prototype,wC=kC.hasOwnProperty;function BC(w,T){var M=Ae(w),F=!M&&il(w),U=!M&&!F&&rs(w),j=!M&&!F&&!U&&yC(w),G=M||F||U||j,J=G?u1(w.length,String):[],lt=J.length;for(var pt in w)(T||wC.call(w,pt))&&!(G&&(pt=="length"||U&&(pt=="offset"||pt=="parent")||j&&(pt=="buffer"||pt=="byteLength"||pt=="byteOffset")||Gu(pt,lt)))&&J.push(pt);return J}var Nc=Object.prototype;function EC(w){var T=w&&w.constructor,M=typeof T=="function"&&T.prototype||Nc;return w===M}function $c(w,T){return function(M){return w(T(M))}}var xC=$c(Object.keys,Object),IC=Object.prototype,TC=IC.hasOwnProperty;function y1(w){if(!EC(w))return xC(w);var T=[];for(var M in Object(w))TC.call(w,M)&&M!="constructor"&&T.push(M);return T}function Hc(w){return ol(w)?BC(w):y1(w)}function k1(w){var T=-1,M=w.length;return function(){return++T<M?{value:w[T],key:T}:null}}function DC(w){var T=-1;return function(){var F=w.next();return F.done?null:(T++,{value:F.value,key:T})}}function SC(w){var T=Hc(w),M=-1,F=T.length;return function U(){var j=T[++M];return j==="__proto__"?U():M<F?{value:w[j],key:j}:null}}function LC(w){if(ol(w))return k1(w);var T=Fc(w);return T?DC(T):SC(w)}function vo(w){return function(){if(w===null)throw new Error("Callback was already called.");var T=w;w=null,T.apply(this,arguments)}}function dl(w){return function(T,M,F){if(F=Ir(F||Nt),w<=0||!T)return F(null);var U=LC(T),j=!1,G=0,J=!1;function lt(at,At){if(G-=1,at)j=!0,F(at);else{if(At===si||j&&G<=0)return j=!0,F(null);J||pt()}}function pt(){for(J=!0;G<w&&!j;){var at=U();if(at===null){j=!0,G<=0&&F(null);return}G+=1,M(at.value,at.key,vo(lt))}J=!1}pt()}}function Tr(w,T,M,F){dl(T)(w,R(M),F)}function je(w,T){return function(M,F,U){return w(M,T,F,U)}}function nd(w,T,M){M=Ir(M||Nt);var F=0,U=0,j=w.length;j===0&&M(null);function G(J,lt){J?M(J):(++U===j||lt===si)&&M(null)}for(;F<j;F++)T(w[F],F,vo(G))}var MC=je(Tr,1/0),Zo=function(w,T,M){var F=ol(w)?nd:MC;F(w,R(T),M)};function Qo(w){return function(T,M,F){return w(Zo,T,R(M),F)}}function od(w,T,M,F){F=F||Nt,T=T||[];var U=[],j=0,G=R(M);w(T,function(J,lt,pt){var at=j++;G(J,function(At,Zt){U[at]=Zt,pt(At)})},function(J){F(J,U)})}var jc=Qo(od),rd=H(jc);function li(w){return function(T,M,F,U){return w(dl(M),T,R(F),U)}}var Dr=li(od),id=je(Dr,1),sd=H(id);function is(w,T){for(var M=-1,F=w==null?0:w.length;++M<F&&T(w[M],M,w)!==!1;);return w}function ld(w){return function(T,M,F){for(var U=-1,j=Object(T),G=F(T),J=G.length;J--;){var lt=G[w?J:++U];if(M(j[lt],lt,j)===!1)break}return T}}var ss=ld();function ls(w,T){return w&&ss(w,T,Hc)}function w1(w,T,M,F){for(var U=w.length,j=M+(F?1:-1);F?j--:++j<U;)if(T(w[j],j,w))return j;return-1}function RC(w){return w!==w}function B1(w,T,M){for(var F=M-1,U=w.length;++F<U;)if(w[F]===T)return F;return-1}function hl(w,T,M){return T===T?B1(w,T,M):w1(w,RC,M)}var Uc=function(w,T,M){typeof T=="function"&&(M=T,T=null),M=Ir(M||Nt);var F=Hc(w),U=F.length;if(!U)return M(null);T||(T=U);var j={},G=0,J=!1,lt=Object.create(null),pt=[],at=[],At={};ls(w,function(he,re){if(!Ae(he)){Zt(re,[he]),at.push(re);return}var pe=he.slice(0,he.length-1),ko=pe.length;if(ko===0){Zt(re,he),at.push(re);return}At[re]=ko,is(pe,function(E){if(!w[E])throw new Error("async.auto task `"+re+"` has a non-existent dependency `"+E+"` in "+pe.join(", "));en(E,function(){ko--,ko===0&&Zt(re,he)})})}),e3(),De();function Zt(he,re){pt.push(function(){yo(he,re)})}function De(){if(pt.length===0&&G===0)return M(null,j);for(;pt.length&&G<T;){var he=pt.shift();he()}}function en(he,re){var pe=lt[he];pe||(pe=lt[he]=[]),pe.push(re)}function Fn(he){var re=lt[he]||[];is(re,function(pe){pe()}),De()}function yo(he,re){if(!J){var pe=vo(function(E,Mr){if(G--,arguments.length>2&&(Mr=o(arguments,1)),E){var ds={};ls(j,function(Pn,Pt){ds[Pt]=Pn}),ds[he]=Mr,J=!0,lt=Object.create(null),M(E,ds)}else j[he]=Mr,Fn(he)});G++;var ko=R(re[re.length-1]);re.length>1?ko(j,pe):ko(pe)}}function e3(){for(var he,re=0;at.length;)he=at.pop(),re++,is(n3(he),function(pe){--At[pe]===0&&at.push(pe)});if(re!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function n3(he){var re=[];return ls(w,function(pe,ko){Ae(pe)&&hl(pe,he,0)>=0&&re.push(ko)}),re}};function ci(w,T){for(var M=-1,F=w==null?0:w.length,U=Array(F);++M<F;)U[M]=T(w[M],M,w);return U}var OC="[object Symbol]";function _C(w){return typeof w=="symbol"||un(w)&&xr(w)==OC}var FC=1/0,cd=ft?ft.prototype:void 0,E1=cd?cd.toString:void 0;function ad(w){if(typeof w=="string")return w;if(Ae(w))return ci(w,ad)+"";if(_C(w))return E1?E1.call(w):"";var T=w+"";return T=="0"&&1/w==-FC?"-0":T}function PC(w,T,M){var F=-1,U=w.length;T<0&&(T=-T>U?0:U+T),M=M>U?U:M,M<0&&(M+=U),U=T>M?0:M-T>>>0,T>>>=0;for(var j=Array(U);++F<U;)j[F]=w[F+T];return j}function NC(w,T,M){var F=w.length;return M=M===void 0?F:M,!T&&M>=F?w:PC(w,T,M)}function ud(w,T){for(var M=w.length;M--&&hl(T,w[M],0)>-1;);return M}function $C(w,T){for(var M=-1,F=w.length;++M<F&&hl(T,w[M],0)>-1;);return M}function HC(w){return w.split("")}var jC="\\ud800-\\udfff",UC="\\u0300-\\u036f",zC="\\ufe20-\\ufe2f",ce="\\u20d0-\\u20ff",oe=UC+zC+ce,VC="\\ufe0e\\ufe0f",WC="\\u200d",qC=RegExp("["+WC+jC+oe+VC+"]");function GC(w){return qC.test(w)}var x1="\\ud800-\\udfff",ZC="\\u0300-\\u036f",I1="\\ufe20-\\ufe2f",QC="\\u20d0-\\u20ff",Ge=ZC+I1+QC,dd="\\ufe0e\\ufe0f",ai="["+x1+"]",zc="["+Ge+"]",fl="\\ud83c[\\udffb-\\udfff]",On="(?:"+zc+"|"+fl+")",hd="[^"+x1+"]",fd="(?:\\ud83c[\\udde6-\\uddff]){2}",md="[\\ud800-\\udbff][\\udc00-\\udfff]",T1="\\u200d",gd=On+"?",pd="["+dd+"]?",wn="(?:"+T1+"(?:"+[hd,fd,md].join("|")+")"+pd+gd+")*",YC=pd+gd+wn,_n="(?:"+[hd+zc+"?",zc,fd,md,ai].join("|")+")",JC=RegExp(fl+"(?="+fl+")|"+_n+YC,"g");function D1(w){return w.match(JC)||[]}function Yo(w){return GC(w)?D1(w):HC(w)}function Vc(w){return w==null?"":ad(w)}var Cd=/^\s+|\s+$/g;function de(w,T,M){if(w=Vc(w),w&&(M||T===void 0))return w.replace(Cd,"");if(!w||!(T=ad(T)))return w;var F=Yo(w),U=Yo(T),j=$C(F,U),G=ud(F,U)+1;return NC(F,j,G).join("")}var Sr=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,Ad=/,/,KC=/(=.+)?(\s*)$/,bd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function XC(w){return w=w.toString().replace(bd,""),w=w.match(Sr)[2].replace(" ",""),w=w?w.split(Ad):[],w=w.map(function(T){return de(T.replace(KC,""))}),w}function S1(w,T){var M={};ls(w,function(F,U){var j,G=_(F),J=!G&&F.length===1||G&&F.length===0;if(Ae(F))j=F.slice(0,-1),F=F[F.length-1],M[U]=j.concat(j.length>0?lt:F);else if(J)M[U]=F;else{if(j=XC(F),F.length===0&&!G&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");G||j.pop(),M[U]=j.concat(lt)}function lt(pt,at){var At=ci(j,function(Zt){return pt[Zt]});At.push(at),R(F).apply(null,At)}}),Uc(M,T)}function Jn(){this.head=this.tail=null,this.length=0}function vd(w,T){w.length=1,w.head=w.tail=T}Jn.prototype.removeLink=function(w){return w.prev?w.prev.next=w.next:this.head=w.next,w.next?w.next.prev=w.prev:this.tail=w.prev,w.prev=w.next=null,this.length-=1,w},Jn.prototype.empty=function(){for(;this.head;)this.shift();return this},Jn.prototype.insertAfter=function(w,T){T.prev=w,T.next=w.next,w.next?w.next.prev=T:this.tail=T,w.next=T,this.length+=1},Jn.prototype.insertBefore=function(w,T){T.prev=w.prev,T.next=w,w.prev?w.prev.next=T:this.head=T,w.prev=T,this.length+=1},Jn.prototype.unshift=function(w){this.head?this.insertBefore(this.head,w):vd(this,w)},Jn.prototype.push=function(w){this.tail?this.insertAfter(this.tail,w):vd(this,w)},Jn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},Jn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},Jn.prototype.toArray=function(){for(var w=Array(this.length),T=this.head,M=0;M<this.length;M++)w[M]=T.data,T=T.next;return w},Jn.prototype.remove=function(w){for(var T=this.head;T;){var M=T.next;w(T)&&this.removeLink(T),T=M}return this};function ml(w,T,M){if(T==null)T=1;else if(T===0)throw new Error("Concurrency must not be zero");var F=R(w),U=0,j=[],G=!1;function J(At,Zt,De){if(De!=null&&typeof De!="function")throw new Error("task callback must be a function");if(at.started=!0,Ae(At)||(At=[At]),At.length===0&&at.idle())return C(function(){at.drain()});for(var en=0,Fn=At.length;en<Fn;en++){var yo={data:At[en],callback:De||Nt};Zt?at._tasks.unshift(yo):at._tasks.push(yo)}G||(G=!0,C(function(){G=!1,at.process()}))}function lt(At){return function(Zt){U-=1;for(var De=0,en=At.length;De<en;De++){var Fn=At[De],yo=hl(j,Fn,0);yo===0?j.shift():yo>0&&j.splice(yo,1),Fn.callback.apply(Fn,arguments),Zt!=null&&at.error(Zt,Fn.data)}U<=at.concurrency-at.buffer&&at.unsaturated(),at.idle()&&at.drain(),at.process()}}var pt=!1,at={_tasks:new Jn,concurrency:T,payload:M,saturated:Nt,unsaturated:Nt,buffer:T/4,empty:Nt,drain:Nt,error:Nt,started:!1,paused:!1,push:function(At,Zt){J(At,!1,Zt)},kill:function(){at.drain=Nt,at._tasks.empty()},unshift:function(At,Zt){J(At,!0,Zt)},remove:function(At){at._tasks.remove(At)},process:function(){if(!pt){for(pt=!0;!at.paused&&U<at.concurrency&&at._tasks.length;){var At=[],Zt=[],De=at._tasks.length;at.payload&&(De=Math.min(De,at.payload));for(var en=0;en<De;en++){var Fn=at._tasks.shift();At.push(Fn),j.push(Fn),Zt.push(Fn.data)}U+=1,at._tasks.length===0&&at.empty(),U===at.concurrency&&at.saturated();var yo=vo(lt(At));F(Zt,yo)}pt=!1}},length:function(){return at._tasks.length},running:function(){return U},workersList:function(){return j},idle:function(){return at._tasks.length+U===0},pause:function(){at.paused=!0},resume:function(){at.paused!==!1&&(at.paused=!1,C(at.process))}};return at}function ui(w,T){return ml(w,1,T)}var cs=je(Tr,1);function Jo(w,T,M,F){F=Ir(F||Nt);var U=R(M);cs(w,function(j,G,J){U(T,j,function(lt,pt){T=pt,J(lt)})},function(j){F(j,T)})}function Wc(){var w=ci(arguments,R);return function(){var T=o(arguments),M=this,F=T[T.length-1];typeof F=="function"?T.pop():F=Nt,Jo(w,T,function(U,j,G){j.apply(M,U.concat(function(J){var lt=o(arguments,1);G(J,lt)}))},function(U,j){F.apply(M,[U].concat(j))})}}var qc=function(){return Wc.apply(null,o(arguments).reverse())},yd=Array.prototype.concat,gl=function(w,T,M,F){F=F||Nt;var U=R(M);Dr(w,T,function(j,G){U(j,function(J){return J?G(J):G(null,o(arguments,1))})},function(j,G){for(var J=[],lt=0;lt<G.length;lt++)G[lt]&&(J=yd.apply(J,G[lt]));return F(j,J)})},L1=je(gl,1/0),Gc=je(gl,1),Zc=function(){var w=o(arguments),T=[null].concat(w);return function(){var M=arguments[arguments.length-1];return M.apply(this,T)}};function pl(w){return w}function di(w,T){return function(M,F,U,j){j=j||Nt;var G=!1,J;M(F,function(lt,pt,at){U(lt,function(At,Zt){At?at(At):w(Zt)&&!J?(G=!0,J=T(!0,lt),at(null,si)):at()})},function(lt){lt?j(lt):j(null,G?J:T(!1))})}}function dn(w,T){return T}var as=Qo(di(pl,dn)),Ko=li(di(pl,dn)),Cl=je(Ko,1);function kd(w){return function(T){var M=o(arguments,1);M.push(function(F){var U=o(arguments,1);typeof console=="object"&&(F?console.error&&console.error(F):console[w]&&is(U,function(j){console[w](j)}))}),R(T).apply(null,M)}}var M1=kd("dir");function R1(w,T,M){M=vo(M||Nt);var F=R(w),U=R(T);function j(J){if(J)return M(J);var lt=o(arguments,1);lt.push(G),U.apply(this,lt)}function G(J,lt){if(J)return M(J);if(!lt)return M(null);F(j)}G(null,!0)}function wd(w,T,M){M=vo(M||Nt);var F=R(w),U=function(j){if(j)return M(j);var G=o(arguments,1);if(T.apply(this,G))return F(U);M.apply(null,[null].concat(G))};F(U)}function O1(w,T,M){wd(w,function(){return!T.apply(this,arguments)},M)}function _1(w,T,M){M=vo(M||Nt);var F=R(T),U=R(w);function j(J){if(J)return M(J);U(G)}function G(J,lt){if(J)return M(J);if(!lt)return M(null);F(j)}U(G)}function hi(w){return function(T,M,F){return w(T,F)}}function Qc(w,T,M){Zo(w,hi(R(T)),M)}function Al(w,T,M,F){dl(T)(w,hi(R(M)),F)}var fi=je(Al,1);function Yc(w){return _(w)?w:i(function(T,M){var F=!0;T.push(function(){var U=arguments;F?C(function(){M.apply(null,U)}):M.apply(null,U)}),w.apply(this,T),F=!1})}function Kn(w){return!w}var mi=Qo(di(Kn,Kn)),bl=li(di(Kn,Kn)),Jc=je(bl,1);function F1(w){return function(T){return T==null?void 0:T[w]}}function us(w,T,M,F){var U=new Array(T.length);w(T,function(j,G,J){M(j,function(lt,pt){U[G]=!!pt,J(lt)})},function(j){if(j)return F(j);for(var G=[],J=0;J<T.length;J++)U[J]&&G.push(T[J]);F(null,G)})}function Xn(w,T,M,F){var U=[];w(T,function(j,G,J){M(j,function(lt,pt){lt?J(lt):(pt&&U.push({index:G,value:j}),J())})},function(j){j?F(j):F(null,ci(U.sort(function(G,J){return G.index-J.index}),F1("value")))})}function Kc(w,T,M,F){var U=ol(T)?us:Xn;U(w,T,R(M),F||Nt)}var Xc=Qo(Kc),vl=li(Kc),ta=je(vl,1);function P1(w,T){var M=vo(T||Nt),F=R(Yc(w));function U(j){if(j)return M(j);F(U)}U()}var ea=function(w,T,M,F){F=F||Nt;var U=R(M);Dr(w,T,function(j,G){U(j,function(J,lt){return J?G(J):G(null,{key:lt,val:j})})},function(j,G){for(var J={},lt=Object.prototype.hasOwnProperty,pt=0;pt<G.length;pt++)if(G[pt]){var at=G[pt].key,At=G[pt].val;lt.call(J,at)?J[at].push(At):J[at]=[At]}return F(j,J)})},gi=je(ea,1/0),N=je(ea,1),q=kd("log");function V(w,T,M,F){F=Ir(F||Nt);var U={},j=R(M);Tr(w,T,function(G,J,lt){j(G,J,function(pt,at){if(pt)return lt(pt);U[J]=at,lt()})},function(G){F(G,U)})}var ht=je(V,1/0),Et=je(V,1);function Vt(w,T){return T in w}function Be(w,T){var M=Object.create(null),F=Object.create(null);T=T||pl;var U=R(w),j=i(function(J,lt){var pt=T.apply(null,J);Vt(M,pt)?C(function(){lt.apply(null,M[pt])}):Vt(F,pt)?F[pt].push(lt):(F[pt]=[lt],U.apply(null,J.concat(function(){var at=o(arguments);M[pt]=at;var At=F[pt];delete F[pt];for(var Zt=0,De=At.length;Zt<De;Zt++)At[Zt].apply(null,at)})))});return j.memo=M,j.unmemoized=w,j}var qt;a?qt=process.nextTick:l?qt=setImmediate:qt=d;var na=h(qt);function Bd(w,T,M){M=M||Nt;var F=ol(T)?[]:{};w(T,function(U,j,G){R(U)(function(J,lt){arguments.length>2&&(lt=o(arguments,1)),F[j]=lt,G(J)})},function(U){M(U,F)})}function Bn(w,T){Bd(Zo,w,T)}function yl(w,T,M){Bd(dl(T),w,M)}var Ed=function(w,T){var M=R(w);return ml(function(F,U){M(F[0],U)},T,1)},pi=function(w,T){var M=Ed(w,T);return M.push=function(F,U,j){if(j==null&&(j=Nt),typeof j!="function")throw new Error("task callback must be a function");if(M.started=!0,Ae(F)||(F=[F]),F.length===0)return C(function(){M.drain()});U=U||0;for(var G=M._tasks.head;G&&U>=G.priority;)G=G.next;for(var J=0,lt=F.length;J<lt;J++){var pt={data:F[J],priority:U,callback:j};G?M._tasks.insertBefore(G,pt):M._tasks.push(pt)}C(M.process)},delete M.unshift,M};function kl(w,T){if(T=Ir(T||Nt),!Ae(w))return T(new TypeError("First argument to race must be an array of functions"));if(!w.length)return T();for(var M=0,F=w.length;M<F;M++)R(w[M])(T)}function Ci(w,T,M,F){var U=o(w).reverse();Jo(U,T,M,F)}function Wt(w){var T=R(w);return i(function(F,U){return F.push(function(G,J){if(G)U(null,{error:G});else{var lt;arguments.length<=2?lt=J:lt=o(arguments,1),U(null,{value:lt})}}),T.apply(this,F)})}function N1(w){var T;return Ae(w)?T=ci(w,Wt):(T={},ls(w,function(M,F){T[F]=Wt.call(this,M)})),T}function xd(w,T,M,F){Kc(w,T,function(U,j){M(U,function(G,J){j(G,!J)})},F)}var wl=Qo(xd),Id=li(xd),$1=je(Id,1);function H1(w){return function(){return w}}function Ai(w,T,M){var F=5,U=0,j={times:F,intervalFunc:H1(U)};function G(at,At){if(typeof At=="object")at.times=+At.times||F,at.intervalFunc=typeof At.interval=="function"?At.interval:H1(+At.interval||U),at.errorFilter=At.errorFilter;else if(typeof At=="number"||typeof At=="string")at.times=+At||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof w=="function"?(M=T||Nt,T=w):(G(j,w),M=M||Nt),typeof T!="function")throw new Error("Invalid arguments for async.retry");var J=R(T),lt=1;function pt(){J(function(at){at&&lt++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(at))?setTimeout(pt,j.intervalFunc(lt)):M.apply(null,arguments)})}pt()}var Xo=function(w,T){T||(T=w,w=null);var M=R(T);return i(function(F,U){function j(G){M.apply(null,F.concat(G))}w?Ai(w,j,U):Ai(j,U)})};function Bl(w,T){Bd(cs,w,T)}var El=Qo(di(Boolean,pl)),Lr=li(di(Boolean,pl)),xl=je(Lr,1);function Td(w,T,M){var F=R(T);jc(w,function(j,G){F(j,function(J,lt){if(J)return G(J);G(null,{value:j,criteria:lt})})},function(j,G){if(j)return M(j);M(null,ci(G.sort(U),F1("value")))});function U(j,G){var J=j.criteria,lt=G.criteria;return J<lt?-1:J>lt?1:0}}function Il(w,T,M){var F=R(w);return i(function(U,j){var G=!1,J;function lt(){var pt=w.name||"anonymous",at=new Error('Callback function "'+pt+'" timed out.');at.code="ETIMEDOUT",M&&(at.info=M),G=!0,j(at)}U.push(function(){G||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(lt,T),F.apply(null,U)})}var j1=Math.ceil,Tl=Math.max;function bi(w,T,M,F){for(var U=-1,j=Tl(j1((T-w)/(M||1)),0),G=Array(j);j--;)G[F?j:++U]=w,w+=M;return G}function vi(w,T,M,F){var U=R(M);Dr(bi(0,w,1),T,U,F)}var U1=je(vi,1/0),z1=je(vi,1);function V1(w,T,M,F){arguments.length<=3&&(F=M,M=T,T=Ae(w)?[]:{}),F=Ir(F||Nt);var U=R(M);Zo(w,function(j,G,J){U(T,j,G,J)},function(j){F(j,T)})}function Dl(w,T){var M=null,F;T=T||Nt,fi(w,function(U,j){R(U)(function(G,J){arguments.length>2?F=o(arguments,1):F=J,M=G,j(!G)})},function(){T(M,F)})}function Sl(w){return function(){return(w.unmemoized||w).apply(null,arguments)}}function Ll(w,T,M){M=vo(M||Nt);var F=R(T);if(!w())return M(null);var U=function(j){if(j)return M(j);if(w())return F(U);var G=o(arguments,1);M.apply(null,[null].concat(G))};F(U)}function W1(w,T,M){Ll(function(){return!w.apply(this,arguments)},T,M)}var Dd=function(w,T){if(T=Ir(T||Nt),!Ae(w))return T(new Error("First argument to waterfall must be an array of functions"));if(!w.length)return T();var M=0;function F(j){var G=R(w[M++]);j.push(vo(U)),G.apply(null,j)}function U(j){if(j||M===w.length)return T.apply(null,arguments);F(o(arguments,1))}F([])},t3={apply:r,applyEach:rd,applyEachSeries:sd,asyncify:v,auto:Uc,autoInject:S1,cargo:ui,compose:qc,concat:L1,concatLimit:gl,concatSeries:Gc,constant:Zc,detect:as,detectLimit:Ko,detectSeries:Cl,dir:M1,doDuring:R1,doUntil:O1,doWhilst:wd,during:_1,each:Qc,eachLimit:Al,eachOf:Zo,eachOfLimit:Tr,eachOfSeries:cs,eachSeries:fi,ensureAsync:Yc,every:mi,everyLimit:bl,everySeries:Jc,filter:Xc,filterLimit:vl,filterSeries:ta,forever:P1,groupBy:gi,groupByLimit:ea,groupBySeries:N,log:q,map:jc,mapLimit:Dr,mapSeries:id,mapValues:ht,mapValuesLimit:V,mapValuesSeries:Et,memoize:Be,nextTick:na,parallel:Bn,parallelLimit:yl,priorityQueue:pi,queue:Ed,race:kl,reduce:Jo,reduceRight:Ci,reflect:Wt,reflectAll:N1,reject:wl,rejectLimit:Id,rejectSeries:$1,retry:Ai,retryable:Xo,seq:Wc,series:Bl,setImmediate:C,some:El,someLimit:Lr,someSeries:xl,sortBy:Td,timeout:Il,times:U1,timesLimit:vi,timesSeries:z1,transform:V1,tryEach:Dl,unmemoize:Sl,until:W1,waterfall:Dd,whilst:Ll,all:mi,allLimit:bl,allSeries:Jc,any:El,anyLimit:Lr,anySeries:xl,find:as,findLimit:Ko,findSeries:Cl,forEach:Qc,forEachSeries:fi,forEachLimit:Al,forEachOf:Zo,forEachOfSeries:cs,forEachOfLimit:Tr,inject:Jo,foldl:Jo,foldr:Ci,select:Xc,selectLimit:vl,selectSeries:ta,wrapSync:v};e.default=t3,e.apply=r,e.applyEach=rd,e.applyEachSeries=sd,e.asyncify=v,e.auto=Uc,e.autoInject=S1,e.cargo=ui,e.compose=qc,e.concat=L1,e.concatLimit=gl,e.concatSeries=Gc,e.constant=Zc,e.detect=as,e.detectLimit=Ko,e.detectSeries=Cl,e.dir=M1,e.doDuring=R1,e.doUntil=O1,e.doWhilst=wd,e.during=_1,e.each=Qc,e.eachLimit=Al,e.eachOf=Zo,e.eachOfLimit=Tr,e.eachOfSeries=cs,e.eachSeries=fi,e.ensureAsync=Yc,e.every=mi,e.everyLimit=bl,e.everySeries=Jc,e.filter=Xc,e.filterLimit=vl,e.filterSeries=ta,e.forever=P1,e.groupBy=gi,e.groupByLimit=ea,e.groupBySeries=N,e.log=q,e.map=jc,e.mapLimit=Dr,e.mapSeries=id,e.mapValues=ht,e.mapValuesLimit=V,e.mapValuesSeries=Et,e.memoize=Be,e.nextTick=na,e.parallel=Bn,e.parallelLimit=yl,e.priorityQueue=pi,e.queue=Ed,e.race=kl,e.reduce=Jo,e.reduceRight=Ci,e.reflect=Wt,e.reflectAll=N1,e.reject=wl,e.rejectLimit=Id,e.rejectSeries=$1,e.retry=Ai,e.retryable=Xo,e.seq=Wc,e.series=Bl,e.setImmediate=C,e.some=El,e.someLimit=Lr,e.someSeries=xl,e.sortBy=Td,e.timeout=Il,e.times=U1,e.timesLimit=vi,e.timesSeries=z1,e.transform=V1,e.tryEach=Dl,e.unmemoize=Sl,e.until=W1,e.waterfall=Dd,e.whilst=Ll,e.all=mi,e.allLimit=bl,e.allSeries=Jc,e.any=El,e.anyLimit=Lr,e.anySeries=xl,e.find=as,e.findLimit=Ko,e.findSeries=Cl,e.forEach=Qc,e.forEachSeries=fi,e.forEachLimit=Al,e.forEachOf=Zo,e.forEachOfSeries=cs,e.forEachOfLimit=Tr,e.inject=Jo,e.foldl=Jo,e.foldr=Ci,e.select=Xc,e.selectLimit=vl,e.selectSeries=ta,e.wrapSync=v,Object.defineProperty(e,"__esModule",{value:!0})})})(ap,ap.exports);var xb={exports:{}},up=xb.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),o=2;e===1/0;o*=2)e=Math.log(Math.pow(2,n/o))/Math.log(t)*o;for(var r=e-Math.floor(e),i="",o=0;o<Math.floor(e);o++){var s=Math.floor(Math.random()*t).toString(t);i=s+i}if(r){var l=Math.pow(t,r),s=Math.floor(Math.random()*l).toString(t);i=s+i}var a=parseInt(i,t);return a!==1/0&&a>=Math.pow(2,n)?up(n,t):i};up.rack=function(n,t,e){var o=function(i){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=up(n,t)}while(Object.hasOwnProperty.call(r,l));return r[l]=i,l},r=o.hats={};return o.get=function(i){return o.hats[i]},o.set=function(i,s){return o.hats[i]=s,o},o.bits=n||128,o.base=t||16,o};var Ib=Ui,AS=Bb,bS=Eb,Zh=$o,dp=ap.exports,vS=xb.exports,Tb=Hs.ACTIONS,Db=Re;function Re(n,t){if(Ib.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}Ib.mixin(Re),Re.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Re.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Re.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||vS();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Re.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(o){if(o)return t._callbackOrEmit(o,n);var r=Object.keys(t._remotePresenceInstances);dp.parallel([function(i){dp.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();dp.each(r,function(s,l){t._remotePresenceInstances[s].destroy(l)},i)}],function(i){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(i,n)})})},Re.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?Tb.presenceSubscribe:Tb.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Re.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Re.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Re.prototype._receiveUpdate=function(n,t){var e=Zh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=Zh.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Re.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Re.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()}},Re.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Re.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Re.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 o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},Re.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Re.prototype._callbackOrEmit=function(n,t){if(t)return Zh.nextTick(t,n);n&&this.emit("error",n)},Re.prototype._createLocalPresence=function(n){return new AS(this,n)},Re.prototype._createRemotePresence=function(n){return new bS(this,n)},Re.prototype._callEachOrEmit=function(n,t){var e=Zh.callEach(n,t);!e&&t&&this.emit("error",t)};var Za=Bb,Sb=zh,yS=$o,Lb=Sb.CODES,kS=jo;function jo(n,t){Za.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()}jo.prototype=Object.create(Za.prototype),jo.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:Lb.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,Za.prototype.submit.call(this,n,t)},jo.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),Za.prototype.destroy.call(this,n)},jo.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={})})}},jo.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)},jo.prototype._transformAgainstOp=function(n,t){var e=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=e._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=e._transformPresence(r.p,n,t),e._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=e._getCallback(r.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(r){this.emit("error",r)}},jo.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},jo.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},jo.prototype._message=function(){var n=Za.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},jo.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!yS.supportsPresence(o))throw new Sb(Lb.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var Mb={};(function(n){var t=Wa,e=zh,o=$o,r=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var a=l.create.type;if(typeof a!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[a];if(d==null||typeof d!="object")return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(r.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(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(r.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,a){if(typeof l!="object")return new e(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&a.v!=null&&l.v!==a.v)return new e(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(a.create){if(l.type)return new e(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=a.create,h=t.map[d.type];if(!h)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(C){return C}}else if(a.del)l.data=void 0,l.type=null,l.v++;else if("op"in a){var p=i(l,a.op);if(p)return p;l.v++}else l.v++};function i(l,a){if(!l.type)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(a===void 0)return new e(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,a)}catch(h){return new e(r.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,a,d){if(a.v!=null&&a.v!==d.v)return new e(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(a.create||"op"in a)return new e(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in a||a.create||a.del)||"op"in d&&a.create)return new e(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in a){if(!l)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{a.op=l.transform(a.op,d.op,"left")}catch(h){return h}}}a.v!=null&&a.v++},n.applyOps=function(l,a,d){d=d||{};for(var h=0;h<a.length;h++){var p=a[h];if(d._normalizeLegacyJson0Ops)try{s(l,p)}catch{return new e(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=p.v;var C=n.apply(l,p);if(C)return C}},n.transformPresence=function(l,a,d){var h=this.checkOp(a);if(h)return h;var p=l.t;if(typeof p=="string"&&(p=t.map[p]),!p)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(p))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(a.create||a.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:p.transformPresence(l.p,a.op,d)}catch(C){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:C.message||C}}l.v++};function s(l,a){if(l.type===t.defaultType.uri){var d=a.op;if(!!d){var h=l.data;d.length>1&&(h=o.clone(h));for(var p=0;p<d.length;p++){var C=d[p];typeof C.lm=="string"&&(C.lm=+C.lm);for(var v=C.p,B=h,D=0;D<v.length;D++){var x=v[D];Object.prototype.toString.call(B)=="[object Array]"?v[D]=+x:B.constructor===Object&&(v[D]=x.toString()),B=B[x]}p<d.length-1&&(h=t.defaultType.apply(h,[C]))}}}}})(Mb);var Qa=Eb,wS=Mb,BS=ho;function ho(n,t){Qa.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()}ho.prototype=Object.create(Qa.prototype),ho.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},ho.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),Qa.prototype.destroy.call(this,n)},ho.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)},ho.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))}})}},ho.prototype._handleOp=function(n,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},Qa.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Qa.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},ho.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)}},ho.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++):wS.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},ho.prototype._startCachingOps=function(){this._opCache=[]},ho.prototype._stopCachingOps=function(){this._opCache=null},ho.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var Rb=Db,ES=kS,xS=BS;function Xl(n,t,e){var o=Xl.channel(t,e);Rb.call(this,n,o),this.collection=t,this.id=e}var IS=Xl;Xl.prototype=Object.create(Rb.prototype),Xl.channel=function(n,t){return n+"."+t},Xl.prototype._createLocalPresence=function(n){return new ES(this,n)},Xl.prototype._createRemotePresence=function(n){return new xS(this,n)};var TS=DS;function DS(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var SS=TS,Ob=Ui,_b=Ya;function Ya(n,t,e,o,r){if(Ob.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=o,this.collection=e,this.callback=r,this.sent=!1}Ob.mixin(Ya),Ya.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Ya.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Ya.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new SS(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var Fb=_b,LS=$o,MS=Hs.ACTIONS,RS=hp;function hp(n,t,e,o,r,i){if(Fb.call(this,n,t,e,o,i),!LS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}hp.prototype=Object.create(Fb.prototype),hp.prototype._message=function(){return{a:MS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var Pb=_b,OS=$o,_S=Hs.ACTIONS,FS=fp;function fp(n,t,e,o,r,i){if(Pb.call(this,n,t,e,o,i),!OS.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}fp.prototype=Object.create(Pb.prototype),fp.prototype._message=function(){return{a:_S.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var PS=aS,NS=mS,$S=Db,Nb=IS,HS=RS,jS=FS,$b=Ui,tc=zh,ne=Hs.ACTIONS,Hb=Wa,Uo=$o,Ja=gb,Ka=tc.CODES;function jb(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var US=Bt;function Bt(n){$b.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=jb(n),this.bindToSocket(n)}$b.mixin(Bt),Bt.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=jb(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Ja.warn("Failed to parse message",o);return}e.debug&&Ja.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){Uo.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(o){e.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?e._setState("closed",o):o==="stopped"||o==="Stopped by server"?e._setState("stopped",o):e._setState("disconnected",o)}},Bt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=Ub(n.error,n),delete n.error),n.a){case ne.initLegacy:return this._handleLegacyInit(n);case ne.handshake:return this._handleHandshake(t,n);case ne.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case ne.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case ne.queryUnsubscribe:return;case ne.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 ne.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case ne.bulkSubscribe:case ne.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case ne.snapshotFetch:case ne.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case ne.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case ne.subscribe:case ne.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case ne.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case ne.presence:return this._handlePresence(t,n);case ne.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case ne.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case ne.presenceRequest:return this._handlePresenceRequest(t,n);case ne.pingPong:return this._handlePingPong(t);default:Ja.warn("Ignoring unrecognized message",n)}};function Ub(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}Bt.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var o in t.data){var r=t.data[o],i=this.getExisting(t.c,o);i&&(n?i[e](n):r.error?i[e](Ub(r.error)):i[e](null,r))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var o=t.b[s],i=this.getExisting(t.c,o);i&&i[e](n)}else if(t.b)for(var o in t.b){var i=this.getExisting(t.c,o);i&&i[e](n)}else Ja.error("Invalid bulk message",t)},Bt.prototype._reset=function(){this.agent=null},Bt.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 tc(Ka.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 o in this.queries){var r=this.queries[o];r._onConnectionStateChanged()}for(var i in this.collections){var s=this.collections[i];for(var o in s)s[o]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var o in this._snapshotRequests){var a=this._snapshotRequests[o];a._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},Bt.prototype.startBulk=function(){this.bulk||(this.bulk={})},Bt.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},Bt.prototype._sendBulk=function(n,t,e){if(!!e){var o=[],r={},i=0,s;for(var l in e){var a=e[l];a==null?o.push(l):(r[l]=a,s=l,i++)}if(o.length===1){var l=o[0];this.send({a:n,c:t,d:l})}else o.length&&this.send({a:"b"+n,c:t,b:o});if(i===1){var d=r[s];this.send({a:n,c:t,d:s,v:d})}else i&&this.send({a:"b"+n,c:t,b:r})}},Bt.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var o=this.bulk[t.collection]||(this.bulk[t.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(t.id);return r[t.id]=e,i}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},Bt.prototype.sendFetch=function(n){return this._sendActions(ne.fetch,n,n.version)},Bt.prototype.sendSubscribe=function(n){return this._sendActions(ne.subscribe,n,n.version)},Bt.prototype.sendUnsubscribe=function(n){return this._sendActions(ne.unsubscribe,n)},Bt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:ne.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)},Bt.prototype.send=function(n){this.debug&&Ja.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},Bt.prototype.ping=function(){if(!this.canSend)throw new tc(Ka.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:ne.pingPong};this.send(n)},Bt.prototype.close=function(){this.socket.close()},Bt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},Bt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new PS(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},Bt.prototype._destroyDoc=function(n){!n._wantsDestroy||(Uo.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},Bt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},Bt.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new NS(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},Bt.prototype._destroyQuery=function(n){delete this.queries[n.id]},Bt.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(ne.queryFetch,n,t,e,o)},Bt.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(ne.querySubscribe,n,t,e,o)},Bt.prototype.hasPending=function(){return!!(this._firstDoc(Qh)||this._firstQuery(Qh)||this._firstSnapshotRequest())};function Qh(n){return n.hasPending()}Bt.prototype.hasWritePending=function(){return!!this._firstDoc(zS)};function zS(n){return n.hasWritePending()}Bt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Qh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Qh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}Uo.nextTick(n)},Bt.prototype._nothingPendingRetry=function(n){var t=this;return function(){Uo.nextTick(function(){t.whenNothingPending(n)})}},Bt.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var o in e){var r=e[o];if(n(r))return r}}},Bt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},Bt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},Bt.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new HS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},Bt.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new jS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},Bt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},Bt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},Bt.prototype._initializeHandshake=function(){this.send({a:ne.handshake,id:this.id})},Bt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},Bt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},Bt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new tc(Ka.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(Hb.map[n.type]!==Hb.defaultType)return this.emit("error",new tc(Ka.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new tc(Ka.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},Bt.prototype.getPresence=function(n){var t=this,e=Uo.digOrCreate(this._presences,n,function(){return new $S(t,n)});return e._wantsDestroy=!1,e},Bt.prototype.getDocPresence=function(n,t){var e=Nb.channel(n,t),o=this,r=Uo.digOrCreate(this._presences,e,function(){return new Nb(o,n,t)});return r._wantsDestroy=!1,r},Bt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},Bt.prototype._addPresence=function(n){Uo.digOrCreate(this._presences,n.channel,function(){return n})},Bt.prototype._handlePresenceSubscribe=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},Bt.prototype._handlePresenceUnsubscribe=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},Bt.prototype._handlePresence=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},Bt.prototype._handlePresenceRequest=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var zb=US,VS=Wa;const Yh={err:1001,msg:"user auth error",name:"AuthError"},WS={err:1002,msg:"you don't have required permission",name:"PermissionError"},mp={err:1003,msg:"Too many user connected",name:"MaxUserError"},Xa={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},qS={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},GS={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},tu="x-live-editor-token",Jh="x-live-editor-base-url",Cn=S("auth-connection");function ZS(n){try{n()}catch(t){Cn.error(t)}}class QS{constructor(t,e){m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new G3.EventEmitter);m(this,"token",null);m(this,"resourceToken",null);this.url=t,this.reauthFunc=e,this.retryCount=0}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return Mi(this.getBaseURL())}async auth(t){g(Cn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[tu]:t.token,[Jh]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=t.token,await o.json()}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[Jh]:Mi(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new HB.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(zb.prototype),g(Cn,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};const o=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=r=>{var s;const i=r;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in i||i.a==="pong")this.handleMessage(i);else{Object.prototype.hasOwnProperty.call(i,"a")&&i.a!=="init"&&i.a!=="hs"&&(this.retryCount=0);try{o(i)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,i);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,i);return}throw l}}},zb.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,Cn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){Cn.error(t),setTimeout(()=>this.handleAuthError(),0)}}else Cn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(Yh.msg);t.code=Yh.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Xa.msg);t.code=Xa.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 o=e.err;if(o===Yh.err)Cn.warn("auth error"),this.handleAuthError();else if(o===mp.err)Cn.warn(mp.msg),this.emitMaxUsersError();else if(o===Xa.err){Cn.warn(Xa.msg);try{this.emitRequestReloadError()}catch(r){Cn.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else Cn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return g(Cn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(g(Cn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){g(Cn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){g(Cn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.reauthFunc=void 0,this.events.removeAllListeners(),ZS(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}S("utils/file");function YS(){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}YS();async function JS(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new jB.Hash;for(let s=0;s<o;s++){const l=s*102400;let a=l+102400;a>e&&(a=e);const h=await n.slice(l,a,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return Mi(i)}const fr=S("sharedb-doc/client");class KS{constructor(t,e,o){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",K());m(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});g(fr,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),fr.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;VS.register(Hd.type),this.connection=new QS(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return g(fr,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,o=>{(t==="error"||this.doc)&&e(o)})}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,o,r,i){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...i},data:{name:o,size:r}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const o=`${this.apiServer()}/resources`;let r=[];t.forEach(l=>{const a=l.split("|");r.push(...a)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[tu]:this.connection.token}));return await Promise.all(i)}async uploadFile(t,e,o,r,i){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=v=>{fr.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await JS(e),d=await this.getFileUrlByHash(t,a,e.name,e.size,o);if(d)return r(-1),d;let h=t;i!=null&&i.thumbnail&&(h+="/thumbnail");const p=new FormData;p.append("file-size",`${e.size}`),p.append("file-hash",a),p.append("file",e,e.name);const C=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return fr.info(C),r(100),Array.isArray(C.data)?C.data[0]:C.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;g(fr,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[tu]:this.connection.token},e,o);return g(fr,s,"no result"),s}async request(t,e){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const a=e||{};a.url=t,a.headers||(a.headers={}),g(fr,o,"no token"),a.headers={...a.headers,[tu]:o,[Jh]:this.connection.getBase64BaseURL()};try{return await NB.default(t,a)}catch(d){if(r=d,((i=d==null?void 0:d.response)==null?void 0:i.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;o=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw g(fr,r,"no error"),r}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,r=(await this.request(e)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),r}async getVersion(t){const o=`${this.apiServer()}/versions/${t}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,o=await this.request(e);return JSON.parse(o.data.data)}async getVersionOps(t,e){let r=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(r+=`&from=${e}`);const i=await this.request(r),s=i.data.ops,l=$B.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(fr,a.create,"no createDoc.create"),d=a.create.data):d=JSON.parse(i.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:i.data.ops}}async updateVersionExtra(t,e,o){const i=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}async revertVersion(t){const o=`${this.apiServer()}/versions/revert/${t}`;await this.request(o,{method:"post",data:{}})}async createVersion(t,e){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const o=`${this.apiServer()}/resources/external/${Mi(t)}`;return(await this.request(o)).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 r=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const i=[];if(e!=null&&e.withToken&&i.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&i.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function XS(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const gp=S("block-ids");class tL{constructor(){m(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<e.length;r++){const i=e[r];if(i>=t){const s=this.ids.get(i);g(gp,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=K();this.ids.set(t,o)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<e.length;o++){const r=e[o];if(r>t){const i=this.ids.get(r);g(gp,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(t){let e=this.ids.get(t);return e||(e=K(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class eL{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new tL,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 o=0;o<e.length;o++){const r=e[o],i=r[1].getById(t);if(i)return{containerId:r[0],blockIndex:i[0]}}return g(gp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class Vb{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,o)=>{t[o]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const Kh=S("op-parse-handler");class nL{constructor(t,e){m(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const o={...t,containerId:(r=>r==="blocks"?"root":r)(t.containerId)};this.actions.push(o)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,o){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:o})}onDeleteBlockData(t,e,o){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:o})}onInsertBlockData(t,e,o,r){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:o,value:r})}onUpdateBlockText(t,e,o){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:o})}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,o=new Map,r=new eL,i=t.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of i)if(s.type==="deleteBlock"){const l=s,a=r.getBlockId(l.containerId,l.blockIndex);r.onDeleteBlock(l.containerId,l.blockIndex);const d=o.get(a);d&&(Kh.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),o.delete(a));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,a=`${l.containerId}-${l.blockIndex}`;if(e.has(a)){Kh.warn("delete block data after delete block, ignore it");continue}const d=r.getBlockId(l.containerId,l.blockIndex);let h=o.get(d);h||(h=new Vb,o.set(d,h)),h.delete(l.key)}else g(Kh,!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,a=r.getBlockId(l.containerId,l.blockIndex);let d=o.get(a);d||(d=new Vb,o.set(a,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(o.entries()).forEach(([s,l])=>{const{containerId:a,blockIndex:d}=r.getBlockIndexById(s);Kh.debug(`update block data: ${a}, ${d}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Oe=S("op-parser");class Wb{}class pp{constructor(t){m(this,"key");this.key=t}}function oL(n,t,e){const o=t.concat(),r=o[0];if(typeof r!="number"||(o.shift(),o.length===1))return!1;const i=o[0];if(typeof i!="object"||!i.i||Object.keys(i).length!==1)return!1;for(let l=1;l<o.length;l++){const a=o[l];if(!Array.isArray(a)||a.length!==2||typeof a[0]!="string")return!1;const h=a[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=i.i;g(Oe,s.id,"block id is required"),g(Oe,s.type,"block type is required");for(let l=1;l<o.length;l++){const a=o[l],d=a[0],h=a[1];s[d]=h.i}return e.onInsertBlock(n,r,s),!0}function Cp(n,t,e,o){if(e==="upsert"&&oL(n,t,o))return;g(Oe,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const r=t.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const a=r[1];if(g(Oe,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),g(Oe,a.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const h=a.e;o.onUpdateBlockText(n,i,h)}g(Oe,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){g(Oe,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];g(Oe,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(g(Oe,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&o.onInsertBlockData(n,i,a,d.i),d.r&&e==="remove"&&o.onDeleteBlockData(n,i,a),d.et==="rich-text"&&e==="upsert"){const p=d.e;o.onUpdateBlockText(n,i,p)}}else e==="remove"&&d.r&&s.push(new pp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i);r.shift()}else if(typeof l=="object"){const a=l;e==="remove"&&a.r&&s.push(new Wb),e==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{g(Oe,typeof l=="string","data is not string"),g(Oe,l!=="text","data !== 'text'"),g(Oe,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const a=l,d=r[1];e==="remove"&&d.r&&s.push(new pp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Wb?o.onDeleteBlock(n,i):l instanceof pp?o.onDeleteBlockData(n,i,l.key):g(Oe,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function rL(n,t,e){Oe.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function iL(n,t,e){const o=n[1],r=n[2];g(Oe,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),g(Oe,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Oe.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?t==="upsert"&&e.onUpdateComment(o):r.i?t==="upsert"&&e.onCreateComment(o):r.r?t==="remove"&&e.onDeleteComment(o):Oe.error(`unknown comment op, ${JSON.stringify(n)}`)}function Ap(n,t,e){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{Ap(s,t,e)});return}const r=o;if(g(Oe,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){rL(n);return}if(r==="comments"){iL(n,t,e);return}const i=r;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{Cp(i,s,t,e)}):n.slice(1).forEach(s=>{Cp(i,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(i),s.i&&t==="upsert"&&e.onCreateContainer(i,s.i)}else g(Oe,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Cp(i,n.slice(1),t,e)}function qb(n,t,e){const o=new nL(t,e);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=mt.default(n),l=s[0];Array.isArray(l)?s.forEach(a=>{Ap(a,i,o)}):Ap(s,i,o)}o.end()}const sL=S("sharedb-comments");function bp(n){const t=n.blocks;g(sL,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(e.blocks[o]=r)}),mt.default(e)}function Gb(n){const{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}=n;return{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}}function vp(n,t){const e=VD(t),{comments:o,meta:r,blocks:i,...s}=e,l={...n,blocks:i,...s},a=mt.default(l);return delete a.children,a}const se=S("sharedb-doc/doc-container"),Zb="ot-json1";Hd.type.registerSubtype(WD.type),Hd.type.name=Zb,Hd.type.invert=null;class eu extends ha{constructor(e,o,r=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new UD);m(this,"batching",0);m(this,"status","clean");m(this,"disableLogout");m(this,"destroyed",!1);m(this,"handleNothingPending",()=>{this.setStatus("clean")});m(this,"handleCreate",()=>{this.handleReload("doc created")});m(this,"handleDel",()=>{});m(this,"handleReload",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});m(this,"handleReset",async e=>{const o=new Error(`reset doc: ${e}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});m(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});m(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});m(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});m(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});m(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,a])=>{if(!aa.default(i[l],a))if(i[l]===void 0){if(a!=null){const d={i:a};s.push([l,d])}}else if(a==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:a};s.push([l,d])}}),Object.entries(i).forEach(([l,a])=>{if((r[l]===void 0||r[l]===null)&&a!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});m(this,"broadcastMessage",async e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});m(this,"data",()=>this.doc.data);m(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){se.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(se.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),se.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(se.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));m(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,Zb,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainers",async e=>{const o=e.map(({containerId:r,blocks:i})=>[ji(r),{i}]);return this.submitOp([o])});m(this,"submitDeleteChildContainer",async e=>{const o=[ji(e),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(e,o,r)=>{const i=[ji(e),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(e,o)=>{const r=[ji(e),o,{r:!0}];return this.submitOp(r)});m(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[ji(e),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a)){const h={r:!0,i:d};i.push([a,h])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(a=>{if(l.has(a))return;const d={r:!0};i.push([a,d])}),Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a))return;const h={i:d};i.push([a,h])}),this.submitOp(i)});m(this,"submitUpdateRichText",async(e,o,r)=>{const i=[ji(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(e,o,r)=>{if(this.destroyed){se.warn("handleOp: destroyed");return}try{qb(e,this,!!o)}catch(i){throw se.error(i),i}});this.client=e,this.doc=o,this.doc.preventCompose=!0,this.disableLogout=r,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,g(se,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new KS(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new eu(o,r,e.disableLogout);if(r.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(e.templateData||XS())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw se.error(o),se.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),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,o)=>{if(this.localPresence)e();else{const r=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);r.on("receive",(i,s)=>{this.onCustomMessage(s)}),r.subscribe(i=>{i?o(i):(this.localPresence=r.create(K()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return Va(this.data())}getContainerBlocks(e){const o=this.data();g(se,o,"no doc data");const r=o[ji(e)];return g(se,r,`no container data: ${e}`),mt.default(r)}getBlockData(e,o){const r=this.data();g(se,r,"no doc data");const i=r[ji(e)];g(se,i,`no container data: ${e}`);const s=i[o];return g(se,s,`no block data: ${o}`),mt.default(s)}localInsertBlock(e,o,r){return this.submitInsertBlock(e,o,r),this.getBlockData(e,o)}localDeleteBlock(e,o){const r=this.getBlockData(e,o);return this.submitDeleteBlock(e,o),r}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(se,i.text,"no block text");const s=mt.default(i.text);this.submitUpdateRichText(e,o,r);const l=ln.apply(s,r);return g(se,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=mt.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainers(e){this.submitInsertChildContainers(e)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>Gb(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return bp(o)}localCreateComment(e,o){const r=vp(e,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(e){const o=["comments",e,{r:!0}];return this.submitOp(o)}localUpdateComment(e,o){const r=vp(e,o),i=["comments",e.id,{r:!0,i:r}];return this.submitOp(i)}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,o,r){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Kl(e),o,r)})}onInsertBlock(e,o,r,i){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Kl(e),o,r,i)})}onUpdateBlockData(e,o,r,i){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Kl(e),o,r,i)})}onUpdateBlockText(e,o,r,i){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Kl(e),o,r,i)})}onDeleteContainer(e,o){g(se,this.callbacks.length>0,"no callbacks"),g(se,e!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Kl(e),o)})}onCreateContainer(e,o,r){g(se,this.callbacks.length>0,"no callbacks"),g(se,e!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Kl(e),o,r)})}onDeleteComment(e,o){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,e,o)})}onCreateComment(e,o){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,e,o)})}onUpdateComment(e,o){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){const o=e;(o==null?void 0:o.type)==="custom"&&(o==null?void 0:o.clientId)!==this.client.clientId?this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,o.data)}):(o==null?void 0:o.type)==="onlineUsers"&&setTimeout(()=>{const r={type:"custom",data:e,clientId:"-"};this.onCustomMessage(r)})}async addResources(e){return await this.client.getFileUrlsByHashes(e)}async uploadResource(e,o){var i;return{resourceId:await this.client.uploadResource(e,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(e,o){return this.client.buildResourceUrl(e,o)}request(e,o){return this.client.request(e,o)}getUser(){const e=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:e,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const o=await this.client.getVersion(e);return Va(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return Va(e)}async getHistoryData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:Va(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:Va(r),versionData:i}}async updateVersionExtra(e,o,r){await this.client.updateVersionExtra(e,o,r)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,o){return this.client.createVersion(e,o)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,o){qb(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}S("remote-cursor");class Qb{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Me.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));m(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const o=this.editor.findBlockById(e);o&&this.editor.reloadBlock(o)})});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 Yb=S("remote-cursor-decorator");class yp{decorateText(t,e,o){const r=t.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=e[e.length-1];g(Yb,typeof s=="string","invalid path containerId"),g(Yb,typeof l=="number","invalid path blockIndex");const a=t.doc.getBlockData(s,l),d=rn(o);return r.getSimpleCursors(a.id).forEach((p,C)=>{C>d&&(C=d);const v=p.map(D=>({id:K(),type:"remote-cursor",name:D.user.displayName,time:D.time,rainbowIndex:D.user.rainbowIndex})),B=i.get(C);B?B.push(...v):i.set(C,v)}),{insertions:i}}}class Jb extends ve.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Gt(zr(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=et(this.editor.getContainerById(t));i&&this.emit("change",this.editor,i,r,o)}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 lL(n,t){n.addCustom("child-block-tracker",()=>new Jb(n)).addListener("change",t)}function cL(n,t){n.addCustom("child-block-tracker",()=>new Jb(n)).removeListener("change",t)}const Ent="",aL={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"}},uL={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},dL={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"}};L.mergeLang({"zh-CN":aL,"en-US":uL,"js-JP":dL});const xnt="";S("button");function fo(n,t,e,o,r){const i=k("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,t),e?typeof e=="string"?e.startsWith("<")?i.innerHTML=e:i.innerText=e:i.appendChild(e):i.innerText=t,o&&(o.indexOf("checked")!==-1&&W(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0),o.indexOf("primary")!==-1&&W(i,"primary")),i}function Kb(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const Int="",Xb=`<?xml version="1.0" ?>
28
28
  <svg
29
29
  fill="currentColor"
30
30
  xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">