@ones-editor/editor 0.0.3-beta.149 → 0.0.3-beta.150

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 a6={boxType:"br",updateBoxContent:_I,convertTo:FI},u6=S("editor-boxes");class d6{constructor(e){g(this,"boxes",new Map);this.editor=e}registerBoxClass(e){const t=e.boxType,o=this.boxes.get(t);m(u6,!o,`duplicated box type: ${t}`),this.boxes.set(t,e)}getBoxClass(e){const t=this.boxes.get(e);return m(u6,t,`unknown box type: ${e}`),t}createBox(e,t){const o=HC(t),r=UC(o);return this.getBoxClass(t.type).updateBoxContent(this.editor,o,r,t),o}}function PI(n,e,t,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=w("img",a,t);i&&(d.style.width=`${i}px`),s&&(d.style.height=`${s}px`),d.src=n.doc.buildResourceUrl(l)}const h6={boxType:"image",updateBoxContent:PI},NI="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIGZpbGw9InJnYigxNzgsIDE4OCwgMjA1KSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0ibTE3IDE1IDEuNTUgMS41NWMtLjk2IDEuNjktMy4zMyAzLjA0LTUuNTUgMy4zN1YxMWgzVjloLTNWNy44MkMxNC4xNiA3LjQgMTUgNi4zIDE1IDVjMC0xLjY1LTEuMzUtMy0zLTNTOSAzLjM1IDkgNWMwIDEuMy44NCAyLjQgMiAyLjgyVjlIOHYyaDN2OC45MmMtMi4yMi0uMzMtNC41OS0xLjY4LTUuNTUtMy4zN0w3IDE1bC00LTN2M2MwIDMuODggNC45MiA3IDkgN3M5LTMuMTIgOS03di0zbC00IDN6TTEyIDRjLjU1IDAgMSAuNDUgMSAxcy0uNDUgMS0xIDEtMS0uNDUtMS0xIC40NS0xIDEtMXoiPjwvcGF0aD4KPC9zdmc+Cg==";function $I(n,e,t){W(t,"editor-box-anchor"),am(NI,[],t)}const f6={boxType:"anchor",updateBoxContent:$I};function HI(n,e,t,o){w("span",[],t,o.text)}const m6={insertionType:"inputting",updateInsertionContent:HI},g6=S("editor-insertion");class p6{constructor(e){g(this,"insertions",new Map);this.editor=e}registerInsertionClass(e){const t=e.insertionType,o=this.insertions.get(t);m(g6,!o,`duplicated insertion type: ${t}`),this.insertions.set(t,e)}getInsertionClass(e){const t=this.insertions.get(e);return m(g6,t,`unknown insertion type: ${e}`),t}createInsertion(e,t){const o=zC(t.type,t.id),r=WC(o);return this.getInsertionClass(t.type).updateInsertionContent(this.editor,o,r,t),o}}class jI{constructor(e){g(this,"cursors",new Map);g(this,"timer");this.editor=e,this.timer=this.startTimer()}add(e,t){this.cursors.set(e,t)}startTimer(){return setInterval(()=>{const e=Date.now();Array.from(this.cursors).forEach(([t,o])=>{if(e-o>3e3){const r=VC(this.editor,t);r&&te(r,"active"),this.cursors.delete(t)}})},1e3)}destroy(){clearInterval(this.timer)}}function UI(n,e,t,o){var l;const r=o;Date.now()-r.time<5*1e3&&(n.addCustom("active-cursors",d=>new jI(d)).add(r.id,r.time),W(e,"active")),w("span",[],t,"|").setAttribute("data-cursor-name",r.name),e.style.setProperty("--cursor-color",n.getColor((l=r.rainbowIndex)!=null?l:0))}const Ag={insertionType:"remote-cursor",updateInsertionContent:UI};class C6{constructor(e){g(this,"decorators",[]);this.editor=e}registerDecorator(e){this.decorators.push(e)}decorateBlock(e,t){let o=t;return this.decorators.forEach(r=>{if(r.decorateBlock){const i=r.decorateBlock(this.editor,e,t);i&&(o=fe.default(i))}}),o}decorateText(e,t){let o=t;const r=new Map;return this.decorators.forEach(i=>{if(i.decorateText){const s=i.decorateText(this.editor,e,t);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=fe.default(a))}}}),{insertions:r,text:o}}}const bg=S("editor-input");class zI{constructor(e,t){g(this,"editor");g(this,"composing",!1);g(this,"callbacks");g(this,"inputElement");g(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var t;const e=(t=document.getSelection())==null?void 0:t.focusNode;e&&this.editor.contains(e)&&!Ul(e)?(this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus()):(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});g(this,"handleEditorSelectionChanged",()=>{const t=!this.editor.isWritable();this.inputElement.readOnly=t});g(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});g(this,"handleCompositionstart",e=>{!this.editor.isWritable()||(this.composing=!0,this.callbacks.onCompositionStart(e))});g(this,"handleCompositionend",e=>{this.composing=!1,this.callbacks.onUpdateCompositionText(e,this.inputElement.value,!0),this.inputElement.value=""});g(this,"handleInput",e=>{if(e instanceof InputEvent&&!!e.data){if(this.editor.readonly||!this.editor.isWritable()){this.inputElement.value="";return}this.composing?this.callbacks.onUpdateCompositionText(e,e.data,!1):(this.callbacks.onInsertText(e,e.data),this.inputElement.value="")}});g(this,"handleKeyDown",e=>{if(!this.composing){if(this.callbacks.onKeyDown(e)){e.preventDefault(),e.stopPropagation();return}!this.editor.isWritable()||setTimeout(()=>{this.composing||(this.inputElement.value="")})}});g(this,"handleCopy",e=>{this.callbacks.onCopy(e)});g(this,"handleCut",e=>{if(this.editor.readonly){e.stopPropagation(),e.preventDefault();return}this.callbacks.onCut(e),bg.debug("on cut")});g(this,"handlePaste",e=>{if(this.editor.readonly){e.stopPropagation(),e.preventDefault();return}this.callbacks.onPaste(e)});g(this,"handlePasteText",e=>{this.callbacks.onPasteText(e)});this.editor=e,this.callbacks=t;const o=w("input",["editor-input"],e.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("selectionchange",this.handleDocumentSelectionChange),this.editor.addListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){this.callbacks.destroy(),document.removeEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.removeListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged);const e=this.inputElement;e.removeEventListener("compositionstart",this.handleCompositionstart),e.removeEventListener("compositionend",this.handleCompositionend),e.onkeydown=null,e.oninput=null,e.oncopy=null,e.onpaste=null,e.oncut=null}getInput(){return this.inputElement}focus(){this.editor.selection.caret.visible()||this.editor.selection.caret.update(),Kt.isMobileSafari?this.inputElement.focus():setTimeout(()=>{this.inputElement.focus()})}handleChanged(e){this.callbacks.onChanged(e)}handleRemoteChanged(e){this.callbacks.onRemoteChanged(e)}addHandler(e){this.callbacks.addHandler(e)}removeHandler(e){this.callbacks.removeHandler(e)}defaultInsertText(e,t,o,r,i){m(bg,e===this.editor,"invalid editor"),this.callbacks.defaultInsertText(e,t,o,r,i)}defaultHandleKeydown(e,t){return m(bg,e===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(e,t)}}function A6(n){const e=n.rootElement,t=e.getBoundingClientRect(),o=vs(e),r=window.innerWidth,i=window.innerHeight,s=t.left<0?0:t.left,l=t.top<0?0:t.top,a=t.right>r?r:t.right,d=t.bottom>i?i:t.bottom,h=(s+a)/2,p=(l+d)/2,A=0-t.left+h,v=0-t.top+p,B=n.input.inputElement;B.style.left=`${A/o}px`,B.style.top=`${v/o}px`}const vg=S("editor-caret");class VI{constructor(e){g(this,"editor");g(this,"caretElem");g(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=e,this.caretElem=w("div",["editor-cursor"],this.editor.contentElement),this.editor.on("readonlyChanged",this.handleReadOnlyChanged)}destroy(){this.editor.off("readonlyChanged",this.handleReadOnlyChanged)}visible(){const e=window.getComputedStyle(this.caretElem);return e.display!=="none"&&e.opacity!=="0"}hasCaret(){if(this.editor.readonly||!this.editor.selection.range.isCollapsed())return!1;const e=this.editor.selection.range.start;if(!(e instanceof jt))return!1;const t=this.editor.getBlockById(e.blockId);return!!ee(this.editor,t)}update(){if(J5(this.editor.rootElement))return;const e=this.caretElem;if(this.hasCaret())e.style.display="";else{e.style.display="none",A6(this.editor);return}const{range:t}=this.editor.selection;m(vg,t.isCollapsed,"range is not collapsed");const o=t.start;m(vg,o instanceof jt,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);m(vg,ee(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=As(s),i=new DOMRect(i.right,i.top,1,i.height)):i=zn(r,o);const l=this.editor.contentElement.getBoundingClientRect(),a=i.left-l.left,d=i.top-l.top;e.style.left=`${a}px`,e.style.top=`${d}px`,e.style.height=`${i.height}px`;const h=this.editor.input.inputElement;h.style.left=`${a}px`,h.style.top=`${d+i.height-24}px`,Kt.isMobileSafari&&(h.style.left=`${a-4}px`,h.style.height=`${i.height}px`);const A=Bo(r,{horizontal:!0}).getBoundingClientRect(),v=A.left-l.left,B=v+A.width;a<v||a>B?(A6(this.editor),e.style.display="none"):e.style.display=""}}function WI(n){YC(n),n.selection.range.getSelectedBlocks().forEach(e=>JC(n,e.block,e.start,e.end))}const qI=S("editor-dom");function b6(n){return Bo(n.rootContainer).clientHeight}function GI(n){return n.getFirstBlock().getBoundingClientRect().top}function ZI(n){return n.getLastBlock().getBoundingClientRect().bottom}function yg(n){const t=Bo(n.rootContainer).getBoundingClientRect(),o=t.x<0?0:t.x,r=t.y<0?0:t.y,i=t.right>window.innerWidth?window.innerWidth:t.right,s=t.bottom>window.innerHeight?window.innerHeight:t.bottom;return new DOMRect(o,r,i-o,s-r)}function QI(n,e){const t=yg(n),o=n.getBlockById(e.blockId),i=To(n,o,e);return ys(t,i.x,i.y)&&ys(t,i.right,i.bottom)}function v6(n,e){const t=yg(n),o=e.getBoundingClientRect();return o.top>=t.top&&o.top<=t.bottom||o.bottom<=t.bottom&&o.bottom>=t.top}function YI(n,e){const t=yg(n),o=e.getBoundingClientRect();return ys(t,o.x,o.y)||ys(t,o.right,o.bottom)}function JI(n){if(!mm(n.rootContainer)){qI.warn("editorScrollIntoView: editor is not visible");return}const e=n.rootContainer.getBoundingClientRect();if(e.height<1&&e.width<1)return;const t=n.selection,o=t.range.focus;if(!o.isSimple()){const h=o,p=n.getContainerById(h.childContainerId);YI(n,p)||p.scrollIntoView();return}if(t.range.start.blockId===t.range.end.blockId){const h=n.getBlockById(t.range.start.blockId);if(Lt(h)&&v6(n,h)||Le(n,h)&&v6(n,h))return}const r=o,i=n.getBlockById(r.blockId);if(QI(n,r))return;const s=To(n,i,r),l=i.getBoundingClientRect(),a=Et(i),d=w("div",["editor-block-anchor"],a);d.style.top=`${s.top-l.top}px`,gm(d,{elementToScroll:Bo(n.rootContainer)}),setTimeout(()=>{d.remove()},200)}function KI(n,e){if(e.isCollapsed())return!1;const t=St(n.rootContainer),o=Gt(n.rootContainer),{start:r,end:i}=e;return r.blockId===re(t)&&r.offset===0&&i.blockId===re(o)&&i.offset===ue(n,o)}const y6=S("range-in-block");function k6(n,e){const t=e.getEditor(),o=t.getBlockById(e.start.blockId),r=t.getBlockById(e.end.blockId),i=o===n||Ke(n,o),s=r===n||Ke(n,r);return!!(i||s)}function w6(n,e){const t=n.doc.toJSON(),o=new Set(Object.values(t.blocks).map(s=>s.map(l=>l.id)).flat());let r,i=lt(e);if(i){for(;i&&!o.has(re(i));)i=lt(i);m(y6,i,"no prev block while deleting a block"),r=vt(n,i,ue(n,i))}else{const s=Ze(e);m(y6,s,"no prev and next block while deleting a block"),r=vt(n,s,0)}return r}const XI=S("block-to-html");function kg(n,e,t,o){const r=Ss(n,e.type);if(r.convertTo)return r.convertTo(n,e,t,"html",o);if(r.blockKind!=="text")return`[${e.type}]`;m(XI,e.text,"no text");const i=rt(e.text);return`<div>${tC(i)}</div>`}const B6=S("block-to-text");function eT(n,e,t){let o="";return e.forEach(r=>{if(m(B6,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,t,"text");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${i.type}]`}o+=r.insert}),o}function fh(n,e,t,o){const r=Ss(n,e.type);return r.convertTo?r.convertTo(n,e,t,"text",o):r.blockKind!=="text"?`[${e.type}]`:(m(B6,e.text,"no text"),eT(n,e.text,t))}function wg(n,e,t,o){const r=Ss(n,e.type);return r.convertTo?r.convertTo(n,e,t,"markdown",o):fh(n,e,t,o)}function mh(n,e){return e.blocks.root.map((r,i)=>kg(n,r,e,[{containerId:"root",blockIndex:i}])).join(`
25
25
  `)}function E6(n,e){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${mh(n,e)}</body></html>`}function Da(n,e){return e.blocks.root.map((r,i)=>fh(n,r,e,[{containerId:"root",blockIndex:i}])).join(`
26
26
  `)}function Sa(n,e){return e.blocks.root.map((r,i)=>wg(n,r,e,[{containerId:"root",blockIndex:i}])).join(`
27
- `)}const tT=S("get-text-position");function ql(n,e){const t=e!=null?e:n.selection.range.start;t instanceof jt||m(tT,!1,`invalid insert pos type: ${typeof t}`);const{blockId:o}=t,r=n.getBlockById(o),i=be(r),s=ne(r),l=ae(s),{offset:a}=t;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const La=S("insert-text");function gh(n,e,t,o){var s;const r=n.doc.getBlockData(e,t);if(m(La,r,"no block data"),m(La,r.text,"no block text"),rn(r.text)===0)return m(La,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=zt(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function nT(n,e,t){const o=ne(e),r=ae(o),i=be(e);return gh(n,r,i,t)}function x6(n,e,t,o,r){const i=ne(e),s=ae(i),l=be(e),a=nT(n,e,t),d=Ba(t,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),mn(n,e)}function I6(n,e,t,o){const r=ne(e),i=ae(r),s=be(e),l=Ba(t," ",o);return n.doc.localUpdateBlockText(i,s,l),mn(n,e)}function Bg(n,e,t,o,r){const i=n.doc.getBlockData(t,o);m(La,i,"no block data"),m(La,i.text,"no block text");const s=gh(n,t,o,r),l=Ba(r,e,s!=null?s:null);return n.doc.localUpdateBlockText(t,o,l),mn(n,n.getBlockById(i.id))}function Eg(n,e){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:t,blockIndex:o,offset:r}=ql(n);Bg(n,e,t,o,r)}const ph=S("update-composition-text");function T6(n){const e=n.selection.range.start;e instanceof jt||m(ph,!1,`invalid insert pos type: ${typeof e}`);const{blockId:t}=e,o=n.getBlockById(t);m(ph,ee(n,o),"not a text kind block");const r=ne(o),i=ae(r),s=be(o),l=n.doc.getBlockData(i,s);m(ph,l,"no block data in doc"),m(ph,l.text,"no text data in text block");const a=Re(o);th(n,Di(o),t,a,l.text)}function D6(n){Ox(n)}function Gl(n,e,t,o,r,i){return n.doc.localInsertBlock(e,t,o,r,i),n.getBlockById(o.id)}const Ma=S("delete-block-text");function xg(n,e,t,o,r){if(!n.isBlockWritable(e))return Ma.error("block is not writable"),0;m(Ma,ee(n,e),"block is not a text kind block");const i=ne(e),s=ae(i),l=be(e),a=n.doc.getBlockData(s,l);m(Ma,a,"no block data in doc"),m(Ma,a.text,"no text data in text block");let d=t;sn(e,t)||(d=Ri(e,d));let h=t+o;m(Ma,h<=ue(n,e),`invalid offset and count: ${t}, ${o}`),sn(e,h)||(h=Os(e,h));const p=h-d,A=$4(d,p);return n.doc.localUpdateBlockText(s,l,A,r),p}const Ig=S("break-text-block");function S6(n,e){const o=n.getBlockData(e).quoted;return o?{quoted:o}:{}}function Zl(n,e,t,o){m(Ig,ee(n,e),`block is not a text kind block: ${De(e)}`),m(Ig,t>=0&&t<=ue(n,e),`invalid offset: ${t}`);const r=ne(e),i=ae(r),s=be(e),l=o!=null&&o.copyBlockAttributes?S6(n,e):{};if(!(o!=null&&o.forceInsertAfter)&&(t===0||t===ue(n,e))){const v=t===0?s:s+1,B={...sr(""),...l,...o==null?void 0:o.newBlockData},D=vt(n,e.id,0),x=Gl(n,i,v,B,D);return{block:e,newBlock:x}}m(Ig,sn(e,t),"not a valid offset");const a=mn(n,e),{right:d}=xn(a,t),h=rn(d);h>0&&xg(n,e,t,h);const p={...sr(d),...l,...o==null?void 0:o.newBlockData},A=Gl(n,i,s+1,p,vt(n,p.id,0));return{block:e,newBlock:A}}const oT=S("prepare-insert-new-block");function rT(n,e,t){if(e&&t!==void 0&&t!==null){const d=n.getContainerById(e),h=bt(d);return m(oT,t>=0&&t<=h.length,`invalid blockIndex: ${t}`),{containerId:e,blockIndex:t}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(e=ae(ne(r)),t=be(r),!ee(n,r))return{containerId:e,blockIndex:t+1};const s=o.offset;if(s===0||s===ue(n,r))return{containerId:e,blockIndex:s===0?t:t+1};const a=Zl(n,r,s).newBlock;return{containerId:e,blockIndex:be(a)}}const iT=S("auto-insert-block");function L6(n,e,t,o,r,i){const s=rT(n,t,o);m(iT,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:e.id,offset:0},a={anchor:l,focus:l};return Gl(n,s.containerId,s.blockIndex,e,r!=null?r:a,i)}const sT=S("delete-block");function Ch(n,e,t){e.children&&(t.push(...e.children),e.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{Ch(n,i,t)})}))}function Ah(n,e,t){const o=ne(e),r=ae(o),i=be(e),s=n.doc.getBlockData(r,i);return m(sT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Ut(n,{anchor:t.start,focus:t.end})),s}function Tg(n,e,t){return n.undoManager.runInGroup(()=>{const o=ne(e);Eo(o)===1&&n.insertTextBlock("",ae(o),0);let r=t?Si(n,t):null;if(!r){const l=n.selection.range;k6(e,l)?r=w6(n,e):r=l}const i=Ah(n,e,r),s=[];return Ch(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function lT(n,e){const t=[e];n.doc.getContainerBlocks(e).forEach(r=>{Ch(n,r,t)}),n.doc.localDeleteChildContainers(t)}function M6(n,e){const t=[...e];e.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{Ch(n,i,t)})}),n.doc.localDeleteChildContainers(t)}const Dg=S("merge-text-block");function R6(n,e,t){m(Dg,ee(n,e),"only text block can be merged"),m(Dg,ee(n,t),"only text block can be merged");const o=_i(n,e),r=_i(n,t),i=o.text,s=r.text;m(Dg,i&&s,"block data has no text");const l=ne(e),a=ae(l),d=be(e),h=ue(n,e),p=Bg(n,s,a,d,h),A=vt(n,e,rn(i));return Tg(n,t,A),p}const lr=S("clear-selected-contents");function bh(n,e){m(lr,ee(n,e.block),"not a text kind block");const{start:t,end:o}=e;m(lr,t.isSimple(),"not a simple block position"),m(lr,o.isSimple(),"not a simple block position");const r=t.offset,i=o.offset;m(lr,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(e.block,r,i-r)}function O6(n,e,t){const o=ae(e),r=bt(e),i=t.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});t.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function cT(n,e){const{block:t,start:o,end:r}=e;if(ee(n,t)){bh(n,e);return}if(Lt(t)||o.isSimple()){m(lr,r.isSimple(),"invalid range");const s=ne(t),l=be(t),a=n.insertTextBlock("",ae(s),l);n.selection.selectBlock(a,0),n.deleteBlock(t);return}m(lr,Le(n,t),"invalid block kind"),m(lr,!o.isSimple()&&!r.isSimple(),"invalid range"),Ms(n,t,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{O6(n,s,{focus:l===0})})}function aT(n){if(!n.isWritable())return;const e=n.selection.range;if(e.isCollapsed())return;const t=e.getSelectedBlocks();if(m(lr,t.length>0,"no selected block"),t.length===1){cT(n,t[0]);return}const o=t[0],r=o.block,i=ne(r);m(lr,t.length>1,"no selected block");const s=t[t.length-1],l=s.block;if(ee(n,r)){bh(n,o);const h=vt(n,o.block,o.start.offset);if(t.slice(1,t.length-1).reverse().forEach(A=>n.deleteBlock(A.block)),ee(n,l)){bh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(ee(n,l)){bh(n,s),t.slice(0,t.length-1).reverse().forEach(h=>n.deleteBlock(h.block)),n.selection.selectBlock(s.block,0);return}if(t.length===Eo(i)){O6(n,i,{focus:!0});return}const a=lt(r),d=Ze(l);m(lr,a||d,"no prev or next block"),t.forEach(h=>n.deleteBlock(h.block))}function Sg(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),aT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const uT=S("core");function _6(n,e,t){const o=ne(e),r=ae(o),i=be(e);return n.doc.localUpdateBlockText(r,i,t),setTimeout(()=>{n.selection.updateSelection(null)}),mn(n,e)}function F6(n,e,t){if(!n.isBlockWritable(e)){uT.error("block is not writable");return}const o=n.getBlockText(e),r=ln.diff(o,t);_6(n,e,r)}function vh(n,e,t){const o=mn(n,e),r=typeof t=="string"?Oi(t):t,i=ln.diff(o,r);return _6(n,e,i)}const Ra=S("update-block-data");function yh(n,e,t,o){const r=ne(e),i=ae(r),s=be(e),l=n.doc.getBlockData(i,s),a={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(t));return d.forEach(A=>{if(!h.has(A)){if(A==="id"||A==="type"||A==="text")return;Ra.debug(`delete key: ${A}`),a.delete.push(A)}}),Object.entries(t).forEach(([A,v])=>{m(Ra,A!=="id"&&A!=="type",`invalid block data delta, ${A}`);const B=l[A];if(v==null){B!=null&&(Ra.debug(`delete key: ${A}`),a.delete.push(A));return}B!==v&&(la.default(B,v)||A==="text"&&ln.diff(B,v).length===0||(d.has(A)?(Ra.debug(`replace key: ${A}`),a.delete.push(A)):Ra.debug(`insert key: ${A}`),a.insert[A]=v))}),n.doc.localUpdateBlockData(i,s,a,o),_i(n,e)}function P6(n,e,t,o){const i={...n.getBlockData(e),embedData:t};return n.updateBlockData(e,i,o)}function Lg(n,e,t){if(!Le(n,e)||!(t!=null&&t.tryFocusToChildSimpleBlock)){n.selection.selectBlock(e,0);return}const r=jn(n,e).getChildContainers(n,e)[0],i=St(r);Lg(n,i,t)}function Ps(n){const e=[];let t={};return n.forEach(o=>{e.push(...o.blocks.root);const{root:r,...i}=o.blocks;t={...t,...i}}),{blocks:{...t,root:e},meta:{},comments:{}}}const Oa=S("clone-block");function Fi(n,e,t,o){const r=n.getBlockClass(t.type);if(r.blockToDoc)return r.blockToDoc(e,t,(h,p)=>(m(Oa,t!==p,"invalid child block"),Fi(n,h,t,o)));let i={};const s=new Map,l=fe.default(t);l.children&&(l.children=l.children.map(h=>{const p=K(),A=e.blocks[h];m(Oa,Array.isArray(A),"invalid child blocks");const v=A.map(_=>Fi(n,e,_,o)),B=Ps(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[A,v]=p;{const B=`${A}/`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}/${D}`;return Oa.debug(`replace key: ${h} -> ${x}`),x}}{const B=`${A}_`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}_${D}`;return Oa.debug(`replace key: ${h} -> ${x}`),x}}}return h};return Array.from(Object.entries(l)).forEach(([h,p])=>{const A=d(h);A!==h&&delete l.key,l[A]=p}),l.id=K(),o&&(o.blockIdMap.set(t.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Mg(n,e,t,o){const r=e.blocks[t];m(Oa,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Fi(n,e,l,o));return Ps(i)}function Rg(n,e,t){const o=e.blocks.root.map(r=>Fi(n.editorBlocks,e,r,t));return fe.default(Ps(o))}const N6=S("insert-doc");function $6(n,e,t,o,r){if(Le(n,e)){N6.warn("failed to insert doc into a complex block");return}const i=Rg(n,o,r),s=ne(e),l=be(e),a=ae(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var M,j,z;Object.entries(i.blocks).forEach(([q,ie])=>{q!=="root"&&n.doc.localInsertChildContainer(q,ie)});const d=i.blocks.root;if(Lt(e)){n.deleteBlock(e);let q;d.reverse().forEach(ie=>{const me=n.insertBlock(a,l,ie);q||(q=me)}),q&&n.selection.selectBlock(q,ue(n,q));return}if(m(N6,ee(n,e),"not a text block"),dt(n,e)){const q=a==="root"&&n.getBlockByIndex(a,0)===e,ie=be(e);let me;d.forEach((Be,je)=>{const Ue=n.insertBlock(a,ie+je,Be);je===d.length-1&&(me=Ue)}),me&&n.selection.selectBlock(me,ue(n,me)),q&&n.deleteBlock(e);return}if(d.length===1){const q=d[0];if(Aa(n,q.type)){n.insertTextToBlock(e,t,(M=q.text)!=null?M:[]);return}n.breakTextBlock(e,t),n.insertBlock(a,l+1,q);return}const h=t===ue(n,e),p=t===0,A=d[0],v=d[d.length-1];let B;!h&&!p?B=n.breakTextBlock(e,t,{forceInsertAfter:!0}):B=e;const D=p?l:l+1;h?(B=n.insertBlock(a,l+1,v),n.selection.selectBlock(B,ue(n,B))):(n.selection.selectBlock(B,0),Aa(n,v.type)?n.insertTextToBlock(B,0,(j=v.text)!=null?j:[]):n.insertBlock(a,D,v));const x=n.selection.range;let _=D;Aa(n,A.type)?p?(n.insertBlock(a,D,A),_+=1):n.insertTextToBlock(e,t,(z=A.text)!=null?z:[]):(n.insertBlock(a,D,A),_+=1),d.slice(1,d.length-1).reverse().forEach(q=>{n.insertBlock(a,_,q)}),n.selection.setRange(x)}),n.doc.endBatchUpdate()}function Og(n,e,t,o,r){const i=Rg(n,o,r),s=ae(e),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([d,h])=>{d!=="root"&&n.doc.localInsertChildContainer(d,h)}),i.blocks.root.reverse().forEach(d=>{const h=n.insertBlock(s,t,d);l.push(h)})}),l}function H6(n,e,t){const o=Eo(e);Og(n,e,o,t);for(let r=0;r<o;r++){const i=St(e);n.deleteBlock(i)}}const _a=S("add-text-attribute");function dT(n,e,t,o){const{start:r,end:i}=t;m(_a,r.blockId===i.blockId&&r.blockId===re(e),"invalid range"),m(_a,o,"invalid attribute name");const s=n.getBlockText(e),l=Wl(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(e,l),l}function j6(n,e,t,o,r){const{start:i,end:s}=t;m(_a,i.blockId===s.blockId&&i.blockId===re(e),"invalid range"),m(_a,o,"invalid attribute name");const l=n.getBlockText(e),a=Ea(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,a),a}function Ql(n,e,t,o,r){const{start:i,end:s}=t;m(_a,i.blockId===s.blockId&&i.blockId===re(e),"invalid range");const l=n.getBlockText(e),a=Z4(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,a),a}function U6(n,e,t,o){const r=Lo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!ee(n,s))return;if(dt(n,s)){o(n,re(s),e,t);return}const d=Ut(n,{anchor:l,focus:a});e==="color"||e==="backgroundColor"?Ql(n,s,d,e,t):(Ql(n,s,d,"color",null),Ql(n,s,d,"backgroundColor",null))})})}function z6(n,e,t){const o=Lo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!ee(n,i))return;if(dt(n,i)){(e==="clearColor"||e==="clearAll")&&t(n,re(i),"color",null),(e==="clearBackground"||e==="clearAll")&&t(n,re(i),"backgroundColor",null);return}const a=Ut(n,{anchor:s,focus:l});(e==="clearColor"||e==="clearAll")&&Ql(n,i,a,"color",null),(e==="clearBackground"||e==="clearAll")&&Ql(n,i,a,"backgroundColor",null)})})}function _g(n,e){const t=Lo(n,{simpleBlockOnly:!0}).filter(s=>ee(n,s.block));if(t.length===0)return[null,null];const o=s=>{if(ue(n,s.block)===0)return e(n,re(s.block));const l=s.start,a=s.end,d=n.getBlockText(s.block);return J4(l.offset,a.offset-l.offset,d)};let[r,i]=o(t[0]);return r===null&&i===null?[r,i]:(t.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 Vn=S("adjust-selection-pos");function V6(n){const e=[];for(;n;){const t=ne(n);if(e.unshift(t),Xe(t))return e;const o=oe(t);m(Vn,o,"child container has not parent container"),n=o}m(Vn,!1,"should not come here: getParentContainers")}function W6(n,e){for(;e;){const t=ne(e);if(t===n)return e;const o=oe(t);m(Vn,o,"could not find parent block for a child container"),e=o}m(Vn,!1,"no parent block in specified container")}function hT(n,e){const t=V6(n),o=V6(e);m(Vn,t.length>0&&o.length>0,"block has not parent container"),m(Vn,t[0]===o[0],"root container does not equal");let r=t[0];for(let l=1;l<t.length||o.length;l++)if(t[l]!==o[l]){r=t[l-1];break}const i=W6(r,n),s=W6(r,e);return{parentContainer:r,newBlock1:i,newBlock2:s}}function q6(n,e){let t=oe(e);for(m(Vn,t,"element is not in a block");t;){const o=ne(t);m(Vn,Do(o),"not a child container");const r=oe(o);if(m(Vn,r,"child container has not parent block"),r===n)return o;t=r}m(Vn,!1,"failed to find parent container in complex block")}function kh(n,e,t){const o=n.getBlockById(e.blockId),r=n.getBlockById(t.blockId);if(o===r)return e instanceof jt&&t instanceof jt?{anchor:e,focus:t}:e instanceof So&&t instanceof So?Xd(n,o,e,t):null;const i=ne(o),s=ne(r);if(i===s)return e instanceof So&&(e=se(o,0,"home")),t instanceof So&&(t=se(r,ue(n,r),"end")),m(Vn,e instanceof jt,"not valid position type"),m(Vn,t instanceof jt,"not valid position type"),{anchor:e,focus:t};if(o.contains(s))return null;if(r.contains(i)){if(e instanceof jt&&t instanceof So){const B=n.getContainerById(t.childContainerId);if(B===i)return{anchor:t,focus:t};const D=oe(i);if(D&&D===oe(B)){const x=ht(D,ae(i)),_=ht(D,ae(B));return Xd(n,D,x,_)}}return null}const l=Nd(o,r)>0,{newBlock1:a,newBlock2:d}=hT(o,r);if(a===d){const B=a,D=q6(B,o),x=q6(B,r);return e=ht(a,ae(D)),t=ht(a,ae(x)),Vn.debug(`select in complex block: ${D.id}, ${x.id}`),Xd(n,B,e,t)}let h=l?ue(n,a):0;a===o&&e instanceof jt&&(h=e.offset);let A=l?0:ue(n,d);return d===r&&t instanceof jt&&(A=t.offset),e=se(a,h,l?"end":"home"),t=se(d,A,l?"home":"end"),{anchor:e,focus:t}}const fT=S("move-complex-block-position");function mT(n,e,t){const o=n.getBlockById(e.blockId);m(fT,Le(n,o),"is not a complex block");const r=jn(n,o),i=n.getContainerById(e.childContainerId),s=r.getNextContainer(n,o,i,t,{noWrap:!0});return s?ht(o,ae(s)):null}const Fa=S("move-simple-block-position");function G6(n,e){const t=En(n,e,{visibleOnly:!0});m(Fa,t.length>0,"complex block has not any child container");const o=t[0];return St(o)}function Z6(n,e){const t=En(n,e,{visibleOnly:!0});m(Fa,t.length>0,"complex block has not any child container");const o=t[t.length-1];return Gt(o)}function Q6(n,e,t){const o=t?G6(n,e):Z6(n,e);return Le(n,o)?Q6(n,o,t):o}function gT(n,e){const t=n.getBlockById(e.blockId);return Le(n,t)&&e.offset===0?G6(n,t):Ds(t)}function pT(n,e){const t=n.getBlockById(e.blockId);return Le(n,t)&&e.offset===1?Z6(n,t):Ts(t)}function Fg(n){return n==="ArrowLeft"||n==="ArrowUp"}function Pg(n,e,t){const o=ne(e);if(Xe(o))return null;const r=oe(o);m(Fa,r,"child container has not parent block"),m(Fa,Le(n,r),"is not a complex block");const i=jn(n,r).getNextContainer(n,r,o,t);return i?Fg(t)?Gt(i):St(i):Pg(n,r,t)}function CT(n,e,t){const o=ne(e);if(Xe(o))return null;const r=oe(o);if(m(Fa,r,"child container has not parent block"),Fg(t)){const l=lt(r);if(l)return l}else{const l=Ze(r);if(l)return l}const i=Pg(n,r,t);if(i)return i;let s=r;for(;!Xe(ne(s));)s=oe(ne(s));return Fg(t)?lt(s):Ze(s)}function AT(n,e,t){return!Le(n,e)||jn(n,e).enableKeyboardSelect?e:Q6(n,e,t==="ArrowDown"||t==="ArrowRight")}function bT(n,e,t){const o=n.getBlockById(e.blockId),i=Qe(n,o).moveCaret(n,o,e,t);if(i)return i;let s=t==="ArrowDown"||t==="ArrowRight"?gT(n,e):pT(n,e);if(s||(s=Pg(n,o,t),s||(s=CT(n,o,t))),!s){if(t==="ArrowDown"||t==="ArrowRight"){if(n.readonly||!Xe(ne(o)))return null;const l=n.insertTextBlock("",ae(n.rootContainer),Eo(n.rootContainer));return se(l,0,"home")}return null}if(s=AT(n,s,t),ee(n,s)){const l=n.selection.getSuggestedCaretX();if(t==="ArrowDown")return qx(n,s,o,e,l);if(t==="ArrowUp")return Wx(n,s,o,e,l)}return t==="ArrowLeft"||t==="ArrowUp"?se(s,ue(n,s),"end"):t==="ArrowRight"||t==="ArrowDown"?se(s,0,"home"):null}function vT(n,e,t){if(e==="ArrowLeft")return t.start;const o=t.end,r=n.getBlockById(o.blockId);if(ee(n,r))return o;const i=Ze(r);if(i)return se(i,0,"home");if(!Xe(ne(r))||n.readonly)return o;const s=n.insertTextBlock("",ae(n.rootContainer),Eo(n.rootContainer));return se(s,0,"home")}function yT(n,e,t){const o=n.selection.range;let r;if(o instanceof Zt)t==="move"&&!o.isCollapsed()&&(e==="ArrowLeft"||e==="ArrowRight")?r=vT(n,e,o):r=bT(n,o.getFocusedPos(),e);else if(r=mT(n,o.focus,e),t==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(e==="ArrowLeft"||e==="ArrowUp"){const l=Gt(s);r=se(l,0,"home")}else{const l=St(s);r=se(l,ue(n,l),"end")}}return r?t==="move"?{anchor:r,focus:r}:kh(n,o.anchor,r):null}function Pi(n,e,t){const o=yT(n,e,t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(e==="ArrowLeft"||e==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function Y6(n){return Pi(n,"ArrowLeft","move"),!0}function J6(n){return Pi(n,"ArrowRight","move"),!0}function K6(n){return Pi(n,"ArrowUp","move"),!0}function X6(n){if(Pi(n,"ArrowDown","move")||n.readonly)return!0;const e=n.getFocusedBlock(),t=ne(e);if(Xe(t)||Gt(t)!==e)return!0;const o=n.rootContainer;return n.insertTextBlock("",ae(o),Eo(o)),!0}function e9(n){return Pi(n,"ArrowDown","select"),!0}function t9(n){return Pi(n,"ArrowLeft","select"),!0}function n9(n){return Pi(n,"ArrowRight","select"),!0}function o9(n){return Pi(n,"ArrowUp","select"),!0}const r9=S("word-offset");function Ng(n,e){const t=n.selection.range.focus;m(r9,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(dt(n,o))return se(o,0,"home");if(t.offset===0||!ee(n,o)){const s=lt(o);if(!s)return null;const l=se(s,ue(n,s),"end");if(e==="select"&&ee(n,s)){const a=pg(n,s,l.offset);return se(s,a,"normal")}return l}const r=pg(n,o,t.offset);return se(o,r,"normal")}function $g(n,e){const t=n.selection.range.focus;m(r9,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(dt(n,o))return se(o,0,"end");if(t.offset===ue(n,o)||!ee(n,o)){const s=Ze(o);if(!s)return null;const l=se(s,0,"home");if(e==="select"&&ee(n,s)){const a=Cg(n,s,l.offset);return se(s,a,"end")}return l}const r=Cg(n,o,t.offset);return se(o,r,"normal")}function i9(n){if(!n.selection.range.focus.isSimple())return!1;const t=Ng(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function s9(n){if(!n.selection.range.focus.isSimple())return!1;const t=$g(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function l9(n){if(!n.selection.range.focus.isSimple())return!1;const t=Ng(n,"select");return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function c9(n){if(!n.selection.range.focus.isSimple())return!1;const t=$g(n,"select");return t?(n.selection.setSelection(n.selection.range.anchor,t),n.selection.updateLastCaretRect(),!0):!1}S("find-block");function Hg(n,e){if(!Le(n,e))return e;const o=jn(n,e).getChildContainers(n,e)[0],i=bt(o)[0];return Hg(n,i)}function jg(n,e){if(!Le(n,e))return e;const t=jn(n,e).getChildContainers(n,e),o=t[t.length-1],r=bt(o),i=r[r.length-1];return jg(n,i)}function a9(n){const e=jg(n,Gt(n.rootContainer)),t=se(e,ue(n,e),"end");return n.selection.setSelection(t),!0}function u9(n){const e=Hg(n,n.getFirstBlock()),t=se(e,0,"home");return n.selection.setSelection(t),!0}function d9(n){const e=Hg(n,n.getFirstBlock()),t=se(e,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}function Ug(n){const e=jg(n,Gt(n.rootContainer)),t=se(e,ue(n,e),"end");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}const h9=S("line-offset");function f9(n){const e=n.selection.range.focus;m(h9,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===0||!ee(n,t))return se(t,0,"home");let r=O4(t,e).start;const{next:i}=Yd(t,r);return i&&ro(i)&&Ca(i)==="br"&&(r+=1),se(t,r,"home")}function m9(n){const e=n.selection.range.focus;m(h9,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===ue(n,t)||!ee(n,t))return se(t,ue(n,t),"end");const o=O4(t,e);return se(t,o.end,"end")}function g9(n){if(!n.selection.range.focus.isSimple())return!1;const t=f9(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function p9(n){if(!n.selection.range.focus.isSimple())return!1;const t=m9(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function C9(n){if(!n.selection.range.focus.isSimple())return!1;const t=f9(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function A9(n){if(!n.selection.range.focus.isSimple())return!1;const t=m9(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}const b9=S("find-block-position");function kT(n,e,t,o){m(b9,Le(n,e),"is not a complex block");const r=jn(n,e).getChildContainers(n,e);m(b9,r.length>0,"complex block has not any child container");const i=To(n,t,o),s=i.left+i.width/2,l=i.top+i.height/2,a=w4(n,e,s,l);return zg(n,a,t,o)}function zg(n,e,t,o){if(Le(n,e))return kT(n,e,t,o);const r=re(e);let i=Number.MAX_SAFE_INTEGER;const s=To(n,t,o),l=s.left+s.width/2,a=s.top+s.height/2;let d=se(r,0,"home");const h=ue(n,e);for(let p=0;p<=h;p++){const A=se(r,p,"normal"),v=To(n,e,A),B=tr(v,l,a);B<i&&(i=B,d=A)}return d}const v9=S("page-offset");function wT(n,e){const t=b6(n)*.9,r=e.getBoundingClientRect().bottom-t;if(r<GI(n))return n.getFirstBlock();const i=lt(e);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=lt(s)}return n.getFirstBlock()}function BT(n,e){const t=b6(n)*.9,o=e.getBoundingClientRect(),r=ZI(n),i=o.top+t;if(i>r)return n.getLastBlock();const s=Ze(e);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Ze(l)}return n.getLastBlock()}function y9(n){const e=n.selection.range.focus;m(v9,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=wT(n,t);let r;return o===n.getFirstBlock()?r=se(o,0,"home"):r=zg(n,o,t,e),r}function k9(n){const e=n.selection.range.focus;m(v9,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=BT(n,t);let r;return o===n.getLastBlock()?r=se(o,ue(n,o),"end"):r=zg(n,o,t,e),r}function w9(n){if(!n.selection.range.focus.isSimple())return!1;const t=y9(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function B9(n){if(!n.selection.range.focus.isSimple())return!1;const t=k9(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function E9(n){if(!n.selection.range.focus.isSimple())return!1;const t=y9(n);if(!t)return!1;const o=kh(n,n.selection.getAnchorPos(),t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function x9(n){if(!n.selection.range.focus.isSimple())return!1;const t=k9(n);if(!t)return!1;const o=kh(n,n.selection.getAnchorPos(),t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const Pa=S("select-all");function I9(n,e){const t=St(n),o=Gt(n);return e.start.offset===0&&e.start.blockId===re(t)&&e.end.offset===ue(e.getEditor(),o)&&e.end.blockId===re(o)}function ET(n,e){const t=e.getEditor(),o=jn(t,n).getChildContainers(t,n),r=o[0],i=o[o.length-1],s=re(n);return e.start.blockId===s&&e.start.childContainerId===ae(r)&&e.end.blockId===s&&e.end.childContainerId===ae(i)}function xT(n,e){m(Pa,e,"no parent block"),m(Pa,Le(n,e),"not a complex block");const t=jn(n,e).getChildContainers(n,e),o=t[0],r=t[t.length-1];n.selection.setRange(Ut(n,{anchor:ht(e,ae(o)),focus:ht(e,ae(r))}))}function T9(n,e){const t=ne(e);Vg(n,t)}function D9(n){const e=n.getFocusedBlock(),t=n.selection.range;if(t.start.isSimple()){if(t.start.blockId===t.end.blockId&&ee(n,e)){const r=t.start,i=t.end,s=ue(n,e);if(r.offset>0||i.offset<s)return n.selection.selectBlock(e,0,s),!1}return W(n.rootContainer,"select-all"),T9(n,St(n.rootContainer)),!1}return m(Pa,!t.isSimple(),"invalid range type"),ET(e,t)?(T9(n,e),!1):(m(Pa,e,"no parent block"),m(Pa,Le(n,e),"not a complex block"),xT(n,e),!0)}function Vg(n,e){const t=bt(e),o=t[0],r=t[t.length-1],i=se(o,0,"home"),s=se(r,ue(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function S9(n){Ug(n),n.focus()}const Wg=S("selected-block-to-doc");function L9(n,e,t){!e.children||e.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{L9(n,i,t)}),t.blocks[o]=fe.default(r)})}function wh(n,e){const t=Qe(n,e.block);if(t.selectionToDoc)return t.selectionToDoc(n,e);const o=fe.default(_i(n,e.block));if(ee(n,e.block)){const i=e.start,s=e.end;if(m(Wg,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=zt(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Lt(e.block))return{blocks:{root:[o]},meta:{},comments:{}};m(Wg,Le(n,e.block),"not complex block"),m(Wg,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return L9(n,o,r),r}function qg(n,e){const t=se(e,0,"normal"),o=se(e,ue(n,e),"end");return wh(n,{block:e,start:t,end:o})}const IT=S("block-to-doc");function TT(n,e){m(IT,e.length>0,"invalid params, no blocks");const t=e.map(o=>qg(n,o));return Ps(t)}function Bh(n){const t=n.selection.range.getSelectedBlocks().map(o=>wh(n,o));return Ps(t)}function M9(n,e){const t=n.getContainerById(e),i=bt(t).map(s=>({start:se(s,0,"home"),end:se(s,ue(n,s),"end"),block:s})).map(s=>wh(n,s));return Ps(i)}const Eh=S("editor-selection");class DT{constructor(e){g(this,"editor");g(this,"caret");g(this,"_range");g(this,"lastCaretRect");g(this,"handleBlockDelete",(e,t,o,r)=>{if(o||r.child)return;const i=this.range;if(k6(t,i)){Eh.debug("adjust selection because remote deleted current block");const s=w6(e,t);this.setRange(s,{noScroll:!0})}});this.editor=e;const t=e.getFirstBlock(),o=re(t);this.caret=new VI(e);const r=se(o,0,"normal");this._range=Ut(e,{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 e=this.range.focus;return this.editor.getBlockById(e.blockId)}getStartBlock(){const e=this.range.start;return this.editor.getBlockById(e.blockId)}getEndBlock(){const e=this.range.end;return this.editor.getBlockById(e.blockId)}selectBlock(e,t,o){const r=se(e,t,"normal");let i;o&&(i=se(e,o,"normal")),this.setSelection(r,i)}setSelection(e,t,o){if(t||(t=e),this.verifyPos(e),this.verifyPos(t),!this.selectionChanging(e,t))return this.range;const r=Ut(this.editor,{anchor:e,focus:t});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),xe(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!KI(this.editor,r))&&te(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(e,t){return this.setSelection(e.anchor,e.focus,t)}updateSelection(){this.caret.update(),WI(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(e,t){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const e=this.range.focus;if(!Nr(e))return;const t=this.editor.getBlockById(e.blockId);this.lastCaretRect=To(this.editor,t,e)}getSuggestedCaretX(){var e;return(e=this.lastCaretRect)==null?void 0:e.x}scrollIntoView(){JI(this.editor)}verifyPos(e){const t=this.editor.getBlockById(e.blockId);if(e.isSimple())e.offset>=0&&e.offset<=ue(this.editor,t)||m(Eh,!1,"invalid block position, out of range");else{const o=e.childContainerId;!!this.editor.getContainerById(o)||m(Eh,!1,"invalid complex block position, no container found")}}updateFocusedBlock(e){if(e&&this.range.start.blockId===e.start.blockId)return;let t;e&&e.start.blockId===e.end.blockId&&(t=this.editor.findBlockById(e.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;t&&xe(t,"focused")&&(te(t,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,t!=null?t:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(e){const t=Bh(this.editor);return e==="text"?Da(this.editor,t):e==="markdown"?Sa(this.editor,t):E6(this.editor,t)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(e=>{te(e,"focused"),te(e,"child-focused")})}setBlockFocused(e){if(xe(e,"focused"))return!1;W(e,"focused");let t=ne(e);for(;Do(t);){const o=oe(t);m(Eh,o,"parent block not found"),W(o,"child-focused"),t=ne(o)}return!0}}function ST(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);!t||n.selection.selectBlock(t,0,ue(n,t))}function LT(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);if(!t||!ee(n,t))return;let o=Ng(n,"select"),r=$g(n,"select");if(!o||!r)return;const i=e.blockId;o.blockId!==i&&(o=se(t,0,"home")),r.blockId!==i&&(r=se(t,ue(n,t),"end")),n.selection.setSelection(o,r)}class MT{constructor(e){g(this,"editor");g(this,"startPos",null);g(this,"lastCaretRect");g(this,"mouseDownEvent",null);g(this,"handleMouseDown",e=>{this.mouseDownEvent=e;const t=x4(this.editor,e.x,e.y);if(t){if(t instanceof or)return;const o=this.editor.selection.range;if(e.shiftKey&&o.isSimple()){const r=o.anchor;this.editor.selection.setSelection(r,t.focus),this.startPos=t.start}else this.editor.selection.setSelection(t.anchor,t.focus),this.startPos=t.start;this.editor.selection.updateLastCaretRect()}});g(this,"handleMouseMove",e=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-e.x)<3&&Math.abs(this.mouseDownEvent.y-e.y)<3)return;const t=eh(this.editor,e.x,e.y);if(!t)return;const o=kh(this.editor,this.startPos,t.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});g(this,"handleMouseUp",e=>{this.startPos=null});this.editor=e,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(e){LT(this.editor)}handleTripleClick(e){ST(this.editor)}}function RT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function OT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const R9=S("delete-text");function O9(n,e,t,o){const r=o!=null?o:n.selection.range.start;r instanceof jt||m(R9,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);m(R9,ee(n,s),"block is not a text kind block");let{offset:l}=r;if(e==="backward"){if(l-t<0)return 0;if(!sn(s,l-t)){const a=Ri(s,l);t=l-a}}else if(e==="forward"&&l+t>ue(n,s))return 0;return e==="backward"&&(l-=t),n.deleteTextFromBlock(s,l,t)}function _9(n,e){if(n.getBlockData(e).quoted){const t={quoted:null};return n.updateBlockData(e,t),!0}return!1}const _T=S("handle-backspace");function Gg(n,e){if(!dt(n,e))return;const t=ne(e);Eo(t)!==1&&n.deleteBlock(e)}function FT(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if(ee(n,o))if(t.offset===0){if(_9(n,o))return;const r=lt(o);if(r){if(!n.isBlockWritable(r))return;if(ee(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Le(n,r)){Gg(n,o);const i=zl(n,r);i?n.selection.selectBlock(i,ue(n,i)):n.selection.selectBlock(r,0,ue(n,r))}else Gg(n,o),m(_T,Lt(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=ne(o);if(Do(i)){const s=v4(n,i);if(s){if(!n.isBlockWritable(s))return;Gg(n,o),n.selection.selectBlock(s,ue(n,s))}}}}else O9(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=be(o),i=ne(o);n.insertTextBlock("",ae(i),r),n.deleteBlock(o)}}function PT(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if(ee(n,o))if(t.offset===ue(n,o)){const r=Ze(o);if(r){if(!n.isBlockWritable(r))return;ee(n,r)?n.mergeTextBlock(o,r,{focus:!0}):dt(n,o)?n.deleteBlock(o,vt(n,r,0)):n.deleteBlock(r)}}else O9(n,"forward",1,null);else{const r=be(o),i=ne(o);n.insertTextBlock("",ae(i),r),n.deleteBlock(o)}}function NT(n){const{range:e}=n.selection,{start:t,end:o}=e,r=n.getBlockById(t.blockId),i=n.getBlockById(o.blockId);if(r!==i||!Le(n,r))return!1;if(Nr(t))return!0;const s=Ms(n,r,t,o),l=En(n,r);return s.length===l.length}function $T(n,e){if(NT(n)){const o=n.getFocusedBlock(),r=be(o),i=ae(ne(o));n.insertTextBlock("",i,r+1);return}n.selection.range.isCollapsed()||n.clearSelectedContents();const t=n.getFocusedBlock();if(ee(n,t)){if(dt(n,t)&&_9(n,t))return;const o=n.selection.range.start,r=n.breakTextBlock(t,o.offset,{copyBlockAttributes:!0});o.offset!==0?n.selection.selectBlock(r,0):n.selection.scrollIntoView()}else{const o=n.insertTextBlock();n.selection.selectBlock(o,0)}}function HT(n,e){const t=n.selection.range.getSelectedBlocks()[0],{block:o}=t;if(!ee(n,o))return!1;const r=t.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:K(),box:!0,created:Date.now()}),!0}const jT=S("input-handler-actions");function UT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>($T(n),!0))}function zT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(PT(n),!0))}function VT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(FT(n),!0))}function WT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(HT(n),!0))}function qT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(e=>{n.input.handlePasteText(e)}).catch(e=>{jT.error(e)}),!0)}const xh={ArrowDown:X6,ArrowUp:K6,ArrowLeft:Y6,ArrowRight:J6,"Shift+ArrowDown":e9,"Shift+ArrowUp":o9,"Shift+ArrowLeft":t9,"Shift+ArrowRight":n9,"CtrlOrCmd+ArrowLeft":i9,"CtrlOrCmd+ArrowRight":s9,"CtrlOrCmd+Shift+ArrowLeft":l9,"CtrlOrCmd+Shift+ArrowRight":c9,"CtrlOrCmd+ArrowUp":u9,"CtrlOrCmd+ArrowDown":a9,"CtrlOrCmd+Shift+ArrowUp":d9,"CtrlOrCmd+Shift+ArrowDown":Ug,"CtrlOrCmd+A":D9,Home:C9,End:A9,"Shift+Home":g9,"Shift+End":p9,PageUp:w9,PageDown:B9,"Shift+PageUp":E9,"Shift+PageDown":x9,"CtrlOrCmd+Z":RT,"CtrlOrCmd+Shift+Z":OT,Enter:UT,Delete:zT,Backspace:VT,"Shift+Enter":WT,"CtrlOrCmd+Shift+V":qT};function F9(n,e){return n.shortcuts.handleKeyboardEvents(n,e)!==void 0}function P9(n,e,t){if(e.type==="embed"){const i=e.embedData,s=i.src;if(s&&typeof s=="string"){const l=t.get(s);l&&(i.src=l)}return}const o=e.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=t.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=e.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{P9(n,l,t)})})}function N9(n,e,t){if(t.size===0)return;e.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,t):P9(e,r,t)})}async function GT(n,e){const t=e.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(t),r=new Map;if(t.length!==o.length)return r;for(let i=0;i<t.length;i++)r.set(t[i],o[i]);return r}function ZT(n,e){var i,s;const o=e.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 QT(n,e){const o=e.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(ZT(n,e)){const s=Array.from(Object.keys(o));r=await GT(n,s),N9(n,e,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&&N9(n,e,i)}async function YT(n,e,t){await QT(n,e),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Lt(i)){const s=ne(i),l=n.getBlockIndex(i),[a]=n.insertDocAt(s,l+1,e,t);a&&n.selection.selectBlock(a,ue(n,a))}else{n.clearSelectedContents();const{block:s,offset:l}=ql(n);n.insertDoc(s,l,e,t)}})}const JT=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function KT(n){let e;for(const t of JT)if(e=n[t],e)break;return e||null}function $9(n,e,t){if(e.type==="embed"){const s=e.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))t.add(l);return}const o=e.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&t.add(i.attributes.src)});const r=e.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{$9(n,l,t)})})}function XT(n,e){const t=new Set;return e.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{t.add(s)}):$9(e,r,t)}),Array.from(t)}function Ih(n,e){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${ws(JSON.stringify(e))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Th(n,e){var i,s,l;const t=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=XT(n,e),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),e.meta={...t,resources:r}}function eD(n,e,t){if(e.preventDefault(),e.stopPropagation(),!e.clipboardData)return;let o=Bh(n);const r=t==null?void 0:t(n,e,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Th(n,o);const i=mh(n,o),s=Sa(n,o),l=Ih(i,o);e.clipboardData.setData("text/html",l),e.clipboardData.setData("text/plain",s),e.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Dh(n,e){const t=qg(n,e);Th(n,t);const o=mh(n,t),r=Sa(n,t),i=Ih(o,t);return Em([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class tD{constructor(e){g(this,"editor");g(this,"handlers",[]);g(this,"onPasteText",async e=>{const t=new DataTransfer;t.setData("text/plain",e);const o=await this.editor.dataConverter.fromData(this.editor,t);o&&this.pasteDocs(o,null)});this.editor=e}onInsertText(e,t){if(!ee(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=ql(this.editor);this.handleBeforeInsertText(o,r,i,t)||(this.defaultInsertText(this.editor,o,r,i,t),this.handleAfterInsertText(o,r,i,t),this.editor.selection.updateLastCaretRect())}onKeyDown(e){if(this.handleBeforeKeyDown(e))return!0;const t=this.defaultHandleKeydown(this.editor,e);return this.handleAfterKeyDown(e)?!0:t}onChanged(e){for(let t=0;t<this.handlers.length;t++){const o=this.handlers[t];o.handleChanged&&o.handleChanged(this.editor,e)}}onRemoteChanged(e){for(let t=0;t<this.handlers.length;t++){const o=this.handlers[t];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,e)}}onCompositionStart(e){this.editor.updateCompositionText("",!1);const{containerId:t,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,t,o,r)}}onUpdateCompositionText(e,t,o){this.editor.updateCompositionText(t,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(e){eD(this.editor,e,(t,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(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,e)===!0)return}if(this.onCopy(e),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;Lt(o)&&this.editor.deleteBlock(o)}else Sg(this.editor)}onPaste(e){if(e.preventDefault(),e.stopPropagation(),!e.clipboardData)return;this.editor.dataConverter.fromData(this.editor,e.clipboardData).then(async o=>{o&&this.pasteDocs(o,e)})}onFocus(){W(this.editor.rootElement,"active")}onBlur(){te(this.editor.rootElement,"active")}addHandler(e){this.handlers.push(e)}removeHandler(e){const t=this.handlers.indexOf(e);t!==-1&&this.handlers.splice(t)}handleBeforeInsertText(e,t,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,e,t,o,r))return!0}return!1}handleAfterInsertText(e,t,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,e,t,o,r))return!0}return!1}handleBeforeKeyDown(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,e))return!0}const t=this.defaultHandleKeydown(this.editor,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,e))return!0}return t}handleAfterKeyDown(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,e))return!0}const t=this.defaultHandleKeydown(this.editor,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,e))return!0}return t}defaultInsertText(e,t,o,r,i){Eg(this.editor,i)}defaultHandleKeydown(e,t){return F9(this.editor,t)?(t.preventDefault(),t.stopPropagation(),!0):!1}async pasteDoc(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,e))return}const t={blockIdMap:new Map,containerIdMap:new Map};await YT(this.editor,e,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,e,t))return}}async pasteDocs(e,t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,t,e))return}const o=KT(e);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,t,e))return}}}destroy(){this.handlers.forEach(e=>{var t;(t=e.destroy)==null||t.call(e,this.editor)}),this.handlers=[]}}function nD(n,e,t){const o=Rr(e,t);return o.remove(),o}S("copy-dom-attributes");const H9=["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 oD(n,e){for(let l=0;l<H9.length;l++){const a=H9[l];e[a]=n[a]}const t=n.attributes,o=e.attributes,r=[],i=[];for(let l=0;l<t.length;l++){const a=t[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];t.getNamedItem(a.name)||s.push(a)}r.forEach(l=>{e.setAttribute(l.name,l.value)}),i.forEach(l=>{e.setAttribute(l.name,l.value)}),s.forEach(l=>{e.removeAttribute(l.name)})}function j9(n){const e=Array.from(n.childNodes).filter(t=>!_C(t));return e.forEach(t=>{t.remove()}),e}function U9(n,e,t){var d;const o=n.getContainerById(e),r=Rr(o,t),i=Di(r),s=n.doc.getBlockData(e,t),l=Qe(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=j9(h);j9(r),p.forEach(v=>{r.appendChild(v)});const A=Zd(h);if(A){const v=Zd(r);v&&v.remove(),r.appendChild(A)}oD(h,r)}XC(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 rD=S("transform-selection");function z9(n,e,t,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==e&&s.blockId!==e)return r;m(rD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===e){const d=ln.transformCursor(i.offset,t,o);l=se(e,d,"normal")}let a=s;if(s.blockId===e){const d=ln.transformCursor(s.offset,t,o);a=se(e,d,"normal")}return Ut(n,{anchor:l,focus:a})}const iD=S("handle-block-text-changed");function sD(n,e,t,o,r){const i=n.getContainerById(e),s=Rr(i,t),l=n.doc.getBlockData(e,t);if(m(iD,l.text,"no block text"),GC(n,s).setBlockText(n,s,l.text),!r){const a=z9(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function lD(n,e){const t=fe.default(n);return e.delete.forEach(r=>{delete t[r]}),{...t,...e.insert}}function V9(n,e,t,o){const r=Qe(n,e);r.handleDeleteBlock&&r.handleDeleteBlock(n,e,t,o),n.emit("blockDeleted",n,e,t,o)}function cD(n,e,t,o){const r=n.getBlockByIndex(e,t);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{V9(n,i,o,{child:!0})}),V9(n,r,o,{child:!1})}const Ro=S("editor-doc");class aD extends ua{constructor(t,o,r){super();g(this,"localEvents",[]);this.editor=t,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(t){this.localEvents.push(t)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(t){return this.externalDoc.getContainerBlocks(t)}getBlockData(t,o){return this.externalDoc.getBlockData(t,o)}verifyBlockWritable(t,o){const r=this.editor.getBlockByIndex(t,o);m(Ro,this.editor.isBlockWritable(r),`block is not writable, ${t}, ${o}`)}localUpdateBlockText(t,o,r,i){m(Ro,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const s=this.getBlockData(t,o),l=s.text;m(Ro,l,`no text, ${t}, ${o}`);const a=z9(this.editor,s.id,r,!0),d=ln.apply(l,r);this.localEvents.forEach(p=>p.onBeforeUpdateBlockText(t,s.id,l,d,a.toDocRange()));const h=this.externalDoc.localUpdateBlockText(t,o,r);return this.editor.selection.setRange(a,i),h}localUpdateBlockData(t,o,r,i){m(Ro,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(t,o);if(!this.editor.isBlockWritable(s)){const h=Array.from(r.delete).filter(A=>A!=="comments"),p=Object.keys(r.insert).filter(A=>A!=="comments");(h.length>0||p.length>0)&&m(Ro,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=fe.default(this.getBlockData(t,o)),a=fe.default(lD(l,r));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(t,l.id,l,a,i));const d=this.externalDoc.localUpdateBlockData(t,o,r,i);return this.editor.selection.setRange(Si(this.editor,i)),d}localInsertBlock(t,o,r,i,s){m(Ro,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(a=>a.onBeforeInsertBlock(t,o,r,i));const l=this.externalDoc.localInsertBlock(t,o,r,i);return this.editor.selection.setRange(Si(this.editor,i),s),l}localDeleteBlock(t,o,r){m(Ro,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const i=fe.default(this.getBlockData(t,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(t,o,i,r));const s=this.externalDoc.localDeleteBlock(t,o,r);return this.editor.selection.setRange(Si(this.editor,r)),s}localDeleteChildContainers(t){return m(Ro,!this.editor.readonly,"editor is readonly"),t.forEach(o=>{const r=fe.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(t)}localInsertChildContainer(t,o){return m(Ro,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(t,fe.default(o))),this.externalDoc.localInsertChildContainer(t,o)}onRequestReload(t){Ro.debug(`reload doc: ${t}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,t)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(t,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,t,o,r,i)}),sD(this.editor,t,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(t,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,t,o,r,i)}),U9(this.editor,t,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(t,o,r,i){this.callbacks.forEach(l=>{var a;return(a=l.onInsertBlock)==null?void 0:a.call(l,t,o,r,i)});const s=this.editor.getContainerById(t);JE(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(t,o,r){cD(this.editor,t,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,t,o,r)});const i=this.editor.getContainerById(t);nD(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(t,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,t,o,r)})}onDeleteChildContainer(t,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,t,o)})}onCustomMessage(t){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,t)})}onStatusChanged(t){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,t)})}onError(t){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,t)})}uploadResource(t,o){return this.externalDoc.uploadResource(t,o)}addResources(t){return this.externalDoc.addResources(t)}buildResourceUrl(t,o){return this.externalDoc.buildResourceUrl(t,o)}request(t,o){return this.externalDoc.request(t,o)}broadcastMessage(t){return this.externalDoc.broadcastMessage(t)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var t,o,r;return(r=(o=(t=this.externalDoc).getServerMeta)==null?void 0:o.call(t))!=null?r:{}}reset(t){Ro.log("reset doc"),this.externalDoc=t,this.externalDoc.registerCallback(this),this.editor.reload()}}function W9(n,e){if(n.length===0){n.push(e);return}const t=n[n.length-1];if(!t.combinable(e)){n.push(e);return}t.combine(e)}const Zg=S("undo-action");class Yl{constructor(e,t,o){g(this,"beforeRange");g(this,"afterRange");this.containerId=t,this.beforeRange=e.selection.range.clone().toDocRange(),this.afterRange=o}undo(e){return!1}redo(e){return!1}combinable(e){return m(Zg,e,"no other action"),!1}combine(e){m(Zg,!1,"no other")}setAfterRange(e){this.afterRange&&Zg.warn("after range has already set"),this.afterRange=e}}const uD=S("block-action");class q9 extends Yl{constructor(t,o,r,i,s){super(t,o,s);g(this,"blockData");g(this,"blockIndex");this.blockData=fe.default(i),this.blockIndex=r}deleteBlock(t,o){if(!t.getContainerById(this.containerId))return!1;const i=t.getBlockById(this.blockData.id);return i?(m(uD,this.blockIndex===be(i),"invalid block index"),Ah(t,i,Si(t,o)),!0):!1}insertBlock(t,o){return Gl(t,this.containerId,this.blockIndex,fe.default(this.blockData),o),!0}}class dD extends q9{undo(e){return this.deleteBlock(e,this.beforeRange)}redo(e){return this.insertBlock(e,this.afterRange)}}class hD extends q9{undo(e){return this.insertBlock(e,this.beforeRange)}redo(e){return this.deleteBlock(e,this.afterRange)}}class fD extends Yl{constructor(t){super(t,ae(t.rootContainer),t.selection.range.toDocRange());g(this,"actions",[])}addAction(t){W9(this.actions,t),this.afterRange=t.afterRange}undo(t){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(t)&&(o=!0)}),o}redo(t){let o=!1;return this.actions.forEach(r=>{r.redo(t)&&(o=!0)}),o}setAfterRange(t){this.afterRange=t;const o=this.actions[this.actions.length-1];!o||o instanceof Yl&&(o.afterRange||o.setAfterRange(t))}}const Ns=S("update-block-data-action");class Sh extends Yl{constructor(t,o,r,i,s,l){super(t,o,l);g(this,"beforeBlockData");g(this,"afterBlockData");g(this,"blockId");this.blockId=r,m(Ns,this.blockId===i.id,"invalid block id"),m(Ns,this.blockId===s.id,"invalid block id"),this.beforeBlockData=fe.default(i),this.afterBlockData=fe.default(s),m(Ns,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(t){m(Ns,t,"no editor");const o=t.getBlockById(this.blockId);if(!o)return!1;const r=t.getContainerById(this.containerId);return m(Ns,r,"no container"),yh(t,o,Sh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(t){m(Ns,t,"no editor");const o=t.getBlockById(this.blockId);if(!o)return!1;const r=t.getContainerById(this.containerId);return m(Ns,r,"no container"),yh(t,o,Sh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(t){const o=fe.default(t);return delete o.id,delete o.type,o}}const Qg=S("update-block-text-action");class Na extends Yl{constructor(t,o,r,i,s,l){super(t,o,l);g(this,"beforeRichTextData");g(this,"afterRichTextData");g(this,"blockId");g(this,"type");this.blockId=r,this.beforeRichTextData=fe.default(i),this.afterRichTextData=fe.default(s),this.type=Na.calType(i,s)}static calType(t,o){m(Qg,t,"no old data"),m(Qg,o,"no new data");const i=ln.diff(t,o),s=new Set;let l=!1;const a=h=>uC(h)?`cjk_${h}`:cC(h)?"number":$d(h)?"space":aC(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(t){if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(vh(t,r,this.beforeRichTextData),!0):!1}redo(t){if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(vh(t,r,this.afterRichTextData),!0):!1}combinable(t){if(!(t instanceof Na)||t.type.begin||this.type.textType!==t.type.textType||t.blockId!==this.blockId)return!1;const o=t.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(t){m(Qg,t instanceof Na,"invalid action type");const o=t;this.afterRichTextData=o.afterRichTextData,this.afterRange=t.afterRange}}class G9 extends Yl{constructor(e,t,o){super(e,t,e.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(e){return e.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(e){return e.doc.localInsertChildContainer(this.containerId,fe.default(this.blocks)),!0}}class mD extends G9{undo(e){return this.deleteChildContainer(e)}redo(e){return this.insertChildContainer(e)}}class gD extends G9{undo(e){return this.insertChildContainer(e)}redo(e){return this.deleteChildContainer(e)}}const Oo=S("undo");class pD{constructor(e){g(this,"editor");g(this,"actions",[]);g(this,"undoCursor");g(this,"currentGroup",null);g(this,"groupCounter",0);g(this,"undoRedoing",!1);g(this,"handleSelectionChange",e=>{if(this.currentGroup){this.currentGroup.setAfterRange(e.selection.range.toDocRange());return}const t=this.actions[this.actions.length-1];!t||t.afterRange||t.setAfterRange(e.selection.range.toDocRange())});this.editor=e,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(e){this.currentGroup?this.currentGroup.addAction(e):(W9(this.actions,e),setTimeout(()=>{this.editor.input.handleChanged(e)}))}beginGroup(){this.groupCounter===0?(m(Oo,!this.currentGroup,"current group already exists"),this.currentGroup=new fD(this.editor),this.groupCounter=1):(m(Oo,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){m(Oo,this.currentGroup,"current group not exists"),m(Oo,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Oo.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(e){this.beginGroup();try{const t=e();return setTimeout(()=>this.editor.selection.caret.update()),t}catch(t){throw Oo.error(`failed to run action: ${t.message}`),t}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const e=this.actions[this.undoCursor];if(e.undo(this.editor)){try{this.editor.selection.setRange(Si(this.editor,e.beforeRange))}catch(t){Oo.error(`undo: failed to restore caret pos: ${t.message}`)}return this.editor.input.handleChanged(e),!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 e=this.actions[this.undoCursor];if(this.undoCursor+=1,e.redo(this.editor)){try{const t=e.afterRange;t?this.editor.selection.setRange(Si(this.editor,t)):Oo.warn("no after range")}catch(t){Oo.error(`redo: failed to set caret pos after redo: ${t.message}`)}return this.editor.input.handleChanged(e),!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 t;const e=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(t=this.actions[e])!=null?t:null}undoTo(e){for(;;){const t=this.lastAction();if(!t||t===e)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(e,t,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),ln.diff(o,r).length!==0&&this.addAction(new Na(this.editor,e,t,o,r,i)))}onBeforeUpdateBlockData(e,t,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Sh(this.editor,e,t,o,r,i);this.addAction(s)}onBeforeInsertBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),m(Oo,t>=0,"invalid block index"),m(Oo,o,"no block data"),this.addAction(new dD(this.editor,e,t,o,r)))}onBeforeDeleteBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new hD(this.editor,e,t,o,r)))}onBeforeInsertChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new mD(this.editor,e,t)))}onBeforeDeleteChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new gD(this.editor,e,t)))}}class CD{async fromData(e,t){const o=t.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class AD{constructor(){g(this,"converters",[]);this.addConverter(new CD)}async fromData(e,t){let o={};for(const r of this.converters){const i=await r.fromData(e,t);i&&(o={...o,...i})}return o}addConverter(e){this.converters.push(e)}}class bD{constructor(e){g(this,"renders",[]);this.editor=e}registerRender(e){this.renders.push(e)}renderText(e,t){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,e,t);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(e,t,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,t,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(e,t,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,e,t,o,r)})}}class gt extends At.TypedEmitter{constructor(t){super();g(this,"hoveringBlock",null);g(this,"hoveringTextChild",null);g(this,"filters",[]);g(this,"finders",[]);g(this,"handleDocumentMouseMove",t=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,t))return}const o=document.elementFromPoint(t.x,t.y);if(!o){this.setHoveringBlock(null,t,null);return}let r=oe(o);if((!r||!Ke(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(t),!r)){this.setHoveringBlock(null,t,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,t,i)});this.editor=t,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(t=>t.destroy()),this.filters=[],this.finders.forEach(t=>t.destroy()),this.finders=[]}addFilter(t){this.filters.push(t)}addFinder(t){this.finders.push(t)}hoveringBlockId(){return this.hoveringBlock?re(this.hoveringBlock):""}findBlockByFinders(t){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,t);if(i)return i}return null}setHoveringBlock(t,o,r){if(this.hoveringBlock===t&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==t){const s=this.hoveringBlock&&Ke(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&te(s,"hover"),t&&W(t,"hover"),this.hoveringBlock=t,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(t){return t.addCustom("standard-hovering-block",()=>new gt(t))}getParentTextContentChild(t,o){if(!ee(this.editor,t))return null;const r=Re(t);return o.parentElement===r?o:Rm(o)}}const Z9="style-color-",Q9="style-bg-color-";class vD{renderText(e,t,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(Z9)?i["data-style-color"]=l.substring(Z9.length):l.startsWith(Q9)?i["data-style-bg-color"]=l.substring(Q9.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(e,t,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=e.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"),gt.get(e).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(e,t,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=e.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&W(o,"focused"),gt.get(e).hoveringBlockId()===r.id&&W(o,"hover")}}function yD(n){n.editorBlocks.registerBlockClass(In),n.editorBlocks.registerBlockClass(b4),n.editorBoxes.registerBoxClass(c6),n.editorBoxes.registerBoxClass(a6),n.editorBoxes.registerBoxClass(h6),n.editorBoxes.registerBoxClass(f6),n.editorInsertions.registerInsertionClass(m6),n.editorBlockRenders.registerRender(new vD)}function kD(n,e){yD(n),e!=null&&e.blocks&&e.blocks.forEach(t=>n.editorBlocks.registerBlockClass(t)),e!=null&&e.boxes&&e.boxes.forEach(t=>n.editorBoxes.registerBoxClass(t)),e!=null&&e.embeds&&e.embeds.forEach(t=>n.editorEmbeds.registerEmbedClass(t)),e!=null&&e.insertions&&e.insertions.forEach(t=>n.editorInsertions.registerInsertionClass(t)),e!=null&&e.decorators&&e.decorators.forEach(t=>n.editorDecorators.registerDecorator(t)),e!=null&&e.dataConverters&&e.dataConverters.forEach(t=>n.dataConverter.addConverter(t)),e!=null&&e.commandProviders&&e.commandProviders.forEach(t=>n.editorCommandProviders.registerCommandProvider(t)),e!=null&&e.textRenders&&e.textRenders.forEach(t=>n.editorBlockRenders.registerRender(t))}const Y9=S("range-commands");function J9(n,e){n.forEach(t=>{t.source=e,t.children&&J9(t.children,e)})}function K9(n,e,t){const o=re(e);m(Y9,o===t.start.blockId,"invalid start range"),m(Y9,o===t.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,e,t);J9(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,e,t,i);l&&(i=l)}}),Le(n,e)&&Ms(n,e,t.start,t.end).forEach(l=>{bt(l).forEach(d=>{const h=ue(n,d),p=Ut(n,{anchor:se(d,0,"home"),focus:se(d,h,"end")}),A=K9(n,d,p);i.push(...A)})}),i}function X9(n){const e=n.getEditor(),t=n.getSelectedBlocks(),o=[];return t.forEach(r=>{const i=Ut(e,{anchor:r.start,focus:r.end});K9(e,r.block,i).forEach(l=>{o.push(l)})}),o}function e7(n,e,t,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const A=s[p];if(A.beforeExecuteCommand&&A.beforeExecuteCommand(n,e,t,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),a={};if((h=l.executeCommand)!=null&&h.call(l,n,e,t,o,r,{}))return i[re(e)]=a,!0;let d=!1;return Le(n,e)&&Ms(n,e,t.start,t.end).forEach(A=>{bt(A).forEach(B=>{const D=ue(n,B),x=Ut(n,{anchor:se(B,0,"home"),focus:se(B,D,"end")});e7(n,B,x,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,e,t,o,r,i)}),d}function t7(n,e,t){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(e.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,e,t,r)||n.getSelectedBlocks().forEach(l=>{const a=Ut(o,{anchor:l.start,focus:l.end});e7(o,l.block,a,e,t,r)}),r}const wD=S("command-providers");class n7{constructor(e){g(this,"providers",[]);this.editor=e}registerCommandProvider(e){this.providers.push(e)}getCommandProviders(){return this.providers}getCommandProvider(e){const t=this.providers.find(o=>o.id===e);return m(wD,t,`no command provider, id=${e}`),t}getCommands(e){return X9(e)}executeCommand(e,t,o){return this.editor.undoManager.runInGroup(()=>t7(e,t,o))}getEmptyBlockTextAttributes(e,t){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,e,t);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function BD(n,e){const t=ne(e),o=ae(t),r=be(e);U9(n,o,r)}const ED=S("table-scroll");class o7{constructor(e,t,o,r,i){g(this,"handleEvent",e=>{this.handler(this.editor,e,this.data)});this.editor=e,this.dom=t,this.name=o,this.handler=r,this.data=i,t.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class xD{constructor(e){g(this,"handlers",new Map);this.editor=e}destroy(){Array.from(this.handlers.entries()).forEach(([e,t])=>{t.forEach(o=>o.destroy()),this.handlers.delete(e)})}addEventListener(e,t,o,r){const i=this.handlers.get(e);if(i){if(i.find(s=>s.handler===o&&s.name===t)){ED.warn(`event has already registered: ${t}`);return}i.push(new o7(this.editor,e,t,o,r))}else{const s=new o7(this.editor,e,t,o,r);this.handlers.set(e,[s])}}removeEventListener(e,t,o){if(!e){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const a=s[l];if(t)t===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(e);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===t);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(e)}}}removeAllListeners(e,t){const o=this.handlers.get(e);if(o)if(t)for(let r=0;r<o.length;r++){const i=o[r];i.name===t&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(e)}}const r7=S("update-block-text");function ID(n,e){const t=n.getBoxById(e.id),o=oe(t);m(r7,o,"no parent block"),m(r7,ee(n,o),"not a text block");const r=n.getBlockText(o),i=X4(r,"id",e.id,e);F6(n,o,i)}function TD(n,e){for(const t of n.blockHooks)if(t.writable){const o=t.writable(n,e);if(typeof o=="boolean")return o}return!0}function DD(n){return n.readonly?!1:!Lo(n).find(o=>!n.isBlockWritable(o.block))}class SD{constructor(e){this.editor=e}getKey(e){return`${this.editor.id}-${e}`}getItem(e){return window.localStorage.getItem(this.getKey(e))}setItem(e,t){if(!t){this.removeItem(e);return}window.localStorage.setItem(this.getKey(e),t)}removeItem(e){window.localStorage.removeItem(this.getKey(e))}}class LD{constructor(){g(this,"shortcuts",[])}handleKeyboardEvents(e,t){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(Mr(t,s)){const a=l(e,t);if(a!==void 0)return a}}}}const Ur=S("editor");class MD extends At.TypedEmitter{constructor(t,o,r){var i,s,l,a,d,h,p;super();g(this,"parent");g(this,"rootElement");g(this,"contentElement");g(this,"rootContainerObject");g(this,"rootContainer");g(this,"input");g(this,"selection");g(this,"selectionHandler");g(this,"doc");g(this,"id");g(this,"clientId");g(this,"compositingText","");g(this,"undoManager");g(this,"shortcuts",new LD);g(this,"dataConverter",new AD);g(this,"editorBlocks",new g4(this));g(this,"editorBoxes",new d6(this));g(this,"editorInsertions",new p6(this));g(this,"editorEmbeds",new C4(this));g(this,"editorDecorators",new C6(this));g(this,"editorCommandProviders",new n7(this));g(this,"editorBlockRenders",new bD(this));g(this,"blockHooks",[]);g(this,"domEvents",new xD(this));g(this,"customs",new Map);g(this,"options");g(this,"inputHandlers",new tD(this));g(this,"settingsProvider");g(this,"_readonly",!1);Ur.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 SD(this),kD(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 pD(this),this.doc=new aD(this,o,this.undoManager),this.parent=t,this.rootElement=w("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=w("div",["editor-content"],this.rootElement),this.rootContainerObject=h4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new zI(this,this.inputHandlers),this.selection=new DT(this),this.selectionHandler=new MT(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),Kt.isMobile&&W(this.rootElement,"mobile"),Kt.isSafari&&W(this.rootElement,"safari"),this._readonly&&W(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(t){this._readonly=t,t?W(this.rootElement,"readonly"):te(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:Bo(this.rootContainer)}addCustom(t,o){const r=this.customs.get(t);if(r)return r;const i=o(this);return this.customs.set(t,i),i}getCustom(t){const o=this.customs.get(t);return m(Ur,o,`${t} does not exists`),o}replaceCustom(t,o){const r=this.customs.get(t);return r&&r.destroy(),this.customs.set(t,o),o}findCustom(t){return this.customs.get(t)}findCustomByType(t){const o=this.customs.values();for(const r of o)if(r instanceof t)return r;return null}destroyCustom(t){const o=this.customs.get(t);o&&(this.customs.delete(t),o.destroy())}getComponentOptions(t){return this.options.componentsOptions[t]}registerLocalEvents(t){this.doc.registerLocalEvents(t)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(t,o,r){return this.editorBlocks.createBlock(t,o,r)}createBox(t,o){return this.editorBoxes.createBox(t,o)}createInsertion(t,o){return this.editorInsertions.createInsertion(t,o)}destroy(){Ur.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(t=>t.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus()}focusToBlock(t,o){Lg(this,t,o)}isWritable(){return DD(this)}isBlockWritable(t){return TD(this,t)}getChildContainerData(t){const o=this.doc.getContainerBlocks(t);return m(Ur,o,`no child container data: ${t}, ${JSON.stringify(this.doc)}`),m(Ur,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(t,o,r){return f4(this,t,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const t=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return t[t.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(t){const o=this.rootContainer.querySelector(`#${t}`);return o&&m(Ur,Es(o),"not an valid block element"),o!=null?o:null}findBoxById(t){const o=this.rootContainer.querySelector(`#${t}`);return o&&m(Ur,Mm(o),"not an valid box element"),o!=null?o:null}getBlockById(t){const o=this.findBlockById(t);return m(Ur,o,`no block, id=${t}`),o}getBoxById(t){const o=this.findBoxById(t);return m(Ur,o,`no box, id=${t}`),o}getBlockByIndex(t,o){const r=this.getContainerById(t);return Rr(r,o)}getBlockIndex(t){if(typeof t=="string"){const o=this.getBlockById(t);return be(o)}return be(t)}getContainerById(t){return Pr(this,t)}getParentContainer(t){return ne(t)}reloadBlock(t){BD(this,t)}contains(t){const o=t instanceof Element?t:t.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(t,o,r,i,s){const l={blockId:r.id,offset:0},a={anchor:l,focus:l};return Gl(this,t,o,r,i!=null?i:a,s)}insertEmbed(t,o,r,i,s){const l={id:K(),type:"embed",embedType:r,embedData:i};return this.insertBlock(t,o,l,s)}deleteBlock(t,o){Tg(this,t,o)}mergeTextBlock(t,o){return R6(this,t,o)}breakTextBlock(t,o,r){return Zl(this,t,o,r).newBlock}getTextPosition(){return ql(this)}getBlockString(t,o){const r=this.getBlockText(t);return rt(r,o)}getBlockData(t){return _i(this,t)}getBoxData(t){return s6(this,t)}getBlockText(t){return mn(this,t)}setBlockText(t,o){F6(this,t,o)}deleteTextFromBlock(t,o,r,i){return xg(this,t,o,r,i)}insertTextToBlock(t,o,r,i){return x6(this,t,o,r,i)}insertBoxToBlock(t,o,r){return I6(this,t,o,r)}pasteDoc(t){return this.inputHandlers.pasteDoc(t)}insertDoc(t,o,r,i){$6(this,t,o,r,i)}insertDocAt(t,o,r,i){return Og(this,t,o,r,i)}deleteChildContainers(t){M6(this,t)}replaceBlockText(t,o){return vh(this,t,o)}updateBlockData(t,o,r){const i={...this.getBlockData(t),...o},{id:s,type:l,...a}=i;return yh(this,t,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(t,o,r){return P6(this,t,o,r)}updateBoxData(t){ID(this,t)}getSelectedText(){const t=Bh(this);return Da(this,t)}clearSelectedContents(){Sg(this)}insertTextBlock(t,o,r,i){const s=sr(t!=null?t:"");return L6(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(t,o){if(t&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!t&&!o){D6(this);return}o?(this.compositingText="",Am()||Eg(this,t)):(this.compositingText=t,T6(this))}getColor(t){const o=this.options.colors;return o.length===0?"#FF1A75":o[t%o.length]}}function $a(n,e,t){return new MD(n,e,t)}function RD(n){const e=(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=sm.default(s.states,r.states)}},t=[];return n.forEach(o=>{o.forEach(r=>{e(t,r)})}),t}const OD=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class Lh extends At.TypedEmitter{constructor(t){super();g(this,"users",new Map);g(this,"cursors",new Map);g(this,"addingUser",!1);g(this,"colors");this.colors=t&&t.length>0?t:OD}setCursor(t){this.addUser(t.user);const o=this.cursors.get(t.user.userId);if(o&&la.default(o,t))return;this.cursors.set(t.user.userId,t);const r=new Set([t.range.anchor.blockId,t.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(t){this.addingUser=!0,t.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(t){this.users.set(t.userId,t),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(t){var o;return(o=this.users.get(t))!=null?o:null}removeUser(t){this.users.delete(t),this.cursors.delete(t),this.emit("change",Array.from(this.users.values()))}updateUsers(t){this.users.clear(),this.addingUser=!0;try{t.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(t){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===t&&ch(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(t){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===t||o.range.focus.blockId===t)}onUpdateBlockText(t,o,r){if(!t.text)return;this.getCursors(t.id).forEach(l=>{if(ch(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===t.id&&(a.offset=ln.transformCursor(a.offset,o,r)),d.blockId===t.id&&(d.offset=ln.transformCursor(d.offset,o,r))}})}getFixedUserColor(t,o){let r=0;Array.from(t).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const Xt=S("local-doc");class Yg extends ua{constructor(t,o){super();g(this,"doc");g(this,"serviceUrl");t?this.doc=t:this.doc={meta:{},comments:{},blocks:{root:[sr("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return fe.default(this.doc)}getContainerBlocks(t){return this.doc.blocks[t]}getBlockData(t,o){const r=this.getContainerBlocks(t);m(Xt,r,`no container data: ${t}`);const i=r[o];return m(Xt,i,`no block data: ${o}`),i}localUpdateBlockText(t,o,r){const i=this.getBlockData(t,o);m(Xt,i.text,"no text for data");const s=ln.apply(i.text,r);return i.text=s,m(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockText)==null?void 0:a.call(l,t,o,r,!0)}),s}localUpdateBlockData(t,o,r){const i=this.getBlockData(t,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),m(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,t,o,r,!0)}),i}localInsertBlock(t,o,r){const i=this.getContainerBlocks(t);return m(Xt,i,`no container data: ${t}`),m(Xt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),m(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,t,o,r,!0)}),r}localDeleteBlock(t,o){const r=this.getContainerBlocks(t);m(Xt,r,`no container data: ${t}`),m(Xt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),m(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,t,o,!0)}),i}localInsertChildContainer(t,o){this.doc.blocks[t]=o,m(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,t,o,!0)})}localDeleteChildContainers(t){Xt.debug(`delete child containers: ${t}`),t.forEach(o=>{m(Xt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),t.forEach(o=>{m(Xt,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(t,o){m(Xt,!1,"not implemented")}async addResources(t){return t}buildResourceUrl(t){return t}request(t,o){m(Xt,!1,"not implemented")}broadcastMessage(t){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Lh}setDoc(t){this.doc=fe.default(t),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class _D{constructor(e){this.cleanup=e}destroy(){var e;(e=this.cleanup)==null||e.call(this)}}function Jg(n,e,t){n.addCustom(e,()=>{var i;const o=(i=t())!=null?i:void 0;return new _D(o)})}const i7=S("find-block");function s7(n,e){const t=Ts(e);if(!t){if(oo(e))return null;const o=xs(e);return m(i7,o,"no parent block"),s7(n,o)}return Le(n,t)?zl(n,t,{visibleOnly:!0}):t}function l7(n,e){const t=Ds(e);if(!t){if(oo(e))return null;const o=xs(e);return m(i7,o,"no parent block"),l7(n,o)}return Le(n,t)?Qm(n,t,{visibleOnly:!0}):t}const FD=S("remote-cursor");class PD{constructor(){g(this,"remoteUsers",new Lh)}onCustomMessage(e){const t=e;if(t.type==="onlineUsers"){const o=t;this.handleUpdateUsers(o.users)}else t.type==="caret"?this.handleUpdateCaret(t):FD.debug(`unknown remote message received: ${e}`)}handleUpdateUsers(e){this.remoteUsers.updateUsers(e)}handleUpdateCaret(e){const t=this.remoteUsers.findUser(e.userId);!t||this.remoteUsers.setCursor({oneseditor:"cursor",user:t,range:e.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function ND(n){const{blocks:e,meta:t,comments:o,...r}=n;return{rootBlocks:e,meta:t,comments:o,childBlocks:r}}function $D(n){const{blocks:e,meta:t,comments:o}=n,{root:r,...i}=e;return{blocks:r,meta:t,comments:o,...i}}function Ha(n){const{childBlocks:e,meta:t,comments:o,rootBlocks:r}=ND(fe.default(n));return{blocks:{root:r,...e},meta:t,comments:o}}function Ni(n){return n==="root"?"blocks":n}function Jl(n){return n==="blocks"?"root":n}const HD={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new on.default(n)},apply(n,e){const t=new on.default(n),o=new on.default(e);return t.compose(o).ops},compose(n,e){const t=new on.default(n),o=new on.default(e);return t.compose(o).ops},diff(n,e){const t=new on.default(n),o=new on.default(e);return t.diff(o).ops},transform(n,e,t){const o=new on.default(n);return new on.default(e).transform(o,t==="left").ops},transformCursor(n,e,t){return e.transformPosition(n,!t)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,e,t){if(!n)return null;const o=new on.default(e),r=this.transformCursor(n.index,o,t),i=this.transformCursor(n.index+n.length,o,t);return{...n,index:r,length:i-r}}}};var cr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},$i={},Kg=U5.default.EventEmitter;$i.EventEmitter=Kg,$i.mixin=jD;function jD(n){for(var e in Kg.prototype)n.prototype[e]=Kg.prototype[e]}var c7=["info","warn","error"];function a7(){var n={};c7.forEach(function(e){n[e]=console[e].bind(console)}),this.setMethods(n)}var UD=a7;a7.prototype.setMethods=function(n){n=n||{};var e=this;c7.forEach(function(t){typeof n[t]=="function"&&(e[t]=n[t])})};var zD=UD,VD=new zD,u7=VD;function $s(n,e){this.code=n,this.message=e||"",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 Mh=$s,ja={},d7=WD;function WD(n,e,t,o){var r=function(s,l,a,d){e(a,s,l,"left"),e(d,l,s,"right")},i=n.transformX=function(s,l){t(s),t(l);for(var a=[],d=0;d<l.length;d++){for(var h=l[d],p=[],A=0;A<s.length;){var v=[];if(r(s[A],h,p,v),A++,v.length===1)h=v[0];else if(v.length===0){for(var B=A;B<s.length;B++)o(p,s[B]);h=null;break}else{for(var D=i(s.slice(A),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?e([],s[0],l[0],a):a==="left"?i(s,l)[0]:i(l,s)[1]}}var h7={exports:{}},Hi=h7.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||""}},Xg=function(n,e,t){return n.slice(0,e)+t+n.slice(e)},ep=function(n){if(typeof n.p!="number")throw new Error("component missing position field");if(typeof n.i=="string"==(typeof n.d=="string"))throw new Error("component needs an i or d field");if(n.p<0)throw new Error("position cannot be negative")},Rh=function(n){for(var e=0;e<n.length;e++)ep(n[e])};Hi.apply=function(n,e){var t;Rh(e);for(var o=0;o<e.length;o++){var r=e[o];if(r.i!=null)n=Xg(n,r.p,r.i);else{if(t=n.slice(r.p,r.p+r.d.length),r.d!==t)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+t+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var zr=Hi._append=function(n,e){if(!(e.i===""||e.d===""))if(n.length===0)n.push(e);else{var t=n[n.length-1];t.i!=null&&e.i!=null&&t.p<=e.p&&e.p<=t.p+t.i.length?n[n.length-1]={i:Xg(t.i,e.p-t.p,e.i),p:t.p}:t.d!=null&&e.d!=null&&e.p<=t.p&&t.p<=e.p+e.d.length?n[n.length-1]={d:Xg(e.d,t.p-e.p,t.d),p:e.p}:n.push(e)}};Hi.compose=function(n,e){Rh(n),Rh(e);for(var t=n.slice(),o=0;o<e.length;o++)zr(t,e[o]);return t},Hi.normalize=function(n){var e=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var t=0;t<n.length;t++){var o=n[t];o.p==null&&(o.p=0),zr(e,o)}return e};var tp=function(n,e,t){return e.i!=null?e.p<n||e.p===n&&t?n+e.i.length:n:n<=e.p?n:n<=e.p+e.d.length?e.p:n-e.d.length};Hi.transformCursor=function(n,e,t){for(var o=t==="right",r=0;r<e.length;r++)n=tp(n,e[r],o);return n};var qD=Hi._tc=function(n,e,t,o){if(ep(e),ep(t),e.i!=null)zr(n,{i:e.i,p:tp(e.p,t,o==="right")});else if(t.i!=null){var r=e.d;e.p<t.p&&(zr(n,{d:r.slice(0,t.p-e.p),p:e.p}),r=r.slice(t.p-e.p)),r!==""&&zr(n,{d:r,p:e.p+t.i.length})}else if(e.p>=t.p+t.d.length)zr(n,{d:e.d,p:e.p-t.d.length});else if(e.p+e.d.length<=t.p)zr(n,e);else{var i={d:"",p:e.p};e.p<t.p&&(i.d=e.d.slice(0,t.p-e.p)),e.p+e.d.length>t.p+t.d.length&&(i.d+=e.d.slice(t.p+t.d.length-e.p));var s=Math.max(e.p,t.p),l=Math.min(e.p+e.d.length,t.p+t.d.length),a=e.d.slice(s-e.p,l-e.p),d=t.d.slice(s-t.p,l-t.p);if(a!==d)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=tp(i.p,t),zr(n,i))}return n},GD=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Hi.invert=function(n){n=n.slice().reverse();for(var e=0;e<n.length;e++)n[e]=GD(n[e]);return n},d7(Hi,qD,Rh,zr);var Oh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},ZD=function(n){return!!n&&n.constructor===Object},_o=function(n){return JSON.parse(JSON.stringify(n))},Ie={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Vr={};Ie.registerSubtype=function(n){Vr[n.name]=n},Ie.create=function(n){return n===void 0?null:_o(n)},Ie.invertComponent=function(n){var e={p:n.p};return n.t&&Vr[n.t]&&(e.t=n.t,e.o=Vr[n.t].invert(n.o)),n.si!==void 0&&(e.sd=n.si),n.sd!==void 0&&(e.si=n.sd),n.oi!==void 0&&(e.od=n.oi),n.od!==void 0&&(e.oi=n.od),n.li!==void 0&&(e.ld=n.li),n.ld!==void 0&&(e.li=n.ld),n.na!==void 0&&(e.na=-n.na),n.lm!==void 0&&(e.lm=n.p[n.p.length-1],e.p=n.p.slice(0,n.p.length-1).concat([n.lm])),e},Ie.invert=function(n){for(var e=n.slice().reverse(),t=[],o=0;o<e.length;o++)t.push(Ie.invertComponent(e[o]));return t},Ie.checkValidOp=function(n){for(var e=0;e<n.length;e++)if(!Oh(n[e].p))throw new Error("Missing path")},Ie.checkList=function(n){if(!Oh(n))throw new Error("Referenced element not a list")},Ie.checkObj=function(n){if(!ZD(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Ua(n){n.t="text0";var e={p:n.p.pop()};n.si!=null&&(e.i=n.si),n.sd!=null&&(e.d=n.sd),n.o=[e]}function za(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}Ie.apply=function(n,e){Ie.checkValidOp(e),e=_o(e);for(var t={data:n},o=0;o<e.length;o++){var r=e[o];(r.si!=null||r.sd!=null)&&Ua(r);for(var i=null,s=t,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&&Vr[r.t])s[l]=Vr[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)Ie.checkList(s),s[l]=r.li;else if(r.li!==void 0)Ie.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)Ie.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(Ie.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)Ie.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)Ie.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return t.data},Ie.shatter=function(n){for(var e=[],t=0;t<n.length;t++)e.push([n[t]]);return e},Ie.incrementalApply=function(n,e,t){for(var o=0;o<e.length;o++){var r=[e[o]];n=Ie.apply(n,r),t(r,n)}return n};var QD=Ie.pathMatches=function(n,e,t){if(n.length!=e.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==e[o]&&(!t||o!==n.length-1))return!1;return!0};Ie.append=function(n,e){if(e=_o(e),n.length===0){n.push(e);return}var t=n[n.length-1];if((e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(Ua(e),Ua(t)),QD(e.p,t.p))if(e.t&&t.t&&e.t===t.t&&Vr[e.t]){if(t.o=Vr[e.t].compose(t.o,e.o),e.si!=null||e.sd!=null){for(var o=e.p,r=0;r<t.o.length-1;r++)e.o=[t.o.pop()],e.p=o.slice(),za(e),n.push(e);za(t)}}else t.na!=null&&e.na!=null?n[n.length-1]={p:t.p,na:t.na+e.na}:t.li!==void 0&&e.li===void 0&&e.ld===t.li?t.ld!==void 0?delete t.li:n.pop():t.od!==void 0&&t.oi===void 0&&e.oi!==void 0&&e.od===void 0?t.oi=e.oi:t.oi!==void 0&&e.od!==void 0?e.oi!==void 0?t.oi=e.oi:t.od!==void 0?delete t.oi:n.pop():e.lm!==void 0&&e.p[e.p.length-1]===e.lm||n.push(e);else(e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(za(e),za(t)),n.push(e)},Ie.compose=function(n,e){Ie.checkValidOp(n),Ie.checkValidOp(e);for(var t=_o(n),o=0;o<e.length;o++)Ie.append(t,e[o]);return t},Ie.normalize=function(n){var e=[];n=Oh(n)?n:[n];for(var t=0;t<n.length;t++){var o=n[t];o.p==null&&(o.p=[]),Ie.append(e,o)}return e},Ie.commonLengthForOps=function(n,e){var t=n.p.length,o=e.p.length;if((n.na!=null||n.t)&&t++,(e.na!=null||e.t)&&o++,t===0)return-1;if(o===0)return null;t--,o--;for(var r=0;r<t;r++){var i=n.p[r];if(r>=o||i!==e.p[r])return null}return t},Ie.canOpAffectPath=function(n,e){return Ie.commonLengthForOps({p:e},n)!=null},Ie.transformComponent=function(n,e,t,o){e=_o(e);var r=Ie.commonLengthForOps(t,e),i=Ie.commonLengthForOps(e,t),s=e.p.length,l=t.p.length;if((e.na!=null||e.t)&&s++,(t.na!=null||t.t)&&l++,i!=null&&l>s&&e.p[i]==t.p[i]){if(e.ld!==void 0){var a=_o(t);a.p=a.p.slice(s),e.ld=Ie.apply(_o(e.ld),[a])}else if(e.od!==void 0){var a=_o(t);a.p=a.p.slice(s),e.od=Ie.apply(_o(e.od),[a])}}if(r!=null){var d=s==l,a=t;if((e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(Ua(e),a=_o(t),Ua(a)),a.t&&Vr[a.t]){if(e.t&&e.t===a.t){var h=Vr[e.t].transform(e.o,a.o,o);if(e.si!=null||e.sd!=null)for(var p=e.p,A=0;A<h.length;A++)e.o=[h[A]],e.p=p.slice(),za(e),Ie.append(n,e);else(!Oh(h)||h.length>0)&&(e.o=h,Ie.append(n,e));return n}}else if(t.na===void 0){if(t.li!==void 0&&t.ld!==void 0){if(t.p[r]===e.p[r])if(d){if(e.ld!==void 0)if(e.li!==void 0&&o==="left")e.ld=_o(t.li);else return n}else return n}else if(t.li!==void 0)e.li!==void 0&&e.ld===void 0&&d&&e.p[r]===t.p[r]?o==="right"&&e.p[r]++:t.p[r]<=e.p[r]&&e.p[r]++,e.lm!==void 0&&d&&t.p[r]<=e.lm&&e.lm++;else if(t.ld!==void 0){if(e.lm!==void 0&&d){if(t.p[r]===e.p[r])return n;var p=t.p[r],v=e.p[r],B=e.lm;(p<B||p===B&&v<B)&&e.lm--}if(t.p[r]<e.p[r])e.p[r]--;else if(t.p[r]===e.p[r]){if(l<s)return n;if(e.ld!==void 0)if(e.li!==void 0)delete e.ld;else return n}}else if(t.lm!==void 0)if(e.lm!==void 0&&s===l){var v=e.p[r],B=e.lm,D=t.p[r],x=t.lm;if(D!==x)if(v===D)if(o==="left")e.p[r]=x,v===B&&(e.lm=x);else return n;else v>D&&e.p[r]--,v>x?e.p[r]++:v===x&&D>x&&(e.p[r]++,v===B&&e.lm++),(B>D||B===D&&B>v)&&e.lm--,B>x?e.lm++:B===x&&(x>D&&B>v||x<D&&B<v?o==="right"&&e.lm++:B>v?e.lm++:B===D&&e.lm--)}else if(e.li!==void 0&&e.ld===void 0&&d){var v=t.p[r],B=t.lm;p=e.p[r],p>v&&e.p[r]--,p>B&&e.p[r]++}else{var v=t.p[r],B=t.lm;p=e.p[r],p===v?e.p[r]=B:(p>v&&e.p[r]--,(p>B||p===B&&v>B)&&e.p[r]++)}else if(t.oi!==void 0&&t.od!==void 0){if(e.p[r]===t.p[r])if(e.oi!==void 0&&d){if(o==="right")return n;e.od=t.oi}else return n}else if(t.oi!==void 0){if(e.oi!==void 0&&e.p[r]===t.p[r])if(o==="left")Ie.append(n,{p:e.p,od:t.oi});else return n}else if(t.od!==void 0&&e.p[r]==t.p[r]){if(!d)return n;if(e.oi!==void 0)delete e.od;else return n}}}return Ie.append(n,e),n},d7(Ie,Ie.transformComponent,Ie.checkValidOp,Ie.append);var YD=h7.exports;Ie.registerSubtype(YD);var JD=Ie,KD={type:JD};(function(n){n.defaultType=KD.type,n.map={},n.register=function(e){e.name&&(n.map[e.name]=e),e.uri&&(n.map[e.uri]=e)},n.register(n.defaultType)})(ja);var Fo={};(function(n){n.doNothing=e;function e(){}n.hasKeys=function(t){for(var o in t)return!0;return!1},n.isInteger=Number.isInteger||function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t},n.isValidVersion=function(t){return t===null?!0:n.isInteger(t)&&t>=0},n.isValidTimestamp=function(t){return n.isValidVersion(t)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var t=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];t=t[r]||(o===arguments.length-1?void 0:{})}return t},n.digOrCreate=function(){for(var t=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];t=t[i]||(t[i]=r===arguments.length-2?o():{})}return t},n.digAndRemove=function(){for(var t=arguments[0],o=[t],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!t.hasOwnProperty(i))break;t=t[i],o.push(t)}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(t){return t&&typeof t.transformPresence=="function"},n.callEach=function(t,o){var r=!1;return t.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(t){return!!t},n.nextTick=function(t){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(){t.apply(null,o)})},n.clone=function(t){return t===void 0?void 0:JSON.parse(JSON.stringify(t))}})(Fo);var f7=Array.isArray,m7=Object.keys,XD=Object.prototype.hasOwnProperty,eS=function n(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var o=f7(e),r=f7(t),i,s,l;if(o&&r){if(s=e.length,s!=t.length)return!1;for(i=s;i--!==0;)if(!n(e[i],t[i]))return!1;return!0}if(o!=r)return!1;var a=e instanceof Date,d=t instanceof Date;if(a!=d)return!1;if(a&&d)return e.getTime()==t.getTime();var h=e instanceof RegExp,p=t instanceof RegExp;if(h!=p)return!1;if(h&&p)return e.toString()==t.toString();var A=m7(e);if(s=A.length,s!==m7(t).length)return!1;for(i=s;i--!==0;)if(!XD.call(t,A[i]))return!1;for(i=s;i--!==0;)if(l=A[i],!n(e[l],t[l]))return!1;return!0}return e!==e&&t!==t},g7=$i,tS=u7,Wn=Mh,_h=ja,Po=Fo,nS=Po.clone,oS=eS,Tn=Wn.CODES,rS=Fe;function Fe(n,e,t){g7.EventEmitter.call(this),this.connection=n,this.collection=e,this.id=t,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}g7.mixin(Fe),Fe.prototype.destroy=function(n){this._wantsDestroy=!0;var e=this;e.whenNothingPending(function(){e.wantSubscribe?e.unsubscribe(function(t){if(t)return n?n(t):e.emit("error",t);e.connection._destroyDoc(e),n&&n()}):(e.connection._destroyDoc(e),n&&n())})},Fe.prototype._setType=function(n){if(typeof n=="string"&&(n=_h.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var e=new Wn(Tn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",e)}},Fe.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Fe.prototype.ingestSnapshot=function(n,e){if(!n)return e&&e();if(typeof n.v!="number"){var t=new Wn(Tn.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return e?e(t):this.emit("error",t)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return e&&this.once("no write pending",e);var t=new Wn(Tn.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return e?e(t):this.emit("error",t)}return n.v>this.version?this.fetch(e):e&&e()}if(this.version>n.v)return e&&e();this.version=n.v;var o=n.type===void 0?_h.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),e&&e()},Fe.prototype.whenNothingPending=function(n){var e=this;Po.nextTick(function(){if(e.hasPending()){e.once("nothing pending",n);return}n()})},Fe.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Fe.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Fe.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Fe.prototype._emitResponseError=function(n,e){if(n&&n.code===Tn.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,e&&e(),this._emitNothingPending();return}if(e){e(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},Fe.prototype._handleFetch=function(n,e){var t=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&t.push(o),t.length&&(o=function(r){Po.callEach(t,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(e,o),this._emitNothingPending()},Fe.prototype._handleSubscribe=function(n,e){var t=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],t.callback&&o.push(t.callback);var r;if(o.length&&(r=function(i){Po.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=t.wantSubscribe,this.subscribed?this.ingestSnapshot(e,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},Fe.prototype._handleOp=function(n,e){if(n)return this.inflightOp?(n.code===Tn.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&e.src===this.inflightOp.src&&e.seq===this.inflightOp.seq){this._opAcknowledged(e);return}if(this.version==null||e.v>this.version){this.fetch();return}if(!(e.v<this.version)){if(this.inflightOp){var t=Fh(this.inflightOp,e);if(t)return this._hardRollback(t)}for(var o=0;o<this.pendingOps.length;o++){var t=Fh(this.pendingOps[o],e);if(t)return this._hardRollback(t)}this.version++;try{this._otApply(e,!1)}catch(r){return this._hardRollback(r)}}},Fe.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))},Fe.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(e){return e.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},Fe.prototype.fetch=function(n){if(this.connection.canSend){var e=this.connection.sendFetch(this);iS(this.inflightFetch,e,n);return}this.pendingFetch.push(n)},Fe.prototype.subscribe=function(n){var e=!0;this._queueSubscribe(e,n)},Fe.prototype.unsubscribe=function(n){var e=!1;this._queueSubscribe(e,n)},Fe.prototype._queueSubscribe=function(n,e){var t=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=t&&t.wantSubscribe===n;if(o){t.callback=sS([t.callback,e]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:e}),this._flushSubscribe()},Fe.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;Po.nextTick(function(){n._handleSubscribe()})}}};function iS(n,e,t){if(e){var o=n.pop();n.push(function(r){o&&o(r),t&&t(r)})}else n.push(t)}function sS(n){return n=n.filter(Po.truthy),n.length?function(e){Po.callEach(n,e)}:null}Fe.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function lS(n){delete n.op,delete n.create,delete n.del}function Fh(n,e){if(n.del)return lS(e);if(e.del)return new Wn(Tn.ERR_DOC_WAS_DELETED,"Document was deleted");if(e.create)return new Wn(Tn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in e){if(n.create)return new Wn(Tn.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var t=n.type.transformX(n.op,e.op);n.op=t[0],e.op=t[1]}else{var o=n.type.transform(n.op,e.op,"left"),r=n.type.transform(e.op,n.op,"right");n.op=o,e.op=r}}}Fe.prototype._otApply=function(n,e){if("op"in n){if(!this.type)throw new Wn(Tn.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,e),!e&&this.type===_h.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var t=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,e,n.src);for(var s=t;s<this.applyStack.length;s++){var l=Fh(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,e,n.src)}this.emit("op batch",n.op,e),this._popApplyStack(t);return}this.emit("before op",n.op,e,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,e,n.src),this.emit("op batch",n.op,e);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",e);return}if(n.del){var a=this.data;this._setType(null),this.emit("del",a,e);return}},Fe.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var e=this.inflightOp;if(!e){var t=new Wn(Tn.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",t)}if(e.sentAt=Date.now(),e.retries=e.retries==null?0:e.retries+1,e.seq==null){if(this.connection.seq>=Po.MAX_SAFE_INTEGER)return this.emit("error",new Wn(Tn.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));e.seq=this.connection.seq++}this.connection.sendOp(this,e),e.src==null&&(e.src=n)}},Fe.prototype._submit=function(n,e,t){if(e||(e=!0),"op"in n){if(!this.type){var o=new Wn(Tn.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return t?t(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,e,t),this._otApply(n,e)}catch(i){return this._hardRollback(i)}var r=this;Po.nextTick(function(){r.flush()})},Fe.prototype._pushOp=function(n,e,t){if(n.source=e,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(t);return}}n.type=this.type,n.callbacks=[t],this.pendingOps.push(n)},Fe.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var e=this.applyStack[0];if(this.applyStack=null,!!e){var t=this.pendingOps.indexOf(e);if(t!==-1)for(var o=this.pendingOps.splice(t),t=0;t<o.length;t++){var e=o[t],r=this._tryCompose(e);r?r.callbacks=r.callbacks.concat(e.callbacks):this.pendingOps.push(e)}}},Fe.prototype._tryCompose=function(n){if(!this.preventCompose){var e=this.pendingOps[this.pendingOps.length-1];if(!(!e||e.sentAt)&&!(this.submitSource&&!oS(n.source,e.source))){if(e.create&&"op"in n)return e.create.data=this.type.apply(e.create.data,n.op),e;if("op"in e&&"op"in n&&this.type.compose)return e.op=this.type.compose(e.op,n.op),e}}},Fe.prototype.submitOp=function(n,e,t){typeof e=="function"&&(t=e,e=null);var o={op:n},r=e&&e.source;this._submit(o,r,t)},Fe.prototype.create=function(n,e,t,o){if(typeof e=="function"?(o=e,t=null,e=null):typeof t=="function"&&(o=t,t=null),e||(e=_h.defaultType.uri),this.type){var r=new Wn(Tn.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:e,data:n}},s=t&&t.source;this._submit(i,s,o)},Fe.prototype.del=function(n,e){if(typeof n=="function"&&(e=n,n=null),!this.type){var t=new Wn(Tn.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return e?e(t):this.emit("error",t)}var o={del:!0},r=n&&n.source;this._submit(o,r,e)},Fe.prototype.pause=function(){this.paused=!0},Fe.prototype.resume=function(){this.paused=!1,this.flush()},Fe.prototype.toSnapshot=function(){return{v:this.version,data:nS(this.data),type:this.type.uri}},Fe.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return tS.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},Fe.prototype._rollback=function(n){var e=this.inflightOp;if("op"in e&&e.type.invert){try{e.op=e.type.invert(e.op)}catch{return this._hardRollback(n)}for(var t=0;t<this.pendingOps.length;t++){var o=Fh(this.pendingOps[t],e);if(o)return this._hardRollback(o)}try{this._otApply(e,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},Fe.prototype._hardRollback=function(n){var e=[];this.inflightOp&&e.push(this.inflightOp),e=e.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var t=this;this.fetch(function(){for(var o=!!e.length,r=0;r<e.length;r++)o=Po.callEach(e[r].callbacks,n)&&o;if(n&&!o)return t.emit("error",n)})},Fe.prototype._clearInflightOp=function(n){var e=this.inflightOp;this.inflightOp=null;var t=Po.callEach(e.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!t)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 p7=$i,C7=Hs.ACTIONS,cS=Fo,aS=Dn;function Dn(n,e,t,o,r,i,s){p7.EventEmitter.call(this),this.action=n,this.connection=e,this.id=t,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}p7.mixin(Dn),Dn.prototype.hasPending=function(){return!this.ready},Dn.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 e=[],t=0;t<this.results.length;t++){var o=this.results[t];e.push([o.id,o.version])}n.r=e}this.connection.send(n),this.sent=!0}},Dn.prototype.destroy=function(n){this.connection.canSend&&this.action===C7.querySubscribe&&this.connection.send({a:C7.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&cS.nextTick(n)},Dn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Dn.prototype._handleFetch=function(n,e,t){this.connection._destroyQuery(this),this._handleResponse(n,e,t)},Dn.prototype._handleSubscribe=function(n,e,t){this._handleResponse(n,e,t)},Dn.prototype._handleResponse=function(n,e,t){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!e)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(e))i+=e.length,this.results=this._ingestSnapshots(e,s),this.extra=t;else for(var l in e){i++;var a=e[l],d=this.connection.get(a.c||this.collection,l);d.ingestSnapshot(a,s)}s()},Dn.prototype._ingestSnapshots=function(n,e){for(var t=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,e),t.push(i)}return t},Dn.prototype._finishResponse=function(n,e){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),e?e(n):this.emit("error",n);e&&e(null,this.results,this.extra)},Dn.prototype._handleError=function(n){this.emit("error",n)},Dn.prototype._handleDiff=function(n){for(var e=0;e<n.length;e++){var t=n[e];t.type==="insert"&&(t.values=this._ingestSnapshots(t.values))}for(var e=0;e<n.length;e++){var t=n[e];switch(t.type){case"insert":var o=t.values;Array.prototype.splice.apply(this.results,[t.index,0].concat(o)),this.emit("insert",o,t.index);break;case"remove":var i=t.howMany||1,r=this.results.splice(t.index,i);this.emit("remove",r,t.index);break;case"move":var i=t.howMany||1,s=this.results.splice(t.from,i);Array.prototype.splice.apply(this.results,[t.to,0].concat(s)),this.emit("move",s,t.from,t.to);break}}this.emit("changed",this.results)},Dn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var A7=$i,uS=Hs.ACTIONS,dS=Fo,b7=ar;function ar(n,e){if(A7.EventEmitter.call(this),!e||typeof e!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=e,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}A7.mixin(ar),ar.prototype.submit=function(n,e){this.value=n,this.send(e)},ar.prototype.send=function(n){var e=this._message();this._pendingMessages.push(e),this._callbacksByPresenceVersion[e.pv]=n,this._sendPending()},ar.prototype.destroy=function(n){var e=this;this.submit(null,function(t){if(t)return e._callbackOrEmit(t,n);delete e.presence.localPresences[e.presenceId],n&&n()})},ar.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(e){n.connection.send(e)}),this._pendingMessages=[]}},ar.prototype._ack=function(n,e){var t=this._getCallback(e);this._callbackOrEmit(n,t)},ar.prototype._message=function(){return{a:uS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},ar.prototype._getCallback=function(n){var e=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],e},ar.prototype._callbackOrEmit=function(n,e){if(e)return dS.nextTick(e,n);n&&this.emit("error",n)};var hS=Fo,v7=np;function np(n,e){this.presence=n,this.presenceId=e,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}np.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},np.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&hS.nextTick(n)};var op={exports:{}};(function(n,e){(function(t,o){o(e)})(cr,function(t){function o(k,T){T=T|0;for(var L=Math.max(k.length-T,0),F=Array(L),U=0;U<L;U++)F[U]=k[T+U];return F}var r=function(k){var T=o(arguments,1);return function(){var L=o(arguments);return k.apply(null,T.concat(L))}},i=function(k){return function(){var T=o(arguments),L=T.pop();k.call(this,T,L)}};function s(k){var T=typeof k;return k!=null&&(T=="object"||T=="function")}var l=typeof setImmediate=="function"&&setImmediate,a=typeof process=="object"&&typeof process.nextTick=="function";function d(k){setTimeout(k,0)}function h(k){return function(T){var L=o(arguments,1);k(function(){T.apply(null,L)})}}var p;l?p=setImmediate:a?p=process.nextTick:p=d;var A=h(p);function v(k){return i(function(T,L){var F;try{F=k.apply(this,T)}catch(U){return L(U)}s(F)&&typeof F.then=="function"?F.then(function(U){B(L,null,U)},function(U){B(L,U.message?U:new Error(U))}):L(null,F)})}function B(k,T,L){try{k(T,L)}catch(F){A(D,F)}}function D(k){throw k}var x=typeof Symbol=="function";function _(k){return x&&k[Symbol.toStringTag]==="AsyncFunction"}function M(k){return _(k)?v(k):k}function j(k){return function(T){var L=o(arguments,1),F=i(function(U,H){var Z=this;return k(T,function(J,le){M(J).apply(Z,U.concat(le))},H)});return L.length?F.apply(this,L):F}}var z=typeof cr=="object"&&cr&&cr.Object===Object&&cr,q=typeof self=="object"&&self&&self.Object===Object&&self,ie=z||q||Function("return this")(),me=ie.Symbol,Be=Object.prototype,je=Be.hasOwnProperty,Ue=Be.toString,tt=me?me.toStringTag:void 0;function Yt(k){var T=je.call(k,tt),L=k[tt];try{k[tt]=void 0;var F=!0}catch{}var U=Ue.call(k);return F&&(T?k[tt]=L:delete k[tt]),U}var Wo=Object.prototype,Nt=Wo.toString;function Ln(k){return Nt.call(k)}var br="[object Null]",bn="[object Undefined]",an=me?me.toStringTag:void 0;function vr(k){return k==null?k===void 0?bn:br:an&&an in Object(k)?Yt(k):Ln(k)}var ti="[object AsyncFunction]",fo="[object Function]",Z2="[object GeneratorFunction]",Q2="[object Proxy]";function Y2(k){if(!s(k))return!1;var T=vr(k);return T==fo||T==Z2||T==ti||T==Q2}var ts=9007199254740991;function tl(k){return typeof k=="number"&&k>-1&&k%1==0&&k<=ts}function nl(k){return k!=null&&tl(k.length)&&!Y2(k)}var ni={};function Ne(){}function yr(k){return function(){if(k!==null){var T=k;k=null,T.apply(this,arguments)}}}var ns=typeof Symbol=="function"&&Symbol.iterator,Oc=function(k){return ns&&k[ns]&&k[ns]()};function Xf(k,T){for(var L=-1,F=Array(k);++L<k;)F[L]=T(L);return F}function un(k){return k!=null&&typeof k=="object"}var ol="[object Arguments]";function e1(k){return un(k)&&vr(k)==ol}var mo=Object.prototype,t1=mo.hasOwnProperty,J2=mo.propertyIsEnumerable,rl=e1(function(){return arguments}())?e1:function(k){return un(k)&&t1.call(k,"callee")&&!J2.call(k,"callee")},pt=Array.isArray;function il(){return!1}var sl=typeof t=="object"&&t&&!t.nodeType&&t,n1=sl&&!0&&n&&!n.nodeType&&n,ll=n1&&n1.exports===sl,o1=ll?ie.Buffer:void 0,cl=o1?o1.isBuffer:void 0,os=cl||il,Nu=9007199254740991,$u=/^(?:0|[1-9]\d*)$/;function Hu(k,T){var L=typeof k;return T=T==null?Nu:T,!!T&&(L=="number"||L!="symbol"&&$u.test(k))&&k>-1&&k%1==0&&k<T}var ju="[object Arguments]",Uu="[object Array]",zu="[object Boolean]",Vu="[object Date]",Wu="[object Error]",qu="[object Function]",K2="[object Map]",X2="[object Number]",e3="[object Object]",r1="[object RegExp]",i1="[object Set]",t3="[object String]",n3="[object WeakMap]",o3="[object ArrayBuffer]",r3="[object DataView]",s1="[object Float32Array]",i3="[object Float64Array]",s3="[object Int8Array]",l3="[object Int16Array]",Gu="[object Int32Array]",c3="[object Uint8Array]",Zu="[object Uint8ClampedArray]",a3="[object Uint16Array]",u3="[object Uint32Array]",it={};it[s1]=it[i3]=it[s3]=it[l3]=it[Gu]=it[c3]=it[Zu]=it[a3]=it[u3]=!0,it[ju]=it[Uu]=it[o3]=it[zu]=it[r3]=it[Vu]=it[Wu]=it[qu]=it[K2]=it[X2]=it[e3]=it[r1]=it[i1]=it[t3]=it[n3]=!1;function d3(k){return un(k)&&tl(k.length)&&!!it[vr(k)]}function h3(k){return function(T){return k(T)}}var l1=typeof t=="object"&&t&&!t.nodeType&&t,al=l1&&!0&&n&&!n.nodeType&&n,f3=al&&al.exports===l1,_c=f3&&z.process,c1=function(){try{var k=al&&al.require&&al.require("util").types;return k||_c&&_c.binding&&_c.binding("util")}catch{}}(),a1=c1&&c1.isTypedArray,m3=a1?h3(a1):d3,g3=Object.prototype,p3=g3.hasOwnProperty;function C3(k,T){var L=pt(k),F=!L&&rl(k),U=!L&&!F&&os(k),H=!L&&!F&&!U&&m3(k),Z=L||F||U||H,J=Z?Xf(k.length,String):[],le=J.length;for(var pe in k)(T||p3.call(k,pe))&&!(Z&&(pe=="length"||U&&(pe=="offset"||pe=="parent")||H&&(pe=="buffer"||pe=="byteLength"||pe=="byteOffset")||Hu(pe,le)))&&J.push(pe);return J}var Fc=Object.prototype;function A3(k){var T=k&&k.constructor,L=typeof T=="function"&&T.prototype||Fc;return k===L}function Pc(k,T){return function(L){return k(T(L))}}var b3=Pc(Object.keys,Object),v3=Object.prototype,y3=v3.hasOwnProperty;function u1(k){if(!A3(k))return b3(k);var T=[];for(var L in Object(k))y3.call(k,L)&&L!="constructor"&&T.push(L);return T}function Nc(k){return nl(k)?C3(k):u1(k)}function d1(k){var T=-1,L=k.length;return function(){return++T<L?{value:k[T],key:T}:null}}function k3(k){var T=-1;return function(){var F=k.next();return F.done?null:(T++,{value:F.value,key:T})}}function w3(k){var T=Nc(k),L=-1,F=T.length;return function U(){var H=T[++L];return H==="__proto__"?U():L<F?{value:k[H],key:H}:null}}function B3(k){if(nl(k))return d1(k);var T=Oc(k);return T?k3(T):w3(k)}function go(k){return function(){if(k===null)throw new Error("Callback was already called.");var T=k;k=null,T.apply(this,arguments)}}function ul(k){return function(T,L,F){if(F=yr(F||Ne),k<=0||!T)return F(null);var U=B3(T),H=!1,Z=0,J=!1;function le(ce,Ae){if(Z-=1,ce)H=!0,F(ce);else{if(Ae===ni||H&&Z<=0)return H=!0,F(null);J||pe()}}function pe(){for(J=!0;Z<k&&!H;){var ce=U();if(ce===null){H=!0,Z<=0&&F(null);return}Z+=1,L(ce.value,ce.key,go(le))}J=!1}pe()}}function kr(k,T,L,F){ul(T)(k,M(L),F)}function $t(k,T){return function(L,F,U){return k(L,T,F,U)}}function Qu(k,T,L){L=yr(L||Ne);var F=0,U=0,H=k.length;H===0&&L(null);function Z(J,le){J?L(J):(++U===H||le===ni)&&L(null)}for(;F<H;F++)T(k[F],F,go(Z))}var E3=$t(kr,1/0),qo=function(k,T,L){var F=nl(k)?Qu:E3;F(k,M(T),L)};function Go(k){return function(T,L,F){return k(qo,T,M(L),F)}}function Yu(k,T,L,F){F=F||Ne,T=T||[];var U=[],H=0,Z=M(L);k(T,function(J,le,pe){var ce=H++;Z(J,function(Ae,Ge){U[ce]=Ge,pe(Ae)})},function(J){F(J,U)})}var $c=Go(Yu),Ju=j($c);function oi(k){return function(T,L,F,U){return k(ul(L),T,M(F),U)}}var wr=oi(Yu),Ku=$t(wr,1),Xu=j(Ku);function rs(k,T){for(var L=-1,F=k==null?0:k.length;++L<F&&T(k[L],L,k)!==!1;);return k}function ed(k){return function(T,L,F){for(var U=-1,H=Object(T),Z=F(T),J=Z.length;J--;){var le=Z[k?J:++U];if(L(H[le],le,H)===!1)break}return T}}var is=ed();function ss(k,T){return k&&is(k,T,Nc)}function h1(k,T,L,F){for(var U=k.length,H=L+(F?1:-1);F?H--:++H<U;)if(T(k[H],H,k))return H;return-1}function x3(k){return k!==k}function f1(k,T,L){for(var F=L-1,U=k.length;++F<U;)if(k[F]===T)return F;return-1}function dl(k,T,L){return T===T?f1(k,T,L):h1(k,x3,L)}var Hc=function(k,T,L){typeof T=="function"&&(L=T,T=null),L=yr(L||Ne);var F=Nc(k),U=F.length;if(!U)return L(null);T||(T=U);var H={},Z=0,J=!1,le=Object.create(null),pe=[],ce=[],Ae={};ss(k,function(ut,ot){if(!pt(ut)){Ge(ot,[ut]),ce.push(ot);return}var mt=ut.slice(0,ut.length-1),Co=mt.length;if(Co===0){Ge(ot,ut),ce.push(ot);return}Ae[ot]=Co,rs(mt,function(E){if(!k[E])throw new Error("async.auto task `"+ot+"` has a non-existent dependency `"+E+"` in "+mt.join(", "));tn(E,function(){Co--,Co===0&&Ge(ot,ut)})})}),Z3(),It();function Ge(ut,ot){pe.push(function(){po(ut,ot)})}function It(){if(pe.length===0&&Z===0)return L(null,H);for(;pe.length&&Z<T;){var ut=pe.shift();ut()}}function tn(ut,ot){var mt=le[ut];mt||(mt=le[ut]=[]),mt.push(ot)}function On(ut){var ot=le[ut]||[];rs(ot,function(mt){mt()}),It()}function po(ut,ot){if(!J){var mt=go(function(E,xr){if(Z--,arguments.length>2&&(xr=o(arguments,1)),E){var us={};ss(H,function(_n,Pe){us[Pe]=_n}),us[ut]=xr,J=!0,le=Object.create(null),L(E,us)}else H[ut]=xr,On(ut)});Z++;var Co=M(ot[ot.length-1]);ot.length>1?Co(H,mt):Co(mt)}}function Z3(){for(var ut,ot=0;ce.length;)ut=ce.pop(),ot++,rs(Q3(ut),function(mt){--Ae[mt]===0&&ce.push(mt)});if(ot!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function Q3(ut){var ot=[];return ss(k,function(mt,Co){pt(mt)&&dl(mt,ut,0)>=0&&ot.push(Co)}),ot}};function ri(k,T){for(var L=-1,F=k==null?0:k.length,U=Array(F);++L<F;)U[L]=T(k[L],L,k);return U}var I3="[object Symbol]";function T3(k){return typeof k=="symbol"||un(k)&&vr(k)==I3}var D3=1/0,td=me?me.prototype:void 0,m1=td?td.toString:void 0;function nd(k){if(typeof k=="string")return k;if(pt(k))return ri(k,nd)+"";if(T3(k))return m1?m1.call(k):"";var T=k+"";return T=="0"&&1/k==-D3?"-0":T}function S3(k,T,L){var F=-1,U=k.length;T<0&&(T=-T>U?0:U+T),L=L>U?U:L,L<0&&(L+=U),U=T>L?0:L-T>>>0,T>>>=0;for(var H=Array(U);++F<U;)H[F]=k[F+T];return H}function L3(k,T,L){var F=k.length;return L=L===void 0?F:L,!T&&L>=F?k:S3(k,T,L)}function od(k,T){for(var L=k.length;L--&&dl(T,k[L],0)>-1;);return L}function M3(k,T){for(var L=-1,F=k.length;++L<F&&dl(T,k[L],0)>-1;);return L}function R3(k){return k.split("")}var O3="\\ud800-\\udfff",_3="\\u0300-\\u036f",F3="\\ufe20-\\ufe2f",st="\\u20d0-\\u20ff",nt=_3+F3+st,P3="\\ufe0e\\ufe0f",N3="\\u200d",$3=RegExp("["+N3+O3+nt+P3+"]");function H3(k){return $3.test(k)}var g1="\\ud800-\\udfff",j3="\\u0300-\\u036f",p1="\\ufe20-\\ufe2f",U3="\\u20d0-\\u20ff",qt=j3+p1+U3,rd="\\ufe0e\\ufe0f",ii="["+g1+"]",jc="["+qt+"]",hl="\\ud83c[\\udffb-\\udfff]",Mn="(?:"+jc+"|"+hl+")",id="[^"+g1+"]",sd="(?:\\ud83c[\\udde6-\\uddff]){2}",ld="[\\ud800-\\udbff][\\udc00-\\udfff]",C1="\\u200d",cd=Mn+"?",ad="["+rd+"]?",vn="(?:"+C1+"(?:"+[id,sd,ld].join("|")+")"+ad+cd+")*",z3=ad+cd+vn,Rn="(?:"+[id+jc+"?",jc,sd,ld,ii].join("|")+")",V3=RegExp(hl+"(?="+hl+")|"+Rn+z3,"g");function A1(k){return k.match(V3)||[]}function Zo(k){return H3(k)?A1(k):R3(k)}function Uc(k){return k==null?"":nd(k)}var ud=/^\s+|\s+$/g;function at(k,T,L){if(k=Uc(k),k&&(L||T===void 0))return k.replace(ud,"");if(!k||!(T=nd(T)))return k;var F=Zo(k),U=Zo(T),H=M3(F,U),Z=od(F,U)+1;return L3(F,H,Z).join("")}var Br=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,dd=/,/,W3=/(=.+)?(\s*)$/,hd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function q3(k){return k=k.toString().replace(hd,""),k=k.match(Br)[2].replace(" ",""),k=k?k.split(dd):[],k=k.map(function(T){return at(T.replace(W3,""))}),k}function b1(k,T){var L={};ss(k,function(F,U){var H,Z=_(F),J=!Z&&F.length===1||Z&&F.length===0;if(pt(F))H=F.slice(0,-1),F=F[F.length-1],L[U]=H.concat(H.length>0?le:F);else if(J)L[U]=F;else{if(H=q3(F),F.length===0&&!Z&&H.length===0)throw new Error("autoInject task functions require explicit parameters.");Z||H.pop(),L[U]=H.concat(le)}function le(pe,ce){var Ae=ri(H,function(Ge){return pe[Ge]});Ae.push(ce),M(F).apply(null,Ae)}}),Hc(L,T)}function Yn(){this.head=this.tail=null,this.length=0}function fd(k,T){k.length=1,k.head=k.tail=T}Yn.prototype.removeLink=function(k){return k.prev?k.prev.next=k.next:this.head=k.next,k.next?k.next.prev=k.prev:this.tail=k.prev,k.prev=k.next=null,this.length-=1,k},Yn.prototype.empty=function(){for(;this.head;)this.shift();return this},Yn.prototype.insertAfter=function(k,T){T.prev=k,T.next=k.next,k.next?k.next.prev=T:this.tail=T,k.next=T,this.length+=1},Yn.prototype.insertBefore=function(k,T){T.prev=k.prev,T.next=k,k.prev?k.prev.next=T:this.head=T,k.prev=T,this.length+=1},Yn.prototype.unshift=function(k){this.head?this.insertBefore(this.head,k):fd(this,k)},Yn.prototype.push=function(k){this.tail?this.insertAfter(this.tail,k):fd(this,k)},Yn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},Yn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},Yn.prototype.toArray=function(){for(var k=Array(this.length),T=this.head,L=0;L<this.length;L++)k[L]=T.data,T=T.next;return k},Yn.prototype.remove=function(k){for(var T=this.head;T;){var L=T.next;k(T)&&this.removeLink(T),T=L}return this};function fl(k,T,L){if(T==null)T=1;else if(T===0)throw new Error("Concurrency must not be zero");var F=M(k),U=0,H=[],Z=!1;function J(Ae,Ge,It){if(It!=null&&typeof It!="function")throw new Error("task callback must be a function");if(ce.started=!0,pt(Ae)||(Ae=[Ae]),Ae.length===0&&ce.idle())return A(function(){ce.drain()});for(var tn=0,On=Ae.length;tn<On;tn++){var po={data:Ae[tn],callback:It||Ne};Ge?ce._tasks.unshift(po):ce._tasks.push(po)}Z||(Z=!0,A(function(){Z=!1,ce.process()}))}function le(Ae){return function(Ge){U-=1;for(var It=0,tn=Ae.length;It<tn;It++){var On=Ae[It],po=dl(H,On,0);po===0?H.shift():po>0&&H.splice(po,1),On.callback.apply(On,arguments),Ge!=null&&ce.error(Ge,On.data)}U<=ce.concurrency-ce.buffer&&ce.unsaturated(),ce.idle()&&ce.drain(),ce.process()}}var pe=!1,ce={_tasks:new Yn,concurrency:T,payload:L,saturated:Ne,unsaturated:Ne,buffer:T/4,empty:Ne,drain:Ne,error:Ne,started:!1,paused:!1,push:function(Ae,Ge){J(Ae,!1,Ge)},kill:function(){ce.drain=Ne,ce._tasks.empty()},unshift:function(Ae,Ge){J(Ae,!0,Ge)},remove:function(Ae){ce._tasks.remove(Ae)},process:function(){if(!pe){for(pe=!0;!ce.paused&&U<ce.concurrency&&ce._tasks.length;){var Ae=[],Ge=[],It=ce._tasks.length;ce.payload&&(It=Math.min(It,ce.payload));for(var tn=0;tn<It;tn++){var On=ce._tasks.shift();Ae.push(On),H.push(On),Ge.push(On.data)}U+=1,ce._tasks.length===0&&ce.empty(),U===ce.concurrency&&ce.saturated();var po=go(le(Ae));F(Ge,po)}pe=!1}},length:function(){return ce._tasks.length},running:function(){return U},workersList:function(){return H},idle:function(){return ce._tasks.length+U===0},pause:function(){ce.paused=!0},resume:function(){ce.paused!==!1&&(ce.paused=!1,A(ce.process))}};return ce}function si(k,T){return fl(k,1,T)}var ls=$t(kr,1);function Qo(k,T,L,F){F=yr(F||Ne);var U=M(L);ls(k,function(H,Z,J){U(T,H,function(le,pe){T=pe,J(le)})},function(H){F(H,T)})}function zc(){var k=ri(arguments,M);return function(){var T=o(arguments),L=this,F=T[T.length-1];typeof F=="function"?T.pop():F=Ne,Qo(k,T,function(U,H,Z){H.apply(L,U.concat(function(J){var le=o(arguments,1);Z(J,le)}))},function(U,H){F.apply(L,[U].concat(H))})}}var Vc=function(){return zc.apply(null,o(arguments).reverse())},md=Array.prototype.concat,ml=function(k,T,L,F){F=F||Ne;var U=M(L);wr(k,T,function(H,Z){U(H,function(J){return J?Z(J):Z(null,o(arguments,1))})},function(H,Z){for(var J=[],le=0;le<Z.length;le++)Z[le]&&(J=md.apply(J,Z[le]));return F(H,J)})},v1=$t(ml,1/0),Wc=$t(ml,1),qc=function(){var k=o(arguments),T=[null].concat(k);return function(){var L=arguments[arguments.length-1];return L.apply(this,T)}};function gl(k){return k}function li(k,T){return function(L,F,U,H){H=H||Ne;var Z=!1,J;L(F,function(le,pe,ce){U(le,function(Ae,Ge){Ae?ce(Ae):k(Ge)&&!J?(Z=!0,J=T(!0,le),ce(null,ni)):ce()})},function(le){le?H(le):H(null,Z?J:T(!1))})}}function dn(k,T){return T}var cs=Go(li(gl,dn)),Yo=oi(li(gl,dn)),pl=$t(Yo,1);function gd(k){return function(T){var L=o(arguments,1);L.push(function(F){var U=o(arguments,1);typeof console=="object"&&(F?console.error&&console.error(F):console[k]&&rs(U,function(H){console[k](H)}))}),M(T).apply(null,L)}}var y1=gd("dir");function k1(k,T,L){L=go(L||Ne);var F=M(k),U=M(T);function H(J){if(J)return L(J);var le=o(arguments,1);le.push(Z),U.apply(this,le)}function Z(J,le){if(J)return L(J);if(!le)return L(null);F(H)}Z(null,!0)}function pd(k,T,L){L=go(L||Ne);var F=M(k),U=function(H){if(H)return L(H);var Z=o(arguments,1);if(T.apply(this,Z))return F(U);L.apply(null,[null].concat(Z))};F(U)}function w1(k,T,L){pd(k,function(){return!T.apply(this,arguments)},L)}function B1(k,T,L){L=go(L||Ne);var F=M(T),U=M(k);function H(J){if(J)return L(J);U(Z)}function Z(J,le){if(J)return L(J);if(!le)return L(null);F(H)}U(Z)}function ci(k){return function(T,L,F){return k(T,F)}}function Gc(k,T,L){qo(k,ci(M(T)),L)}function Cl(k,T,L,F){ul(T)(k,ci(M(L)),F)}var ai=$t(Cl,1);function Zc(k){return _(k)?k:i(function(T,L){var F=!0;T.push(function(){var U=arguments;F?A(function(){L.apply(null,U)}):L.apply(null,U)}),k.apply(this,T),F=!1})}function Jn(k){return!k}var ui=Go(li(Jn,Jn)),Al=oi(li(Jn,Jn)),Qc=$t(Al,1);function E1(k){return function(T){return T==null?void 0:T[k]}}function as(k,T,L,F){var U=new Array(T.length);k(T,function(H,Z,J){L(H,function(le,pe){U[Z]=!!pe,J(le)})},function(H){if(H)return F(H);for(var Z=[],J=0;J<T.length;J++)U[J]&&Z.push(T[J]);F(null,Z)})}function Kn(k,T,L,F){var U=[];k(T,function(H,Z,J){L(H,function(le,pe){le?J(le):(pe&&U.push({index:Z,value:H}),J())})},function(H){H?F(H):F(null,ri(U.sort(function(Z,J){return Z.index-J.index}),E1("value")))})}function Yc(k,T,L,F){var U=nl(T)?as:Kn;U(k,T,M(L),F||Ne)}var Jc=Go(Yc),bl=oi(Yc),Kc=$t(bl,1);function x1(k,T){var L=go(T||Ne),F=M(Zc(k));function U(H){if(H)return L(H);F(U)}U()}var Xc=function(k,T,L,F){F=F||Ne;var U=M(L);wr(k,T,function(H,Z){U(H,function(J,le){return J?Z(J):Z(null,{key:le,val:H})})},function(H,Z){for(var J={},le=Object.prototype.hasOwnProperty,pe=0;pe<Z.length;pe++)if(Z[pe]){var ce=Z[pe].key,Ae=Z[pe].val;le.call(J,ce)?J[ce].push(Ae):J[ce]=[Ae]}return F(H,J)})},di=$t(Xc,1/0),N=$t(Xc,1),G=gd("log");function V(k,T,L,F){F=yr(F||Ne);var U={},H=M(L);kr(k,T,function(Z,J,le){H(Z,J,function(pe,ce){if(pe)return le(pe);U[J]=ce,le()})},function(Z){F(Z,U)})}var he=$t(V,1/0),Ee=$t(V,1);function Ve(k,T){return T in k}function kt(k,T){var L=Object.create(null),F=Object.create(null);T=T||gl;var U=M(k),H=i(function(J,le){var pe=T.apply(null,J);Ve(L,pe)?A(function(){le.apply(null,L[pe])}):Ve(F,pe)?F[pe].push(le):(F[pe]=[le],U.apply(null,J.concat(function(){var ce=o(arguments);L[pe]=ce;var Ae=F[pe];delete F[pe];for(var Ge=0,It=Ae.length;Ge<It;Ge++)Ae[Ge].apply(null,ce)})))});return H.memo=L,H.unmemoized=k,H}var qe;a?qe=process.nextTick:l?qe=setImmediate:qe=d;var ea=h(qe);function Cd(k,T,L){L=L||Ne;var F=nl(T)?[]:{};k(T,function(U,H,Z){M(U)(function(J,le){arguments.length>2&&(le=o(arguments,1)),F[H]=le,Z(J)})},function(U){L(U,F)})}function yn(k,T){Cd(qo,k,T)}function vl(k,T,L){Cd(ul(T),k,L)}var Ad=function(k,T){var L=M(k);return fl(function(F,U){L(F[0],U)},T,1)},hi=function(k,T){var L=Ad(k,T);return L.push=function(F,U,H){if(H==null&&(H=Ne),typeof H!="function")throw new Error("task callback must be a function");if(L.started=!0,pt(F)||(F=[F]),F.length===0)return A(function(){L.drain()});U=U||0;for(var Z=L._tasks.head;Z&&U>=Z.priority;)Z=Z.next;for(var J=0,le=F.length;J<le;J++){var pe={data:F[J],priority:U,callback:H};Z?L._tasks.insertBefore(Z,pe):L._tasks.push(pe)}A(L.process)},delete L.unshift,L};function yl(k,T){if(T=yr(T||Ne),!pt(k))return T(new TypeError("First argument to race must be an array of functions"));if(!k.length)return T();for(var L=0,F=k.length;L<F;L++)M(k[L])(T)}function fi(k,T,L,F){var U=o(k).reverse();Qo(U,T,L,F)}function We(k){var T=M(k);return i(function(F,U){return F.push(function(Z,J){if(Z)U(null,{error:Z});else{var le;arguments.length<=2?le=J:le=o(arguments,1),U(null,{value:le})}}),T.apply(this,F)})}function I1(k){var T;return pt(k)?T=ri(k,We):(T={},ss(k,function(L,F){T[F]=We.call(this,L)})),T}function bd(k,T,L,F){Yc(k,T,function(U,H){L(U,function(Z,J){H(Z,!J)})},F)}var kl=Go(bd),vd=oi(bd),T1=$t(vd,1);function D1(k){return function(){return k}}function mi(k,T,L){var F=5,U=0,H={times:F,intervalFunc:D1(U)};function Z(ce,Ae){if(typeof Ae=="object")ce.times=+Ae.times||F,ce.intervalFunc=typeof Ae.interval=="function"?Ae.interval:D1(+Ae.interval||U),ce.errorFilter=Ae.errorFilter;else if(typeof Ae=="number"||typeof Ae=="string")ce.times=+Ae||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof k=="function"?(L=T||Ne,T=k):(Z(H,k),L=L||Ne),typeof T!="function")throw new Error("Invalid arguments for async.retry");var J=M(T),le=1;function pe(){J(function(ce){ce&&le++<H.times&&(typeof H.errorFilter!="function"||H.errorFilter(ce))?setTimeout(pe,H.intervalFunc(le)):L.apply(null,arguments)})}pe()}var Jo=function(k,T){T||(T=k,k=null);var L=M(T);return i(function(F,U){function H(Z){L.apply(null,F.concat(Z))}k?mi(k,H,U):mi(H,U)})};function wl(k,T){Cd(ls,k,T)}var Bl=Go(li(Boolean,gl)),Er=oi(li(Boolean,gl)),El=$t(Er,1);function yd(k,T,L){var F=M(T);$c(k,function(H,Z){F(H,function(J,le){if(J)return Z(J);Z(null,{value:H,criteria:le})})},function(H,Z){if(H)return L(H);L(null,ri(Z.sort(U),E1("value")))});function U(H,Z){var J=H.criteria,le=Z.criteria;return J<le?-1:J>le?1:0}}function xl(k,T,L){var F=M(k);return i(function(U,H){var Z=!1,J;function le(){var pe=k.name||"anonymous",ce=new Error('Callback function "'+pe+'" timed out.');ce.code="ETIMEDOUT",L&&(ce.info=L),Z=!0,H(ce)}U.push(function(){Z||(H.apply(null,arguments),clearTimeout(J))}),J=setTimeout(le,T),F.apply(null,U)})}var S1=Math.ceil,Il=Math.max;function gi(k,T,L,F){for(var U=-1,H=Il(S1((T-k)/(L||1)),0),Z=Array(H);H--;)Z[F?H:++U]=k,k+=L;return Z}function pi(k,T,L,F){var U=M(L);wr(gi(0,k,1),T,U,F)}var L1=$t(pi,1/0),M1=$t(pi,1);function R1(k,T,L,F){arguments.length<=3&&(F=L,L=T,T=pt(k)?[]:{}),F=yr(F||Ne);var U=M(L);qo(k,function(H,Z,J){U(T,H,Z,J)},function(H){F(H,T)})}function Tl(k,T){var L=null,F;T=T||Ne,ai(k,function(U,H){M(U)(function(Z,J){arguments.length>2?F=o(arguments,1):F=J,L=Z,H(!Z)})},function(){T(L,F)})}function Dl(k){return function(){return(k.unmemoized||k).apply(null,arguments)}}function Sl(k,T,L){L=go(L||Ne);var F=M(T);if(!k())return L(null);var U=function(H){if(H)return L(H);if(k())return F(U);var Z=o(arguments,1);L.apply(null,[null].concat(Z))};F(U)}function O1(k,T,L){Sl(function(){return!k.apply(this,arguments)},T,L)}var kd=function(k,T){if(T=yr(T||Ne),!pt(k))return T(new Error("First argument to waterfall must be an array of functions"));if(!k.length)return T();var L=0;function F(H){var Z=M(k[L++]);H.push(go(U)),Z.apply(null,H)}function U(H){if(H||L===k.length)return T.apply(null,arguments);F(o(arguments,1))}F([])},G3={apply:r,applyEach:Ju,applyEachSeries:Xu,asyncify:v,auto:Hc,autoInject:b1,cargo:si,compose:Vc,concat:v1,concatLimit:ml,concatSeries:Wc,constant:qc,detect:cs,detectLimit:Yo,detectSeries:pl,dir:y1,doDuring:k1,doUntil:w1,doWhilst:pd,during:B1,each:Gc,eachLimit:Cl,eachOf:qo,eachOfLimit:kr,eachOfSeries:ls,eachSeries:ai,ensureAsync:Zc,every:ui,everyLimit:Al,everySeries:Qc,filter:Jc,filterLimit:bl,filterSeries:Kc,forever:x1,groupBy:di,groupByLimit:Xc,groupBySeries:N,log:G,map:$c,mapLimit:wr,mapSeries:Ku,mapValues:he,mapValuesLimit:V,mapValuesSeries:Ee,memoize:kt,nextTick:ea,parallel:yn,parallelLimit:vl,priorityQueue:hi,queue:Ad,race:yl,reduce:Qo,reduceRight:fi,reflect:We,reflectAll:I1,reject:kl,rejectLimit:vd,rejectSeries:T1,retry:mi,retryable:Jo,seq:zc,series:wl,setImmediate:A,some:Bl,someLimit:Er,someSeries:El,sortBy:yd,timeout:xl,times:L1,timesLimit:pi,timesSeries:M1,transform:R1,tryEach:Tl,unmemoize:Dl,until:O1,waterfall:kd,whilst:Sl,all:ui,allLimit:Al,allSeries:Qc,any:Bl,anyLimit:Er,anySeries:El,find:cs,findLimit:Yo,findSeries:pl,forEach:Gc,forEachSeries:ai,forEachLimit:Cl,forEachOf:qo,forEachOfSeries:ls,forEachOfLimit:kr,inject:Qo,foldl:Qo,foldr:fi,select:Jc,selectLimit:bl,selectSeries:Kc,wrapSync:v};t.default=G3,t.apply=r,t.applyEach=Ju,t.applyEachSeries=Xu,t.asyncify=v,t.auto=Hc,t.autoInject=b1,t.cargo=si,t.compose=Vc,t.concat=v1,t.concatLimit=ml,t.concatSeries=Wc,t.constant=qc,t.detect=cs,t.detectLimit=Yo,t.detectSeries=pl,t.dir=y1,t.doDuring=k1,t.doUntil=w1,t.doWhilst=pd,t.during=B1,t.each=Gc,t.eachLimit=Cl,t.eachOf=qo,t.eachOfLimit=kr,t.eachOfSeries=ls,t.eachSeries=ai,t.ensureAsync=Zc,t.every=ui,t.everyLimit=Al,t.everySeries=Qc,t.filter=Jc,t.filterLimit=bl,t.filterSeries=Kc,t.forever=x1,t.groupBy=di,t.groupByLimit=Xc,t.groupBySeries=N,t.log=G,t.map=$c,t.mapLimit=wr,t.mapSeries=Ku,t.mapValues=he,t.mapValuesLimit=V,t.mapValuesSeries=Ee,t.memoize=kt,t.nextTick=ea,t.parallel=yn,t.parallelLimit=vl,t.priorityQueue=hi,t.queue=Ad,t.race=yl,t.reduce=Qo,t.reduceRight=fi,t.reflect=We,t.reflectAll=I1,t.reject=kl,t.rejectLimit=vd,t.rejectSeries=T1,t.retry=mi,t.retryable=Jo,t.seq=zc,t.series=wl,t.setImmediate=A,t.some=Bl,t.someLimit=Er,t.someSeries=El,t.sortBy=yd,t.timeout=xl,t.times=L1,t.timesLimit=pi,t.timesSeries=M1,t.transform=R1,t.tryEach=Tl,t.unmemoize=Dl,t.until=O1,t.waterfall=kd,t.whilst=Sl,t.all=ui,t.allLimit=Al,t.allSeries=Qc,t.any=Bl,t.anyLimit=Er,t.anySeries=El,t.find=cs,t.findLimit=Yo,t.findSeries=pl,t.forEach=Gc,t.forEachSeries=ai,t.forEachLimit=Cl,t.forEachOf=qo,t.forEachOfSeries=ls,t.forEachOfLimit=kr,t.inject=Qo,t.foldl=Qo,t.foldr=fi,t.select=Jc,t.selectLimit=bl,t.selectSeries=Kc,t.wrapSync=v,Object.defineProperty(t,"__esModule",{value:!0})})})(op,op.exports);var y7={exports:{}},rp=y7.exports=function(n,e){if(e||(e=16),n===void 0&&(n=128),n<=0)return"0";for(var t=Math.log(Math.pow(2,n))/Math.log(e),o=2;t===1/0;o*=2)t=Math.log(Math.pow(2,n/o))/Math.log(e)*o;for(var r=t-Math.floor(t),i="",o=0;o<Math.floor(t);o++){var s=Math.floor(Math.random()*e).toString(e);i=s+i}if(r){var l=Math.pow(e,r),s=Math.floor(Math.random()*l).toString(e);i=s+i}var a=parseInt(i,e);return a!==1/0&&a>=Math.pow(2,n)?rp(n,e):i};rp.rack=function(n,e,t){var o=function(i){var s=0;do{if(s++>10)if(t)n+=t;else throw new Error("too many ID collisions, use more bits");var l=rp(n,e)}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=e||16,o};var k7=$i,fS=b7,mS=v7,Ph=Fo,ip=op.exports,gS=y7.exports,w7=Hs.ACTIONS,B7=Mt;function Mt(n,e){if(k7.EventEmitter.call(this),!e||typeof e!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=e,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}k7.mixin(Mt),Mt.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Mt.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Mt.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||gS();var e=this._createLocalPresence(n);return this.localPresences[n]=e,e},Mt.prototype.destroy=function(n){this._wantsDestroy=!0;var e=this,t=Object.keys(e.localPresences);this.unsubscribe(function(o){if(o)return e._callbackOrEmit(o,n);var r=Object.keys(e._remotePresenceInstances);ip.parallel([function(i){ip.each(t,function(s,l){e.localPresences[s].destroy(l)},i)},function(i){if(!e._wantsDestroy)return i();ip.each(r,function(s,l){e._remotePresenceInstances[s].destroy(l)},i)}],function(i){e._wantsDestroy&&delete e.connection._presences[e.channel],e._callbackOrEmit(i,n)})})},Mt.prototype._sendSubscriptionAction=function(n,e){this.wantSubscribe=!!n;var t=this.wantSubscribe?w7.presenceSubscribe:w7.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=e,this.connection.canSend&&this.connection._sendPresenceAction(t,o,this)},Mt.prototype._handleSubscribe=function(n,e){this.wantSubscribe&&(this.subscribed=!0);var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},Mt.prototype._handleUnsubscribe=function(n,e){this.subscribed=!1;var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},Mt.prototype._receiveUpdate=function(n,e){var t=Ph.dig(this.localPresences,e.id);if(t)return t._ack(n,e.pv);if(n)return this.emit("error",n);var o=this,r=Ph.digOrCreate(this._remotePresenceInstances,e.id,function(){return o._createRemotePresence(e.id)});r.receiveUpdate(e)},Mt.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Mt.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var e in this.localPresences){var t=this.localPresences[e];t.value!==null&&t.send()}},Mt.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Mt.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Mt.prototype._resubscribe=function(){var n=[];for(var e in this._subscriptionCallbacksBySeq){var t=this._subscriptionCallback(e);n.push(t)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},Mt.prototype._subscriptionCallback=function(n){var e=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],e},Mt.prototype._callbackOrEmit=function(n,e){if(e)return Ph.nextTick(e,n);n&&this.emit("error",n)},Mt.prototype._createLocalPresence=function(n){return new fS(this,n)},Mt.prototype._createRemotePresence=function(n){return new mS(this,n)},Mt.prototype._callEachOrEmit=function(n,e){var t=Ph.callEach(n,e);!t&&e&&this.emit("error",e)};var Va=b7,E7=Mh,pS=Fo,x7=E7.CODES,CS=No;function No(n,e){Va.call(this,n,e),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()}No.prototype=Object.create(Va.prototype),No.prototype.submit=function(n,e){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,e);var t={code:x7.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(t,e)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,Va.prototype.submit.call(this,n,e)},No.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),Va.prototype.destroy.call(this,n)},No.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(e){e.t=n._doc.type.uri,e.v=n._doc.version,n.connection.send(e)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},No.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)},No.prototype._transformAgainstOp=function(n,e){var t=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=t._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=t._transformPresence(r.p,n,e),t._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=t._getCallback(r.pv);t._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,e)}catch(r){this.emit("error",r)}},No.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},No.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},No.prototype._message=function(){var n=Va.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},No.prototype._transformPresence=function(n,e,t){var o=this._doc.type;if(!pS.supportsPresence(o))throw new E7(x7.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,e,t)};var I7={};(function(n){var e=ja,t=Mh,o=Fo,r=t.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var a=l.create.type;if(typeof a!="string")return new t(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=e.map[a];if(d==null||typeof d!="object")return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new t(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new t(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new t(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new t(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 t(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return e.map[l]&&e.map[l].uri},n.apply=function(l,a){if(typeof l!="object")return new t(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&a.v!=null&&l.v!==a.v)return new t(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(a.create){if(l.type)return new t(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=a.create,h=e.map[d.type];if(!h)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(A){return A}}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 t(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(a===void 0)return new t(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=e.map[l.type];if(!d)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,a)}catch(h){return new t(r.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,a,d){if(a.v!=null&&a.v!==d.v)return new t(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(a.create||"op"in a)return new t(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 t(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in a){if(!l)return new t(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=e.map[l],!l))return new t(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 t(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=p.v;var A=n.apply(l,p);if(A)return A}},n.transformPresence=function(l,a,d){var h=this.checkOp(a);if(h)return h;var p=l.t;if(typeof p=="string"&&(p=e.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(A){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:A.message||A}}l.v++};function s(l,a){if(l.type===e.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 A=d[p];typeof A.lm=="string"&&(A.lm=+A.lm);for(var v=A.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=e.defaultType.apply(h,[A]))}}}}})(I7);var Wa=v7,AS=I7,bS=lo;function lo(n,e){Wa.call(this,n,e),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()}lo.prototype=Object.create(Wa.prototype),lo.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},lo.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),Wa.prototype.destroy.call(this,n)},lo.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)},lo.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))}})}},lo.prototype._handleOp=function(n,e,t){var o=t===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},Wa.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Wa.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},lo.prototype._transformAgainstOp=function(n,e){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,e)}catch(t){return this.presence.emit("error",t)}this.presence._updateRemotePresence(this)}},lo.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],e=n.op,t=n.isOwnOp;e===null?(this._pending.p=null,this._pending.v++):AS.transformPresence(this._pending,e,t)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},lo.prototype._startCachingOps=function(){this._opCache=[]},lo.prototype._stopCachingOps=function(){this._opCache=null},lo.prototype._cacheOp=function(n,e){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:e})};var T7=B7,vS=CS,yS=bS;function Kl(n,e,t){var o=Kl.channel(e,t);T7.call(this,n,o),this.collection=e,this.id=t}var kS=Kl;Kl.prototype=Object.create(T7.prototype),Kl.channel=function(n,e){return n+"."+e},Kl.prototype._createLocalPresence=function(n){return new vS(this,n)},Kl.prototype._createRemotePresence=function(n){return new yS(this,n)};var wS=BS;function BS(n,e,t,o,r){this.id=n,this.v=e,this.type=t,this.data=o,this.m=r}var ES=wS,D7=$i,S7=qa;function qa(n,e,t,o,r){if(D7.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=e,this.connection=n,this.id=o,this.collection=t,this.callback=r,this.sent=!1}D7.mixin(qa),qa.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},qa.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},qa.prototype._handleResponse=function(n,e){if(this.emit("ready"),n)return this.callback(n);var t=e.meta?e.meta:null,o=new ES(this.id,e.v,e.type,e.data,t);this.callback(null,o)};var L7=S7,xS=Fo,IS=Hs.ACTIONS,TS=sp;function sp(n,e,t,o,r,i){if(L7.call(this,n,e,t,o,i),!xS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}sp.prototype=Object.create(L7.prototype),sp.prototype._message=function(){return{a:IS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var M7=S7,DS=Fo,SS=Hs.ACTIONS,LS=lp;function lp(n,e,t,o,r,i){if(M7.call(this,n,e,t,o,i),!DS.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}lp.prototype=Object.create(M7.prototype),lp.prototype._message=function(){return{a:SS.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var MS=rS,RS=aS,OS=B7,R7=kS,_S=TS,FS=LS,O7=$i,Xl=Mh,et=Hs.ACTIONS,_7=ja,$o=Fo,Ga=u7,Za=Xl.CODES;function F7(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var PS=we;function we(n){O7.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=F7(n),this.bindToSocket(n)}O7.mixin(we),we.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 e=F7(n);this._setState(e),this.canSend=!1;var t=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Ga.warn("Failed to parse message",o);return}t.debug&&Ga.info("RECV",JSON.stringify(r));var i={data:r};if(t.emit("receive",i),!!i.data)try{t.handleMessage(i.data)}catch(s){$o.nextTick(function(){t.emit("error",s)})}},n.readyState===1&&t._initializeHandshake(),n.onopen=function(){t._setState("connecting"),t._initializeHandshake()},n.onerror=function(o){t.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?t._setState("closed",o):o==="stopped"||o==="Stopped by server"?t._setState("stopped",o):t._setState("disconnected",o)}},we.prototype.handleMessage=function(n){var e=null;switch(n.error&&(e=P7(n.error,n),delete n.error),n.a){case et.initLegacy:return this._handleLegacyInit(n);case et.handshake:return this._handleHandshake(e,n);case et.queryFetch:var t=this.queries[n.id];t&&t._handleFetch(e,n.data,n.extra);return;case et.querySubscribe:var t=this.queries[n.id];t&&t._handleSubscribe(e,n.data,n.extra);return;case et.queryUnsubscribe:return;case et.queryUpdate:var t=this.queries[n.id];if(!t)return;if(e)return t._handleError(e);n.diff&&t._handleDiff(n.diff),n.hasOwnProperty("extra")&&t._handleExtra(n.extra);return;case et.bulkFetch:return this._handleBulkMessage(e,n,"_handleFetch");case et.bulkSubscribe:case et.bulkUnsubscribe:return this._handleBulkMessage(e,n,"_handleSubscribe");case et.snapshotFetch:case et.snapshotFetchByTimestamp:return this._handleSnapshotFetch(e,n);case et.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(e,n.data);return;case et.subscribe:case et.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(e,n.data);return;case et.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(e,n);return;case et.presence:return this._handlePresence(e,n);case et.presenceSubscribe:return this._handlePresenceSubscribe(e,n);case et.presenceUnsubscribe:return this._handlePresenceUnsubscribe(e,n);case et.presenceRequest:return this._handlePresenceRequest(e,n);case et.pingPong:return this._handlePingPong(e);default:Ga.warn("Ignoring unrecognized message",n)}};function P7(n,e){var t=new Error(n.message);return t.code=n.code,e&&(t.data=e),t}we.prototype._handleBulkMessage=function(n,e,t){if(e.data)for(var o in e.data){var r=e.data[o],i=this.getExisting(e.c,o);i&&(n?i[t](n):r.error?i[t](P7(r.error)):i[t](null,r))}else if(Array.isArray(e.b))for(var s=0;s<e.b.length;s++){var o=e.b[s],i=this.getExisting(e.c,o);i&&i[t](n)}else if(e.b)for(var o in e.b){var i=this.getExisting(e.c,o);i&&i[t](n)}else Ga.error("Invalid bulk message",e)},we.prototype._reset=function(){this.agent=null},we.prototype._setState=function(n,e){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var t=new Xl(Za.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",t)}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,e),this.emit("state",n,e)}},we.prototype.startBulk=function(){this.bulk||(this.bulk={})},we.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var e=this.bulk[n];this._sendBulk("f",n,e.f),this._sendBulk("s",n,e.s),this._sendBulk("u",n,e.u)}this.bulk=null},we.prototype._sendBulk=function(n,e,t){if(!!t){var o=[],r={},i=0,s;for(var l in t){var a=t[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:e,d:l})}else o.length&&this.send({a:"b"+n,c:e,b:o});if(i===1){var d=r[s];this.send({a:n,c:e,d:s,v:d})}else i&&this.send({a:"b"+n,c:e,b:r})}},we.prototype._sendActions=function(n,e,t){if(this._addDoc(e),this.bulk){var o=this.bulk[e.collection]||(this.bulk[e.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(e.id);return r[e.id]=t,i}else{var s={a:n,c:e.collection,d:e.id,v:t};this.send(s)}},we.prototype.sendFetch=function(n){return this._sendActions(et.fetch,n,n.version)},we.prototype.sendSubscribe=function(n){return this._sendActions(et.subscribe,n,n.version)},we.prototype.sendUnsubscribe=function(n){return this._sendActions(et.unsubscribe,n)},we.prototype.sendOp=function(n,e){this._addDoc(n);var t={a:et.op,c:n.collection,d:n.id,v:n.version,src:e.src,seq:e.seq,x:{}};"op"in e&&(t.op=e.op),e.create&&(t.create=e.create),e.del&&(t.del=e.del),n.submitSource&&(t.x.source=e.source),this.send(t)},we.prototype.send=function(n){this.debug&&Ga.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},we.prototype.ping=function(){if(!this.canSend)throw new Xl(Za.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:et.pingPong};this.send(n)},we.prototype.close=function(){this.socket.close()},we.prototype.getExisting=function(n,e){if(this.collections[n])return this.collections[n][e]},we.prototype.get=function(n,e){var t=this.collections[n]||(this.collections[n]={}),o=t[e];return o||(o=t[e]=new MS(this,n,e),this.emit("doc",o)),o._wantsDestroy=!1,o},we.prototype._destroyDoc=function(n){!n._wantsDestroy||($o.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},we.prototype._addDoc=function(n){var e=this.collections[n.collection];e||(e=this.collections[n.collection]={}),e[n.id]!==n&&(e[n.id]=n)},we.prototype._createQuery=function(n,e,t,o,r){var i=this.nextQueryId++,s=new RS(n,this,i,e,t,o,r);return this.queries[i]=s,s.send(),s},we.prototype._destroyQuery=function(n){delete this.queries[n.id]},we.prototype.createFetchQuery=function(n,e,t,o){return this._createQuery(et.queryFetch,n,e,t,o)},we.prototype.createSubscribeQuery=function(n,e,t,o){return this._createQuery(et.querySubscribe,n,e,t,o)},we.prototype.hasPending=function(){return!!(this._firstDoc(Nh)||this._firstQuery(Nh)||this._firstSnapshotRequest())};function Nh(n){return n.hasPending()}we.prototype.hasWritePending=function(){return!!this._firstDoc(NS)};function NS(n){return n.hasWritePending()}we.prototype.whenNothingPending=function(n){var e=this._firstDoc(Nh);if(e){e.once("nothing pending",this._nothingPendingRetry(n));return}var t=this._firstQuery(Nh);if(t){t.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}$o.nextTick(n)},we.prototype._nothingPendingRetry=function(n){var e=this;return function(){$o.nextTick(function(){e.whenNothingPending(n)})}},we.prototype._firstDoc=function(n){for(var e in this.collections){var t=this.collections[e];for(var o in t){var r=t[o];if(n(r))return r}}},we.prototype._firstQuery=function(n){for(var e in this.queries){var t=this.queries[e];if(n(t))return t}},we.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},we.prototype.fetchSnapshot=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new _S(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},we.prototype.fetchSnapshotByTimestamp=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new FS(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},we.prototype._handleSnapshotFetch=function(n,e){var t=this._snapshotRequests[e.id];!t||(delete this._snapshotRequests[e.id],t._handleResponse(n,e))},we.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},we.prototype._initializeHandshake=function(){this.send({a:et.handshake,id:this.id})},we.prototype._handleHandshake=function(n,e){if(n)return this.emit("error",n);this._initialize(e)},we.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},we.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new Xl(Za.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(_7.map[n.type]!==_7.defaultType)return this.emit("error",new Xl(Za.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Xl(Za.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},we.prototype.getPresence=function(n){var e=this,t=$o.digOrCreate(this._presences,n,function(){return new OS(e,n)});return t._wantsDestroy=!1,t},we.prototype.getDocPresence=function(n,e){var t=R7.channel(n,e),o=this,r=$o.digOrCreate(this._presences,t,function(){return new R7(o,n,e)});return r._wantsDestroy=!1,r},we.prototype._sendPresenceAction=function(n,e,t){this._addPresence(t);var o={a:n,ch:t.channel,seq:e};return this.send(o),o.seq},we.prototype._addPresence=function(n){$o.digOrCreate(this._presences,n.channel,function(){return n})},we.prototype._handlePresenceSubscribe=function(n,e){var t=$o.dig(this._presences,e.ch);t&&t._handleSubscribe(n,e.seq)},we.prototype._handlePresenceUnsubscribe=function(n,e){var t=$o.dig(this._presences,e.ch);t&&t._handleUnsubscribe(n,e.seq)},we.prototype._handlePresence=function(n,e){var t=$o.dig(this._presences,e.ch);t&&t._receiveUpdate(n,e)},we.prototype._handlePresenceRequest=function(n,e){var t=$o.dig(this._presences,e.ch);t&&t._broadcastAllLocalPresence(n,e)};var N7=PS,$S=ja;const $h={err:1001,msg:"user auth error",name:"AuthError"},HS={err:1002,msg:"you don't have required permission",name:"PermissionError"},cp={err:1003,msg:"Too many user connected",name:"MaxUserError"},Qa={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},jS={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},US={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},Ya="x-live-editor-token",Hh="x-live-editor-base-url",gn=S("auth-connection");function zS(n){try{n()}catch(e){gn.error(e)}}class VS{constructor(e,t){g(this,"connection");g(this,"ws");g(this,"retryCount");g(this,"events",new H5.EventEmitter);g(this,"token",null);g(this,"resourceToken",null);this.url=e,this.reauthFunc=t,this.retryCount=0}getBaseURL(){const e=new URL(this.url);return`${e.protocol==="wss:"?"https:":"http:"}//${e.host}${e.pathname}`}getBase64BaseURL(){return ws(this.getBaseURL())}async auth(e){m(gn,e.token,"no auth token");const t=`${this.getBaseURL()}/auth`,o=await window.fetch(t,{method:"GET",headers:{[Ya]:e.token,[Hh]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=e.token,await o.json()}async logout(){if(!this.token)return;const e=`${this.getBaseURL()}/logout`;await window.fetch(e,{method:"GET",headers:{[Hh]:ws(this.getBaseURL())}})}async init(e){const t=await this.auth(e);this.resourceToken=t.read,this.ws=new $B.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(N7.prototype),m(gn,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:e})};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}}},N7.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,gn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const e=await this.reauthFunc();await this.auth(e),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:e})}}}catch(e){gn.error(e),setTimeout(()=>this.handleAuthError(),0)}}else gn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const e=new Error($h.msg);e.code=$h.err,this.events.emit("error",e)}emitRequestReloadError(){const e=new Error(Qa.msg);e.code=Qa.err,this.events.emit("requestReloadError",e)}emitWriteConflictError(e,t){e.orgMsg=t,this.events.emit("writeConflictError",e)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(e){const t=e;if(t.a==="pong")return;const o=t.err;if(o===$h.err)gn.warn("auth error"),this.handleAuthError();else if(o===cp.err)gn.warn(cp.msg),this.emitMaxUsersError();else if(o===Qa.err){gn.warn(Qa.msg);try{this.emitRequestReloadError()}catch(r){gn.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else gn.error(`unknown message received: ${JSON.stringify(t)}`),this.emitAuthError()}get(e,t){return m(gn,this.connection,"no this.connection"),this.connection.get(e,t)}addEventListener(e,t){e==="error"?this.events.addListener(e,t):(m(gn,this.ws,"no this.ws"),this.ws.addEventListener(e,t))}onWriteConflictError(e){this.events.addListener("writeConflictError",e)}onMaxUsersError(e){m(gn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",e)}onRequestReloadError(e){m(gn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",e)}end(e){var t;this.reauthFunc=void 0,this.events.removeAllListeners(),zS(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(t=this.ws)==null||t.close(),this.ws=void 0,e&&this.logout()}}S("utils/file");function WS(){function n(){return new Promise(e=>{const t=new FileReader;t.onload=()=>{e(t.result)},t.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}WS();async function qS(n){const t=n.size,o=Math.floor((t+102400-1)/102400),r=new HB.Hash;for(let s=0;s<o;s++){const l=s*102400;let a=l+102400;a>t&&(a=t);const h=await n.slice(l,a,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return ws(i)}const ur=S("sharedb-doc/client");class GS{constructor(e,t,o){g(this,"connection");g(this,"auth");g(this,"doc",null);g(this,"reauthFunc");g(this,"clientId",K());g(this,"getDoc",async()=>{const e=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});m(ur,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const t=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=t,await e(t),ur.debug(t),t});this.auth=e;const r=`${t}/${this.auth.appId}/${this.auth.docId}`;$S.register(Rd.type),this.connection=new VS(r,o),this.reauthFunc=o}editorServer(){const e=this.apiServer(),t=`/${this.auth.appId}/${this.auth.docId}`;return m(ur,e.endsWith(t),`invalid api server: ${e}, ${t}`),e.substr(0,e.length-t.length)}close(e){this.connection.end(e),this.doc=null}on(e,t){this.connection.addEventListener(e,o=>{(e==="error"||this.doc)&&t(o)})}onWriteConflictError(e){this.connection.onWriteConflictError(e)}onMaxUsersError(e){this.connection.onMaxUsersError(e)}onRequestReloadError(e){this.connection.onRequestReloadError(e)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const e=this.connection.url;if(e.startsWith("ws://"))return`http://${e.substring(5)}`;if(e.startsWith("wss://"))return`https://${e.substring(6)}`;throw new Error(`invalid server url: ${e}`)}async getFileUrlByHash(e,t,o,r,i){try{const s=`${e}/${t}`,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(e){const o=`${this.apiServer()}/resources`;let r=[];e.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,{[Ya]:this.connection.token}));return await Promise.all(i)}async uploadFile(e,t,o,r,i){let s=t.size;if(s===0)throw new Error("file is empty");s+=500;const l=v=>{ur.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await qS(t),d=await this.getFileUrlByHash(e,a,t.name,t.size,o);if(d)return r(-1),d;let h=e;i!=null&&i.thumbnail&&(h+="/thumbnail");const p=new FormData;p.append("file-size",`${t.size}`),p.append("file-hash",a),p.append("file",t,t.name);const A=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return ur.info(A),r(100),Array.isArray(A.data)?A.data[0]:A.data}async uploadResource(e,t=()=>{},o){const i=`${this.apiServer()}/resources`;m(ur,this.connection.token,"no connection token");const s=await this.uploadFile(i,e,{[Ya]:this.connection.token},t,o);return m(ur,s,"no result"),s}async request(e,t){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const a=t||{};a.url=e,a.headers||(a.headers={}),m(ur,o,"no token"),a.headers={...a.headers,[Ya]:o,[Hh]:this.connection.getBase64BaseURL()};try{return await PB.default(e,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 m(ur,r,"no error"),r}async getVersions(){const t=`${this.apiServer()}/versions?withExtra=true`,r=(await this.request(t)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),r}async getVersion(e){const o=`${this.apiServer()}/versions/${e}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const t=`${this.apiServer()}/versions/latest`,o=await this.request(t);return JSON.parse(o.data.data)}async getVersionOps(e,t){let r=`${this.apiServer()}/versions/before/${e}?withOp=true`;t!==void 0&&t!==0&&(r+=`&from=${t}`);const i=await this.request(r),s=i.data.ops,l=NB.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(m(ur,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(e,t,o){const i=`${this.apiServer()}/versions/${e}/tags/${t}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}async revertVersion(e){const o=`${this.apiServer()}/versions/revert/${e}`;await this.request(o,{method:"post",data:{}})}async createVersion(e,t){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:t,tag:e}})).data}async recognizeLink(e){const o=`${this.apiServer()}/resources/external/${ws(e)}`;return(await this.request(o)).data}buildResourceUrl(e,t){if(!e)return"";if(e.startsWith("https:")||e.startsWith("http:")||e.startsWith("file:")||e.startsWith("data:")||e.startsWith("blob:"))return e;let r=`${this.apiServer()}/resources/${encodeURIComponent(e)}`;const i=[];if(t!=null&&t.withToken&&i.push(`token=${this.getResourceToken()}`),t!=null&&t.downloadFileName&&i.push(`&fileName=${encodeURIComponent(t.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function ZS(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const ap=S("block-ids");class QS{constructor(){g(this,"ids",new Map)}onInsertBlock(e){const t=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<t.length;r++){const i=t[r];if(i>=e){const s=this.ids.get(i);m(ap,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=K();this.ids.set(e,o)}onDeleteBlock(e){this.ids.delete(e);const t=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<t.length;o++){const r=t[o];if(r>e){const i=this.ids.get(r);m(ap,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(e){let t=this.ids.get(e);return t||(t=K(),this.ids.set(e,t)),t}getById(e){return Array.from(this.ids.entries()).find(([,t])=>t===e)}}class YS{constructor(){g(this,"ids",new Map)}getContainerIds(e){let t=this.ids.get(e);return t||(t=new QS,this.ids.set(e,t)),t}onInsertBlock(e,t){this.getContainerIds(e).onInsertBlock(t)}onDeleteBlock(e,t){this.getContainerIds(e).onDeleteBlock(t)}getBlockId(e,t){return this.getContainerIds(e).getId(t)}getBlockIndexById(e){const t=Array.from(this.ids.entries());for(let o=0;o<t.length;o++){const r=t[o],i=r[1].getById(e);if(i)return{containerId:r[0],blockIndex:i[0]}}return m(ap,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class $7{constructor(e=new Set,t=new Map){this.deletedKeys=e,this.insertedValues=t}insert(e,t){this.insertedValues.set(e,t)}delete(e){this.deletedKeys.add(e)}toDocBlockDelta(){const e={};return this.insertedValues.forEach((t,o)=>{e[o]=t}),{insert:e,delete:Array.from(this.deletedKeys)}}}const jh=S("op-parse-handler");class JS{constructor(e,t){g(this,"actions",[]);this.outerHandler=e,this.local=t}pushActions(e){if(!e.containerId){this.actions.push(e);return}const o={...e,containerId:(r=>r==="blocks"?"root":r)(e.containerId)};this.actions.push(o)}onDeleteBlock(e,t){this.pushActions({type:"deleteBlock",containerId:e,blockIndex:t})}onInsertBlock(e,t,o){this.pushActions({type:"insertBlock",containerId:e,blockIndex:t,data:o})}onDeleteBlockData(e,t,o){this.pushActions({type:"deleteBlockData",containerId:e,blockIndex:t,key:o})}onInsertBlockData(e,t,o,r){this.pushActions({type:"insertBlockData",containerId:e,blockIndex:t,key:o,value:r})}onUpdateBlockText(e,t,o){this.pushActions({type:"updateBlockText",containerId:e,blockIndex:t,richTextData:o})}onDeleteContainer(e){this.pushActions({type:"deleteContainer",containerId:e})}onCreateContainer(e,t){this.pushActions({type:"createContainer",containerId:e,data:t})}onDeleteComment(e){this.pushActions({type:"deleteComment",commentId:e})}onCreateComment(e){this.pushActions({type:"createComment",commentId:e})}onUpdateComment(e){this.pushActions({type:"updateComment",commentId:e})}end(){const e=this.actions,t=new Set,o=new Map,r=new YS,i=e.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&&(jh.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),o.delete(a));const h=`${l.containerId}-${l.blockIndex}`;t.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(t.has(a)){jh.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 $7,o.set(d,h)),h.delete(l.key)}else m(jh,!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 $7,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);jh.debug(`update block data: ${a}, ${d}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Rt=S("op-parser");class H7{}class up{constructor(e){g(this,"key");this.key=e}}function KS(n,e,t){const o=e.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;m(Rt,s.id,"block id is required"),m(Rt,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 t.onInsertBlock(n,r,s),!0}function dp(n,e,t,o){if(t==="upsert"&&KS(n,e,o))return;m(Rt,Array.isArray(e),`invalid block op: ${n}, ${JSON.stringify(e)}`);const r=e.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const a=r[1];if(m(Rt,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(e)}`),m(Rt,a.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(e)}`),r.splice(0,2),t==="upsert"){const h=a.e;o.onUpdateBlockText(n,i,h)}m(Rt,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){m(Rt,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];m(Rt,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(m(Rt,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&t==="upsert"&&o.onInsertBlockData(n,i,a,d.i),d.r&&t==="remove"&&o.onDeleteBlockData(n,i,a),d.et==="rich-text"&&t==="upsert"){const p=d.e;o.onUpdateBlockText(n,i,p)}}else t==="remove"&&d.r&&s.push(new up(a)),t==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i);r.shift()}else if(typeof l=="object"){const a=l;t==="remove"&&a.r&&s.push(new H7),t==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{m(Rt,typeof l=="string","data is not string"),m(Rt,l!=="text","data !== 'text'"),m(Rt,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const a=l,d=r[1];t==="remove"&&d.r&&s.push(new up(a)),t==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof H7?o.onDeleteBlock(n,i):l instanceof up?o.onDeleteBlockData(n,i,l.key):m(Rt,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function XS(n,e,t){Rt.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function eL(n,e,t){const o=n[1],r=n[2];m(Rt,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),m(Rt,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Rt.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?e==="upsert"&&t.onUpdateComment(o):r.i?e==="upsert"&&t.onCreateComment(o):r.r?e==="remove"&&t.onDeleteComment(o):Rt.error(`unknown comment op, ${JSON.stringify(n)}`)}function hp(n,e,t){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{hp(s,e,t)});return}const r=o;if(m(Rt,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){XS(n);return}if(r==="comments"){eL(n,e,t);return}const i=r;if(Array.isArray(n[1]))e==="remove"?n.slice(1).reverse().forEach(s=>{dp(i,s,e,t)}):n.slice(1).forEach(s=>{dp(i,s,e,t)});else if(typeof n[1]=="object"){const s=n[1];s.r&&e==="remove"&&t.onDeleteContainer(i),s.i&&e==="upsert"&&t.onCreateContainer(i,s.i)}else m(Rt,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),dp(i,n.slice(1),e,t)}function j7(n,e,t){const o=new JS(e,t);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=fe.default(n),l=s[0];Array.isArray(l)?s.forEach(a=>{hp(a,i,o)}):hp(s,i,o)}o.end()}const tL=S("sharedb-comments");function fp(n){const e=n.blocks;m(tL,e,"no comment blocks");const t={blocks:{root:e},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(t.blocks[o]=r)}),fe.default(t)}function U7(n){const{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}=n;return{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}}function mp(n,e){const t=$D(e),{comments:o,meta:r,blocks:i,...s}=t,l={...n,blocks:i,...s},a=fe.default(l);return delete a.children,a}const ct=S("sharedb-doc/doc-container"),z7="ot-json1";Rd.type.registerSubtype(HD.type),Rd.type.name=z7,Rd.type.invert=null;class Ja extends ua{constructor(t,o,r=!0){super();g(this,"doc");g(this,"client");g(this,"localPresence");g(this,"remoteCaretHandler",new PD);g(this,"batching",0);g(this,"status","clean");g(this,"disableLogout");g(this,"destroyed",!1);g(this,"handleNothingPending",()=>{this.setStatus("clean")});g(this,"handleCreate",()=>{this.handleReload("doc created")});g(this,"handleDel",()=>{});g(this,"handleReload",t=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,t)})});g(this,"handleReset",async t=>{const o=new Error(`reset doc: ${t}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});g(this,"handleWriteConflictError",t=>{this.handleReset(`write conflict: ${t.message}, ${JSON.stringify(t.orgMsg)}`)});g(this,"insertObject",async(t,o,r)=>{const i=[t,o,{i:r}];return this.submitOp(i)});g(this,"deleteObject",async(t,o)=>{const r=[t,o,{r:!0}];return this.submitOp(r)});g(this,"replaceObject",async(t,o,r)=>{const i=[t,o,{r:!0,i:r}];return this.submitOp(i)});g(this,"updateObject",async(t,o,r)=>{const i=this.data()[t][o],s=[t,o];return Object.entries(r).forEach(([l,a])=>{if(!la.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)});g(this,"broadcastMessage",async t=>{const o={type:"custom",data:t,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});g(this,"data",()=>this.doc.data);g(this,"submitOp",async t=>new Promise((o,r)=>{if(this.destroyed){ct.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(t,{},i=>{i?(ct.error(`invalid op, ${i.message}, ${JSON.stringify(t)}`),r(i),ct.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ct.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(t)}`))}));g(this,"createDoc",async t=>new Promise((o,r)=>{this.doc.create(t,z7,i=>{i?r(i):o()})}));g(this,"submitInsertChildContainer",async(t,o)=>{const r=[Ni(t),{i:o}];return this.submitOp(r)});g(this,"submitDeleteChildContainer",async t=>{const o=[Ni(t),{r:!0}];return this.submitOp(o)});g(this,"submitInsertBlock",async(t,o,r)=>{const i=[Ni(t),o,{i:r}];return this.submitOp(i)});g(this,"submitDeleteBlock",async(t,o)=>{const r=[Ni(t),o,{r:!0}];return this.submitOp(r)});g(this,"submitUpdateBlockData",async(t,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[Ni(t),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)});g(this,"submitUpdateRichText",async(t,o,r)=>{const i=[Ni(t),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});g(this,"handleOp",(t,o,r)=>{if(this.destroyed){ct.warn("handleOp: destroyed");return}j7(t,this,!!o)});this.client=t,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--,m(ct,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(t){try{const o=new GS(t.auth,t.serverUrl,t.reauthFunc),r=await o.getDoc(),i=new Ja(o,r,t.disableLogout);if(r.type===null){if(t.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(t.templateData||ZS())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ct.error(o),ct.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,t)}))}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((t,o)=>{if(this.localPresence)t();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()),t())})}})}subscribe(){return new Promise((t,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),t())})})}toJSON(){return Ha(this.data())}getContainerBlocks(t){const o=this.data();m(ct,o,"no doc data");const r=o[Ni(t)];return m(ct,r,`no container data: ${t}`),fe.default(r)}getBlockData(t,o){const r=this.data();m(ct,r,"no doc data");const i=r[Ni(t)];m(ct,i,`no container data: ${t}`);const s=i[o];return m(ct,s,`no block data: ${o}`),fe.default(s)}localInsertBlock(t,o,r){return this.submitInsertBlock(t,o,r),this.getBlockData(t,o)}localDeleteBlock(t,o){const r=this.getBlockData(t,o);return this.submitDeleteBlock(t,o),r}localUpdateBlockText(t,o,r){const i=this.getBlockData(t,o);m(ct,i.text,"no block text");const s=fe.default(i.text);this.submitUpdateRichText(t,o,r);const l=ln.apply(s,r);return m(ct,l,"no block text"),l}localUpdateBlockData(t,o,r){const i=fe.default(this.getBlockData(t,o));return this.submitUpdateBlockData(t,o,r),i}localInsertChildContainer(t,o){this.submitInsertChildContainer(t,o)}localDeleteChildContainers(t){this.beginBatchUpdate(),t.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>U7(o))}getComment(t){return this.data().comments[t]}getCommentDoc(t){const o=this.data().comments[t];return fp(o)}localCreateComment(t,o){const r=mp(t,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(t){const o=["comments",t,{r:!0}];return this.submitOp(o)}localUpdateComment(t,o){const r=mp(t,o),i=["comments",t.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var t;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(t=this.localPresence)==null||t.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(t,o,r){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Jl(t),o,r)})}onInsertBlock(t,o,r,i){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Jl(t),o,r,i)})}onUpdateBlockData(t,o,r,i){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Jl(t),o,r,i)})}onUpdateBlockText(t,o,r,i){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Jl(t),o,r,i)})}onDeleteContainer(t,o){m(ct,this.callbacks.length>0,"no callbacks"),m(ct,t!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Jl(t),o)})}onCreateContainer(t,o,r){m(ct,this.callbacks.length>0,"no callbacks"),m(ct,t!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Jl(t),o,r)})}onDeleteComment(t,o){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,t,o)})}onCreateComment(t,o){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,t,o)})}onUpdateComment(t,o){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,t,o)})}onCustomMessage(t){const o=t;(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:t,clientId:"-"};this.onCustomMessage(r)})}async addResources(t){return await this.client.getFileUrlsByHashes(t)}async uploadResource(t,o){var i;return{resourceId:await this.client.uploadResource(t,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(t,o){return this.client.buildResourceUrl(t,o)}request(t,o){return this.client.request(t,o)}getUser(){const t=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:t,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(t){const o=await this.client.getVersion(t);return Ha(o)}async getLatestVersion(){const t=await this.client.getLatestVersion();return Ha(t)}async getHistoryData(t,o){const{doc:r,ops:i}=await this.client.getVersionOps(t,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:Ha(r),historyData:s}}async getVersionData(t,o){const{doc:r,ops:i}=await this.client.getVersionOps(t,o);return{doc:Ha(r),versionData:i}}async updateVersionExtra(t,o,r){await this.client.updateVersionExtra(t,o,r)}revertVersion(t){return this.client.revertVersion(t)}createVersion(t,o){return this.client.createVersion(t,o)}async recognizeLink(t){return this.client.recognizeLink(t)}parseHistoryData(t,o){j7(t.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}S("remote-cursor");class V7{constructor(e){g(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});g(this,"broadcastCaretPos",Ht.default(()=>{const e={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(e)},300));g(this,"handleRemoteCaretsChanged",e=>{e.forEach(t=>{const o=this.editor.findBlockById(t);o&&this.editor.reloadBlock(o)})});this.editor=e,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 W7=S("remote-cursor-decorator");class gp{decorateText(e,t,o){const r=e.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=t[t.length-1];m(W7,typeof s=="string","invalid path containerId"),m(W7,typeof l=="number","invalid path blockIndex");const a=e.doc.getBlockData(s,l),d=rn(o);return r.getSimpleCursors(a.id).forEach((p,A)=>{A>d&&(A=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(A);B?B.push(...v):i.set(A,v)}),{insertions:i}}}class q7 extends At.TypedEmitter{constructor(e){super(),this.editor=e,this.editor.doc.registerCallback(this)}handleChild(e,t,o){if(Xe(Pr(this.editor,e)))return;const r=this.editor.getBlockByIndex(e,t),i=oe(this.editor.getContainerById(e));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(e,t){this.handleChild(e,t,"data-change")}onUpdateBlockText(e,t){this.handleChild(e,t,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function nL(n,e){n.addCustom("child-block-tracker",()=>new q7(n)).addListener("change",e)}function oL(n,e){n.addCustom("child-block-tracker",()=>new q7(n)).removeListener("change",e)}const qte="",rL={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4",name:"\u6587\u672C\u989C\u8272"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},iL={colorPalette:{colorDesc:"Text Color",name:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},sL={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};O.mergeLang({"zh-CN":rL,"en-US":iL,"js-JP":sL});const Gte="";S("button");function ji(n,e,t,o,r){const i=w("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,e),t?typeof t=="string"?t.startsWith("<")?i.innerHTML=t:i.innerText=t:i.appendChild(t):i.innerText=e,o&&(o.indexOf("checked")!==-1&&W(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function G7(n,e,t){t?n.setAttribute(`data-editor-tooltip-${t}`,e):n.innerText=e}const Zte="",ec=S("ui-command-bar-base"),lL={itemElementTag:"div",tippyArrow:!1},q2=class extends At.TypedEmitter{constructor(t,o,r){var i,s;super();g(this,"content");g(this,"items");g(this,"subBar",null);g(this,"parentItem",null);g(this,"closeable",null);g(this,"closeReason",null);g(this,"options");g(this,"id");g(this,"header",null);g(this,"footer",null);g(this,"handleDocumentKeydown",t=>{if(!!this.isVisible&&!t.isComposing&&!Ul(t.target)){if(this.subBar){this.subBar.handleDocumentKeydown(t);return}if(this.items.length!==0){if(t.key==="Escape"){this.close("cancelBar");return}if(t.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),t.preventDefault(),t.stopPropagation()}else if(t.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),t.preventDefault(),t.stopPropagation()}else if(t.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(t.key==="ArrowLeft")this.parentItem&&this.close("switchItem");else if(t.key==="Enter"){const o=this.getSelectedItemIndex();if(o===-1)return;const r=this.items[o],i=this.getItemElementById(r.id);i&&this.emit("click",this,r,i)}}}});g(this,"handleDocumentMouseDown",t=>{if(t.target instanceof Element&&!this.isInCommandBar(t.target)){const o=this.listeners("closing");for(let r=0;r<o.length;r++)if(o[r](this,t)===!1)return;this.close("clickBackground")}});g(this,"handleHidden",()=>{this.closeReason!=="fromHover"&&this.emit("close",this),this.close(null),bC(this.id)});g(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&W(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&AC(this.id)});g(this,"lastEnterPauseTime",0);g(this,"startPauseMouseEnter",()=>{this.lastEnterPauseTime=Date.now()});g(this,"handleItemMouseEnter",t=>{if(Date.now()-this.lastEnterPauseTime<100)return;const o=this.getParentCommandItemElement(t.target);if(!o)return;const r=this.getItemElementId(o),i=this.getItemById(r);if(this.selectItem(r),i.manualShowChildren)return;const s=i.childrenMenuId||"";this.showSubCommandBar(s)});g(this,"handleItemMouseLeave",t=>{var r,i;const o=this.getParentCommandItemElement(t.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(te(o,"selected"),this.emit("selectionChange",this,""))});g(this,"handleItemClick",t=>{const o=this.getParentCommandItemElement(t.target);if(!o)return;const r=this.getItemElementId(o),i=this.items.find(s=>s.id===r);if(!!i&&!(i.states&&i.states.indexOf("disabled")!==-1)){if(i.children&&i.children.length>0&&i.manualShowChildren){this.showSubCommandBar(i.childrenMenuId);return}i.element||(this.emit("click",this,i,o),this.options.autoClose&&this.close("clickItem"))}});g(this,"handleWheel",t=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=t.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=Bo(r);if(!Ke(this.content,i)){t.stopPropagation(),t.preventDefault();return}t.deltaY<0?i.scrollTop===0&&(t.stopPropagation(),t.preventDefault()):t.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(t.stopPropagation(),t.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:K(),this.options={...lL,...r},this.items=t,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(t)}close(t){this.closeReason=t,this.subBar&&this.subBar.close(t),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(t,o){this.emit("click",this,t,o)}createPopperOptions(){var r,i;const t={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=t==null?void 0:t.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),this.options.padding&&((i=t==null?void 0:t.modifiers)==null||i.push({name:"preventOverflow",options:{padding:this.options.padding}})),t}destroy(){var t;this.close(null),this.removeAllListeners(),(t=this.subBar)==null||t.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(t){var r;this.subBar&&t.findIndex(s=>{var l,a;return s.id===((a=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:a.id)})===-1&&((r=this.subBar)==null||r.destroy(),this.subBar=null),this.items=t;const o=this.createCommandBarContent(t);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const t=this.getSelectedItem();return t?this.items.indexOf(t):-1}getPrevItemIndex(t){if(t<=0)return this.items.length-1;let o=t-1;for(;;){const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o-=1,o<=0)return this.items.length-1}}getNextItemIndex(t){let o=t+1;for(;;){if(!this.items[o])return this.getNextItemIndex(-1);const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o+=1,o>this.items.length-1)return 0}}clearSelectedItem(){const t=this.getSelectedItem();if(!t)return;const o=this.getItemElementById(t.id);o&&te(o,"selected")}selectItem(t){const o=this.getSelectedItem();if(o){if(o.id===t)return;const i=o.id,s=this.getItemElementById(i);s&&te(s,"selected")}const r=this.getItemElementById(t);r?(W(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(t){var s,l;const o=this.getSelectedItem();if(!o)return;if(this.subBar){if(((s=this.subBar.parentItem)==null?void 0:s.id)===o.id){o.manualShowChildren&&this.subBar.close("switchItem");return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=q2.createSubCommandBar(o,(l=this.closeable)!=null?l:this,t?{id:t}:{});this.subBar=i,this.subBar.on("click",(a,d,h)=>{this.emit("click",a,d,h)}),this.subBar.on("close",()=>{var a;(a=this.subBar)==null||a.destroy(),this.subBar=null,te(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),W(r,"active")}isInCommandBar(t){if(!t||!(t instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&Ke(o,t)||Ke(this.content,t)?!0:this.subBar?this.subBar.isInCommandBar(t):!1}createCommandItem(t){var i,s,l,a;let o=(i=this.options.itemElementTag)!=null?i:"div";t.element&&(o="div");const r=w(o,["command-item"],null);return r.setAttribute("data-id",t.id),t.type==="separator"?r.classList.add("separator"):t.type==="section"?(r.classList.add("section","text"),t.element&&(typeof t.element=="function"?r.appendChild(t.element(t)):r.appendChild(t.element))):((s=t.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=t.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(a=t.states)!=null&&a.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,t.element?typeof t.element=="function"?r.appendChild(t.element(t)):r.appendChild(t.element):r.classList.add("standard")),this.initItemElement(t,r),r}getItemById(t){const o=this.items.find(r=>r.id===t);return m(ec,o,`can not find command item for id: ${t}`),o}getSelectedItem(){const t=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(t){const o=this.getItemElementId(t),r=this.items.find(i=>i.id===o);return m(ec,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(t){const o=t.getAttribute("data-id");return m(ec,o,"no data-id attribute"),o}getItemElementById(t){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${t}"]`);return m(ec,o,`no exists command item, id=${t}`),o}getParentCommandItemElement(t){if(!t||!(t instanceof Element))return null;if(xe(t,"command-item"))return t;const o=t.closest(".command-item");return o||null}createCommandBarContent(t){this.content&&this.content.removeEventListener("wheel",this.handleWheel);const o=w("div",["editor-command-bar-root"],null);if(this.options.header){const i=w("div",["editor-command-bar-header"],null);if(this.options.header instanceof Function){const s=this.options.header();s&&i.appendChild(s)}else this.header||i.appendChild(this.options.header);this.header=i,this.header&&o.appendChild(this.header)}const r=w("div",["editor-command-bar"],o);if(t.forEach(i=>{var l;const s=this.createCommandItem(i);r.appendChild(s),i.element&&i.setCloseable&&i.setCloseable((l=this.closeable)!=null?l:this)}),this.options.footer){const i=w("div",["menu-item","editor-command-bar","footer"],null);if(this.options.footer instanceof Function){const s=this.options.footer();s&&i.appendChild(s)}else this.footer||i.appendChild(this.options.footer);this.footer=i,this.footer&&o.appendChild(this.footer)}return(this.options.header||this.options.footer)&&W(o,"scrollable-bar"),this.initCommandBarElement(r),o.addEventListener("wheel",this.handleWheel,{passive:!1}),o}getSubBarOptions(t){var o;return{placement:(o=t.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(t,o){this.commandBarCreators.set(t,o)}static createSubCommandBar(t,o,r){var l;m(ec,t.children&&t.children.length>0,"no item children");const i=(l=t.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return m(ec,s,`no creator for command type: ${i}`),s(t,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let Ui=q2;g(Ui,"commandBarCreators",new Map),S("ui-command-bar");class Uh extends Ui{constructor(){super(...arguments);g(this,"tippyInstance",null)}manualShow(t,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=jB.default(t,{interactive:!0,content:this.content,trigger:"manual",triggerTarget:null,hideOnClick:!1,placement:(r=o==null?void 0:o.placement)!=null?r:"bottom-start",maxWidth:650,arrow:this.options.tippyArrow,appendTo:document.body,onShow:this.handleShow,onHidden:this.handleHidden,theme:o==null?void 0:o.theme,getReferenceClientRect:o==null?void 0:o.getReferenceClientRect,offset:(i=o==null?void 0:o.offset)!=null?i:[0,0],popperOptions:this.createPopperOptions()}),o!=null&&o.point){const{x:s,y:l}=o.point;this.tippyInstance.setProps({getReferenceClientRect:()=>new DOMRect(s,l,0,0)})}this.clearSelectedItem(),this.tippyInstance.show(),this.parentItem||(document.addEventListener("keydown",this.handleDocumentKeydown),document.addEventListener("mousedown",this.handleDocumentMouseDown)),this.popper&&this.options.id&&this.popper.setAttribute("data-command-bar-id",this.options.id)}}close(t){var o;super.close(t),this.isVisible&&((o=this.tippyInstance)==null||o.hide())}destroy(){var t;(t=this.tippyInstance)==null||t.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var t,o;return(o=(t=this.tippyInstance)==null?void 0:t.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const Z7=S("ui-base");class Ka extends Uh{constructor(e,t){var i;const r=[{id:(i=t==null?void 0:t.id)!=null?i:`popup-${K()}`,name:"",element:e}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(e){W(e,"popper")}initItemElement(e,t){}get popupContent(){const e=this.items[0];m(Z7,e,"no dialog item");const t=typeof e.element=="function"?e.element(e):e.element;return m(Z7,t,"no item element"),t}}const zi=S("filterable-list");function Q7(n){var t,o;const e=w("div",["list-item"],null);return e.setAttribute("data-id",n.id),e.appendChild(w("div",["list-item-text"],null,n.name)),(t=n.states)!=null&&t.includes("selected")&&W(e,"selected"),(o=n.states)!=null&&o.includes("disabled")&&W(e,"disabled"),e}function Y7(n){const e=w("div",["list-root"],null);return n.forEach(t=>{e.appendChild(Q7(t))}),n.length||e.appendChild(Q7({id:"placeholder",states:["disabled"],name:O.t("search.emptyTips")})),e}function J7(n,e){let t=n;return e&&(t=n.map(o=>({...o,states:o.id===e?["selected"]:void 0}))),t}function cL(n,e){const t=w("div",["filterable-list"],null),o=w("div",["filter"],t),r=w("div",["filter-container"],o),i=w("input",["filter-input"],r);e&&e.placeholder&&(i.placeholder=e.placeholder);const s=w("div",["list"],t),l=Y7(J7(n,e==null?void 0:e.initialSelectedId));return s.appendChild(l),t}function K7(n,e,t){const o=n.querySelector(".list");m(zi,o,"no list root");const r=Y7(J7(e,t)),i=o.querySelector(".list-root");if(m(zi,i,"no exists menu"),ma(i,r),t){const s=o.querySelector(".list-item.selected");s&&(m(zi,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class aL{constructor(e,t){g(this,"root");g(this,"visibleItems");g(this,"selectedId");g(this,"filter","");g(this,"onSelected",null);g(this,"handleKeydown",e=>{this.processKeyDown(e)});g(this,"handleInputChanged",()=>{const e=this.root.querySelector(".filter-input");m(zi,e,"no input");const t=e.value.toLocaleLowerCase();this.setFilter(t)});g(this,"handleClick",e=>{this.processClick(e)});var o;this.items=e,this.options=t,this.root=cL(e,t),this.bindEvents(),this.selectedId=(o=t==null?void 0:t.initialSelectedId)!=null?o:"",this.visibleItems=e}bindEvents(){const e=this.root.querySelector(".filter-input");m(zi,e,"no input"),e.addEventListener("keyup",this.handleInputChanged),e.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const e=this.root.querySelector(".filter-input");m(zi,e,"no input"),e.removeEventListener("keyup",this.handleInputChanged),e.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(e=>e.id===this.selectedId):-1}setSelectedId(e){this.selectedId=e,K7(this.root,this.visibleItems,e)}focus(){const e=this.root.querySelector(".filter-input");m(zi,e,"no input"),e.focus()}reset(){this.setFilter("");const e=this.root.querySelector(".filter-input");m(zi,e,"no input"),e.value=""}setFilter(e){this.filter!==e&&(this.filter=e,this.visibleItems=this.items.filter(t=>t.name.toLocaleLowerCase().includes(e)),K7(this.root,this.visibleItems,this.selectedId))}processClick(e){var s,l;const t=e.target;if(!(t instanceof HTMLElement))return;const o=t.closest(".list-item");if(!o)return;const r=(s=o.getAttribute("data-id"))!=null?s:"",i=(l=this.visibleItems.find(a=>a.id===r))!=null?l:null;this.onSelected&&this.onSelected(this,i)}processKeyDown(e){var t;if(e.key==="ArrowUp"){let o=this.getSelectedIndex();o===-1?o=this.visibleItems.length-1:o>0&&(o-=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(e.key==="ArrowDown"){let o=this.getSelectedIndex();o===-1?o=0:o<this.visibleItems.length-1&&(o+=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(e.key==="Enter"){const o=(t=this.visibleItems.find(r=>r.id===this.selectedId))!=null?t:null;this.onSelected&&this.onSelected(this,o)}}}class uL extends aL{constructor(t,o,r){super(t,r);g(this,"popup");g(this,"onShow",null);g(this,"onHide",null);g(this,"custom",null);g(this,"handleShow",()=>{this.onShow&&this.onShow(this)});g(this,"handleHide",()=>{this.onHide&&this.onHide(this)});g(this,"handleShown",()=>{this.focus()});this.popup=new Ka(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(t){this.reset(),this.popup.manualShow(t,{theme:"dropdown-list"}),this.focus()}processKeyDown(t){super.processKeyDown(t),(t.key==="Esc"||t.key==="Enter")&&this.popup.close("cancelBar")}processClick(t){super.processClick(t);const o=t.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close("clickItem")}}const Qte="",Yte="";function dL(n,e){const t=document.createElement("div");t.classList.add("toast","show"),e!=null&&e.theme&&t.setAttribute("data-theme",e.theme),e!=null&&e.id&&t.setAttribute("data-id",e.id),e!=null&&e.html?t.innerHTML=n:t.textContent=n,e!=null&&e.position&&(t.style.left=`${e.position.x}px`,t.style.top=`${e.position.y}px`,t.classList.add("positioned")),document.body.appendChild(t),setTimeout(()=>{t.classList.remove("show"),setTimeout(()=>{t.remove()},500)},(e==null?void 0:e.duration)||3e3)}const X7=`<?xml version="1.0" ?>
27
+ `)}const tT=S("get-text-position");function ql(n,e){const t=e!=null?e:n.selection.range.start;t instanceof jt||m(tT,!1,`invalid insert pos type: ${typeof t}`);const{blockId:o}=t,r=n.getBlockById(o),i=be(r),s=ne(r),l=ae(s),{offset:a}=t;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const La=S("insert-text");function gh(n,e,t,o){var s;const r=n.doc.getBlockData(e,t);if(m(La,r,"no block data"),m(La,r.text,"no block text"),rn(r.text)===0)return m(La,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=zt(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function nT(n,e,t){const o=ne(e),r=ae(o),i=be(e);return gh(n,r,i,t)}function x6(n,e,t,o,r){const i=ne(e),s=ae(i),l=be(e),a=nT(n,e,t),d=Ba(t,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),mn(n,e)}function I6(n,e,t,o){const r=ne(e),i=ae(r),s=be(e),l=Ba(t," ",o);return n.doc.localUpdateBlockText(i,s,l),mn(n,e)}function Bg(n,e,t,o,r){const i=n.doc.getBlockData(t,o);m(La,i,"no block data"),m(La,i.text,"no block text");const s=gh(n,t,o,r),l=Ba(r,e,s!=null?s:null);return n.doc.localUpdateBlockText(t,o,l),mn(n,n.getBlockById(i.id))}function Eg(n,e){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:t,blockIndex:o,offset:r}=ql(n);Bg(n,e,t,o,r)}const ph=S("update-composition-text");function T6(n){const e=n.selection.range.start;e instanceof jt||m(ph,!1,`invalid insert pos type: ${typeof e}`);const{blockId:t}=e,o=n.getBlockById(t);m(ph,ee(n,o),"not a text kind block");const r=ne(o),i=ae(r),s=be(o),l=n.doc.getBlockData(i,s);m(ph,l,"no block data in doc"),m(ph,l.text,"no text data in text block");const a=Re(o);th(n,Di(o),t,a,l.text)}function D6(n){Ox(n)}function Gl(n,e,t,o,r,i){return n.doc.localInsertBlock(e,t,o,r,i),n.getBlockById(o.id)}const Ma=S("delete-block-text");function xg(n,e,t,o,r){if(!n.isBlockWritable(e))return Ma.error("block is not writable"),0;m(Ma,ee(n,e),"block is not a text kind block");const i=ne(e),s=ae(i),l=be(e),a=n.doc.getBlockData(s,l);m(Ma,a,"no block data in doc"),m(Ma,a.text,"no text data in text block");let d=t;sn(e,t)||(d=Ri(e,d));let h=t+o;m(Ma,h<=ue(n,e),`invalid offset and count: ${t}, ${o}`),sn(e,h)||(h=Os(e,h));const p=h-d,A=$4(d,p);return n.doc.localUpdateBlockText(s,l,A,r),p}const Ig=S("break-text-block");function S6(n,e){const o=n.getBlockData(e).quoted;return o?{quoted:o}:{}}function Zl(n,e,t,o){m(Ig,ee(n,e),`block is not a text kind block: ${De(e)}`),m(Ig,t>=0&&t<=ue(n,e),`invalid offset: ${t}`);const r=ne(e),i=ae(r),s=be(e),l=o!=null&&o.copyBlockAttributes?S6(n,e):{};if(!(o!=null&&o.forceInsertAfter)&&(t===0||t===ue(n,e))){const v=t===0?s:s+1,B={...sr(""),...l,...o==null?void 0:o.newBlockData},D=vt(n,e.id,0),x=Gl(n,i,v,B,D);return{block:e,newBlock:x}}m(Ig,sn(e,t),"not a valid offset");const a=mn(n,e),{right:d}=xn(a,t),h=rn(d);h>0&&xg(n,e,t,h);const p={...sr(d),...l,...o==null?void 0:o.newBlockData},A=Gl(n,i,s+1,p,vt(n,p.id,0));return{block:e,newBlock:A}}const oT=S("prepare-insert-new-block");function rT(n,e,t){if(e&&t!==void 0&&t!==null){const d=n.getContainerById(e),h=bt(d);return m(oT,t>=0&&t<=h.length,`invalid blockIndex: ${t}`),{containerId:e,blockIndex:t}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(e=ae(ne(r)),t=be(r),!ee(n,r))return{containerId:e,blockIndex:t+1};const s=o.offset;if(s===0||s===ue(n,r))return{containerId:e,blockIndex:s===0?t:t+1};const a=Zl(n,r,s).newBlock;return{containerId:e,blockIndex:be(a)}}const iT=S("auto-insert-block");function L6(n,e,t,o,r,i){const s=rT(n,t,o);m(iT,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:e.id,offset:0},a={anchor:l,focus:l};return Gl(n,s.containerId,s.blockIndex,e,r!=null?r:a,i)}const sT=S("delete-block");function Ch(n,e,t){e.children&&(t.push(...e.children),e.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{Ch(n,i,t)})}))}function Ah(n,e,t){const o=ne(e),r=ae(o),i=be(e),s=n.doc.getBlockData(r,i);return m(sT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Ut(n,{anchor:t.start,focus:t.end})),s}function Tg(n,e,t){return n.undoManager.runInGroup(()=>{const o=ne(e);Eo(o)===1&&n.insertTextBlock("",ae(o),0);let r=t?Si(n,t):null;if(!r){const l=n.selection.range;k6(e,l)?r=w6(n,e):r=l}const i=Ah(n,e,r),s=[];return Ch(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function lT(n,e){const t=[e];n.doc.getContainerBlocks(e).forEach(r=>{Ch(n,r,t)}),n.doc.localDeleteChildContainers(t)}function M6(n,e){const t=[...e];e.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{Ch(n,i,t)})}),n.doc.localDeleteChildContainers(t)}const Dg=S("merge-text-block");function R6(n,e,t){m(Dg,ee(n,e),"only text block can be merged"),m(Dg,ee(n,t),"only text block can be merged");const o=_i(n,e),r=_i(n,t),i=o.text,s=r.text;m(Dg,i&&s,"block data has no text");const l=ne(e),a=ae(l),d=be(e),h=ue(n,e),p=Bg(n,s,a,d,h),A=vt(n,e,rn(i));return Tg(n,t,A),p}const lr=S("clear-selected-contents");function bh(n,e){m(lr,ee(n,e.block),"not a text kind block");const{start:t,end:o}=e;m(lr,t.isSimple(),"not a simple block position"),m(lr,o.isSimple(),"not a simple block position");const r=t.offset,i=o.offset;m(lr,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(e.block,r,i-r)}function O6(n,e,t){const o=ae(e),r=bt(e),i=t.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});t.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function cT(n,e){const{block:t,start:o,end:r}=e;if(ee(n,t)){bh(n,e);return}if(Lt(t)||o.isSimple()){m(lr,r.isSimple(),"invalid range");const s=ne(t),l=be(t),a=n.insertTextBlock("",ae(s),l);n.selection.selectBlock(a,0),n.deleteBlock(t);return}m(lr,Le(n,t),"invalid block kind"),m(lr,!o.isSimple()&&!r.isSimple(),"invalid range"),Ms(n,t,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{O6(n,s,{focus:l===0})})}function aT(n){if(!n.isWritable())return;const e=n.selection.range;if(e.isCollapsed())return;const t=e.getSelectedBlocks();if(m(lr,t.length>0,"no selected block"),t.length===1){cT(n,t[0]);return}const o=t[0],r=o.block,i=ne(r);m(lr,t.length>1,"no selected block");const s=t[t.length-1],l=s.block;if(ee(n,r)){bh(n,o);const h=vt(n,o.block,o.start.offset);if(t.slice(1,t.length-1).reverse().forEach(A=>n.deleteBlock(A.block)),ee(n,l)){bh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(ee(n,l)){bh(n,s),t.slice(0,t.length-1).reverse().forEach(h=>n.deleteBlock(h.block)),n.selection.selectBlock(s.block,0);return}if(t.length===Eo(i)){O6(n,i,{focus:!0});return}const a=lt(r),d=Ze(l);m(lr,a||d,"no prev or next block"),t.forEach(h=>n.deleteBlock(h.block))}function Sg(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),aT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const uT=S("core");function _6(n,e,t){const o=ne(e),r=ae(o),i=be(e);return n.doc.localUpdateBlockText(r,i,t),setTimeout(()=>{n.selection.updateSelection(null)}),mn(n,e)}function F6(n,e,t){if(!n.isBlockWritable(e)){uT.error("block is not writable");return}const o=n.getBlockText(e),r=ln.diff(o,t);_6(n,e,r)}function vh(n,e,t){const o=mn(n,e),r=typeof t=="string"?Oi(t):t,i=ln.diff(o,r);return _6(n,e,i)}const Ra=S("update-block-data");function yh(n,e,t,o){const r=ne(e),i=ae(r),s=be(e),l=n.doc.getBlockData(i,s),a={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(t));return d.forEach(A=>{if(!h.has(A)){if(A==="id"||A==="type"||A==="text")return;Ra.debug(`delete key: ${A}`),a.delete.push(A)}}),Object.entries(t).forEach(([A,v])=>{m(Ra,A!=="id"&&A!=="type",`invalid block data delta, ${A}`);const B=l[A];if(v==null){B!=null&&(Ra.debug(`delete key: ${A}`),a.delete.push(A));return}B!==v&&(la.default(B,v)||A==="text"&&ln.diff(B,v).length===0||(d.has(A)?(Ra.debug(`replace key: ${A}`),a.delete.push(A)):Ra.debug(`insert key: ${A}`),a.insert[A]=v))}),n.doc.localUpdateBlockData(i,s,a,o),_i(n,e)}function P6(n,e,t,o){const i={...n.getBlockData(e),embedData:t};return n.updateBlockData(e,i,o)}function Lg(n,e,t){if(!Le(n,e)||!(t!=null&&t.tryFocusToChildSimpleBlock)){n.selection.selectBlock(e,0);return}const r=jn(n,e).getChildContainers(n,e)[0],i=St(r);Lg(n,i,t)}function Ps(n){const e=[];let t={};return n.forEach(o=>{e.push(...o.blocks.root);const{root:r,...i}=o.blocks;t={...t,...i}}),{blocks:{...t,root:e},meta:{},comments:{}}}const Oa=S("clone-block");function Fi(n,e,t,o){const r=n.getBlockClass(t.type);if(r.blockToDoc)return r.blockToDoc(e,t,(h,p)=>(m(Oa,t!==p,"invalid child block"),Fi(n,h,t,o)));let i={};const s=new Map,l=fe.default(t);l.children&&(l.children=l.children.map(h=>{const p=K(),A=e.blocks[h];m(Oa,Array.isArray(A),"invalid child blocks");const v=A.map(_=>Fi(n,e,_,o)),B=Ps(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[A,v]=p;{const B=`${A}/`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}/${D}`;return Oa.debug(`replace key: ${h} -> ${x}`),x}}{const B=`${A}_`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}_${D}`;return Oa.debug(`replace key: ${h} -> ${x}`),x}}}return h};return Array.from(Object.entries(l)).forEach(([h,p])=>{const A=d(h);A!==h&&delete l.key,l[A]=p}),l.id=K(),o&&(o.blockIdMap.set(t.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Mg(n,e,t,o){const r=e.blocks[t];m(Oa,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Fi(n,e,l,o));return Ps(i)}function Rg(n,e,t){const o=e.blocks.root.map(r=>Fi(n.editorBlocks,e,r,t));return fe.default(Ps(o))}const N6=S("insert-doc");function $6(n,e,t,o,r){if(Le(n,e)){N6.warn("failed to insert doc into a complex block");return}const i=Rg(n,o,r),s=ne(e),l=be(e),a=ae(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var M,j,z;Object.entries(i.blocks).forEach(([q,ie])=>{q!=="root"&&n.doc.localInsertChildContainer(q,ie)});const d=i.blocks.root;if(Lt(e)){n.deleteBlock(e);let q;d.reverse().forEach(ie=>{const me=n.insertBlock(a,l,ie);q||(q=me)}),q&&n.selection.selectBlock(q,ue(n,q));return}if(m(N6,ee(n,e),"not a text block"),dt(n,e)){const q=a==="root"&&n.getBlockByIndex(a,0)===e,ie=be(e);let me;d.forEach((Be,je)=>{const Ue=n.insertBlock(a,ie+je,Be);je===d.length-1&&(me=Ue)}),me&&n.selection.selectBlock(me,ue(n,me)),q&&n.deleteBlock(e);return}if(d.length===1){const q=d[0];if(Aa(n,q.type)){n.insertTextToBlock(e,t,(M=q.text)!=null?M:[]);return}n.breakTextBlock(e,t),n.insertBlock(a,l+1,q);return}const h=t===ue(n,e),p=t===0,A=d[0],v=d[d.length-1];let B;!h&&!p?B=n.breakTextBlock(e,t,{forceInsertAfter:!0}):B=e;const D=p?l:l+1;h?(B=n.insertBlock(a,l+1,v),n.selection.selectBlock(B,ue(n,B))):(n.selection.selectBlock(B,0),Aa(n,v.type)?n.insertTextToBlock(B,0,(j=v.text)!=null?j:[]):n.insertBlock(a,D,v));const x=n.selection.range;let _=D;Aa(n,A.type)?p?(n.insertBlock(a,D,A),_+=1):n.insertTextToBlock(e,t,(z=A.text)!=null?z:[]):(n.insertBlock(a,D,A),_+=1),d.slice(1,d.length-1).reverse().forEach(q=>{n.insertBlock(a,_,q)}),n.selection.setRange(x)}),n.doc.endBatchUpdate()}function Og(n,e,t,o,r){const i=Rg(n,o,r),s=ae(e),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([d,h])=>{d!=="root"&&n.doc.localInsertChildContainer(d,h)}),i.blocks.root.reverse().forEach(d=>{const h=n.insertBlock(s,t,d);l.push(h)})}),l}function H6(n,e,t){const o=Eo(e);Og(n,e,o,t);for(let r=0;r<o;r++){const i=St(e);n.deleteBlock(i)}}const _a=S("add-text-attribute");function dT(n,e,t,o){const{start:r,end:i}=t;m(_a,r.blockId===i.blockId&&r.blockId===re(e),"invalid range"),m(_a,o,"invalid attribute name");const s=n.getBlockText(e),l=Wl(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(e,l),l}function j6(n,e,t,o,r){const{start:i,end:s}=t;m(_a,i.blockId===s.blockId&&i.blockId===re(e),"invalid range"),m(_a,o,"invalid attribute name");const l=n.getBlockText(e),a=Ea(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,a),a}function Ql(n,e,t,o,r){const{start:i,end:s}=t;m(_a,i.blockId===s.blockId&&i.blockId===re(e),"invalid range");const l=n.getBlockText(e),a=Z4(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,a),a}function U6(n,e,t,o){const r=Lo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!ee(n,s))return;if(dt(n,s)){o(n,re(s),e,t);return}const d=Ut(n,{anchor:l,focus:a});e==="color"||e==="backgroundColor"?Ql(n,s,d,e,t):(Ql(n,s,d,"color",null),Ql(n,s,d,"backgroundColor",null))})})}function z6(n,e,t){const o=Lo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!ee(n,i))return;if(dt(n,i)){(e==="clearColor"||e==="clearAll")&&t(n,re(i),"color",null),(e==="clearBackground"||e==="clearAll")&&t(n,re(i),"backgroundColor",null);return}const a=Ut(n,{anchor:s,focus:l});(e==="clearColor"||e==="clearAll")&&Ql(n,i,a,"color",null),(e==="clearBackground"||e==="clearAll")&&Ql(n,i,a,"backgroundColor",null)})})}function _g(n,e){const t=Lo(n,{simpleBlockOnly:!0}).filter(s=>ee(n,s.block));if(t.length===0)return[null,null];const o=s=>{if(ue(n,s.block)===0)return e(n,re(s.block));const l=s.start,a=s.end,d=n.getBlockText(s.block);return J4(l.offset,a.offset-l.offset,d)};let[r,i]=o(t[0]);return r===null&&i===null?[r,i]:(t.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 Vn=S("adjust-selection-pos");function V6(n){const e=[];for(;n;){const t=ne(n);if(e.unshift(t),Xe(t))return e;const o=oe(t);m(Vn,o,"child container has not parent container"),n=o}m(Vn,!1,"should not come here: getParentContainers")}function W6(n,e){for(;e;){const t=ne(e);if(t===n)return e;const o=oe(t);m(Vn,o,"could not find parent block for a child container"),e=o}m(Vn,!1,"no parent block in specified container")}function hT(n,e){const t=V6(n),o=V6(e);m(Vn,t.length>0&&o.length>0,"block has not parent container"),m(Vn,t[0]===o[0],"root container does not equal");let r=t[0];for(let l=1;l<t.length||o.length;l++)if(t[l]!==o[l]){r=t[l-1];break}const i=W6(r,n),s=W6(r,e);return{parentContainer:r,newBlock1:i,newBlock2:s}}function q6(n,e){let t=oe(e);for(m(Vn,t,"element is not in a block");t;){const o=ne(t);m(Vn,Do(o),"not a child container");const r=oe(o);if(m(Vn,r,"child container has not parent block"),r===n)return o;t=r}m(Vn,!1,"failed to find parent container in complex block")}function kh(n,e,t){const o=n.getBlockById(e.blockId),r=n.getBlockById(t.blockId);if(o===r)return e instanceof jt&&t instanceof jt?{anchor:e,focus:t}:e instanceof So&&t instanceof So?Xd(n,o,e,t):null;const i=ne(o),s=ne(r);if(i===s)return e instanceof So&&(e=se(o,0,"home")),t instanceof So&&(t=se(r,ue(n,r),"end")),m(Vn,e instanceof jt,"not valid position type"),m(Vn,t instanceof jt,"not valid position type"),{anchor:e,focus:t};if(o.contains(s))return null;if(r.contains(i)){if(e instanceof jt&&t instanceof So){const B=n.getContainerById(t.childContainerId);if(B===i)return{anchor:t,focus:t};const D=oe(i);if(D&&D===oe(B)){const x=ht(D,ae(i)),_=ht(D,ae(B));return Xd(n,D,x,_)}}return null}const l=Nd(o,r)>0,{newBlock1:a,newBlock2:d}=hT(o,r);if(a===d){const B=a,D=q6(B,o),x=q6(B,r);return e=ht(a,ae(D)),t=ht(a,ae(x)),Vn.debug(`select in complex block: ${D.id}, ${x.id}`),Xd(n,B,e,t)}let h=l?ue(n,a):0;a===o&&e instanceof jt&&(h=e.offset);let A=l?0:ue(n,d);return d===r&&t instanceof jt&&(A=t.offset),e=se(a,h,l?"end":"home"),t=se(d,A,l?"home":"end"),{anchor:e,focus:t}}const fT=S("move-complex-block-position");function mT(n,e,t){const o=n.getBlockById(e.blockId);m(fT,Le(n,o),"is not a complex block");const r=jn(n,o),i=n.getContainerById(e.childContainerId),s=r.getNextContainer(n,o,i,t,{noWrap:!0});return s?ht(o,ae(s)):null}const Fa=S("move-simple-block-position");function G6(n,e){const t=En(n,e,{visibleOnly:!0});m(Fa,t.length>0,"complex block has not any child container");const o=t[0];return St(o)}function Z6(n,e){const t=En(n,e,{visibleOnly:!0});m(Fa,t.length>0,"complex block has not any child container");const o=t[t.length-1];return Gt(o)}function Q6(n,e,t){const o=t?G6(n,e):Z6(n,e);return Le(n,o)?Q6(n,o,t):o}function gT(n,e){const t=n.getBlockById(e.blockId);return Le(n,t)&&e.offset===0?G6(n,t):Ds(t)}function pT(n,e){const t=n.getBlockById(e.blockId);return Le(n,t)&&e.offset===1?Z6(n,t):Ts(t)}function Fg(n){return n==="ArrowLeft"||n==="ArrowUp"}function Pg(n,e,t){const o=ne(e);if(Xe(o))return null;const r=oe(o);m(Fa,r,"child container has not parent block"),m(Fa,Le(n,r),"is not a complex block");const i=jn(n,r).getNextContainer(n,r,o,t);return i?Fg(t)?Gt(i):St(i):Pg(n,r,t)}function CT(n,e,t){const o=ne(e);if(Xe(o))return null;const r=oe(o);if(m(Fa,r,"child container has not parent block"),Fg(t)){const l=lt(r);if(l)return l}else{const l=Ze(r);if(l)return l}const i=Pg(n,r,t);if(i)return i;let s=r;for(;!Xe(ne(s));)s=oe(ne(s));return Fg(t)?lt(s):Ze(s)}function AT(n,e,t){return!Le(n,e)||jn(n,e).enableKeyboardSelect?e:Q6(n,e,t==="ArrowDown"||t==="ArrowRight")}function bT(n,e,t){const o=n.getBlockById(e.blockId),i=Qe(n,o).moveCaret(n,o,e,t);if(i)return i;let s=t==="ArrowDown"||t==="ArrowRight"?gT(n,e):pT(n,e);if(s||(s=Pg(n,o,t),s||(s=CT(n,o,t))),!s){if(t==="ArrowDown"||t==="ArrowRight"){if(n.readonly||!Xe(ne(o)))return null;const l=n.insertTextBlock("",ae(n.rootContainer),Eo(n.rootContainer));return se(l,0,"home")}return null}if(s=AT(n,s,t),ee(n,s)){const l=n.selection.getSuggestedCaretX();if(t==="ArrowDown")return qx(n,s,o,e,l);if(t==="ArrowUp")return Wx(n,s,o,e,l)}return t==="ArrowLeft"||t==="ArrowUp"?se(s,ue(n,s),"end"):t==="ArrowRight"||t==="ArrowDown"?se(s,0,"home"):null}function vT(n,e,t){if(e==="ArrowLeft")return t.start;const o=t.end,r=n.getBlockById(o.blockId);if(ee(n,r))return o;const i=Ze(r);if(i)return se(i,0,"home");if(!Xe(ne(r))||n.readonly)return o;const s=n.insertTextBlock("",ae(n.rootContainer),Eo(n.rootContainer));return se(s,0,"home")}function yT(n,e,t){const o=n.selection.range;let r;if(o instanceof Zt)t==="move"&&!o.isCollapsed()&&(e==="ArrowLeft"||e==="ArrowRight")?r=vT(n,e,o):r=bT(n,o.getFocusedPos(),e);else if(r=mT(n,o.focus,e),t==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(e==="ArrowLeft"||e==="ArrowUp"){const l=Gt(s);r=se(l,0,"home")}else{const l=St(s);r=se(l,ue(n,l),"end")}}return r?t==="move"?{anchor:r,focus:r}:kh(n,o.anchor,r):null}function Pi(n,e,t){const o=yT(n,e,t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(e==="ArrowLeft"||e==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function Y6(n){return Pi(n,"ArrowLeft","move"),!0}function J6(n){return Pi(n,"ArrowRight","move"),!0}function K6(n){return Pi(n,"ArrowUp","move"),!0}function X6(n){if(Pi(n,"ArrowDown","move")||n.readonly)return!0;const e=n.getFocusedBlock(),t=ne(e);if(Xe(t)||Gt(t)!==e)return!0;const o=n.rootContainer;return n.insertTextBlock("",ae(o),Eo(o)),!0}function e9(n){return Pi(n,"ArrowDown","select"),!0}function t9(n){return Pi(n,"ArrowLeft","select"),!0}function n9(n){return Pi(n,"ArrowRight","select"),!0}function o9(n){return Pi(n,"ArrowUp","select"),!0}const r9=S("word-offset");function Ng(n,e){const t=n.selection.range.focus;m(r9,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(dt(n,o))return se(o,0,"home");if(t.offset===0||!ee(n,o)){const s=lt(o);if(!s)return null;const l=se(s,ue(n,s),"end");if(e==="select"&&ee(n,s)){const a=pg(n,s,l.offset);return se(s,a,"normal")}return l}const r=pg(n,o,t.offset);return se(o,r,"normal")}function $g(n,e){const t=n.selection.range.focus;m(r9,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(dt(n,o))return se(o,0,"end");if(t.offset===ue(n,o)||!ee(n,o)){const s=Ze(o);if(!s)return null;const l=se(s,0,"home");if(e==="select"&&ee(n,s)){const a=Cg(n,s,l.offset);return se(s,a,"end")}return l}const r=Cg(n,o,t.offset);return se(o,r,"normal")}function i9(n){if(!n.selection.range.focus.isSimple())return!1;const t=Ng(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function s9(n){if(!n.selection.range.focus.isSimple())return!1;const t=$g(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function l9(n){if(!n.selection.range.focus.isSimple())return!1;const t=Ng(n,"select");return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function c9(n){if(!n.selection.range.focus.isSimple())return!1;const t=$g(n,"select");return t?(n.selection.setSelection(n.selection.range.anchor,t),n.selection.updateLastCaretRect(),!0):!1}S("find-block");function Hg(n,e){if(!Le(n,e))return e;const o=jn(n,e).getChildContainers(n,e)[0],i=bt(o)[0];return Hg(n,i)}function jg(n,e){if(!Le(n,e))return e;const t=jn(n,e).getChildContainers(n,e),o=t[t.length-1],r=bt(o),i=r[r.length-1];return jg(n,i)}function a9(n){const e=jg(n,Gt(n.rootContainer)),t=se(e,ue(n,e),"end");return n.selection.setSelection(t),!0}function u9(n){const e=Hg(n,n.getFirstBlock()),t=se(e,0,"home");return n.selection.setSelection(t),!0}function d9(n){const e=Hg(n,n.getFirstBlock()),t=se(e,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}function Ug(n){const e=jg(n,Gt(n.rootContainer)),t=se(e,ue(n,e),"end");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}const h9=S("line-offset");function f9(n){const e=n.selection.range.focus;m(h9,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===0||!ee(n,t))return se(t,0,"home");let r=O4(t,e).start;const{next:i}=Yd(t,r);return i&&ro(i)&&Ca(i)==="br"&&(r+=1),se(t,r,"home")}function m9(n){const e=n.selection.range.focus;m(h9,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===ue(n,t)||!ee(n,t))return se(t,ue(n,t),"end");const o=O4(t,e);return se(t,o.end,"end")}function g9(n){if(!n.selection.range.focus.isSimple())return!1;const t=f9(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function p9(n){if(!n.selection.range.focus.isSimple())return!1;const t=m9(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function C9(n){if(!n.selection.range.focus.isSimple())return!1;const t=f9(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function A9(n){if(!n.selection.range.focus.isSimple())return!1;const t=m9(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}const b9=S("find-block-position");function kT(n,e,t,o){m(b9,Le(n,e),"is not a complex block");const r=jn(n,e).getChildContainers(n,e);m(b9,r.length>0,"complex block has not any child container");const i=To(n,t,o),s=i.left+i.width/2,l=i.top+i.height/2,a=w4(n,e,s,l);return zg(n,a,t,o)}function zg(n,e,t,o){if(Le(n,e))return kT(n,e,t,o);const r=re(e);let i=Number.MAX_SAFE_INTEGER;const s=To(n,t,o),l=s.left+s.width/2,a=s.top+s.height/2;let d=se(r,0,"home");const h=ue(n,e);for(let p=0;p<=h;p++){const A=se(r,p,"normal"),v=To(n,e,A),B=tr(v,l,a);B<i&&(i=B,d=A)}return d}const v9=S("page-offset");function wT(n,e){const t=b6(n)*.9,r=e.getBoundingClientRect().bottom-t;if(r<GI(n))return n.getFirstBlock();const i=lt(e);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=lt(s)}return n.getFirstBlock()}function BT(n,e){const t=b6(n)*.9,o=e.getBoundingClientRect(),r=ZI(n),i=o.top+t;if(i>r)return n.getLastBlock();const s=Ze(e);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Ze(l)}return n.getLastBlock()}function y9(n){const e=n.selection.range.focus;m(v9,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=wT(n,t);let r;return o===n.getFirstBlock()?r=se(o,0,"home"):r=zg(n,o,t,e),r}function k9(n){const e=n.selection.range.focus;m(v9,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=BT(n,t);let r;return o===n.getLastBlock()?r=se(o,ue(n,o),"end"):r=zg(n,o,t,e),r}function w9(n){if(!n.selection.range.focus.isSimple())return!1;const t=y9(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function B9(n){if(!n.selection.range.focus.isSimple())return!1;const t=k9(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function E9(n){if(!n.selection.range.focus.isSimple())return!1;const t=y9(n);if(!t)return!1;const o=kh(n,n.selection.getAnchorPos(),t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function x9(n){if(!n.selection.range.focus.isSimple())return!1;const t=k9(n);if(!t)return!1;const o=kh(n,n.selection.getAnchorPos(),t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const Pa=S("select-all");function I9(n,e){const t=St(n),o=Gt(n);return e.start.offset===0&&e.start.blockId===re(t)&&e.end.offset===ue(e.getEditor(),o)&&e.end.blockId===re(o)}function ET(n,e){const t=e.getEditor(),o=jn(t,n).getChildContainers(t,n),r=o[0],i=o[o.length-1],s=re(n);return e.start.blockId===s&&e.start.childContainerId===ae(r)&&e.end.blockId===s&&e.end.childContainerId===ae(i)}function xT(n,e){m(Pa,e,"no parent block"),m(Pa,Le(n,e),"not a complex block");const t=jn(n,e).getChildContainers(n,e),o=t[0],r=t[t.length-1];n.selection.setRange(Ut(n,{anchor:ht(e,ae(o)),focus:ht(e,ae(r))}))}function T9(n,e){const t=ne(e);Vg(n,t)}function D9(n){const e=n.getFocusedBlock(),t=n.selection.range;if(t.start.isSimple()){if(t.start.blockId===t.end.blockId&&ee(n,e)){const r=t.start,i=t.end,s=ue(n,e);if(r.offset>0||i.offset<s)return n.selection.selectBlock(e,0,s),!1}return W(n.rootContainer,"select-all"),T9(n,St(n.rootContainer)),!1}return m(Pa,!t.isSimple(),"invalid range type"),ET(e,t)?(T9(n,e),!1):(m(Pa,e,"no parent block"),m(Pa,Le(n,e),"not a complex block"),xT(n,e),!0)}function Vg(n,e){const t=bt(e),o=t[0],r=t[t.length-1],i=se(o,0,"home"),s=se(r,ue(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function S9(n){Ug(n),n.focus()}const Wg=S("selected-block-to-doc");function L9(n,e,t){!e.children||e.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{L9(n,i,t)}),t.blocks[o]=fe.default(r)})}function wh(n,e){const t=Qe(n,e.block);if(t.selectionToDoc)return t.selectionToDoc(n,e);const o=fe.default(_i(n,e.block));if(ee(n,e.block)){const i=e.start,s=e.end;if(m(Wg,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=zt(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Lt(e.block))return{blocks:{root:[o]},meta:{},comments:{}};m(Wg,Le(n,e.block),"not complex block"),m(Wg,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return L9(n,o,r),r}function qg(n,e){const t=se(e,0,"normal"),o=se(e,ue(n,e),"end");return wh(n,{block:e,start:t,end:o})}const IT=S("block-to-doc");function TT(n,e){m(IT,e.length>0,"invalid params, no blocks");const t=e.map(o=>qg(n,o));return Ps(t)}function Bh(n){const t=n.selection.range.getSelectedBlocks().map(o=>wh(n,o));return Ps(t)}function M9(n,e){const t=n.getContainerById(e),i=bt(t).map(s=>({start:se(s,0,"home"),end:se(s,ue(n,s),"end"),block:s})).map(s=>wh(n,s));return Ps(i)}const Eh=S("editor-selection");class DT{constructor(e){g(this,"editor");g(this,"caret");g(this,"_range");g(this,"lastCaretRect");g(this,"handleBlockDelete",(e,t,o,r)=>{if(o||r.child)return;const i=this.range;if(k6(t,i)){Eh.debug("adjust selection because remote deleted current block");const s=w6(e,t);this.setRange(s,{noScroll:!0})}});this.editor=e;const t=e.getFirstBlock(),o=re(t);this.caret=new VI(e);const r=se(o,0,"normal");this._range=Ut(e,{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 e=this.range.focus;return this.editor.getBlockById(e.blockId)}getStartBlock(){const e=this.range.start;return this.editor.getBlockById(e.blockId)}getEndBlock(){const e=this.range.end;return this.editor.getBlockById(e.blockId)}selectBlock(e,t,o){const r=se(e,t,"normal");let i;o&&(i=se(e,o,"normal")),this.setSelection(r,i)}setSelection(e,t,o){if(t||(t=e),this.verifyPos(e),this.verifyPos(t),!this.selectionChanging(e,t))return this.range;const r=Ut(this.editor,{anchor:e,focus:t});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),xe(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!KI(this.editor,r))&&te(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(e,t){return this.setSelection(e.anchor,e.focus,t)}updateSelection(){this.caret.update(),WI(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(e,t){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const e=this.range.focus;if(!Nr(e))return;const t=this.editor.getBlockById(e.blockId);this.lastCaretRect=To(this.editor,t,e)}getSuggestedCaretX(){var e;return(e=this.lastCaretRect)==null?void 0:e.x}scrollIntoView(){JI(this.editor)}verifyPos(e){const t=this.editor.getBlockById(e.blockId);if(e.isSimple())e.offset>=0&&e.offset<=ue(this.editor,t)||m(Eh,!1,"invalid block position, out of range");else{const o=e.childContainerId;!!this.editor.getContainerById(o)||m(Eh,!1,"invalid complex block position, no container found")}}updateFocusedBlock(e){if(e&&this.range.start.blockId===e.start.blockId)return;let t;e&&e.start.blockId===e.end.blockId&&(t=this.editor.findBlockById(e.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;t&&xe(t,"focused")&&(te(t,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,t!=null?t:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(e){const t=Bh(this.editor);return e==="text"?Da(this.editor,t):e==="markdown"?Sa(this.editor,t):E6(this.editor,t)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(e=>{te(e,"focused"),te(e,"child-focused")})}setBlockFocused(e){if(xe(e,"focused"))return!1;W(e,"focused");let t=ne(e);for(;Do(t);){const o=oe(t);m(Eh,o,"parent block not found"),W(o,"child-focused"),t=ne(o)}return!0}}function ST(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);!t||n.selection.selectBlock(t,0,ue(n,t))}function LT(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);if(!t||!ee(n,t))return;let o=Ng(n,"select"),r=$g(n,"select");if(!o||!r)return;const i=e.blockId;o.blockId!==i&&(o=se(t,0,"home")),r.blockId!==i&&(r=se(t,ue(n,t),"end")),n.selection.setSelection(o,r)}class MT{constructor(e){g(this,"editor");g(this,"startPos",null);g(this,"lastCaretRect");g(this,"mouseDownEvent",null);g(this,"handleMouseDown",e=>{this.mouseDownEvent=e;const t=x4(this.editor,e.x,e.y);if(t){if(t instanceof or)return;const o=this.editor.selection.range;if(e.shiftKey&&o.isSimple()){const r=o.anchor;this.editor.selection.setSelection(r,t.focus),this.startPos=t.start}else this.editor.selection.setSelection(t.anchor,t.focus),this.startPos=t.start;this.editor.selection.updateLastCaretRect()}});g(this,"handleMouseMove",e=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-e.x)<3&&Math.abs(this.mouseDownEvent.y-e.y)<3)return;const t=eh(this.editor,e.x,e.y);if(!t)return;const o=kh(this.editor,this.startPos,t.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});g(this,"handleMouseUp",e=>{this.startPos=null});this.editor=e,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(e){LT(this.editor)}handleTripleClick(e){ST(this.editor)}}function RT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function OT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const R9=S("delete-text");function O9(n,e,t,o){const r=o!=null?o:n.selection.range.start;r instanceof jt||m(R9,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);m(R9,ee(n,s),"block is not a text kind block");let{offset:l}=r;if(e==="backward"){if(l-t<0)return 0;if(!sn(s,l-t)){const a=Ri(s,l);t=l-a}}else if(e==="forward"&&l+t>ue(n,s))return 0;return e==="backward"&&(l-=t),n.deleteTextFromBlock(s,l,t)}function _9(n,e){if(n.getBlockData(e).quoted){const t={quoted:null};return n.updateBlockData(e,t),!0}return!1}const _T=S("handle-backspace");function Gg(n,e){if(!dt(n,e))return;const t=ne(e);Eo(t)!==1&&n.deleteBlock(e)}function FT(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if(ee(n,o))if(t.offset===0){if(_9(n,o))return;const r=lt(o);if(r){if(!n.isBlockWritable(r))return;if(ee(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Le(n,r)){Gg(n,o);const i=zl(n,r);i?n.selection.selectBlock(i,ue(n,i)):n.selection.selectBlock(r,0,ue(n,r))}else Gg(n,o),m(_T,Lt(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=ne(o);if(Do(i)){const s=v4(n,i);if(s){if(!n.isBlockWritable(s))return;Gg(n,o),n.selection.selectBlock(s,ue(n,s))}}}}else O9(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=be(o),i=ne(o);n.insertTextBlock("",ae(i),r),n.deleteBlock(o)}}function PT(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if(ee(n,o))if(t.offset===ue(n,o)){const r=Ze(o);if(r){if(!n.isBlockWritable(r))return;ee(n,r)?n.mergeTextBlock(o,r,{focus:!0}):dt(n,o)?n.deleteBlock(o,vt(n,r,0)):n.deleteBlock(r)}}else O9(n,"forward",1,null);else{const r=be(o),i=ne(o);n.insertTextBlock("",ae(i),r),n.deleteBlock(o)}}function NT(n){const{range:e}=n.selection,{start:t,end:o}=e,r=n.getBlockById(t.blockId),i=n.getBlockById(o.blockId);if(r!==i||!Le(n,r))return!1;if(Nr(t))return!0;const s=Ms(n,r,t,o),l=En(n,r);return s.length===l.length}function $T(n,e){if(NT(n)){const o=n.getFocusedBlock(),r=be(o),i=ae(ne(o));n.insertTextBlock("",i,r+1);return}n.selection.range.isCollapsed()||n.clearSelectedContents();const t=n.getFocusedBlock();if(ee(n,t)){if(dt(n,t)&&_9(n,t))return;const o=n.selection.range.start,r=n.breakTextBlock(t,o.offset,{copyBlockAttributes:!0});o.offset!==0?n.selection.selectBlock(r,0):n.selection.scrollIntoView()}else{const o=n.insertTextBlock();n.selection.selectBlock(o,0)}}function HT(n,e){const t=n.selection.range.getSelectedBlocks()[0],{block:o}=t;if(!ee(n,o))return!1;const r=t.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:K(),box:!0,created:Date.now()}),!0}const jT=S("input-handler-actions");function UT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>($T(n),!0))}function zT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(PT(n),!0))}function VT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(FT(n),!0))}function WT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(HT(n),!0))}function qT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(e=>{n.input.handlePasteText(e)}).catch(e=>{jT.error(e)}),!0)}const xh={ArrowDown:X6,ArrowUp:K6,ArrowLeft:Y6,ArrowRight:J6,"Shift+ArrowDown":e9,"Shift+ArrowUp":o9,"Shift+ArrowLeft":t9,"Shift+ArrowRight":n9,"CtrlOrCmd+ArrowLeft":i9,"CtrlOrCmd+ArrowRight":s9,"CtrlOrCmd+Shift+ArrowLeft":l9,"CtrlOrCmd+Shift+ArrowRight":c9,"CtrlOrCmd+ArrowUp":u9,"CtrlOrCmd+ArrowDown":a9,"CtrlOrCmd+Shift+ArrowUp":d9,"CtrlOrCmd+Shift+ArrowDown":Ug,"CtrlOrCmd+A":D9,Home:C9,End:A9,"Shift+Home":g9,"Shift+End":p9,PageUp:w9,PageDown:B9,"Shift+PageUp":E9,"Shift+PageDown":x9,"CtrlOrCmd+Z":RT,"CtrlOrCmd+Shift+Z":OT,Enter:UT,Delete:zT,Backspace:VT,"Shift+Enter":WT,"CtrlOrCmd+Shift+V":qT};function F9(n,e){return n.shortcuts.handleKeyboardEvents(n,e)!==void 0}function P9(n,e,t){if(e.type==="embed"){const i=e.embedData,s=i.src;if(s&&typeof s=="string"){const l=t.get(s);l&&(i.src=l)}return}const o=e.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=t.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=e.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{P9(n,l,t)})})}function N9(n,e,t){if(t.size===0)return;e.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,t):P9(e,r,t)})}async function GT(n,e){const t=e.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(t),r=new Map;if(t.length!==o.length)return r;for(let i=0;i<t.length;i++)r.set(t[i],o[i]);return r}function ZT(n,e){var i,s;const o=e.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 QT(n,e){const o=e.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(ZT(n,e)){const s=Array.from(Object.keys(o));r=await GT(n,s),N9(n,e,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&&N9(n,e,i)}async function YT(n,e,t){await QT(n,e),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Lt(i)){const s=ne(i),l=n.getBlockIndex(i),[a]=n.insertDocAt(s,l+1,e,t);a&&n.selection.selectBlock(a,ue(n,a))}else{n.clearSelectedContents();const{block:s,offset:l}=ql(n);n.insertDoc(s,l,e,t)}})}const JT=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function KT(n){let e;for(const t of JT)if(e=n[t],e)break;return e||null}function $9(n,e,t){if(e.type==="embed"){const s=e.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))t.add(l);return}const o=e.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&t.add(i.attributes.src)});const r=e.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{$9(n,l,t)})})}function XT(n,e){const t=new Set;return e.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{t.add(s)}):$9(e,r,t)}),Array.from(t)}function Ih(n,e){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${ws(JSON.stringify(e))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Th(n,e){var i,s,l;const t=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=XT(n,e),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),e.meta={...t,resources:r}}function eD(n,e,t){if(e.preventDefault(),e.stopPropagation(),!e.clipboardData)return;let o=Bh(n);const r=t==null?void 0:t(n,e,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Th(n,o);const i=mh(n,o),s=Sa(n,o),l=Ih(i,o);e.clipboardData.setData("text/html",l),e.clipboardData.setData("text/plain",s),e.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Dh(n,e){const t=qg(n,e);Th(n,t);const o=mh(n,t),r=Sa(n,t),i=Ih(o,t);return Em([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class tD{constructor(e){g(this,"editor");g(this,"handlers",[]);g(this,"onPasteText",async e=>{const t=new DataTransfer;t.setData("text/plain",e);const o=await this.editor.dataConverter.fromData(this.editor,t);o&&this.pasteDocs(o,null)});this.editor=e}onInsertText(e,t){if(!ee(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=ql(this.editor);this.handleBeforeInsertText(o,r,i,t)||(this.defaultInsertText(this.editor,o,r,i,t),this.handleAfterInsertText(o,r,i,t),this.editor.selection.updateLastCaretRect())}onKeyDown(e){if(this.handleBeforeKeyDown(e))return!0;const t=this.defaultHandleKeydown(this.editor,e);return this.handleAfterKeyDown(e)?!0:t}onChanged(e){for(let t=0;t<this.handlers.length;t++){const o=this.handlers[t];o.handleChanged&&o.handleChanged(this.editor,e)}}onRemoteChanged(e){for(let t=0;t<this.handlers.length;t++){const o=this.handlers[t];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,e)}}onCompositionStart(e){this.editor.updateCompositionText("",!1);const{containerId:t,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,t,o,r)}}onUpdateCompositionText(e,t,o){this.editor.updateCompositionText(t,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(e){eD(this.editor,e,(t,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(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,e)===!0)return}if(this.onCopy(e),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;Lt(o)&&this.editor.deleteBlock(o)}else Sg(this.editor)}onPaste(e){if(e.preventDefault(),e.stopPropagation(),!e.clipboardData)return;this.editor.dataConverter.fromData(this.editor,e.clipboardData).then(async o=>{o&&this.pasteDocs(o,e)})}onFocus(){W(this.editor.rootElement,"active")}onBlur(){te(this.editor.rootElement,"active")}addHandler(e){this.handlers.push(e)}removeHandler(e){const t=this.handlers.indexOf(e);t!==-1&&this.handlers.splice(t)}handleBeforeInsertText(e,t,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,e,t,o,r))return!0}return!1}handleAfterInsertText(e,t,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,e,t,o,r))return!0}return!1}handleBeforeKeyDown(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,e))return!0}const t=this.defaultHandleKeydown(this.editor,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,e))return!0}return t}handleAfterKeyDown(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,e))return!0}const t=this.defaultHandleKeydown(this.editor,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,e))return!0}return t}defaultInsertText(e,t,o,r,i){Eg(this.editor,i)}defaultHandleKeydown(e,t){return F9(this.editor,t)?(t.preventDefault(),t.stopPropagation(),!0):!1}async pasteDoc(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,e))return}const t={blockIdMap:new Map,containerIdMap:new Map};await YT(this.editor,e,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,e,t))return}}async pasteDocs(e,t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,t,e))return}const o=KT(e);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,t,e))return}}}destroy(){this.handlers.forEach(e=>{var t;(t=e.destroy)==null||t.call(e,this.editor)}),this.handlers=[]}}function nD(n,e,t){const o=Rr(e,t);return o.remove(),o}S("copy-dom-attributes");const H9=["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 oD(n,e){for(let l=0;l<H9.length;l++){const a=H9[l];e[a]=n[a]}const t=n.attributes,o=e.attributes,r=[],i=[];for(let l=0;l<t.length;l++){const a=t[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];t.getNamedItem(a.name)||s.push(a)}r.forEach(l=>{e.setAttribute(l.name,l.value)}),i.forEach(l=>{e.setAttribute(l.name,l.value)}),s.forEach(l=>{e.removeAttribute(l.name)})}function j9(n){const e=Array.from(n.childNodes).filter(t=>!_C(t));return e.forEach(t=>{t.remove()}),e}function U9(n,e,t){var d;const o=n.getContainerById(e),r=Rr(o,t),i=Di(r),s=n.doc.getBlockData(e,t),l=Qe(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=j9(h);j9(r),p.forEach(v=>{r.appendChild(v)});const A=Zd(h);if(A){const v=Zd(r);v&&v.remove(),r.appendChild(A)}oD(h,r)}XC(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 rD=S("transform-selection");function z9(n,e,t,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==e&&s.blockId!==e)return r;m(rD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===e){const d=ln.transformCursor(i.offset,t,o);l=se(e,d,"normal")}let a=s;if(s.blockId===e){const d=ln.transformCursor(s.offset,t,o);a=se(e,d,"normal")}return Ut(n,{anchor:l,focus:a})}const iD=S("handle-block-text-changed");function sD(n,e,t,o,r){const i=n.getContainerById(e),s=Rr(i,t),l=n.doc.getBlockData(e,t);if(m(iD,l.text,"no block text"),GC(n,s).setBlockText(n,s,l.text),!r){const a=z9(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function lD(n,e){const t=fe.default(n);return e.delete.forEach(r=>{delete t[r]}),{...t,...e.insert}}function V9(n,e,t,o){const r=Qe(n,e);r.handleDeleteBlock&&r.handleDeleteBlock(n,e,t,o),n.emit("blockDeleted",n,e,t,o)}function cD(n,e,t,o){const r=n.getBlockByIndex(e,t);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{V9(n,i,o,{child:!0})}),V9(n,r,o,{child:!1})}const Ro=S("editor-doc");class aD extends ua{constructor(t,o,r){super();g(this,"localEvents",[]);this.editor=t,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(t){this.localEvents.push(t)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(t){return this.externalDoc.getContainerBlocks(t)}getBlockData(t,o){return this.externalDoc.getBlockData(t,o)}verifyBlockWritable(t,o){const r=this.editor.getBlockByIndex(t,o);m(Ro,this.editor.isBlockWritable(r),`block is not writable, ${t}, ${o}`)}localUpdateBlockText(t,o,r,i){m(Ro,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const s=this.getBlockData(t,o),l=s.text;m(Ro,l,`no text, ${t}, ${o}`);const a=z9(this.editor,s.id,r,!0),d=ln.apply(l,r);this.localEvents.forEach(p=>p.onBeforeUpdateBlockText(t,s.id,l,d,a.toDocRange()));const h=this.externalDoc.localUpdateBlockText(t,o,r);return this.editor.selection.setRange(a,i),h}localUpdateBlockData(t,o,r,i){m(Ro,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(t,o);if(!this.editor.isBlockWritable(s)){const h=Array.from(r.delete).filter(A=>A!=="comments"),p=Object.keys(r.insert).filter(A=>A!=="comments");(h.length>0||p.length>0)&&m(Ro,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=fe.default(this.getBlockData(t,o)),a=fe.default(lD(l,r));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(t,l.id,l,a,i));const d=this.externalDoc.localUpdateBlockData(t,o,r,i);return this.editor.selection.setRange(Si(this.editor,i)),d}localInsertBlock(t,o,r,i,s){m(Ro,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(a=>a.onBeforeInsertBlock(t,o,r,i));const l=this.externalDoc.localInsertBlock(t,o,r,i);return this.editor.selection.setRange(Si(this.editor,i),s),l}localDeleteBlock(t,o,r){m(Ro,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const i=fe.default(this.getBlockData(t,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(t,o,i,r));const s=this.externalDoc.localDeleteBlock(t,o,r);return this.editor.selection.setRange(Si(this.editor,r)),s}localDeleteChildContainers(t){return m(Ro,!this.editor.readonly,"editor is readonly"),t.forEach(o=>{const r=fe.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(t)}localInsertChildContainer(t,o){return m(Ro,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(t,fe.default(o))),this.externalDoc.localInsertChildContainer(t,o)}onRequestReload(t){Ro.debug(`reload doc: ${t}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,t)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(t,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,t,o,r,i)}),sD(this.editor,t,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(t,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,t,o,r,i)}),U9(this.editor,t,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(t,o,r,i){this.callbacks.forEach(l=>{var a;return(a=l.onInsertBlock)==null?void 0:a.call(l,t,o,r,i)});const s=this.editor.getContainerById(t);JE(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(t,o,r){cD(this.editor,t,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,t,o,r)});const i=this.editor.getContainerById(t);nD(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(t,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,t,o,r)})}onDeleteChildContainer(t,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,t,o)})}onCustomMessage(t){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,t)})}onStatusChanged(t){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,t)})}onError(t){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,t)})}uploadResource(t,o){return this.externalDoc.uploadResource(t,o)}addResources(t){return this.externalDoc.addResources(t)}buildResourceUrl(t,o){return this.externalDoc.buildResourceUrl(t,o)}request(t,o){return this.externalDoc.request(t,o)}broadcastMessage(t){return this.externalDoc.broadcastMessage(t)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var t,o,r;return(r=(o=(t=this.externalDoc).getServerMeta)==null?void 0:o.call(t))!=null?r:{}}reset(t){Ro.log("reset doc"),this.externalDoc=t,this.externalDoc.registerCallback(this),this.editor.reload()}}function W9(n,e){if(n.length===0){n.push(e);return}const t=n[n.length-1];if(!t.combinable(e)){n.push(e);return}t.combine(e)}const Zg=S("undo-action");class Yl{constructor(e,t,o){g(this,"beforeRange");g(this,"afterRange");this.containerId=t,this.beforeRange=e.selection.range.clone().toDocRange(),this.afterRange=o}undo(e){return!1}redo(e){return!1}combinable(e){return m(Zg,e,"no other action"),!1}combine(e){m(Zg,!1,"no other")}setAfterRange(e){this.afterRange&&Zg.warn("after range has already set"),this.afterRange=e}}const uD=S("block-action");class q9 extends Yl{constructor(t,o,r,i,s){super(t,o,s);g(this,"blockData");g(this,"blockIndex");this.blockData=fe.default(i),this.blockIndex=r}deleteBlock(t,o){if(!t.getContainerById(this.containerId))return!1;const i=t.getBlockById(this.blockData.id);return i?(m(uD,this.blockIndex===be(i),"invalid block index"),Ah(t,i,Si(t,o)),!0):!1}insertBlock(t,o){return Gl(t,this.containerId,this.blockIndex,fe.default(this.blockData),o),!0}}class dD extends q9{undo(e){return this.deleteBlock(e,this.beforeRange)}redo(e){return this.insertBlock(e,this.afterRange)}}class hD extends q9{undo(e){return this.insertBlock(e,this.beforeRange)}redo(e){return this.deleteBlock(e,this.afterRange)}}class fD extends Yl{constructor(t){super(t,ae(t.rootContainer),t.selection.range.toDocRange());g(this,"actions",[])}addAction(t){W9(this.actions,t),this.afterRange=t.afterRange}undo(t){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(t)&&(o=!0)}),o}redo(t){let o=!1;return this.actions.forEach(r=>{r.redo(t)&&(o=!0)}),o}setAfterRange(t){this.afterRange=t;const o=this.actions[this.actions.length-1];!o||o instanceof Yl&&(o.afterRange||o.setAfterRange(t))}}const Ns=S("update-block-data-action");class Sh extends Yl{constructor(t,o,r,i,s,l){super(t,o,l);g(this,"beforeBlockData");g(this,"afterBlockData");g(this,"blockId");this.blockId=r,m(Ns,this.blockId===i.id,"invalid block id"),m(Ns,this.blockId===s.id,"invalid block id"),this.beforeBlockData=fe.default(i),this.afterBlockData=fe.default(s),m(Ns,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(t){m(Ns,t,"no editor");const o=t.getBlockById(this.blockId);if(!o)return!1;const r=t.getContainerById(this.containerId);return m(Ns,r,"no container"),yh(t,o,Sh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(t){m(Ns,t,"no editor");const o=t.getBlockById(this.blockId);if(!o)return!1;const r=t.getContainerById(this.containerId);return m(Ns,r,"no container"),yh(t,o,Sh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(t){const o=fe.default(t);return delete o.id,delete o.type,o}}const Qg=S("update-block-text-action");class Na extends Yl{constructor(t,o,r,i,s,l){super(t,o,l);g(this,"beforeRichTextData");g(this,"afterRichTextData");g(this,"blockId");g(this,"type");this.blockId=r,this.beforeRichTextData=fe.default(i),this.afterRichTextData=fe.default(s),this.type=Na.calType(i,s)}static calType(t,o){m(Qg,t,"no old data"),m(Qg,o,"no new data");const i=ln.diff(t,o),s=new Set;let l=!1;const a=h=>uC(h)?`cjk_${h}`:cC(h)?"number":$d(h)?"space":aC(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(t){if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(vh(t,r,this.beforeRichTextData),!0):!1}redo(t){if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(vh(t,r,this.afterRichTextData),!0):!1}combinable(t){if(!(t instanceof Na)||t.type.begin||this.type.textType!==t.type.textType||t.blockId!==this.blockId)return!1;const o=t.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(t){m(Qg,t instanceof Na,"invalid action type");const o=t;this.afterRichTextData=o.afterRichTextData,this.afterRange=t.afterRange}}class G9 extends Yl{constructor(e,t,o){super(e,t,e.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(e){return e.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(e){return e.doc.localInsertChildContainer(this.containerId,fe.default(this.blocks)),!0}}class mD extends G9{undo(e){return this.deleteChildContainer(e)}redo(e){return this.insertChildContainer(e)}}class gD extends G9{undo(e){return this.insertChildContainer(e)}redo(e){return this.deleteChildContainer(e)}}const Oo=S("undo");class pD{constructor(e){g(this,"editor");g(this,"actions",[]);g(this,"undoCursor");g(this,"currentGroup",null);g(this,"groupCounter",0);g(this,"undoRedoing",!1);g(this,"handleSelectionChange",e=>{if(this.currentGroup){this.currentGroup.setAfterRange(e.selection.range.toDocRange());return}const t=this.actions[this.actions.length-1];!t||t.afterRange||t.setAfterRange(e.selection.range.toDocRange())});this.editor=e,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(e){this.currentGroup?this.currentGroup.addAction(e):(W9(this.actions,e),setTimeout(()=>{this.editor.input.handleChanged(e)}))}beginGroup(){this.groupCounter===0?(m(Oo,!this.currentGroup,"current group already exists"),this.currentGroup=new fD(this.editor),this.groupCounter=1):(m(Oo,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){m(Oo,this.currentGroup,"current group not exists"),m(Oo,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Oo.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(e){this.beginGroup();try{const t=e();return setTimeout(()=>this.editor.selection.caret.update()),t}catch(t){throw Oo.error(`failed to run action: ${t.message}`),t}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const e=this.actions[this.undoCursor];if(e.undo(this.editor)){try{this.editor.selection.setRange(Si(this.editor,e.beforeRange))}catch(t){Oo.error(`undo: failed to restore caret pos: ${t.message}`)}return this.editor.input.handleChanged(e),!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 e=this.actions[this.undoCursor];if(this.undoCursor+=1,e.redo(this.editor)){try{const t=e.afterRange;t?this.editor.selection.setRange(Si(this.editor,t)):Oo.warn("no after range")}catch(t){Oo.error(`redo: failed to set caret pos after redo: ${t.message}`)}return this.editor.input.handleChanged(e),!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 t;const e=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(t=this.actions[e])!=null?t:null}undoTo(e){for(;;){const t=this.lastAction();if(!t||t===e)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(e,t,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),ln.diff(o,r).length!==0&&this.addAction(new Na(this.editor,e,t,o,r,i)))}onBeforeUpdateBlockData(e,t,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Sh(this.editor,e,t,o,r,i);this.addAction(s)}onBeforeInsertBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),m(Oo,t>=0,"invalid block index"),m(Oo,o,"no block data"),this.addAction(new dD(this.editor,e,t,o,r)))}onBeforeDeleteBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new hD(this.editor,e,t,o,r)))}onBeforeInsertChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new mD(this.editor,e,t)))}onBeforeDeleteChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new gD(this.editor,e,t)))}}class CD{async fromData(e,t){const o=t.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class AD{constructor(){g(this,"converters",[]);this.addConverter(new CD)}async fromData(e,t){let o={};for(const r of this.converters){const i=await r.fromData(e,t);i&&(o={...o,...i})}return o}addConverter(e){this.converters.push(e)}}class bD{constructor(e){g(this,"renders",[]);this.editor=e}registerRender(e){this.renders.push(e)}renderText(e,t){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,e,t);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(e,t,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,t,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(e,t,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,e,t,o,r)})}}class gt extends At.TypedEmitter{constructor(t){super();g(this,"hoveringBlock",null);g(this,"hoveringTextChild",null);g(this,"filters",[]);g(this,"finders",[]);g(this,"handleDocumentMouseMove",t=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,t))return}const o=document.elementFromPoint(t.x,t.y);if(!o){this.setHoveringBlock(null,t,null);return}let r=oe(o);if((!r||!Ke(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(t),!r)){this.setHoveringBlock(null,t,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,t,i)});this.editor=t,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(t=>t.destroy()),this.filters=[],this.finders.forEach(t=>t.destroy()),this.finders=[]}addFilter(t){this.filters.push(t)}addFinder(t){this.finders.push(t)}hoveringBlockId(){return this.hoveringBlock?re(this.hoveringBlock):""}findBlockByFinders(t){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,t);if(i)return i}return null}setHoveringBlock(t,o,r){if(this.hoveringBlock===t&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==t){const s=this.hoveringBlock&&Ke(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&te(s,"hover"),t&&W(t,"hover"),this.hoveringBlock=t,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(t){return t.addCustom("standard-hovering-block",()=>new gt(t))}getParentTextContentChild(t,o){if(!ee(this.editor,t))return null;const r=Re(t);return o.parentElement===r?o:Rm(o)}}const Z9="style-color-",Q9="style-bg-color-";class vD{renderText(e,t,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(Z9)?i["data-style-color"]=l.substring(Z9.length):l.startsWith(Q9)?i["data-style-bg-color"]=l.substring(Q9.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(e,t,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=e.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"),gt.get(e).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(e,t,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=e.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&W(o,"focused"),gt.get(e).hoveringBlockId()===r.id&&W(o,"hover")}}function yD(n){n.editorBlocks.registerBlockClass(In),n.editorBlocks.registerBlockClass(b4),n.editorBoxes.registerBoxClass(c6),n.editorBoxes.registerBoxClass(a6),n.editorBoxes.registerBoxClass(h6),n.editorBoxes.registerBoxClass(f6),n.editorInsertions.registerInsertionClass(m6),n.editorBlockRenders.registerRender(new vD)}function kD(n,e){yD(n),e!=null&&e.blocks&&e.blocks.forEach(t=>n.editorBlocks.registerBlockClass(t)),e!=null&&e.boxes&&e.boxes.forEach(t=>n.editorBoxes.registerBoxClass(t)),e!=null&&e.embeds&&e.embeds.forEach(t=>n.editorEmbeds.registerEmbedClass(t)),e!=null&&e.insertions&&e.insertions.forEach(t=>n.editorInsertions.registerInsertionClass(t)),e!=null&&e.decorators&&e.decorators.forEach(t=>n.editorDecorators.registerDecorator(t)),e!=null&&e.dataConverters&&e.dataConverters.forEach(t=>n.dataConverter.addConverter(t)),e!=null&&e.commandProviders&&e.commandProviders.forEach(t=>n.editorCommandProviders.registerCommandProvider(t)),e!=null&&e.textRenders&&e.textRenders.forEach(t=>n.editorBlockRenders.registerRender(t))}const Y9=S("range-commands");function J9(n,e){n.forEach(t=>{t.source=e,t.children&&J9(t.children,e)})}function K9(n,e,t){const o=re(e);m(Y9,o===t.start.blockId,"invalid start range"),m(Y9,o===t.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,e,t);J9(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,e,t,i);l&&(i=l)}}),Le(n,e)&&Ms(n,e,t.start,t.end).forEach(l=>{bt(l).forEach(d=>{const h=ue(n,d),p=Ut(n,{anchor:se(d,0,"home"),focus:se(d,h,"end")}),A=K9(n,d,p);i.push(...A)})}),i}function X9(n){const e=n.getEditor(),t=n.getSelectedBlocks(),o=[];return t.forEach(r=>{const i=Ut(e,{anchor:r.start,focus:r.end});K9(e,r.block,i).forEach(l=>{o.push(l)})}),o}function e7(n,e,t,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const A=s[p];if(A.beforeExecuteCommand&&A.beforeExecuteCommand(n,e,t,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),a={};if((h=l.executeCommand)!=null&&h.call(l,n,e,t,o,r,{}))return i[re(e)]=a,!0;let d=!1;return Le(n,e)&&Ms(n,e,t.start,t.end).forEach(A=>{bt(A).forEach(B=>{const D=ue(n,B),x=Ut(n,{anchor:se(B,0,"home"),focus:se(B,D,"end")});e7(n,B,x,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,e,t,o,r,i)}),d}function t7(n,e,t){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(e.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,e,t,r)||n.getSelectedBlocks().forEach(l=>{const a=Ut(o,{anchor:l.start,focus:l.end});e7(o,l.block,a,e,t,r)}),r}const wD=S("command-providers");class n7{constructor(e){g(this,"providers",[]);this.editor=e}registerCommandProvider(e){this.providers.push(e)}getCommandProviders(){return this.providers}getCommandProvider(e){const t=this.providers.find(o=>o.id===e);return m(wD,t,`no command provider, id=${e}`),t}getCommands(e){return X9(e)}executeCommand(e,t,o){return this.editor.undoManager.runInGroup(()=>t7(e,t,o))}getEmptyBlockTextAttributes(e,t){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,e,t);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function BD(n,e){const t=ne(e),o=ae(t),r=be(e);U9(n,o,r)}const ED=S("table-scroll");class o7{constructor(e,t,o,r,i){g(this,"handleEvent",e=>{this.handler(this.editor,e,this.data)});this.editor=e,this.dom=t,this.name=o,this.handler=r,this.data=i,t.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class xD{constructor(e){g(this,"handlers",new Map);this.editor=e}destroy(){Array.from(this.handlers.entries()).forEach(([e,t])=>{t.forEach(o=>o.destroy()),this.handlers.delete(e)})}addEventListener(e,t,o,r){const i=this.handlers.get(e);if(i){if(i.find(s=>s.handler===o&&s.name===t)){ED.warn(`event has already registered: ${t}`);return}i.push(new o7(this.editor,e,t,o,r))}else{const s=new o7(this.editor,e,t,o,r);this.handlers.set(e,[s])}}removeEventListener(e,t,o){if(!e){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const a=s[l];if(t)t===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(e);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===t);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(e)}}}removeAllListeners(e,t){const o=this.handlers.get(e);if(o)if(t)for(let r=0;r<o.length;r++){const i=o[r];i.name===t&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(e)}}const r7=S("update-block-text");function ID(n,e){const t=n.getBoxById(e.id),o=oe(t);m(r7,o,"no parent block"),m(r7,ee(n,o),"not a text block");const r=n.getBlockText(o),i=X4(r,"id",e.id,e);F6(n,o,i)}function TD(n,e){for(const t of n.blockHooks)if(t.writable){const o=t.writable(n,e);if(typeof o=="boolean")return o}return!0}function DD(n){return n.readonly?!1:!Lo(n).find(o=>!n.isBlockWritable(o.block))}class SD{constructor(e){this.editor=e}getKey(e){return`${this.editor.id}-${e}`}getItem(e){return window.localStorage.getItem(this.getKey(e))}setItem(e,t){if(!t){this.removeItem(e);return}window.localStorage.setItem(this.getKey(e),t)}removeItem(e){window.localStorage.removeItem(this.getKey(e))}}class LD{constructor(){g(this,"shortcuts",[])}handleKeyboardEvents(e,t){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(Mr(t,s)){const a=l(e,t);if(a!==void 0)return a}}}}const Ur=S("editor");class MD extends At.TypedEmitter{constructor(t,o,r){var i,s,l,a,d,h,p;super();g(this,"parent");g(this,"rootElement");g(this,"contentElement");g(this,"rootContainerObject");g(this,"rootContainer");g(this,"input");g(this,"selection");g(this,"selectionHandler");g(this,"doc");g(this,"id");g(this,"clientId");g(this,"compositingText","");g(this,"undoManager");g(this,"shortcuts",new LD);g(this,"dataConverter",new AD);g(this,"editorBlocks",new g4(this));g(this,"editorBoxes",new d6(this));g(this,"editorInsertions",new p6(this));g(this,"editorEmbeds",new C4(this));g(this,"editorDecorators",new C6(this));g(this,"editorCommandProviders",new n7(this));g(this,"editorBlockRenders",new bD(this));g(this,"blockHooks",[]);g(this,"domEvents",new xD(this));g(this,"customs",new Map);g(this,"options");g(this,"inputHandlers",new tD(this));g(this,"settingsProvider");g(this,"_readonly",!1);Ur.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 SD(this),kD(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 pD(this),this.doc=new aD(this,o,this.undoManager),this.parent=t,this.rootElement=w("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=w("div",["editor-content"],this.rootElement),this.rootContainerObject=h4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new zI(this,this.inputHandlers),this.selection=new DT(this),this.selectionHandler=new MT(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),Kt.isMobile&&W(this.rootElement,"mobile"),Kt.isSafari&&W(this.rootElement,"safari"),this._readonly&&W(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(t){this._readonly=t,t?W(this.rootElement,"readonly"):te(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:Bo(this.rootContainer)}addCustom(t,o){const r=this.customs.get(t);if(r)return r;const i=o(this);return this.customs.set(t,i),i}getCustom(t){const o=this.customs.get(t);return m(Ur,o,`${t} does not exists`),o}replaceCustom(t,o){const r=this.customs.get(t);return r&&r.destroy(),this.customs.set(t,o),o}findCustom(t){return this.customs.get(t)}findCustomByType(t){const o=this.customs.values();for(const r of o)if(r instanceof t)return r;return null}destroyCustom(t){const o=this.customs.get(t);o&&(this.customs.delete(t),o.destroy())}getComponentOptions(t){return this.options.componentsOptions[t]}registerLocalEvents(t){this.doc.registerLocalEvents(t)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(t,o,r){return this.editorBlocks.createBlock(t,o,r)}createBox(t,o){return this.editorBoxes.createBox(t,o)}createInsertion(t,o){return this.editorInsertions.createInsertion(t,o)}destroy(){Ur.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(t=>t.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus()}focusToBlock(t,o){Lg(this,t,o)}isWritable(){return DD(this)}isBlockWritable(t){return TD(this,t)}getChildContainerData(t){const o=this.doc.getContainerBlocks(t);return m(Ur,o,`no child container data: ${t}, ${JSON.stringify(this.doc)}`),m(Ur,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(t,o,r){return f4(this,t,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const t=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return t[t.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(t){const o=this.rootContainer.querySelector(`#${t}`);return o&&m(Ur,Es(o),"not an valid block element"),o!=null?o:null}findBoxById(t){const o=this.rootContainer.querySelector(`#${t}`);return o&&m(Ur,Mm(o),"not an valid box element"),o!=null?o:null}getBlockById(t){const o=this.findBlockById(t);return m(Ur,o,`no block, id=${t}`),o}getBoxById(t){const o=this.findBoxById(t);return m(Ur,o,`no box, id=${t}`),o}getBlockByIndex(t,o){const r=this.getContainerById(t);return Rr(r,o)}getBlockIndex(t){if(typeof t=="string"){const o=this.getBlockById(t);return be(o)}return be(t)}getContainerById(t){return Pr(this,t)}getParentContainer(t){return ne(t)}reloadBlock(t){BD(this,t)}contains(t){const o=t instanceof Element?t:t.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(t,o,r,i,s){const l={blockId:r.id,offset:0},a={anchor:l,focus:l};return Gl(this,t,o,r,i!=null?i:a,s)}insertEmbed(t,o,r,i,s){const l={id:K(),type:"embed",embedType:r,embedData:i};return this.insertBlock(t,o,l,s)}deleteBlock(t,o){Tg(this,t,o)}mergeTextBlock(t,o){return R6(this,t,o)}breakTextBlock(t,o,r){return Zl(this,t,o,r).newBlock}getTextPosition(){return ql(this)}getBlockString(t,o){const r=this.getBlockText(t);return rt(r,o)}getBlockData(t){return _i(this,t)}getBoxData(t){return s6(this,t)}getBlockText(t){return mn(this,t)}setBlockText(t,o){F6(this,t,o)}deleteTextFromBlock(t,o,r,i){return xg(this,t,o,r,i)}insertTextToBlock(t,o,r,i){return x6(this,t,o,r,i)}insertBoxToBlock(t,o,r){return I6(this,t,o,r)}pasteDoc(t){return this.inputHandlers.pasteDoc(t)}insertDoc(t,o,r,i){$6(this,t,o,r,i)}insertDocAt(t,o,r,i){return Og(this,t,o,r,i)}deleteChildContainers(t){M6(this,t)}replaceBlockText(t,o){return vh(this,t,o)}updateBlockData(t,o,r){const i={...this.getBlockData(t),...o},{id:s,type:l,...a}=i;return yh(this,t,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(t,o,r){return P6(this,t,o,r)}updateBoxData(t){ID(this,t)}getSelectedText(){const t=Bh(this);return Da(this,t)}clearSelectedContents(){Sg(this)}insertTextBlock(t,o,r,i){const s=sr(t!=null?t:"");return L6(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(t,o){if(t&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!t&&!o){D6(this);return}o?(this.compositingText="",Am()||Eg(this,t)):(this.compositingText=t,T6(this))}getColor(t){const o=this.options.colors;return o.length===0?"#FF1A75":o[t%o.length]}}function $a(n,e,t){return new MD(n,e,t)}function RD(n){const e=(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=sm.default(s.states,r.states)}},t=[];return n.forEach(o=>{o.forEach(r=>{e(t,r)})}),t}const OD=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class Lh extends At.TypedEmitter{constructor(t){super();g(this,"users",new Map);g(this,"cursors",new Map);g(this,"addingUser",!1);g(this,"colors");this.colors=t&&t.length>0?t:OD}setCursor(t){this.addUser(t.user);const o=this.cursors.get(t.user.userId);if(o&&la.default(o,t))return;this.cursors.set(t.user.userId,t);const r=new Set([t.range.anchor.blockId,t.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(t){this.addingUser=!0,t.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(t){this.users.set(t.userId,t),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(t){var o;return(o=this.users.get(t))!=null?o:null}removeUser(t){this.users.delete(t),this.cursors.delete(t),this.emit("change",Array.from(this.users.values()))}updateUsers(t){this.users.clear(),this.addingUser=!0;try{t.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(t){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===t&&ch(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(t){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===t||o.range.focus.blockId===t)}onUpdateBlockText(t,o,r){if(!t.text)return;this.getCursors(t.id).forEach(l=>{if(ch(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===t.id&&(a.offset=ln.transformCursor(a.offset,o,r)),d.blockId===t.id&&(d.offset=ln.transformCursor(d.offset,o,r))}})}getFixedUserColor(t,o){let r=0;Array.from(t).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const Xt=S("local-doc");class Yg extends ua{constructor(t,o){super();g(this,"doc");g(this,"serviceUrl");t?this.doc=t:this.doc={meta:{},comments:{},blocks:{root:[sr("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return fe.default(this.doc)}getContainerBlocks(t){return this.doc.blocks[t]}getBlockData(t,o){const r=this.getContainerBlocks(t);m(Xt,r,`no container data: ${t}`);const i=r[o];return m(Xt,i,`no block data: ${o}`),i}localUpdateBlockText(t,o,r){const i=this.getBlockData(t,o);m(Xt,i.text,"no text for data");const s=ln.apply(i.text,r);return i.text=s,m(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockText)==null?void 0:a.call(l,t,o,r,!0)}),s}localUpdateBlockData(t,o,r){const i=this.getBlockData(t,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),m(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,t,o,r,!0)}),i}localInsertBlock(t,o,r){const i=this.getContainerBlocks(t);return m(Xt,i,`no container data: ${t}`),m(Xt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),m(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,t,o,r,!0)}),r}localDeleteBlock(t,o){const r=this.getContainerBlocks(t);m(Xt,r,`no container data: ${t}`),m(Xt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),m(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,t,o,!0)}),i}localInsertChildContainer(t,o){this.doc.blocks[t]=o,m(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,t,o,!0)})}localDeleteChildContainers(t){Xt.debug(`delete child containers: ${t}`),t.forEach(o=>{m(Xt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),t.forEach(o=>{m(Xt,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(t,o){m(Xt,!1,"not implemented")}async addResources(t){return t}buildResourceUrl(t){return t}request(t,o){m(Xt,!1,"not implemented")}broadcastMessage(t){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Lh}setDoc(t){this.doc=fe.default(t),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class _D{constructor(e){this.cleanup=e}destroy(){var e;(e=this.cleanup)==null||e.call(this)}}function Jg(n,e,t){n.addCustom(e,()=>{var i;const o=(i=t())!=null?i:void 0;return new _D(o)})}const i7=S("find-block");function s7(n,e){const t=Ts(e);if(!t){if(oo(e))return null;const o=xs(e);return m(i7,o,"no parent block"),s7(n,o)}return Le(n,t)?zl(n,t,{visibleOnly:!0}):t}function l7(n,e){const t=Ds(e);if(!t){if(oo(e))return null;const o=xs(e);return m(i7,o,"no parent block"),l7(n,o)}return Le(n,t)?Qm(n,t,{visibleOnly:!0}):t}const FD=S("remote-cursor");class PD{constructor(){g(this,"remoteUsers",new Lh)}onCustomMessage(e){const t=e;if(t.type==="onlineUsers"){const o=t;this.handleUpdateUsers(o.users)}else t.type==="caret"?this.handleUpdateCaret(t):FD.debug(`unknown remote message received: ${e}`)}handleUpdateUsers(e){this.remoteUsers.updateUsers(e)}handleUpdateCaret(e){const t=this.remoteUsers.findUser(e.userId);!t||this.remoteUsers.setCursor({oneseditor:"cursor",user:t,range:e.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function ND(n){const{blocks:e,meta:t,comments:o,...r}=n;return{rootBlocks:e,meta:t,comments:o,childBlocks:r}}function $D(n){const{blocks:e,meta:t,comments:o}=n,{root:r,...i}=e;return{blocks:r,meta:t,comments:o,...i}}function Ha(n){const{childBlocks:e,meta:t,comments:o,rootBlocks:r}=ND(fe.default(n));return{blocks:{root:r,...e},meta:t,comments:o}}function Ni(n){return n==="root"?"blocks":n}function Jl(n){return n==="blocks"?"root":n}const HD={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new on.default(n)},apply(n,e){const t=new on.default(n),o=new on.default(e);return t.compose(o).ops},compose(n,e){const t=new on.default(n),o=new on.default(e);return t.compose(o).ops},diff(n,e){const t=new on.default(n),o=new on.default(e);return t.diff(o).ops},transform(n,e,t){const o=new on.default(n);return new on.default(e).transform(o,t==="left").ops},transformCursor(n,e,t){return e.transformPosition(n,!t)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,e,t){if(!n)return null;const o=new on.default(e),r=this.transformCursor(n.index,o,t),i=this.transformCursor(n.index+n.length,o,t);return{...n,index:r,length:i-r}}}};var cr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},$i={},Kg=U5.default.EventEmitter;$i.EventEmitter=Kg,$i.mixin=jD;function jD(n){for(var e in Kg.prototype)n.prototype[e]=Kg.prototype[e]}var c7=["info","warn","error"];function a7(){var n={};c7.forEach(function(e){n[e]=console[e].bind(console)}),this.setMethods(n)}var UD=a7;a7.prototype.setMethods=function(n){n=n||{};var e=this;c7.forEach(function(t){typeof n[t]=="function"&&(e[t]=n[t])})};var zD=UD,VD=new zD,u7=VD;function $s(n,e){this.code=n,this.message=e||"",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 Mh=$s,ja={},d7=WD;function WD(n,e,t,o){var r=function(s,l,a,d){e(a,s,l,"left"),e(d,l,s,"right")},i=n.transformX=function(s,l){t(s),t(l);for(var a=[],d=0;d<l.length;d++){for(var h=l[d],p=[],A=0;A<s.length;){var v=[];if(r(s[A],h,p,v),A++,v.length===1)h=v[0];else if(v.length===0){for(var B=A;B<s.length;B++)o(p,s[B]);h=null;break}else{for(var D=i(s.slice(A),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?e([],s[0],l[0],a):a==="left"?i(s,l)[0]:i(l,s)[1]}}var h7={exports:{}},Hi=h7.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||""}},Xg=function(n,e,t){return n.slice(0,e)+t+n.slice(e)},ep=function(n){if(typeof n.p!="number")throw new Error("component missing position field");if(typeof n.i=="string"==(typeof n.d=="string"))throw new Error("component needs an i or d field");if(n.p<0)throw new Error("position cannot be negative")},Rh=function(n){for(var e=0;e<n.length;e++)ep(n[e])};Hi.apply=function(n,e){var t;Rh(e);for(var o=0;o<e.length;o++){var r=e[o];if(r.i!=null)n=Xg(n,r.p,r.i);else{if(t=n.slice(r.p,r.p+r.d.length),r.d!==t)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+t+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var zr=Hi._append=function(n,e){if(!(e.i===""||e.d===""))if(n.length===0)n.push(e);else{var t=n[n.length-1];t.i!=null&&e.i!=null&&t.p<=e.p&&e.p<=t.p+t.i.length?n[n.length-1]={i:Xg(t.i,e.p-t.p,e.i),p:t.p}:t.d!=null&&e.d!=null&&e.p<=t.p&&t.p<=e.p+e.d.length?n[n.length-1]={d:Xg(e.d,t.p-e.p,t.d),p:e.p}:n.push(e)}};Hi.compose=function(n,e){Rh(n),Rh(e);for(var t=n.slice(),o=0;o<e.length;o++)zr(t,e[o]);return t},Hi.normalize=function(n){var e=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var t=0;t<n.length;t++){var o=n[t];o.p==null&&(o.p=0),zr(e,o)}return e};var tp=function(n,e,t){return e.i!=null?e.p<n||e.p===n&&t?n+e.i.length:n:n<=e.p?n:n<=e.p+e.d.length?e.p:n-e.d.length};Hi.transformCursor=function(n,e,t){for(var o=t==="right",r=0;r<e.length;r++)n=tp(n,e[r],o);return n};var qD=Hi._tc=function(n,e,t,o){if(ep(e),ep(t),e.i!=null)zr(n,{i:e.i,p:tp(e.p,t,o==="right")});else if(t.i!=null){var r=e.d;e.p<t.p&&(zr(n,{d:r.slice(0,t.p-e.p),p:e.p}),r=r.slice(t.p-e.p)),r!==""&&zr(n,{d:r,p:e.p+t.i.length})}else if(e.p>=t.p+t.d.length)zr(n,{d:e.d,p:e.p-t.d.length});else if(e.p+e.d.length<=t.p)zr(n,e);else{var i={d:"",p:e.p};e.p<t.p&&(i.d=e.d.slice(0,t.p-e.p)),e.p+e.d.length>t.p+t.d.length&&(i.d+=e.d.slice(t.p+t.d.length-e.p));var s=Math.max(e.p,t.p),l=Math.min(e.p+e.d.length,t.p+t.d.length),a=e.d.slice(s-e.p,l-e.p),d=t.d.slice(s-t.p,l-t.p);if(a!==d)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=tp(i.p,t),zr(n,i))}return n},GD=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Hi.invert=function(n){n=n.slice().reverse();for(var e=0;e<n.length;e++)n[e]=GD(n[e]);return n},d7(Hi,qD,Rh,zr);var Oh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},ZD=function(n){return!!n&&n.constructor===Object},_o=function(n){return JSON.parse(JSON.stringify(n))},Ie={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Vr={};Ie.registerSubtype=function(n){Vr[n.name]=n},Ie.create=function(n){return n===void 0?null:_o(n)},Ie.invertComponent=function(n){var e={p:n.p};return n.t&&Vr[n.t]&&(e.t=n.t,e.o=Vr[n.t].invert(n.o)),n.si!==void 0&&(e.sd=n.si),n.sd!==void 0&&(e.si=n.sd),n.oi!==void 0&&(e.od=n.oi),n.od!==void 0&&(e.oi=n.od),n.li!==void 0&&(e.ld=n.li),n.ld!==void 0&&(e.li=n.ld),n.na!==void 0&&(e.na=-n.na),n.lm!==void 0&&(e.lm=n.p[n.p.length-1],e.p=n.p.slice(0,n.p.length-1).concat([n.lm])),e},Ie.invert=function(n){for(var e=n.slice().reverse(),t=[],o=0;o<e.length;o++)t.push(Ie.invertComponent(e[o]));return t},Ie.checkValidOp=function(n){for(var e=0;e<n.length;e++)if(!Oh(n[e].p))throw new Error("Missing path")},Ie.checkList=function(n){if(!Oh(n))throw new Error("Referenced element not a list")},Ie.checkObj=function(n){if(!ZD(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Ua(n){n.t="text0";var e={p:n.p.pop()};n.si!=null&&(e.i=n.si),n.sd!=null&&(e.d=n.sd),n.o=[e]}function za(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}Ie.apply=function(n,e){Ie.checkValidOp(e),e=_o(e);for(var t={data:n},o=0;o<e.length;o++){var r=e[o];(r.si!=null||r.sd!=null)&&Ua(r);for(var i=null,s=t,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&&Vr[r.t])s[l]=Vr[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)Ie.checkList(s),s[l]=r.li;else if(r.li!==void 0)Ie.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)Ie.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(Ie.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)Ie.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)Ie.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return t.data},Ie.shatter=function(n){for(var e=[],t=0;t<n.length;t++)e.push([n[t]]);return e},Ie.incrementalApply=function(n,e,t){for(var o=0;o<e.length;o++){var r=[e[o]];n=Ie.apply(n,r),t(r,n)}return n};var QD=Ie.pathMatches=function(n,e,t){if(n.length!=e.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==e[o]&&(!t||o!==n.length-1))return!1;return!0};Ie.append=function(n,e){if(e=_o(e),n.length===0){n.push(e);return}var t=n[n.length-1];if((e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(Ua(e),Ua(t)),QD(e.p,t.p))if(e.t&&t.t&&e.t===t.t&&Vr[e.t]){if(t.o=Vr[e.t].compose(t.o,e.o),e.si!=null||e.sd!=null){for(var o=e.p,r=0;r<t.o.length-1;r++)e.o=[t.o.pop()],e.p=o.slice(),za(e),n.push(e);za(t)}}else t.na!=null&&e.na!=null?n[n.length-1]={p:t.p,na:t.na+e.na}:t.li!==void 0&&e.li===void 0&&e.ld===t.li?t.ld!==void 0?delete t.li:n.pop():t.od!==void 0&&t.oi===void 0&&e.oi!==void 0&&e.od===void 0?t.oi=e.oi:t.oi!==void 0&&e.od!==void 0?e.oi!==void 0?t.oi=e.oi:t.od!==void 0?delete t.oi:n.pop():e.lm!==void 0&&e.p[e.p.length-1]===e.lm||n.push(e);else(e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(za(e),za(t)),n.push(e)},Ie.compose=function(n,e){Ie.checkValidOp(n),Ie.checkValidOp(e);for(var t=_o(n),o=0;o<e.length;o++)Ie.append(t,e[o]);return t},Ie.normalize=function(n){var e=[];n=Oh(n)?n:[n];for(var t=0;t<n.length;t++){var o=n[t];o.p==null&&(o.p=[]),Ie.append(e,o)}return e},Ie.commonLengthForOps=function(n,e){var t=n.p.length,o=e.p.length;if((n.na!=null||n.t)&&t++,(e.na!=null||e.t)&&o++,t===0)return-1;if(o===0)return null;t--,o--;for(var r=0;r<t;r++){var i=n.p[r];if(r>=o||i!==e.p[r])return null}return t},Ie.canOpAffectPath=function(n,e){return Ie.commonLengthForOps({p:e},n)!=null},Ie.transformComponent=function(n,e,t,o){e=_o(e);var r=Ie.commonLengthForOps(t,e),i=Ie.commonLengthForOps(e,t),s=e.p.length,l=t.p.length;if((e.na!=null||e.t)&&s++,(t.na!=null||t.t)&&l++,i!=null&&l>s&&e.p[i]==t.p[i]){if(e.ld!==void 0){var a=_o(t);a.p=a.p.slice(s),e.ld=Ie.apply(_o(e.ld),[a])}else if(e.od!==void 0){var a=_o(t);a.p=a.p.slice(s),e.od=Ie.apply(_o(e.od),[a])}}if(r!=null){var d=s==l,a=t;if((e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(Ua(e),a=_o(t),Ua(a)),a.t&&Vr[a.t]){if(e.t&&e.t===a.t){var h=Vr[e.t].transform(e.o,a.o,o);if(e.si!=null||e.sd!=null)for(var p=e.p,A=0;A<h.length;A++)e.o=[h[A]],e.p=p.slice(),za(e),Ie.append(n,e);else(!Oh(h)||h.length>0)&&(e.o=h,Ie.append(n,e));return n}}else if(t.na===void 0){if(t.li!==void 0&&t.ld!==void 0){if(t.p[r]===e.p[r])if(d){if(e.ld!==void 0)if(e.li!==void 0&&o==="left")e.ld=_o(t.li);else return n}else return n}else if(t.li!==void 0)e.li!==void 0&&e.ld===void 0&&d&&e.p[r]===t.p[r]?o==="right"&&e.p[r]++:t.p[r]<=e.p[r]&&e.p[r]++,e.lm!==void 0&&d&&t.p[r]<=e.lm&&e.lm++;else if(t.ld!==void 0){if(e.lm!==void 0&&d){if(t.p[r]===e.p[r])return n;var p=t.p[r],v=e.p[r],B=e.lm;(p<B||p===B&&v<B)&&e.lm--}if(t.p[r]<e.p[r])e.p[r]--;else if(t.p[r]===e.p[r]){if(l<s)return n;if(e.ld!==void 0)if(e.li!==void 0)delete e.ld;else return n}}else if(t.lm!==void 0)if(e.lm!==void 0&&s===l){var v=e.p[r],B=e.lm,D=t.p[r],x=t.lm;if(D!==x)if(v===D)if(o==="left")e.p[r]=x,v===B&&(e.lm=x);else return n;else v>D&&e.p[r]--,v>x?e.p[r]++:v===x&&D>x&&(e.p[r]++,v===B&&e.lm++),(B>D||B===D&&B>v)&&e.lm--,B>x?e.lm++:B===x&&(x>D&&B>v||x<D&&B<v?o==="right"&&e.lm++:B>v?e.lm++:B===D&&e.lm--)}else if(e.li!==void 0&&e.ld===void 0&&d){var v=t.p[r],B=t.lm;p=e.p[r],p>v&&e.p[r]--,p>B&&e.p[r]++}else{var v=t.p[r],B=t.lm;p=e.p[r],p===v?e.p[r]=B:(p>v&&e.p[r]--,(p>B||p===B&&v>B)&&e.p[r]++)}else if(t.oi!==void 0&&t.od!==void 0){if(e.p[r]===t.p[r])if(e.oi!==void 0&&d){if(o==="right")return n;e.od=t.oi}else return n}else if(t.oi!==void 0){if(e.oi!==void 0&&e.p[r]===t.p[r])if(o==="left")Ie.append(n,{p:e.p,od:t.oi});else return n}else if(t.od!==void 0&&e.p[r]==t.p[r]){if(!d)return n;if(e.oi!==void 0)delete e.od;else return n}}}return Ie.append(n,e),n},d7(Ie,Ie.transformComponent,Ie.checkValidOp,Ie.append);var YD=h7.exports;Ie.registerSubtype(YD);var JD=Ie,KD={type:JD};(function(n){n.defaultType=KD.type,n.map={},n.register=function(e){e.name&&(n.map[e.name]=e),e.uri&&(n.map[e.uri]=e)},n.register(n.defaultType)})(ja);var Fo={};(function(n){n.doNothing=e;function e(){}n.hasKeys=function(t){for(var o in t)return!0;return!1},n.isInteger=Number.isInteger||function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t},n.isValidVersion=function(t){return t===null?!0:n.isInteger(t)&&t>=0},n.isValidTimestamp=function(t){return n.isValidVersion(t)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var t=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];t=t[r]||(o===arguments.length-1?void 0:{})}return t},n.digOrCreate=function(){for(var t=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];t=t[i]||(t[i]=r===arguments.length-2?o():{})}return t},n.digAndRemove=function(){for(var t=arguments[0],o=[t],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!t.hasOwnProperty(i))break;t=t[i],o.push(t)}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(t){return t&&typeof t.transformPresence=="function"},n.callEach=function(t,o){var r=!1;return t.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(t){return!!t},n.nextTick=function(t){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(){t.apply(null,o)})},n.clone=function(t){return t===void 0?void 0:JSON.parse(JSON.stringify(t))}})(Fo);var f7=Array.isArray,m7=Object.keys,XD=Object.prototype.hasOwnProperty,eS=function n(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var o=f7(e),r=f7(t),i,s,l;if(o&&r){if(s=e.length,s!=t.length)return!1;for(i=s;i--!==0;)if(!n(e[i],t[i]))return!1;return!0}if(o!=r)return!1;var a=e instanceof Date,d=t instanceof Date;if(a!=d)return!1;if(a&&d)return e.getTime()==t.getTime();var h=e instanceof RegExp,p=t instanceof RegExp;if(h!=p)return!1;if(h&&p)return e.toString()==t.toString();var A=m7(e);if(s=A.length,s!==m7(t).length)return!1;for(i=s;i--!==0;)if(!XD.call(t,A[i]))return!1;for(i=s;i--!==0;)if(l=A[i],!n(e[l],t[l]))return!1;return!0}return e!==e&&t!==t},g7=$i,tS=u7,Wn=Mh,_h=ja,Po=Fo,nS=Po.clone,oS=eS,Tn=Wn.CODES,rS=Fe;function Fe(n,e,t){g7.EventEmitter.call(this),this.connection=n,this.collection=e,this.id=t,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}g7.mixin(Fe),Fe.prototype.destroy=function(n){this._wantsDestroy=!0;var e=this;e.whenNothingPending(function(){e.wantSubscribe?e.unsubscribe(function(t){if(t)return n?n(t):e.emit("error",t);e.connection._destroyDoc(e),n&&n()}):(e.connection._destroyDoc(e),n&&n())})},Fe.prototype._setType=function(n){if(typeof n=="string"&&(n=_h.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var e=new Wn(Tn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",e)}},Fe.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Fe.prototype.ingestSnapshot=function(n,e){if(!n)return e&&e();if(typeof n.v!="number"){var t=new Wn(Tn.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return e?e(t):this.emit("error",t)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return e&&this.once("no write pending",e);var t=new Wn(Tn.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return e?e(t):this.emit("error",t)}return n.v>this.version?this.fetch(e):e&&e()}if(this.version>n.v)return e&&e();this.version=n.v;var o=n.type===void 0?_h.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),e&&e()},Fe.prototype.whenNothingPending=function(n){var e=this;Po.nextTick(function(){if(e.hasPending()){e.once("nothing pending",n);return}n()})},Fe.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Fe.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Fe.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Fe.prototype._emitResponseError=function(n,e){if(n&&n.code===Tn.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,e&&e(),this._emitNothingPending();return}if(e){e(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},Fe.prototype._handleFetch=function(n,e){var t=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&t.push(o),t.length&&(o=function(r){Po.callEach(t,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(e,o),this._emitNothingPending()},Fe.prototype._handleSubscribe=function(n,e){var t=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],t.callback&&o.push(t.callback);var r;if(o.length&&(r=function(i){Po.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=t.wantSubscribe,this.subscribed?this.ingestSnapshot(e,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},Fe.prototype._handleOp=function(n,e){if(n)return this.inflightOp?(n.code===Tn.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&e.src===this.inflightOp.src&&e.seq===this.inflightOp.seq){this._opAcknowledged(e);return}if(this.version==null||e.v>this.version){this.fetch();return}if(!(e.v<this.version)){if(this.inflightOp){var t=Fh(this.inflightOp,e);if(t)return this._hardRollback(t)}for(var o=0;o<this.pendingOps.length;o++){var t=Fh(this.pendingOps[o],e);if(t)return this._hardRollback(t)}this.version++;try{this._otApply(e,!1)}catch(r){return this._hardRollback(r)}}},Fe.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))},Fe.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(e){return e.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},Fe.prototype.fetch=function(n){if(this.connection.canSend){var e=this.connection.sendFetch(this);iS(this.inflightFetch,e,n);return}this.pendingFetch.push(n)},Fe.prototype.subscribe=function(n){var e=!0;this._queueSubscribe(e,n)},Fe.prototype.unsubscribe=function(n){var e=!1;this._queueSubscribe(e,n)},Fe.prototype._queueSubscribe=function(n,e){var t=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=t&&t.wantSubscribe===n;if(o){t.callback=sS([t.callback,e]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:e}),this._flushSubscribe()},Fe.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;Po.nextTick(function(){n._handleSubscribe()})}}};function iS(n,e,t){if(e){var o=n.pop();n.push(function(r){o&&o(r),t&&t(r)})}else n.push(t)}function sS(n){return n=n.filter(Po.truthy),n.length?function(e){Po.callEach(n,e)}:null}Fe.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function lS(n){delete n.op,delete n.create,delete n.del}function Fh(n,e){if(n.del)return lS(e);if(e.del)return new Wn(Tn.ERR_DOC_WAS_DELETED,"Document was deleted");if(e.create)return new Wn(Tn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in e){if(n.create)return new Wn(Tn.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var t=n.type.transformX(n.op,e.op);n.op=t[0],e.op=t[1]}else{var o=n.type.transform(n.op,e.op,"left"),r=n.type.transform(e.op,n.op,"right");n.op=o,e.op=r}}}Fe.prototype._otApply=function(n,e){if("op"in n){if(!this.type)throw new Wn(Tn.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,e),!e&&this.type===_h.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var t=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,e,n.src);for(var s=t;s<this.applyStack.length;s++){var l=Fh(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,e,n.src)}this.emit("op batch",n.op,e),this._popApplyStack(t);return}this.emit("before op",n.op,e,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,e,n.src),this.emit("op batch",n.op,e);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",e);return}if(n.del){var a=this.data;this._setType(null),this.emit("del",a,e);return}},Fe.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var e=this.inflightOp;if(!e){var t=new Wn(Tn.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",t)}if(e.sentAt=Date.now(),e.retries=e.retries==null?0:e.retries+1,e.seq==null){if(this.connection.seq>=Po.MAX_SAFE_INTEGER)return this.emit("error",new Wn(Tn.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));e.seq=this.connection.seq++}this.connection.sendOp(this,e),e.src==null&&(e.src=n)}},Fe.prototype._submit=function(n,e,t){if(e||(e=!0),"op"in n){if(!this.type){var o=new Wn(Tn.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return t?t(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,e,t),this._otApply(n,e)}catch(i){return this._hardRollback(i)}var r=this;Po.nextTick(function(){r.flush()})},Fe.prototype._pushOp=function(n,e,t){if(n.source=e,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(t);return}}n.type=this.type,n.callbacks=[t],this.pendingOps.push(n)},Fe.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var e=this.applyStack[0];if(this.applyStack=null,!!e){var t=this.pendingOps.indexOf(e);if(t!==-1)for(var o=this.pendingOps.splice(t),t=0;t<o.length;t++){var e=o[t],r=this._tryCompose(e);r?r.callbacks=r.callbacks.concat(e.callbacks):this.pendingOps.push(e)}}},Fe.prototype._tryCompose=function(n){if(!this.preventCompose){var e=this.pendingOps[this.pendingOps.length-1];if(!(!e||e.sentAt)&&!(this.submitSource&&!oS(n.source,e.source))){if(e.create&&"op"in n)return e.create.data=this.type.apply(e.create.data,n.op),e;if("op"in e&&"op"in n&&this.type.compose)return e.op=this.type.compose(e.op,n.op),e}}},Fe.prototype.submitOp=function(n,e,t){typeof e=="function"&&(t=e,e=null);var o={op:n},r=e&&e.source;this._submit(o,r,t)},Fe.prototype.create=function(n,e,t,o){if(typeof e=="function"?(o=e,t=null,e=null):typeof t=="function"&&(o=t,t=null),e||(e=_h.defaultType.uri),this.type){var r=new Wn(Tn.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:e,data:n}},s=t&&t.source;this._submit(i,s,o)},Fe.prototype.del=function(n,e){if(typeof n=="function"&&(e=n,n=null),!this.type){var t=new Wn(Tn.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return e?e(t):this.emit("error",t)}var o={del:!0},r=n&&n.source;this._submit(o,r,e)},Fe.prototype.pause=function(){this.paused=!0},Fe.prototype.resume=function(){this.paused=!1,this.flush()},Fe.prototype.toSnapshot=function(){return{v:this.version,data:nS(this.data),type:this.type.uri}},Fe.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return tS.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},Fe.prototype._rollback=function(n){var e=this.inflightOp;if("op"in e&&e.type.invert){try{e.op=e.type.invert(e.op)}catch{return this._hardRollback(n)}for(var t=0;t<this.pendingOps.length;t++){var o=Fh(this.pendingOps[t],e);if(o)return this._hardRollback(o)}try{this._otApply(e,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},Fe.prototype._hardRollback=function(n){var e=[];this.inflightOp&&e.push(this.inflightOp),e=e.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var t=this;this.fetch(function(){for(var o=!!e.length,r=0;r<e.length;r++)o=Po.callEach(e[r].callbacks,n)&&o;if(n&&!o)return t.emit("error",n)})},Fe.prototype._clearInflightOp=function(n){var e=this.inflightOp;this.inflightOp=null;var t=Po.callEach(e.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!t)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 p7=$i,C7=Hs.ACTIONS,cS=Fo,aS=Dn;function Dn(n,e,t,o,r,i,s){p7.EventEmitter.call(this),this.action=n,this.connection=e,this.id=t,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}p7.mixin(Dn),Dn.prototype.hasPending=function(){return!this.ready},Dn.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 e=[],t=0;t<this.results.length;t++){var o=this.results[t];e.push([o.id,o.version])}n.r=e}this.connection.send(n),this.sent=!0}},Dn.prototype.destroy=function(n){this.connection.canSend&&this.action===C7.querySubscribe&&this.connection.send({a:C7.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&cS.nextTick(n)},Dn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Dn.prototype._handleFetch=function(n,e,t){this.connection._destroyQuery(this),this._handleResponse(n,e,t)},Dn.prototype._handleSubscribe=function(n,e,t){this._handleResponse(n,e,t)},Dn.prototype._handleResponse=function(n,e,t){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!e)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(e))i+=e.length,this.results=this._ingestSnapshots(e,s),this.extra=t;else for(var l in e){i++;var a=e[l],d=this.connection.get(a.c||this.collection,l);d.ingestSnapshot(a,s)}s()},Dn.prototype._ingestSnapshots=function(n,e){for(var t=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,e),t.push(i)}return t},Dn.prototype._finishResponse=function(n,e){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),e?e(n):this.emit("error",n);e&&e(null,this.results,this.extra)},Dn.prototype._handleError=function(n){this.emit("error",n)},Dn.prototype._handleDiff=function(n){for(var e=0;e<n.length;e++){var t=n[e];t.type==="insert"&&(t.values=this._ingestSnapshots(t.values))}for(var e=0;e<n.length;e++){var t=n[e];switch(t.type){case"insert":var o=t.values;Array.prototype.splice.apply(this.results,[t.index,0].concat(o)),this.emit("insert",o,t.index);break;case"remove":var i=t.howMany||1,r=this.results.splice(t.index,i);this.emit("remove",r,t.index);break;case"move":var i=t.howMany||1,s=this.results.splice(t.from,i);Array.prototype.splice.apply(this.results,[t.to,0].concat(s)),this.emit("move",s,t.from,t.to);break}}this.emit("changed",this.results)},Dn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var A7=$i,uS=Hs.ACTIONS,dS=Fo,b7=ar;function ar(n,e){if(A7.EventEmitter.call(this),!e||typeof e!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=e,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}A7.mixin(ar),ar.prototype.submit=function(n,e){this.value=n,this.send(e)},ar.prototype.send=function(n){var e=this._message();this._pendingMessages.push(e),this._callbacksByPresenceVersion[e.pv]=n,this._sendPending()},ar.prototype.destroy=function(n){var e=this;this.submit(null,function(t){if(t)return e._callbackOrEmit(t,n);delete e.presence.localPresences[e.presenceId],n&&n()})},ar.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(e){n.connection.send(e)}),this._pendingMessages=[]}},ar.prototype._ack=function(n,e){var t=this._getCallback(e);this._callbackOrEmit(n,t)},ar.prototype._message=function(){return{a:uS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},ar.prototype._getCallback=function(n){var e=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],e},ar.prototype._callbackOrEmit=function(n,e){if(e)return dS.nextTick(e,n);n&&this.emit("error",n)};var hS=Fo,v7=np;function np(n,e){this.presence=n,this.presenceId=e,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}np.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},np.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&hS.nextTick(n)};var op={exports:{}};(function(n,e){(function(t,o){o(e)})(cr,function(t){function o(k,T){T=T|0;for(var L=Math.max(k.length-T,0),F=Array(L),U=0;U<L;U++)F[U]=k[T+U];return F}var r=function(k){var T=o(arguments,1);return function(){var L=o(arguments);return k.apply(null,T.concat(L))}},i=function(k){return function(){var T=o(arguments),L=T.pop();k.call(this,T,L)}};function s(k){var T=typeof k;return k!=null&&(T=="object"||T=="function")}var l=typeof setImmediate=="function"&&setImmediate,a=typeof process=="object"&&typeof process.nextTick=="function";function d(k){setTimeout(k,0)}function h(k){return function(T){var L=o(arguments,1);k(function(){T.apply(null,L)})}}var p;l?p=setImmediate:a?p=process.nextTick:p=d;var A=h(p);function v(k){return i(function(T,L){var F;try{F=k.apply(this,T)}catch(U){return L(U)}s(F)&&typeof F.then=="function"?F.then(function(U){B(L,null,U)},function(U){B(L,U.message?U:new Error(U))}):L(null,F)})}function B(k,T,L){try{k(T,L)}catch(F){A(D,F)}}function D(k){throw k}var x=typeof Symbol=="function";function _(k){return x&&k[Symbol.toStringTag]==="AsyncFunction"}function M(k){return _(k)?v(k):k}function j(k){return function(T){var L=o(arguments,1),F=i(function(U,H){var Z=this;return k(T,function(J,le){M(J).apply(Z,U.concat(le))},H)});return L.length?F.apply(this,L):F}}var z=typeof cr=="object"&&cr&&cr.Object===Object&&cr,q=typeof self=="object"&&self&&self.Object===Object&&self,ie=z||q||Function("return this")(),me=ie.Symbol,Be=Object.prototype,je=Be.hasOwnProperty,Ue=Be.toString,tt=me?me.toStringTag:void 0;function Yt(k){var T=je.call(k,tt),L=k[tt];try{k[tt]=void 0;var F=!0}catch{}var U=Ue.call(k);return F&&(T?k[tt]=L:delete k[tt]),U}var Wo=Object.prototype,Nt=Wo.toString;function Ln(k){return Nt.call(k)}var br="[object Null]",bn="[object Undefined]",an=me?me.toStringTag:void 0;function vr(k){return k==null?k===void 0?bn:br:an&&an in Object(k)?Yt(k):Ln(k)}var ti="[object AsyncFunction]",fo="[object Function]",Z2="[object GeneratorFunction]",Q2="[object Proxy]";function Y2(k){if(!s(k))return!1;var T=vr(k);return T==fo||T==Z2||T==ti||T==Q2}var ts=9007199254740991;function tl(k){return typeof k=="number"&&k>-1&&k%1==0&&k<=ts}function nl(k){return k!=null&&tl(k.length)&&!Y2(k)}var ni={};function Ne(){}function yr(k){return function(){if(k!==null){var T=k;k=null,T.apply(this,arguments)}}}var ns=typeof Symbol=="function"&&Symbol.iterator,Oc=function(k){return ns&&k[ns]&&k[ns]()};function Xf(k,T){for(var L=-1,F=Array(k);++L<k;)F[L]=T(L);return F}function un(k){return k!=null&&typeof k=="object"}var ol="[object Arguments]";function e1(k){return un(k)&&vr(k)==ol}var mo=Object.prototype,t1=mo.hasOwnProperty,J2=mo.propertyIsEnumerable,rl=e1(function(){return arguments}())?e1:function(k){return un(k)&&t1.call(k,"callee")&&!J2.call(k,"callee")},pt=Array.isArray;function il(){return!1}var sl=typeof t=="object"&&t&&!t.nodeType&&t,n1=sl&&!0&&n&&!n.nodeType&&n,ll=n1&&n1.exports===sl,o1=ll?ie.Buffer:void 0,cl=o1?o1.isBuffer:void 0,os=cl||il,Nu=9007199254740991,$u=/^(?:0|[1-9]\d*)$/;function Hu(k,T){var L=typeof k;return T=T==null?Nu:T,!!T&&(L=="number"||L!="symbol"&&$u.test(k))&&k>-1&&k%1==0&&k<T}var ju="[object Arguments]",Uu="[object Array]",zu="[object Boolean]",Vu="[object Date]",Wu="[object Error]",qu="[object Function]",K2="[object Map]",X2="[object Number]",e3="[object Object]",r1="[object RegExp]",i1="[object Set]",t3="[object String]",n3="[object WeakMap]",o3="[object ArrayBuffer]",r3="[object DataView]",s1="[object Float32Array]",i3="[object Float64Array]",s3="[object Int8Array]",l3="[object Int16Array]",Gu="[object Int32Array]",c3="[object Uint8Array]",Zu="[object Uint8ClampedArray]",a3="[object Uint16Array]",u3="[object Uint32Array]",it={};it[s1]=it[i3]=it[s3]=it[l3]=it[Gu]=it[c3]=it[Zu]=it[a3]=it[u3]=!0,it[ju]=it[Uu]=it[o3]=it[zu]=it[r3]=it[Vu]=it[Wu]=it[qu]=it[K2]=it[X2]=it[e3]=it[r1]=it[i1]=it[t3]=it[n3]=!1;function d3(k){return un(k)&&tl(k.length)&&!!it[vr(k)]}function h3(k){return function(T){return k(T)}}var l1=typeof t=="object"&&t&&!t.nodeType&&t,al=l1&&!0&&n&&!n.nodeType&&n,f3=al&&al.exports===l1,_c=f3&&z.process,c1=function(){try{var k=al&&al.require&&al.require("util").types;return k||_c&&_c.binding&&_c.binding("util")}catch{}}(),a1=c1&&c1.isTypedArray,m3=a1?h3(a1):d3,g3=Object.prototype,p3=g3.hasOwnProperty;function C3(k,T){var L=pt(k),F=!L&&rl(k),U=!L&&!F&&os(k),H=!L&&!F&&!U&&m3(k),Z=L||F||U||H,J=Z?Xf(k.length,String):[],le=J.length;for(var pe in k)(T||p3.call(k,pe))&&!(Z&&(pe=="length"||U&&(pe=="offset"||pe=="parent")||H&&(pe=="buffer"||pe=="byteLength"||pe=="byteOffset")||Hu(pe,le)))&&J.push(pe);return J}var Fc=Object.prototype;function A3(k){var T=k&&k.constructor,L=typeof T=="function"&&T.prototype||Fc;return k===L}function Pc(k,T){return function(L){return k(T(L))}}var b3=Pc(Object.keys,Object),v3=Object.prototype,y3=v3.hasOwnProperty;function u1(k){if(!A3(k))return b3(k);var T=[];for(var L in Object(k))y3.call(k,L)&&L!="constructor"&&T.push(L);return T}function Nc(k){return nl(k)?C3(k):u1(k)}function d1(k){var T=-1,L=k.length;return function(){return++T<L?{value:k[T],key:T}:null}}function k3(k){var T=-1;return function(){var F=k.next();return F.done?null:(T++,{value:F.value,key:T})}}function w3(k){var T=Nc(k),L=-1,F=T.length;return function U(){var H=T[++L];return H==="__proto__"?U():L<F?{value:k[H],key:H}:null}}function B3(k){if(nl(k))return d1(k);var T=Oc(k);return T?k3(T):w3(k)}function go(k){return function(){if(k===null)throw new Error("Callback was already called.");var T=k;k=null,T.apply(this,arguments)}}function ul(k){return function(T,L,F){if(F=yr(F||Ne),k<=0||!T)return F(null);var U=B3(T),H=!1,Z=0,J=!1;function le(ce,Ae){if(Z-=1,ce)H=!0,F(ce);else{if(Ae===ni||H&&Z<=0)return H=!0,F(null);J||pe()}}function pe(){for(J=!0;Z<k&&!H;){var ce=U();if(ce===null){H=!0,Z<=0&&F(null);return}Z+=1,L(ce.value,ce.key,go(le))}J=!1}pe()}}function kr(k,T,L,F){ul(T)(k,M(L),F)}function $t(k,T){return function(L,F,U){return k(L,T,F,U)}}function Qu(k,T,L){L=yr(L||Ne);var F=0,U=0,H=k.length;H===0&&L(null);function Z(J,le){J?L(J):(++U===H||le===ni)&&L(null)}for(;F<H;F++)T(k[F],F,go(Z))}var E3=$t(kr,1/0),qo=function(k,T,L){var F=nl(k)?Qu:E3;F(k,M(T),L)};function Go(k){return function(T,L,F){return k(qo,T,M(L),F)}}function Yu(k,T,L,F){F=F||Ne,T=T||[];var U=[],H=0,Z=M(L);k(T,function(J,le,pe){var ce=H++;Z(J,function(Ae,Ge){U[ce]=Ge,pe(Ae)})},function(J){F(J,U)})}var $c=Go(Yu),Ju=j($c);function oi(k){return function(T,L,F,U){return k(ul(L),T,M(F),U)}}var wr=oi(Yu),Ku=$t(wr,1),Xu=j(Ku);function rs(k,T){for(var L=-1,F=k==null?0:k.length;++L<F&&T(k[L],L,k)!==!1;);return k}function ed(k){return function(T,L,F){for(var U=-1,H=Object(T),Z=F(T),J=Z.length;J--;){var le=Z[k?J:++U];if(L(H[le],le,H)===!1)break}return T}}var is=ed();function ss(k,T){return k&&is(k,T,Nc)}function h1(k,T,L,F){for(var U=k.length,H=L+(F?1:-1);F?H--:++H<U;)if(T(k[H],H,k))return H;return-1}function x3(k){return k!==k}function f1(k,T,L){for(var F=L-1,U=k.length;++F<U;)if(k[F]===T)return F;return-1}function dl(k,T,L){return T===T?f1(k,T,L):h1(k,x3,L)}var Hc=function(k,T,L){typeof T=="function"&&(L=T,T=null),L=yr(L||Ne);var F=Nc(k),U=F.length;if(!U)return L(null);T||(T=U);var H={},Z=0,J=!1,le=Object.create(null),pe=[],ce=[],Ae={};ss(k,function(ut,ot){if(!pt(ut)){Ge(ot,[ut]),ce.push(ot);return}var mt=ut.slice(0,ut.length-1),Co=mt.length;if(Co===0){Ge(ot,ut),ce.push(ot);return}Ae[ot]=Co,rs(mt,function(E){if(!k[E])throw new Error("async.auto task `"+ot+"` has a non-existent dependency `"+E+"` in "+mt.join(", "));tn(E,function(){Co--,Co===0&&Ge(ot,ut)})})}),Z3(),It();function Ge(ut,ot){pe.push(function(){po(ut,ot)})}function It(){if(pe.length===0&&Z===0)return L(null,H);for(;pe.length&&Z<T;){var ut=pe.shift();ut()}}function tn(ut,ot){var mt=le[ut];mt||(mt=le[ut]=[]),mt.push(ot)}function On(ut){var ot=le[ut]||[];rs(ot,function(mt){mt()}),It()}function po(ut,ot){if(!J){var mt=go(function(E,xr){if(Z--,arguments.length>2&&(xr=o(arguments,1)),E){var us={};ss(H,function(_n,Pe){us[Pe]=_n}),us[ut]=xr,J=!0,le=Object.create(null),L(E,us)}else H[ut]=xr,On(ut)});Z++;var Co=M(ot[ot.length-1]);ot.length>1?Co(H,mt):Co(mt)}}function Z3(){for(var ut,ot=0;ce.length;)ut=ce.pop(),ot++,rs(Q3(ut),function(mt){--Ae[mt]===0&&ce.push(mt)});if(ot!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function Q3(ut){var ot=[];return ss(k,function(mt,Co){pt(mt)&&dl(mt,ut,0)>=0&&ot.push(Co)}),ot}};function ri(k,T){for(var L=-1,F=k==null?0:k.length,U=Array(F);++L<F;)U[L]=T(k[L],L,k);return U}var I3="[object Symbol]";function T3(k){return typeof k=="symbol"||un(k)&&vr(k)==I3}var D3=1/0,td=me?me.prototype:void 0,m1=td?td.toString:void 0;function nd(k){if(typeof k=="string")return k;if(pt(k))return ri(k,nd)+"";if(T3(k))return m1?m1.call(k):"";var T=k+"";return T=="0"&&1/k==-D3?"-0":T}function S3(k,T,L){var F=-1,U=k.length;T<0&&(T=-T>U?0:U+T),L=L>U?U:L,L<0&&(L+=U),U=T>L?0:L-T>>>0,T>>>=0;for(var H=Array(U);++F<U;)H[F]=k[F+T];return H}function L3(k,T,L){var F=k.length;return L=L===void 0?F:L,!T&&L>=F?k:S3(k,T,L)}function od(k,T){for(var L=k.length;L--&&dl(T,k[L],0)>-1;);return L}function M3(k,T){for(var L=-1,F=k.length;++L<F&&dl(T,k[L],0)>-1;);return L}function R3(k){return k.split("")}var O3="\\ud800-\\udfff",_3="\\u0300-\\u036f",F3="\\ufe20-\\ufe2f",st="\\u20d0-\\u20ff",nt=_3+F3+st,P3="\\ufe0e\\ufe0f",N3="\\u200d",$3=RegExp("["+N3+O3+nt+P3+"]");function H3(k){return $3.test(k)}var g1="\\ud800-\\udfff",j3="\\u0300-\\u036f",p1="\\ufe20-\\ufe2f",U3="\\u20d0-\\u20ff",qt=j3+p1+U3,rd="\\ufe0e\\ufe0f",ii="["+g1+"]",jc="["+qt+"]",hl="\\ud83c[\\udffb-\\udfff]",Mn="(?:"+jc+"|"+hl+")",id="[^"+g1+"]",sd="(?:\\ud83c[\\udde6-\\uddff]){2}",ld="[\\ud800-\\udbff][\\udc00-\\udfff]",C1="\\u200d",cd=Mn+"?",ad="["+rd+"]?",vn="(?:"+C1+"(?:"+[id,sd,ld].join("|")+")"+ad+cd+")*",z3=ad+cd+vn,Rn="(?:"+[id+jc+"?",jc,sd,ld,ii].join("|")+")",V3=RegExp(hl+"(?="+hl+")|"+Rn+z3,"g");function A1(k){return k.match(V3)||[]}function Zo(k){return H3(k)?A1(k):R3(k)}function Uc(k){return k==null?"":nd(k)}var ud=/^\s+|\s+$/g;function at(k,T,L){if(k=Uc(k),k&&(L||T===void 0))return k.replace(ud,"");if(!k||!(T=nd(T)))return k;var F=Zo(k),U=Zo(T),H=M3(F,U),Z=od(F,U)+1;return L3(F,H,Z).join("")}var Br=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,dd=/,/,W3=/(=.+)?(\s*)$/,hd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function q3(k){return k=k.toString().replace(hd,""),k=k.match(Br)[2].replace(" ",""),k=k?k.split(dd):[],k=k.map(function(T){return at(T.replace(W3,""))}),k}function b1(k,T){var L={};ss(k,function(F,U){var H,Z=_(F),J=!Z&&F.length===1||Z&&F.length===0;if(pt(F))H=F.slice(0,-1),F=F[F.length-1],L[U]=H.concat(H.length>0?le:F);else if(J)L[U]=F;else{if(H=q3(F),F.length===0&&!Z&&H.length===0)throw new Error("autoInject task functions require explicit parameters.");Z||H.pop(),L[U]=H.concat(le)}function le(pe,ce){var Ae=ri(H,function(Ge){return pe[Ge]});Ae.push(ce),M(F).apply(null,Ae)}}),Hc(L,T)}function Yn(){this.head=this.tail=null,this.length=0}function fd(k,T){k.length=1,k.head=k.tail=T}Yn.prototype.removeLink=function(k){return k.prev?k.prev.next=k.next:this.head=k.next,k.next?k.next.prev=k.prev:this.tail=k.prev,k.prev=k.next=null,this.length-=1,k},Yn.prototype.empty=function(){for(;this.head;)this.shift();return this},Yn.prototype.insertAfter=function(k,T){T.prev=k,T.next=k.next,k.next?k.next.prev=T:this.tail=T,k.next=T,this.length+=1},Yn.prototype.insertBefore=function(k,T){T.prev=k.prev,T.next=k,k.prev?k.prev.next=T:this.head=T,k.prev=T,this.length+=1},Yn.prototype.unshift=function(k){this.head?this.insertBefore(this.head,k):fd(this,k)},Yn.prototype.push=function(k){this.tail?this.insertAfter(this.tail,k):fd(this,k)},Yn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},Yn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},Yn.prototype.toArray=function(){for(var k=Array(this.length),T=this.head,L=0;L<this.length;L++)k[L]=T.data,T=T.next;return k},Yn.prototype.remove=function(k){for(var T=this.head;T;){var L=T.next;k(T)&&this.removeLink(T),T=L}return this};function fl(k,T,L){if(T==null)T=1;else if(T===0)throw new Error("Concurrency must not be zero");var F=M(k),U=0,H=[],Z=!1;function J(Ae,Ge,It){if(It!=null&&typeof It!="function")throw new Error("task callback must be a function");if(ce.started=!0,pt(Ae)||(Ae=[Ae]),Ae.length===0&&ce.idle())return A(function(){ce.drain()});for(var tn=0,On=Ae.length;tn<On;tn++){var po={data:Ae[tn],callback:It||Ne};Ge?ce._tasks.unshift(po):ce._tasks.push(po)}Z||(Z=!0,A(function(){Z=!1,ce.process()}))}function le(Ae){return function(Ge){U-=1;for(var It=0,tn=Ae.length;It<tn;It++){var On=Ae[It],po=dl(H,On,0);po===0?H.shift():po>0&&H.splice(po,1),On.callback.apply(On,arguments),Ge!=null&&ce.error(Ge,On.data)}U<=ce.concurrency-ce.buffer&&ce.unsaturated(),ce.idle()&&ce.drain(),ce.process()}}var pe=!1,ce={_tasks:new Yn,concurrency:T,payload:L,saturated:Ne,unsaturated:Ne,buffer:T/4,empty:Ne,drain:Ne,error:Ne,started:!1,paused:!1,push:function(Ae,Ge){J(Ae,!1,Ge)},kill:function(){ce.drain=Ne,ce._tasks.empty()},unshift:function(Ae,Ge){J(Ae,!0,Ge)},remove:function(Ae){ce._tasks.remove(Ae)},process:function(){if(!pe){for(pe=!0;!ce.paused&&U<ce.concurrency&&ce._tasks.length;){var Ae=[],Ge=[],It=ce._tasks.length;ce.payload&&(It=Math.min(It,ce.payload));for(var tn=0;tn<It;tn++){var On=ce._tasks.shift();Ae.push(On),H.push(On),Ge.push(On.data)}U+=1,ce._tasks.length===0&&ce.empty(),U===ce.concurrency&&ce.saturated();var po=go(le(Ae));F(Ge,po)}pe=!1}},length:function(){return ce._tasks.length},running:function(){return U},workersList:function(){return H},idle:function(){return ce._tasks.length+U===0},pause:function(){ce.paused=!0},resume:function(){ce.paused!==!1&&(ce.paused=!1,A(ce.process))}};return ce}function si(k,T){return fl(k,1,T)}var ls=$t(kr,1);function Qo(k,T,L,F){F=yr(F||Ne);var U=M(L);ls(k,function(H,Z,J){U(T,H,function(le,pe){T=pe,J(le)})},function(H){F(H,T)})}function zc(){var k=ri(arguments,M);return function(){var T=o(arguments),L=this,F=T[T.length-1];typeof F=="function"?T.pop():F=Ne,Qo(k,T,function(U,H,Z){H.apply(L,U.concat(function(J){var le=o(arguments,1);Z(J,le)}))},function(U,H){F.apply(L,[U].concat(H))})}}var Vc=function(){return zc.apply(null,o(arguments).reverse())},md=Array.prototype.concat,ml=function(k,T,L,F){F=F||Ne;var U=M(L);wr(k,T,function(H,Z){U(H,function(J){return J?Z(J):Z(null,o(arguments,1))})},function(H,Z){for(var J=[],le=0;le<Z.length;le++)Z[le]&&(J=md.apply(J,Z[le]));return F(H,J)})},v1=$t(ml,1/0),Wc=$t(ml,1),qc=function(){var k=o(arguments),T=[null].concat(k);return function(){var L=arguments[arguments.length-1];return L.apply(this,T)}};function gl(k){return k}function li(k,T){return function(L,F,U,H){H=H||Ne;var Z=!1,J;L(F,function(le,pe,ce){U(le,function(Ae,Ge){Ae?ce(Ae):k(Ge)&&!J?(Z=!0,J=T(!0,le),ce(null,ni)):ce()})},function(le){le?H(le):H(null,Z?J:T(!1))})}}function dn(k,T){return T}var cs=Go(li(gl,dn)),Yo=oi(li(gl,dn)),pl=$t(Yo,1);function gd(k){return function(T){var L=o(arguments,1);L.push(function(F){var U=o(arguments,1);typeof console=="object"&&(F?console.error&&console.error(F):console[k]&&rs(U,function(H){console[k](H)}))}),M(T).apply(null,L)}}var y1=gd("dir");function k1(k,T,L){L=go(L||Ne);var F=M(k),U=M(T);function H(J){if(J)return L(J);var le=o(arguments,1);le.push(Z),U.apply(this,le)}function Z(J,le){if(J)return L(J);if(!le)return L(null);F(H)}Z(null,!0)}function pd(k,T,L){L=go(L||Ne);var F=M(k),U=function(H){if(H)return L(H);var Z=o(arguments,1);if(T.apply(this,Z))return F(U);L.apply(null,[null].concat(Z))};F(U)}function w1(k,T,L){pd(k,function(){return!T.apply(this,arguments)},L)}function B1(k,T,L){L=go(L||Ne);var F=M(T),U=M(k);function H(J){if(J)return L(J);U(Z)}function Z(J,le){if(J)return L(J);if(!le)return L(null);F(H)}U(Z)}function ci(k){return function(T,L,F){return k(T,F)}}function Gc(k,T,L){qo(k,ci(M(T)),L)}function Cl(k,T,L,F){ul(T)(k,ci(M(L)),F)}var ai=$t(Cl,1);function Zc(k){return _(k)?k:i(function(T,L){var F=!0;T.push(function(){var U=arguments;F?A(function(){L.apply(null,U)}):L.apply(null,U)}),k.apply(this,T),F=!1})}function Jn(k){return!k}var ui=Go(li(Jn,Jn)),Al=oi(li(Jn,Jn)),Qc=$t(Al,1);function E1(k){return function(T){return T==null?void 0:T[k]}}function as(k,T,L,F){var U=new Array(T.length);k(T,function(H,Z,J){L(H,function(le,pe){U[Z]=!!pe,J(le)})},function(H){if(H)return F(H);for(var Z=[],J=0;J<T.length;J++)U[J]&&Z.push(T[J]);F(null,Z)})}function Kn(k,T,L,F){var U=[];k(T,function(H,Z,J){L(H,function(le,pe){le?J(le):(pe&&U.push({index:Z,value:H}),J())})},function(H){H?F(H):F(null,ri(U.sort(function(Z,J){return Z.index-J.index}),E1("value")))})}function Yc(k,T,L,F){var U=nl(T)?as:Kn;U(k,T,M(L),F||Ne)}var Jc=Go(Yc),bl=oi(Yc),Kc=$t(bl,1);function x1(k,T){var L=go(T||Ne),F=M(Zc(k));function U(H){if(H)return L(H);F(U)}U()}var Xc=function(k,T,L,F){F=F||Ne;var U=M(L);wr(k,T,function(H,Z){U(H,function(J,le){return J?Z(J):Z(null,{key:le,val:H})})},function(H,Z){for(var J={},le=Object.prototype.hasOwnProperty,pe=0;pe<Z.length;pe++)if(Z[pe]){var ce=Z[pe].key,Ae=Z[pe].val;le.call(J,ce)?J[ce].push(Ae):J[ce]=[Ae]}return F(H,J)})},di=$t(Xc,1/0),N=$t(Xc,1),G=gd("log");function V(k,T,L,F){F=yr(F||Ne);var U={},H=M(L);kr(k,T,function(Z,J,le){H(Z,J,function(pe,ce){if(pe)return le(pe);U[J]=ce,le()})},function(Z){F(Z,U)})}var he=$t(V,1/0),Ee=$t(V,1);function Ve(k,T){return T in k}function kt(k,T){var L=Object.create(null),F=Object.create(null);T=T||gl;var U=M(k),H=i(function(J,le){var pe=T.apply(null,J);Ve(L,pe)?A(function(){le.apply(null,L[pe])}):Ve(F,pe)?F[pe].push(le):(F[pe]=[le],U.apply(null,J.concat(function(){var ce=o(arguments);L[pe]=ce;var Ae=F[pe];delete F[pe];for(var Ge=0,It=Ae.length;Ge<It;Ge++)Ae[Ge].apply(null,ce)})))});return H.memo=L,H.unmemoized=k,H}var qe;a?qe=process.nextTick:l?qe=setImmediate:qe=d;var ea=h(qe);function Cd(k,T,L){L=L||Ne;var F=nl(T)?[]:{};k(T,function(U,H,Z){M(U)(function(J,le){arguments.length>2&&(le=o(arguments,1)),F[H]=le,Z(J)})},function(U){L(U,F)})}function yn(k,T){Cd(qo,k,T)}function vl(k,T,L){Cd(ul(T),k,L)}var Ad=function(k,T){var L=M(k);return fl(function(F,U){L(F[0],U)},T,1)},hi=function(k,T){var L=Ad(k,T);return L.push=function(F,U,H){if(H==null&&(H=Ne),typeof H!="function")throw new Error("task callback must be a function");if(L.started=!0,pt(F)||(F=[F]),F.length===0)return A(function(){L.drain()});U=U||0;for(var Z=L._tasks.head;Z&&U>=Z.priority;)Z=Z.next;for(var J=0,le=F.length;J<le;J++){var pe={data:F[J],priority:U,callback:H};Z?L._tasks.insertBefore(Z,pe):L._tasks.push(pe)}A(L.process)},delete L.unshift,L};function yl(k,T){if(T=yr(T||Ne),!pt(k))return T(new TypeError("First argument to race must be an array of functions"));if(!k.length)return T();for(var L=0,F=k.length;L<F;L++)M(k[L])(T)}function fi(k,T,L,F){var U=o(k).reverse();Qo(U,T,L,F)}function We(k){var T=M(k);return i(function(F,U){return F.push(function(Z,J){if(Z)U(null,{error:Z});else{var le;arguments.length<=2?le=J:le=o(arguments,1),U(null,{value:le})}}),T.apply(this,F)})}function I1(k){var T;return pt(k)?T=ri(k,We):(T={},ss(k,function(L,F){T[F]=We.call(this,L)})),T}function bd(k,T,L,F){Yc(k,T,function(U,H){L(U,function(Z,J){H(Z,!J)})},F)}var kl=Go(bd),vd=oi(bd),T1=$t(vd,1);function D1(k){return function(){return k}}function mi(k,T,L){var F=5,U=0,H={times:F,intervalFunc:D1(U)};function Z(ce,Ae){if(typeof Ae=="object")ce.times=+Ae.times||F,ce.intervalFunc=typeof Ae.interval=="function"?Ae.interval:D1(+Ae.interval||U),ce.errorFilter=Ae.errorFilter;else if(typeof Ae=="number"||typeof Ae=="string")ce.times=+Ae||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof k=="function"?(L=T||Ne,T=k):(Z(H,k),L=L||Ne),typeof T!="function")throw new Error("Invalid arguments for async.retry");var J=M(T),le=1;function pe(){J(function(ce){ce&&le++<H.times&&(typeof H.errorFilter!="function"||H.errorFilter(ce))?setTimeout(pe,H.intervalFunc(le)):L.apply(null,arguments)})}pe()}var Jo=function(k,T){T||(T=k,k=null);var L=M(T);return i(function(F,U){function H(Z){L.apply(null,F.concat(Z))}k?mi(k,H,U):mi(H,U)})};function wl(k,T){Cd(ls,k,T)}var Bl=Go(li(Boolean,gl)),Er=oi(li(Boolean,gl)),El=$t(Er,1);function yd(k,T,L){var F=M(T);$c(k,function(H,Z){F(H,function(J,le){if(J)return Z(J);Z(null,{value:H,criteria:le})})},function(H,Z){if(H)return L(H);L(null,ri(Z.sort(U),E1("value")))});function U(H,Z){var J=H.criteria,le=Z.criteria;return J<le?-1:J>le?1:0}}function xl(k,T,L){var F=M(k);return i(function(U,H){var Z=!1,J;function le(){var pe=k.name||"anonymous",ce=new Error('Callback function "'+pe+'" timed out.');ce.code="ETIMEDOUT",L&&(ce.info=L),Z=!0,H(ce)}U.push(function(){Z||(H.apply(null,arguments),clearTimeout(J))}),J=setTimeout(le,T),F.apply(null,U)})}var S1=Math.ceil,Il=Math.max;function gi(k,T,L,F){for(var U=-1,H=Il(S1((T-k)/(L||1)),0),Z=Array(H);H--;)Z[F?H:++U]=k,k+=L;return Z}function pi(k,T,L,F){var U=M(L);wr(gi(0,k,1),T,U,F)}var L1=$t(pi,1/0),M1=$t(pi,1);function R1(k,T,L,F){arguments.length<=3&&(F=L,L=T,T=pt(k)?[]:{}),F=yr(F||Ne);var U=M(L);qo(k,function(H,Z,J){U(T,H,Z,J)},function(H){F(H,T)})}function Tl(k,T){var L=null,F;T=T||Ne,ai(k,function(U,H){M(U)(function(Z,J){arguments.length>2?F=o(arguments,1):F=J,L=Z,H(!Z)})},function(){T(L,F)})}function Dl(k){return function(){return(k.unmemoized||k).apply(null,arguments)}}function Sl(k,T,L){L=go(L||Ne);var F=M(T);if(!k())return L(null);var U=function(H){if(H)return L(H);if(k())return F(U);var Z=o(arguments,1);L.apply(null,[null].concat(Z))};F(U)}function O1(k,T,L){Sl(function(){return!k.apply(this,arguments)},T,L)}var kd=function(k,T){if(T=yr(T||Ne),!pt(k))return T(new Error("First argument to waterfall must be an array of functions"));if(!k.length)return T();var L=0;function F(H){var Z=M(k[L++]);H.push(go(U)),Z.apply(null,H)}function U(H){if(H||L===k.length)return T.apply(null,arguments);F(o(arguments,1))}F([])},G3={apply:r,applyEach:Ju,applyEachSeries:Xu,asyncify:v,auto:Hc,autoInject:b1,cargo:si,compose:Vc,concat:v1,concatLimit:ml,concatSeries:Wc,constant:qc,detect:cs,detectLimit:Yo,detectSeries:pl,dir:y1,doDuring:k1,doUntil:w1,doWhilst:pd,during:B1,each:Gc,eachLimit:Cl,eachOf:qo,eachOfLimit:kr,eachOfSeries:ls,eachSeries:ai,ensureAsync:Zc,every:ui,everyLimit:Al,everySeries:Qc,filter:Jc,filterLimit:bl,filterSeries:Kc,forever:x1,groupBy:di,groupByLimit:Xc,groupBySeries:N,log:G,map:$c,mapLimit:wr,mapSeries:Ku,mapValues:he,mapValuesLimit:V,mapValuesSeries:Ee,memoize:kt,nextTick:ea,parallel:yn,parallelLimit:vl,priorityQueue:hi,queue:Ad,race:yl,reduce:Qo,reduceRight:fi,reflect:We,reflectAll:I1,reject:kl,rejectLimit:vd,rejectSeries:T1,retry:mi,retryable:Jo,seq:zc,series:wl,setImmediate:A,some:Bl,someLimit:Er,someSeries:El,sortBy:yd,timeout:xl,times:L1,timesLimit:pi,timesSeries:M1,transform:R1,tryEach:Tl,unmemoize:Dl,until:O1,waterfall:kd,whilst:Sl,all:ui,allLimit:Al,allSeries:Qc,any:Bl,anyLimit:Er,anySeries:El,find:cs,findLimit:Yo,findSeries:pl,forEach:Gc,forEachSeries:ai,forEachLimit:Cl,forEachOf:qo,forEachOfSeries:ls,forEachOfLimit:kr,inject:Qo,foldl:Qo,foldr:fi,select:Jc,selectLimit:bl,selectSeries:Kc,wrapSync:v};t.default=G3,t.apply=r,t.applyEach=Ju,t.applyEachSeries=Xu,t.asyncify=v,t.auto=Hc,t.autoInject=b1,t.cargo=si,t.compose=Vc,t.concat=v1,t.concatLimit=ml,t.concatSeries=Wc,t.constant=qc,t.detect=cs,t.detectLimit=Yo,t.detectSeries=pl,t.dir=y1,t.doDuring=k1,t.doUntil=w1,t.doWhilst=pd,t.during=B1,t.each=Gc,t.eachLimit=Cl,t.eachOf=qo,t.eachOfLimit=kr,t.eachOfSeries=ls,t.eachSeries=ai,t.ensureAsync=Zc,t.every=ui,t.everyLimit=Al,t.everySeries=Qc,t.filter=Jc,t.filterLimit=bl,t.filterSeries=Kc,t.forever=x1,t.groupBy=di,t.groupByLimit=Xc,t.groupBySeries=N,t.log=G,t.map=$c,t.mapLimit=wr,t.mapSeries=Ku,t.mapValues=he,t.mapValuesLimit=V,t.mapValuesSeries=Ee,t.memoize=kt,t.nextTick=ea,t.parallel=yn,t.parallelLimit=vl,t.priorityQueue=hi,t.queue=Ad,t.race=yl,t.reduce=Qo,t.reduceRight=fi,t.reflect=We,t.reflectAll=I1,t.reject=kl,t.rejectLimit=vd,t.rejectSeries=T1,t.retry=mi,t.retryable=Jo,t.seq=zc,t.series=wl,t.setImmediate=A,t.some=Bl,t.someLimit=Er,t.someSeries=El,t.sortBy=yd,t.timeout=xl,t.times=L1,t.timesLimit=pi,t.timesSeries=M1,t.transform=R1,t.tryEach=Tl,t.unmemoize=Dl,t.until=O1,t.waterfall=kd,t.whilst=Sl,t.all=ui,t.allLimit=Al,t.allSeries=Qc,t.any=Bl,t.anyLimit=Er,t.anySeries=El,t.find=cs,t.findLimit=Yo,t.findSeries=pl,t.forEach=Gc,t.forEachSeries=ai,t.forEachLimit=Cl,t.forEachOf=qo,t.forEachOfSeries=ls,t.forEachOfLimit=kr,t.inject=Qo,t.foldl=Qo,t.foldr=fi,t.select=Jc,t.selectLimit=bl,t.selectSeries=Kc,t.wrapSync=v,Object.defineProperty(t,"__esModule",{value:!0})})})(op,op.exports);var y7={exports:{}},rp=y7.exports=function(n,e){if(e||(e=16),n===void 0&&(n=128),n<=0)return"0";for(var t=Math.log(Math.pow(2,n))/Math.log(e),o=2;t===1/0;o*=2)t=Math.log(Math.pow(2,n/o))/Math.log(e)*o;for(var r=t-Math.floor(t),i="",o=0;o<Math.floor(t);o++){var s=Math.floor(Math.random()*e).toString(e);i=s+i}if(r){var l=Math.pow(e,r),s=Math.floor(Math.random()*l).toString(e);i=s+i}var a=parseInt(i,e);return a!==1/0&&a>=Math.pow(2,n)?rp(n,e):i};rp.rack=function(n,e,t){var o=function(i){var s=0;do{if(s++>10)if(t)n+=t;else throw new Error("too many ID collisions, use more bits");var l=rp(n,e)}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=e||16,o};var k7=$i,fS=b7,mS=v7,Ph=Fo,ip=op.exports,gS=y7.exports,w7=Hs.ACTIONS,B7=Mt;function Mt(n,e){if(k7.EventEmitter.call(this),!e||typeof e!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=e,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}k7.mixin(Mt),Mt.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Mt.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Mt.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||gS();var e=this._createLocalPresence(n);return this.localPresences[n]=e,e},Mt.prototype.destroy=function(n){this._wantsDestroy=!0;var e=this,t=Object.keys(e.localPresences);this.unsubscribe(function(o){if(o)return e._callbackOrEmit(o,n);var r=Object.keys(e._remotePresenceInstances);ip.parallel([function(i){ip.each(t,function(s,l){e.localPresences[s].destroy(l)},i)},function(i){if(!e._wantsDestroy)return i();ip.each(r,function(s,l){e._remotePresenceInstances[s].destroy(l)},i)}],function(i){e._wantsDestroy&&delete e.connection._presences[e.channel],e._callbackOrEmit(i,n)})})},Mt.prototype._sendSubscriptionAction=function(n,e){this.wantSubscribe=!!n;var t=this.wantSubscribe?w7.presenceSubscribe:w7.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=e,this.connection.canSend&&this.connection._sendPresenceAction(t,o,this)},Mt.prototype._handleSubscribe=function(n,e){this.wantSubscribe&&(this.subscribed=!0);var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},Mt.prototype._handleUnsubscribe=function(n,e){this.subscribed=!1;var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},Mt.prototype._receiveUpdate=function(n,e){var t=Ph.dig(this.localPresences,e.id);if(t)return t._ack(n,e.pv);if(n)return this.emit("error",n);var o=this,r=Ph.digOrCreate(this._remotePresenceInstances,e.id,function(){return o._createRemotePresence(e.id)});r.receiveUpdate(e)},Mt.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Mt.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var e in this.localPresences){var t=this.localPresences[e];t.value!==null&&t.send()}},Mt.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Mt.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Mt.prototype._resubscribe=function(){var n=[];for(var e in this._subscriptionCallbacksBySeq){var t=this._subscriptionCallback(e);n.push(t)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},Mt.prototype._subscriptionCallback=function(n){var e=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],e},Mt.prototype._callbackOrEmit=function(n,e){if(e)return Ph.nextTick(e,n);n&&this.emit("error",n)},Mt.prototype._createLocalPresence=function(n){return new fS(this,n)},Mt.prototype._createRemotePresence=function(n){return new mS(this,n)},Mt.prototype._callEachOrEmit=function(n,e){var t=Ph.callEach(n,e);!t&&e&&this.emit("error",e)};var Va=b7,E7=Mh,pS=Fo,x7=E7.CODES,CS=No;function No(n,e){Va.call(this,n,e),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()}No.prototype=Object.create(Va.prototype),No.prototype.submit=function(n,e){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,e);var t={code:x7.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(t,e)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,Va.prototype.submit.call(this,n,e)},No.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),Va.prototype.destroy.call(this,n)},No.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(e){e.t=n._doc.type.uri,e.v=n._doc.version,n.connection.send(e)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},No.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)},No.prototype._transformAgainstOp=function(n,e){var t=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=t._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=t._transformPresence(r.p,n,e),t._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=t._getCallback(r.pv);t._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,e)}catch(r){this.emit("error",r)}},No.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},No.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},No.prototype._message=function(){var n=Va.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},No.prototype._transformPresence=function(n,e,t){var o=this._doc.type;if(!pS.supportsPresence(o))throw new E7(x7.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,e,t)};var I7={};(function(n){var e=ja,t=Mh,o=Fo,r=t.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var a=l.create.type;if(typeof a!="string")return new t(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=e.map[a];if(d==null||typeof d!="object")return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new t(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new t(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new t(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new t(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 t(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return e.map[l]&&e.map[l].uri},n.apply=function(l,a){if(typeof l!="object")return new t(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&a.v!=null&&l.v!==a.v)return new t(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(a.create){if(l.type)return new t(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=a.create,h=e.map[d.type];if(!h)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(A){return A}}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 t(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(a===void 0)return new t(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=e.map[l.type];if(!d)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,a)}catch(h){return new t(r.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,a,d){if(a.v!=null&&a.v!==d.v)return new t(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(a.create||"op"in a)return new t(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 t(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in a){if(!l)return new t(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=e.map[l],!l))return new t(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 t(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=p.v;var A=n.apply(l,p);if(A)return A}},n.transformPresence=function(l,a,d){var h=this.checkOp(a);if(h)return h;var p=l.t;if(typeof p=="string"&&(p=e.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(A){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:A.message||A}}l.v++};function s(l,a){if(l.type===e.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 A=d[p];typeof A.lm=="string"&&(A.lm=+A.lm);for(var v=A.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=e.defaultType.apply(h,[A]))}}}}})(I7);var Wa=v7,AS=I7,bS=lo;function lo(n,e){Wa.call(this,n,e),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()}lo.prototype=Object.create(Wa.prototype),lo.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},lo.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),Wa.prototype.destroy.call(this,n)},lo.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)},lo.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))}})}},lo.prototype._handleOp=function(n,e,t){var o=t===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},Wa.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Wa.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},lo.prototype._transformAgainstOp=function(n,e){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,e)}catch(t){return this.presence.emit("error",t)}this.presence._updateRemotePresence(this)}},lo.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],e=n.op,t=n.isOwnOp;e===null?(this._pending.p=null,this._pending.v++):AS.transformPresence(this._pending,e,t)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},lo.prototype._startCachingOps=function(){this._opCache=[]},lo.prototype._stopCachingOps=function(){this._opCache=null},lo.prototype._cacheOp=function(n,e){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:e})};var T7=B7,vS=CS,yS=bS;function Kl(n,e,t){var o=Kl.channel(e,t);T7.call(this,n,o),this.collection=e,this.id=t}var kS=Kl;Kl.prototype=Object.create(T7.prototype),Kl.channel=function(n,e){return n+"."+e},Kl.prototype._createLocalPresence=function(n){return new vS(this,n)},Kl.prototype._createRemotePresence=function(n){return new yS(this,n)};var wS=BS;function BS(n,e,t,o,r){this.id=n,this.v=e,this.type=t,this.data=o,this.m=r}var ES=wS,D7=$i,S7=qa;function qa(n,e,t,o,r){if(D7.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=e,this.connection=n,this.id=o,this.collection=t,this.callback=r,this.sent=!1}D7.mixin(qa),qa.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},qa.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},qa.prototype._handleResponse=function(n,e){if(this.emit("ready"),n)return this.callback(n);var t=e.meta?e.meta:null,o=new ES(this.id,e.v,e.type,e.data,t);this.callback(null,o)};var L7=S7,xS=Fo,IS=Hs.ACTIONS,TS=sp;function sp(n,e,t,o,r,i){if(L7.call(this,n,e,t,o,i),!xS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}sp.prototype=Object.create(L7.prototype),sp.prototype._message=function(){return{a:IS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var M7=S7,DS=Fo,SS=Hs.ACTIONS,LS=lp;function lp(n,e,t,o,r,i){if(M7.call(this,n,e,t,o,i),!DS.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}lp.prototype=Object.create(M7.prototype),lp.prototype._message=function(){return{a:SS.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var MS=rS,RS=aS,OS=B7,R7=kS,_S=TS,FS=LS,O7=$i,Xl=Mh,et=Hs.ACTIONS,_7=ja,$o=Fo,Ga=u7,Za=Xl.CODES;function F7(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var PS=we;function we(n){O7.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=F7(n),this.bindToSocket(n)}O7.mixin(we),we.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 e=F7(n);this._setState(e),this.canSend=!1;var t=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Ga.warn("Failed to parse message",o);return}t.debug&&Ga.info("RECV",JSON.stringify(r));var i={data:r};if(t.emit("receive",i),!!i.data)try{t.handleMessage(i.data)}catch(s){$o.nextTick(function(){t.emit("error",s)})}},n.readyState===1&&t._initializeHandshake(),n.onopen=function(){t._setState("connecting"),t._initializeHandshake()},n.onerror=function(o){t.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?t._setState("closed",o):o==="stopped"||o==="Stopped by server"?t._setState("stopped",o):t._setState("disconnected",o)}},we.prototype.handleMessage=function(n){var e=null;switch(n.error&&(e=P7(n.error,n),delete n.error),n.a){case et.initLegacy:return this._handleLegacyInit(n);case et.handshake:return this._handleHandshake(e,n);case et.queryFetch:var t=this.queries[n.id];t&&t._handleFetch(e,n.data,n.extra);return;case et.querySubscribe:var t=this.queries[n.id];t&&t._handleSubscribe(e,n.data,n.extra);return;case et.queryUnsubscribe:return;case et.queryUpdate:var t=this.queries[n.id];if(!t)return;if(e)return t._handleError(e);n.diff&&t._handleDiff(n.diff),n.hasOwnProperty("extra")&&t._handleExtra(n.extra);return;case et.bulkFetch:return this._handleBulkMessage(e,n,"_handleFetch");case et.bulkSubscribe:case et.bulkUnsubscribe:return this._handleBulkMessage(e,n,"_handleSubscribe");case et.snapshotFetch:case et.snapshotFetchByTimestamp:return this._handleSnapshotFetch(e,n);case et.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(e,n.data);return;case et.subscribe:case et.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(e,n.data);return;case et.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(e,n);return;case et.presence:return this._handlePresence(e,n);case et.presenceSubscribe:return this._handlePresenceSubscribe(e,n);case et.presenceUnsubscribe:return this._handlePresenceUnsubscribe(e,n);case et.presenceRequest:return this._handlePresenceRequest(e,n);case et.pingPong:return this._handlePingPong(e);default:Ga.warn("Ignoring unrecognized message",n)}};function P7(n,e){var t=new Error(n.message);return t.code=n.code,e&&(t.data=e),t}we.prototype._handleBulkMessage=function(n,e,t){if(e.data)for(var o in e.data){var r=e.data[o],i=this.getExisting(e.c,o);i&&(n?i[t](n):r.error?i[t](P7(r.error)):i[t](null,r))}else if(Array.isArray(e.b))for(var s=0;s<e.b.length;s++){var o=e.b[s],i=this.getExisting(e.c,o);i&&i[t](n)}else if(e.b)for(var o in e.b){var i=this.getExisting(e.c,o);i&&i[t](n)}else Ga.error("Invalid bulk message",e)},we.prototype._reset=function(){this.agent=null},we.prototype._setState=function(n,e){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var t=new Xl(Za.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",t)}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,e),this.emit("state",n,e)}},we.prototype.startBulk=function(){this.bulk||(this.bulk={})},we.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var e=this.bulk[n];this._sendBulk("f",n,e.f),this._sendBulk("s",n,e.s),this._sendBulk("u",n,e.u)}this.bulk=null},we.prototype._sendBulk=function(n,e,t){if(!!t){var o=[],r={},i=0,s;for(var l in t){var a=t[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:e,d:l})}else o.length&&this.send({a:"b"+n,c:e,b:o});if(i===1){var d=r[s];this.send({a:n,c:e,d:s,v:d})}else i&&this.send({a:"b"+n,c:e,b:r})}},we.prototype._sendActions=function(n,e,t){if(this._addDoc(e),this.bulk){var o=this.bulk[e.collection]||(this.bulk[e.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(e.id);return r[e.id]=t,i}else{var s={a:n,c:e.collection,d:e.id,v:t};this.send(s)}},we.prototype.sendFetch=function(n){return this._sendActions(et.fetch,n,n.version)},we.prototype.sendSubscribe=function(n){return this._sendActions(et.subscribe,n,n.version)},we.prototype.sendUnsubscribe=function(n){return this._sendActions(et.unsubscribe,n)},we.prototype.sendOp=function(n,e){this._addDoc(n);var t={a:et.op,c:n.collection,d:n.id,v:n.version,src:e.src,seq:e.seq,x:{}};"op"in e&&(t.op=e.op),e.create&&(t.create=e.create),e.del&&(t.del=e.del),n.submitSource&&(t.x.source=e.source),this.send(t)},we.prototype.send=function(n){this.debug&&Ga.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},we.prototype.ping=function(){if(!this.canSend)throw new Xl(Za.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:et.pingPong};this.send(n)},we.prototype.close=function(){this.socket.close()},we.prototype.getExisting=function(n,e){if(this.collections[n])return this.collections[n][e]},we.prototype.get=function(n,e){var t=this.collections[n]||(this.collections[n]={}),o=t[e];return o||(o=t[e]=new MS(this,n,e),this.emit("doc",o)),o._wantsDestroy=!1,o},we.prototype._destroyDoc=function(n){!n._wantsDestroy||($o.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},we.prototype._addDoc=function(n){var e=this.collections[n.collection];e||(e=this.collections[n.collection]={}),e[n.id]!==n&&(e[n.id]=n)},we.prototype._createQuery=function(n,e,t,o,r){var i=this.nextQueryId++,s=new RS(n,this,i,e,t,o,r);return this.queries[i]=s,s.send(),s},we.prototype._destroyQuery=function(n){delete this.queries[n.id]},we.prototype.createFetchQuery=function(n,e,t,o){return this._createQuery(et.queryFetch,n,e,t,o)},we.prototype.createSubscribeQuery=function(n,e,t,o){return this._createQuery(et.querySubscribe,n,e,t,o)},we.prototype.hasPending=function(){return!!(this._firstDoc(Nh)||this._firstQuery(Nh)||this._firstSnapshotRequest())};function Nh(n){return n.hasPending()}we.prototype.hasWritePending=function(){return!!this._firstDoc(NS)};function NS(n){return n.hasWritePending()}we.prototype.whenNothingPending=function(n){var e=this._firstDoc(Nh);if(e){e.once("nothing pending",this._nothingPendingRetry(n));return}var t=this._firstQuery(Nh);if(t){t.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}$o.nextTick(n)},we.prototype._nothingPendingRetry=function(n){var e=this;return function(){$o.nextTick(function(){e.whenNothingPending(n)})}},we.prototype._firstDoc=function(n){for(var e in this.collections){var t=this.collections[e];for(var o in t){var r=t[o];if(n(r))return r}}},we.prototype._firstQuery=function(n){for(var e in this.queries){var t=this.queries[e];if(n(t))return t}},we.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},we.prototype.fetchSnapshot=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new _S(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},we.prototype.fetchSnapshotByTimestamp=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new FS(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},we.prototype._handleSnapshotFetch=function(n,e){var t=this._snapshotRequests[e.id];!t||(delete this._snapshotRequests[e.id],t._handleResponse(n,e))},we.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},we.prototype._initializeHandshake=function(){this.send({a:et.handshake,id:this.id})},we.prototype._handleHandshake=function(n,e){if(n)return this.emit("error",n);this._initialize(e)},we.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},we.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new Xl(Za.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(_7.map[n.type]!==_7.defaultType)return this.emit("error",new Xl(Za.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Xl(Za.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},we.prototype.getPresence=function(n){var e=this,t=$o.digOrCreate(this._presences,n,function(){return new OS(e,n)});return t._wantsDestroy=!1,t},we.prototype.getDocPresence=function(n,e){var t=R7.channel(n,e),o=this,r=$o.digOrCreate(this._presences,t,function(){return new R7(o,n,e)});return r._wantsDestroy=!1,r},we.prototype._sendPresenceAction=function(n,e,t){this._addPresence(t);var o={a:n,ch:t.channel,seq:e};return this.send(o),o.seq},we.prototype._addPresence=function(n){$o.digOrCreate(this._presences,n.channel,function(){return n})},we.prototype._handlePresenceSubscribe=function(n,e){var t=$o.dig(this._presences,e.ch);t&&t._handleSubscribe(n,e.seq)},we.prototype._handlePresenceUnsubscribe=function(n,e){var t=$o.dig(this._presences,e.ch);t&&t._handleUnsubscribe(n,e.seq)},we.prototype._handlePresence=function(n,e){var t=$o.dig(this._presences,e.ch);t&&t._receiveUpdate(n,e)},we.prototype._handlePresenceRequest=function(n,e){var t=$o.dig(this._presences,e.ch);t&&t._broadcastAllLocalPresence(n,e)};var N7=PS,$S=ja;const $h={err:1001,msg:"user auth error",name:"AuthError"},HS={err:1002,msg:"you don't have required permission",name:"PermissionError"},cp={err:1003,msg:"Too many user connected",name:"MaxUserError"},Qa={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},jS={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},US={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},Ya="x-live-editor-token",Hh="x-live-editor-base-url",gn=S("auth-connection");function zS(n){try{n()}catch(e){gn.error(e)}}class VS{constructor(e,t){g(this,"connection");g(this,"ws");g(this,"retryCount");g(this,"events",new H5.EventEmitter);g(this,"token",null);g(this,"resourceToken",null);this.url=e,this.reauthFunc=t,this.retryCount=0}getBaseURL(){const e=new URL(this.url);return`${e.protocol==="wss:"?"https:":"http:"}//${e.host}${e.pathname}`}getBase64BaseURL(){return ws(this.getBaseURL())}async auth(e){m(gn,e.token,"no auth token");const t=`${this.getBaseURL()}/auth`,o=await window.fetch(t,{method:"GET",headers:{[Ya]:e.token,[Hh]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=e.token,await o.json()}async logout(){if(!this.token)return;const e=`${this.getBaseURL()}/logout`;await window.fetch(e,{method:"GET",headers:{[Hh]:ws(this.getBaseURL())}})}async init(e){const t=await this.auth(e);this.resourceToken=t.read,this.ws=new $B.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(N7.prototype),m(gn,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:e})};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}}},N7.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,gn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const e=await this.reauthFunc();await this.auth(e),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:e})}}}catch(e){gn.error(e),setTimeout(()=>this.handleAuthError(),0)}}else gn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const e=new Error($h.msg);e.code=$h.err,this.events.emit("error",e)}emitRequestReloadError(){const e=new Error(Qa.msg);e.code=Qa.err,this.events.emit("requestReloadError",e)}emitWriteConflictError(e,t){e.orgMsg=t,this.events.emit("writeConflictError",e)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(e){const t=e;if(t.a==="pong")return;const o=t.err;if(o===$h.err)gn.warn("auth error"),this.handleAuthError();else if(o===cp.err)gn.warn(cp.msg),this.emitMaxUsersError();else if(o===Qa.err){gn.warn(Qa.msg);try{this.emitRequestReloadError()}catch(r){gn.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else gn.error(`unknown message received: ${JSON.stringify(t)}`),this.emitAuthError()}get(e,t){return m(gn,this.connection,"no this.connection"),this.connection.get(e,t)}addEventListener(e,t){e==="error"?this.events.addListener(e,t):(m(gn,this.ws,"no this.ws"),this.ws.addEventListener(e,t))}onWriteConflictError(e){this.events.addListener("writeConflictError",e)}onMaxUsersError(e){m(gn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",e)}onRequestReloadError(e){m(gn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",e)}end(e){var t;this.reauthFunc=void 0,this.events.removeAllListeners(),zS(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(t=this.ws)==null||t.close(),this.ws=void 0,e&&this.logout()}}S("utils/file");function WS(){function n(){return new Promise(e=>{const t=new FileReader;t.onload=()=>{e(t.result)},t.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}WS();async function qS(n){const t=n.size,o=Math.floor((t+102400-1)/102400),r=new HB.Hash;for(let s=0;s<o;s++){const l=s*102400;let a=l+102400;a>t&&(a=t);const h=await n.slice(l,a,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return ws(i)}const ur=S("sharedb-doc/client");class GS{constructor(e,t,o){g(this,"connection");g(this,"auth");g(this,"doc",null);g(this,"reauthFunc");g(this,"clientId",K());g(this,"getDoc",async()=>{const e=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});m(ur,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const t=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=t,await e(t),ur.debug(t),t});this.auth=e;const r=`${t}/${this.auth.appId}/${this.auth.docId}`;$S.register(Rd.type),this.connection=new VS(r,o),this.reauthFunc=o}editorServer(){const e=this.apiServer(),t=`/${this.auth.appId}/${this.auth.docId}`;return m(ur,e.endsWith(t),`invalid api server: ${e}, ${t}`),e.substr(0,e.length-t.length)}close(e){this.connection.end(e),this.doc=null}on(e,t){this.connection.addEventListener(e,o=>{(e==="error"||this.doc)&&t(o)})}onWriteConflictError(e){this.connection.onWriteConflictError(e)}onMaxUsersError(e){this.connection.onMaxUsersError(e)}onRequestReloadError(e){this.connection.onRequestReloadError(e)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const e=this.connection.url;if(e.startsWith("ws://"))return`http://${e.substring(5)}`;if(e.startsWith("wss://"))return`https://${e.substring(6)}`;throw new Error(`invalid server url: ${e}`)}async getFileUrlByHash(e,t,o,r,i){try{const s=`${e}/${t}`,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(e){const o=`${this.apiServer()}/resources`;let r=[];e.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,{[Ya]:this.connection.token}));return await Promise.all(i)}async uploadFile(e,t,o,r,i){let s=t.size;if(s===0)throw new Error("file is empty");s+=500;const l=v=>{ur.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await qS(t),d=await this.getFileUrlByHash(e,a,t.name,t.size,o);if(d)return r(-1),d;let h=e;i!=null&&i.thumbnail&&(h+="/thumbnail");const p=new FormData;p.append("file-size",`${t.size}`),p.append("file-hash",a),p.append("file",t,t.name);const A=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return ur.info(A),r(100),Array.isArray(A.data)?A.data[0]:A.data}async uploadResource(e,t=()=>{},o){const i=`${this.apiServer()}/resources`;m(ur,this.connection.token,"no connection token");const s=await this.uploadFile(i,e,{[Ya]:this.connection.token},t,o);return m(ur,s,"no result"),s}async request(e,t){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const a=t||{};a.url=e,a.headers||(a.headers={}),m(ur,o,"no token"),a.headers={...a.headers,[Ya]:o,[Hh]:this.connection.getBase64BaseURL()};try{return await PB.default(e,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 m(ur,r,"no error"),r}async getVersions(){const t=`${this.apiServer()}/versions?withExtra=true`,r=(await this.request(t)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),r}async getVersion(e){const o=`${this.apiServer()}/versions/${e}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const t=`${this.apiServer()}/versions/latest`,o=await this.request(t);return JSON.parse(o.data.data)}async getVersionOps(e,t){let r=`${this.apiServer()}/versions/before/${e}?withOp=true`;t!==void 0&&t!==0&&(r+=`&from=${t}`);const i=await this.request(r),s=i.data.ops,l=NB.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(m(ur,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(e,t,o){const i=`${this.apiServer()}/versions/${e}/tags/${t}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}async revertVersion(e){const o=`${this.apiServer()}/versions/revert/${e}`;await this.request(o,{method:"post",data:{}})}async createVersion(e,t){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:t,tag:e}})).data}async recognizeLink(e){const o=`${this.apiServer()}/resources/external/${ws(e)}`;return(await this.request(o)).data}buildResourceUrl(e,t){if(!e)return"";if(e.startsWith("https:")||e.startsWith("http:")||e.startsWith("file:")||e.startsWith("data:")||e.startsWith("blob:"))return e;let r=`${this.apiServer()}/resources/${encodeURIComponent(e)}`;const i=[];if(t!=null&&t.withToken&&i.push(`token=${this.getResourceToken()}`),t!=null&&t.downloadFileName&&i.push(`&fileName=${encodeURIComponent(t.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function ZS(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const ap=S("block-ids");class QS{constructor(){g(this,"ids",new Map)}onInsertBlock(e){const t=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<t.length;r++){const i=t[r];if(i>=e){const s=this.ids.get(i);m(ap,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=K();this.ids.set(e,o)}onDeleteBlock(e){this.ids.delete(e);const t=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<t.length;o++){const r=t[o];if(r>e){const i=this.ids.get(r);m(ap,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(e){let t=this.ids.get(e);return t||(t=K(),this.ids.set(e,t)),t}getById(e){return Array.from(this.ids.entries()).find(([,t])=>t===e)}}class YS{constructor(){g(this,"ids",new Map)}getContainerIds(e){let t=this.ids.get(e);return t||(t=new QS,this.ids.set(e,t)),t}onInsertBlock(e,t){this.getContainerIds(e).onInsertBlock(t)}onDeleteBlock(e,t){this.getContainerIds(e).onDeleteBlock(t)}getBlockId(e,t){return this.getContainerIds(e).getId(t)}getBlockIndexById(e){const t=Array.from(this.ids.entries());for(let o=0;o<t.length;o++){const r=t[o],i=r[1].getById(e);if(i)return{containerId:r[0],blockIndex:i[0]}}return m(ap,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class $7{constructor(e=new Set,t=new Map){this.deletedKeys=e,this.insertedValues=t}insert(e,t){this.insertedValues.set(e,t)}delete(e){this.deletedKeys.add(e)}toDocBlockDelta(){const e={};return this.insertedValues.forEach((t,o)=>{e[o]=t}),{insert:e,delete:Array.from(this.deletedKeys)}}}const jh=S("op-parse-handler");class JS{constructor(e,t){g(this,"actions",[]);this.outerHandler=e,this.local=t}pushActions(e){if(!e.containerId){this.actions.push(e);return}const o={...e,containerId:(r=>r==="blocks"?"root":r)(e.containerId)};this.actions.push(o)}onDeleteBlock(e,t){this.pushActions({type:"deleteBlock",containerId:e,blockIndex:t})}onInsertBlock(e,t,o){this.pushActions({type:"insertBlock",containerId:e,blockIndex:t,data:o})}onDeleteBlockData(e,t,o){this.pushActions({type:"deleteBlockData",containerId:e,blockIndex:t,key:o})}onInsertBlockData(e,t,o,r){this.pushActions({type:"insertBlockData",containerId:e,blockIndex:t,key:o,value:r})}onUpdateBlockText(e,t,o){this.pushActions({type:"updateBlockText",containerId:e,blockIndex:t,richTextData:o})}onDeleteContainer(e){this.pushActions({type:"deleteContainer",containerId:e})}onCreateContainer(e,t){this.pushActions({type:"createContainer",containerId:e,data:t})}onDeleteComment(e){this.pushActions({type:"deleteComment",commentId:e})}onCreateComment(e){this.pushActions({type:"createComment",commentId:e})}onUpdateComment(e){this.pushActions({type:"updateComment",commentId:e})}end(){const e=this.actions,t=new Set,o=new Map,r=new YS,i=e.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&&(jh.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),o.delete(a));const h=`${l.containerId}-${l.blockIndex}`;t.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(t.has(a)){jh.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 $7,o.set(d,h)),h.delete(l.key)}else m(jh,!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 $7,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);jh.debug(`update block data: ${a}, ${d}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Rt=S("op-parser");class H7{}class up{constructor(e){g(this,"key");this.key=e}}function KS(n,e,t){const o=e.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;m(Rt,s.id,"block id is required"),m(Rt,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 t.onInsertBlock(n,r,s),!0}function dp(n,e,t,o){if(t==="upsert"&&KS(n,e,o))return;m(Rt,Array.isArray(e),`invalid block op: ${n}, ${JSON.stringify(e)}`);const r=e.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const a=r[1];if(m(Rt,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(e)}`),m(Rt,a.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(e)}`),r.splice(0,2),t==="upsert"){const h=a.e;o.onUpdateBlockText(n,i,h)}m(Rt,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){m(Rt,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];m(Rt,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(m(Rt,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&t==="upsert"&&o.onInsertBlockData(n,i,a,d.i),d.r&&t==="remove"&&o.onDeleteBlockData(n,i,a),d.et==="rich-text"&&t==="upsert"){const p=d.e;o.onUpdateBlockText(n,i,p)}}else t==="remove"&&d.r&&s.push(new up(a)),t==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i);r.shift()}else if(typeof l=="object"){const a=l;t==="remove"&&a.r&&s.push(new H7),t==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{m(Rt,typeof l=="string","data is not string"),m(Rt,l!=="text","data !== 'text'"),m(Rt,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const a=l,d=r[1];t==="remove"&&d.r&&s.push(new up(a)),t==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof H7?o.onDeleteBlock(n,i):l instanceof up?o.onDeleteBlockData(n,i,l.key):m(Rt,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function XS(n,e,t){Rt.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function eL(n,e,t){const o=n[1],r=n[2];m(Rt,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),m(Rt,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Rt.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?e==="upsert"&&t.onUpdateComment(o):r.i?e==="upsert"&&t.onCreateComment(o):r.r?e==="remove"&&t.onDeleteComment(o):Rt.error(`unknown comment op, ${JSON.stringify(n)}`)}function hp(n,e,t){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{hp(s,e,t)});return}const r=o;if(m(Rt,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){XS(n);return}if(r==="comments"){eL(n,e,t);return}const i=r;if(Array.isArray(n[1]))e==="remove"?n.slice(1).reverse().forEach(s=>{dp(i,s,e,t)}):n.slice(1).forEach(s=>{dp(i,s,e,t)});else if(typeof n[1]=="object"){const s=n[1];s.r&&e==="remove"&&t.onDeleteContainer(i),s.i&&e==="upsert"&&t.onCreateContainer(i,s.i)}else m(Rt,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),dp(i,n.slice(1),e,t)}function j7(n,e,t){const o=new JS(e,t);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=fe.default(n),l=s[0];Array.isArray(l)?s.forEach(a=>{hp(a,i,o)}):hp(s,i,o)}o.end()}const tL=S("sharedb-comments");function fp(n){const e=n.blocks;m(tL,e,"no comment blocks");const t={blocks:{root:e},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(t.blocks[o]=r)}),fe.default(t)}function U7(n){const{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}=n;return{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}}function mp(n,e){const t=$D(e),{comments:o,meta:r,blocks:i,...s}=t,l={...n,blocks:i,...s},a=fe.default(l);return delete a.children,a}const ct=S("sharedb-doc/doc-container"),z7="ot-json1";Rd.type.registerSubtype(HD.type),Rd.type.name=z7,Rd.type.invert=null;class Ja extends ua{constructor(t,o,r=!0){super();g(this,"doc");g(this,"client");g(this,"localPresence");g(this,"remoteCaretHandler",new PD);g(this,"batching",0);g(this,"status","clean");g(this,"disableLogout");g(this,"destroyed",!1);g(this,"handleNothingPending",()=>{this.setStatus("clean")});g(this,"handleCreate",()=>{this.handleReload("doc created")});g(this,"handleDel",()=>{});g(this,"handleReload",t=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,t)})});g(this,"handleReset",async t=>{const o=new Error(`reset doc: ${t}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});g(this,"handleWriteConflictError",t=>{this.handleReset(`write conflict: ${t.message}, ${JSON.stringify(t.orgMsg)}`)});g(this,"insertObject",async(t,o,r)=>{const i=[t,o,{i:r}];return this.submitOp(i)});g(this,"deleteObject",async(t,o)=>{const r=[t,o,{r:!0}];return this.submitOp(r)});g(this,"replaceObject",async(t,o,r)=>{const i=[t,o,{r:!0,i:r}];return this.submitOp(i)});g(this,"updateObject",async(t,o,r)=>{const i=this.data()[t][o],s=[t,o];return Object.entries(r).forEach(([l,a])=>{if(!la.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)});g(this,"broadcastMessage",async t=>{const o={type:"custom",data:t,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});g(this,"data",()=>this.doc.data);g(this,"submitOp",async t=>new Promise((o,r)=>{if(this.destroyed){ct.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(t,{},i=>{i?(ct.error(`invalid op, ${i.message}, ${JSON.stringify(t)}`),r(i),ct.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ct.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(t)}`))}));g(this,"createDoc",async t=>new Promise((o,r)=>{this.doc.create(t,z7,i=>{i?r(i):o()})}));g(this,"submitInsertChildContainer",async(t,o)=>{const r=[Ni(t),{i:o}];return this.submitOp(r)});g(this,"submitDeleteChildContainer",async t=>{const o=[Ni(t),{r:!0}];return this.submitOp(o)});g(this,"submitInsertBlock",async(t,o,r)=>{const i=[Ni(t),o,{i:r}];return this.submitOp(i)});g(this,"submitDeleteBlock",async(t,o)=>{const r=[Ni(t),o,{r:!0}];return this.submitOp(r)});g(this,"submitUpdateBlockData",async(t,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[Ni(t),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)});g(this,"submitUpdateRichText",async(t,o,r)=>{const i=[Ni(t),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});g(this,"handleOp",(t,o,r)=>{if(this.destroyed){ct.warn("handleOp: destroyed");return}j7(t,this,!!o)});this.client=t,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--,m(ct,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(t){try{const o=new GS(t.auth,t.serverUrl,t.reauthFunc),r=await o.getDoc(),i=new Ja(o,r,t.disableLogout);if(r.type===null){if(t.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(t.templateData||ZS())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ct.error(o),ct.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,t)}))}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((t,o)=>{if(this.localPresence)t();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()),t())})}})}subscribe(){return new Promise((t,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),t())})})}toJSON(){return Ha(this.data())}getContainerBlocks(t){const o=this.data();m(ct,o,"no doc data");const r=o[Ni(t)];return m(ct,r,`no container data: ${t}`),fe.default(r)}getBlockData(t,o){const r=this.data();m(ct,r,"no doc data");const i=r[Ni(t)];m(ct,i,`no container data: ${t}`);const s=i[o];return m(ct,s,`no block data: ${o}`),fe.default(s)}localInsertBlock(t,o,r){return this.submitInsertBlock(t,o,r),this.getBlockData(t,o)}localDeleteBlock(t,o){const r=this.getBlockData(t,o);return this.submitDeleteBlock(t,o),r}localUpdateBlockText(t,o,r){const i=this.getBlockData(t,o);m(ct,i.text,"no block text");const s=fe.default(i.text);this.submitUpdateRichText(t,o,r);const l=ln.apply(s,r);return m(ct,l,"no block text"),l}localUpdateBlockData(t,o,r){const i=fe.default(this.getBlockData(t,o));return this.submitUpdateBlockData(t,o,r),i}localInsertChildContainer(t,o){this.submitInsertChildContainer(t,o)}localDeleteChildContainers(t){this.beginBatchUpdate(),t.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>U7(o))}getComment(t){return this.data().comments[t]}getCommentDoc(t){const o=this.data().comments[t];return fp(o)}localCreateComment(t,o){const r=mp(t,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(t){const o=["comments",t,{r:!0}];return this.submitOp(o)}localUpdateComment(t,o){const r=mp(t,o),i=["comments",t.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var t;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(t=this.localPresence)==null||t.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(t,o,r){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Jl(t),o,r)})}onInsertBlock(t,o,r,i){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Jl(t),o,r,i)})}onUpdateBlockData(t,o,r,i){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Jl(t),o,r,i)})}onUpdateBlockText(t,o,r,i){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Jl(t),o,r,i)})}onDeleteContainer(t,o){m(ct,this.callbacks.length>0,"no callbacks"),m(ct,t!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Jl(t),o)})}onCreateContainer(t,o,r){m(ct,this.callbacks.length>0,"no callbacks"),m(ct,t!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Jl(t),o,r)})}onDeleteComment(t,o){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,t,o)})}onCreateComment(t,o){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,t,o)})}onUpdateComment(t,o){m(ct,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,t,o)})}onCustomMessage(t){const o=t;(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:t,clientId:"-"};this.onCustomMessage(r)})}async addResources(t){return await this.client.getFileUrlsByHashes(t)}async uploadResource(t,o){var i;return{resourceId:await this.client.uploadResource(t,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(t,o){return this.client.buildResourceUrl(t,o)}request(t,o){return this.client.request(t,o)}getUser(){const t=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:t,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(t){const o=await this.client.getVersion(t);return Ha(o)}async getLatestVersion(){const t=await this.client.getLatestVersion();return Ha(t)}async getHistoryData(t,o){const{doc:r,ops:i}=await this.client.getVersionOps(t,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:Ha(r),historyData:s}}async getVersionData(t,o){const{doc:r,ops:i}=await this.client.getVersionOps(t,o);return{doc:Ha(r),versionData:i}}async updateVersionExtra(t,o,r){await this.client.updateVersionExtra(t,o,r)}revertVersion(t){return this.client.revertVersion(t)}createVersion(t,o){return this.client.createVersion(t,o)}async recognizeLink(t){return this.client.recognizeLink(t)}parseHistoryData(t,o){j7(t.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}S("remote-cursor");class V7{constructor(e){g(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});g(this,"broadcastCaretPos",Ht.default(()=>{const e={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(e)},300));g(this,"handleRemoteCaretsChanged",e=>{e.forEach(t=>{const o=this.editor.findBlockById(t);o&&this.editor.reloadBlock(o)})});this.editor=e,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 W7=S("remote-cursor-decorator");class gp{decorateText(e,t,o){const r=e.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=t[t.length-1];m(W7,typeof s=="string","invalid path containerId"),m(W7,typeof l=="number","invalid path blockIndex");const a=e.doc.getBlockData(s,l),d=rn(o);return r.getSimpleCursors(a.id).forEach((p,A)=>{A>d&&(A=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(A);B?B.push(...v):i.set(A,v)}),{insertions:i}}}class q7 extends At.TypedEmitter{constructor(e){super(),this.editor=e,this.editor.doc.registerCallback(this)}handleChild(e,t,o){if(Xe(Pr(this.editor,e)))return;const r=this.editor.getBlockByIndex(e,t),i=oe(this.editor.getContainerById(e));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(e,t){this.handleChild(e,t,"data-change")}onUpdateBlockText(e,t){this.handleChild(e,t,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function nL(n,e){n.addCustom("child-block-tracker",()=>new q7(n)).addListener("change",e)}function oL(n,e){n.addCustom("child-block-tracker",()=>new q7(n)).removeListener("change",e)}const qte="",rL={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4",name:"\u6587\u672C\u989C\u8272"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},iL={colorPalette:{colorDesc:"Text Color",name:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},sL={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};O.mergeLang({"zh-CN":rL,"en-US":iL,"js-JP":sL});const Gte="";S("button");function ji(n,e,t,o,r){const i=w("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,e),t?typeof t=="string"?t.startsWith("<")?i.innerHTML=t:i.innerText=t:i.appendChild(t):i.innerText=e,o&&(o.indexOf("checked")!==-1&&W(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function G7(n,e,t){t?n.setAttribute(`data-editor-tooltip-${t}`,e):n.innerText=e}const Zte="",ec=S("ui-command-bar-base"),lL={itemElementTag:"div",tippyArrow:!1},q2=class extends At.TypedEmitter{constructor(t,o,r){var i,s;super();g(this,"content");g(this,"items");g(this,"subBar",null);g(this,"parentItem",null);g(this,"closeable",null);g(this,"closeReason",null);g(this,"options");g(this,"id");g(this,"header",null);g(this,"footer",null);g(this,"handleDocumentKeydown",t=>{if(!!this.isVisible&&!t.isComposing&&!Ul(t.target)){if(this.subBar){this.subBar.handleDocumentKeydown(t);return}if(this.items.length!==0){if(t.key==="Escape"){this.close("cancelBar");return}if(t.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),t.preventDefault(),t.stopPropagation()}else if(t.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),t.preventDefault(),t.stopPropagation()}else if(t.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(t.key==="ArrowLeft")this.parentItem&&this.close("switchItem");else if(t.key==="Enter"){const o=this.getSelectedItemIndex();if(o===-1)return;const r=this.items[o],i=this.getItemElementById(r.id);i&&this.emit("click",this,r,i)}}}});g(this,"handleDocumentMouseDown",t=>{if(t.target instanceof Element&&!this.isInCommandBar(t.target)){const o=this.listeners("closing");for(let r=0;r<o.length;r++)if(o[r](this,t)===!1)return;this.close("clickBackground")}});g(this,"handleHidden",()=>{this.closeReason!=="fromHover"&&this.emit("close",this),this.close(null),bC(this.id)});g(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&W(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&AC(this.id)});g(this,"lastEnterPauseTime",0);g(this,"startPauseMouseEnter",()=>{this.lastEnterPauseTime=Date.now()});g(this,"handleItemMouseEnter",t=>{if(Date.now()-this.lastEnterPauseTime<100)return;const o=this.getParentCommandItemElement(t.target);if(!o)return;const r=this.getItemElementId(o),i=this.getItemById(r);if(this.selectItem(r),i.manualShowChildren)return;const s=i.childrenMenuId||"";this.showSubCommandBar(s)});g(this,"handleItemMouseLeave",t=>{var r,i;const o=this.getParentCommandItemElement(t.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(te(o,"selected"),this.emit("selectionChange",this,""))});g(this,"handleItemClick",t=>{const o=this.getParentCommandItemElement(t.target);if(!o)return;const r=this.getItemElementId(o),i=this.items.find(s=>s.id===r);if(!!i&&!(i.states&&i.states.indexOf("disabled")!==-1)){if(i.children&&i.children.length>0&&i.manualShowChildren){this.showSubCommandBar(i.childrenMenuId);return}i.element||(this.emit("click",this,i,o),this.options.autoClose&&this.close("clickItem"))}});g(this,"handleWheel",t=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=t.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=Bo(r);if(!Ke(this.content,i)){t.stopPropagation(),t.preventDefault();return}t.deltaY<0?i.scrollTop===0&&(t.stopPropagation(),t.preventDefault()):t.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(t.stopPropagation(),t.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:K(),this.options={...lL,...r},this.items=t,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(t)}close(t){this.closeReason=t,this.subBar&&this.subBar.close(t),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(t,o){this.emit("click",this,t,o)}createPopperOptions(){var r,i;const t={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=t==null?void 0:t.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),this.options.padding&&((i=t==null?void 0:t.modifiers)==null||i.push({name:"preventOverflow",options:{padding:this.options.padding}})),t}destroy(){var t;this.close(null),this.removeAllListeners(),(t=this.subBar)==null||t.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(t){var r;this.subBar&&t.findIndex(s=>{var l,a;return s.id===((a=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:a.id)})===-1&&((r=this.subBar)==null||r.destroy(),this.subBar=null),this.items=t;const o=this.createCommandBarContent(t);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const t=this.getSelectedItem();return t?this.items.indexOf(t):-1}getPrevItemIndex(t){if(t<=0)return this.items.length-1;let o=t-1;for(;;){const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o-=1,o<=0)return this.items.length-1}}getNextItemIndex(t){let o=t+1;for(;;){if(!this.items[o])return this.getNextItemIndex(-1);const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o+=1,o>this.items.length-1)return 0}}clearSelectedItem(){const t=this.getSelectedItem();if(!t)return;const o=this.getItemElementById(t.id);o&&te(o,"selected")}selectItem(t){const o=this.getSelectedItem();if(o){if(o.id===t)return;const i=o.id,s=this.getItemElementById(i);s&&te(s,"selected")}const r=this.getItemElementById(t);r?(W(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(t){var s,l;const o=this.getSelectedItem();if(!o)return;if(this.subBar){if(((s=this.subBar.parentItem)==null?void 0:s.id)===o.id){o.manualShowChildren&&this.subBar.close("switchItem");return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=q2.createSubCommandBar(o,(l=this.closeable)!=null?l:this,t?{id:t}:{});this.subBar=i,this.subBar.on("click",(a,d,h)=>{this.emit("click",a,d,h)}),this.subBar.on("close",()=>{var a;(a=this.subBar)==null||a.destroy(),this.subBar=null,te(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),W(r,"active")}isInCommandBar(t){if(!t||!(t instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&Ke(o,t)||Ke(this.content,t)?!0:this.subBar?this.subBar.isInCommandBar(t):!1}createCommandItem(t){var i,s,l,a;let o=(i=this.options.itemElementTag)!=null?i:"div";t.element&&(o="div");const r=w(o,["command-item"],null);return r.setAttribute("data-id",t.id),t.type==="separator"?r.classList.add("separator"):t.type==="section"?(r.classList.add("section","text"),t.element&&(typeof t.element=="function"?r.appendChild(t.element(t)):r.appendChild(t.element))):((s=t.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=t.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(a=t.states)!=null&&a.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,t.element?typeof t.element=="function"?r.appendChild(t.element(t)):r.appendChild(t.element):r.classList.add("standard")),this.initItemElement(t,r),r}getItemById(t){const o=this.items.find(r=>r.id===t);return m(ec,o,`can not find command item for id: ${t}`),o}getSelectedItem(){const t=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(t){const o=this.getItemElementId(t),r=this.items.find(i=>i.id===o);return m(ec,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(t){const o=t.getAttribute("data-id");return m(ec,o,"no data-id attribute"),o}getItemElementById(t){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${t}"]`);return m(ec,o,`no exists command item, id=${t}`),o}getParentCommandItemElement(t){if(!t||!(t instanceof Element))return null;if(xe(t,"command-item"))return t;const o=t.closest(".command-item");return o||null}createCommandBarContent(t){this.content&&this.content.removeEventListener("wheel",this.handleWheel);const o=w("div",["editor-command-bar-root"],null);if(this.options.header){const i=w("div",["editor-command-bar-header"],null);if(this.options.header instanceof Function){const s=this.options.header();s&&i.appendChild(s)}else i.appendChild(this.options.header);this.header=i,this.header&&o.appendChild(this.header)}const r=w("div",["editor-command-bar"],o);if(t.forEach(i=>{var l;const s=this.createCommandItem(i);r.appendChild(s),i.element&&i.setCloseable&&i.setCloseable((l=this.closeable)!=null?l:this)}),this.options.footer){const i=w("div",["menu-item","editor-command-bar","footer"],null);if(this.options.footer instanceof Function){const s=this.options.footer();s&&i.appendChild(s)}else i.appendChild(this.options.footer);this.footer=i,this.footer&&o.appendChild(this.footer)}return(this.options.header||this.options.footer)&&W(o,"scrollable-bar"),this.initCommandBarElement(r),o.addEventListener("wheel",this.handleWheel,{passive:!1}),o}getSubBarOptions(t){var o;return{placement:(o=t.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(t,o){this.commandBarCreators.set(t,o)}static createSubCommandBar(t,o,r){var l;m(ec,t.children&&t.children.length>0,"no item children");const i=(l=t.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return m(ec,s,`no creator for command type: ${i}`),s(t,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let Ui=q2;g(Ui,"commandBarCreators",new Map),S("ui-command-bar");class Uh extends Ui{constructor(){super(...arguments);g(this,"tippyInstance",null)}manualShow(t,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=jB.default(t,{interactive:!0,content:this.content,trigger:"manual",triggerTarget:null,hideOnClick:!1,placement:(r=o==null?void 0:o.placement)!=null?r:"bottom-start",maxWidth:650,arrow:this.options.tippyArrow,appendTo:document.body,onShow:this.handleShow,onHidden:this.handleHidden,theme:o==null?void 0:o.theme,getReferenceClientRect:o==null?void 0:o.getReferenceClientRect,offset:(i=o==null?void 0:o.offset)!=null?i:[0,0],popperOptions:this.createPopperOptions()}),o!=null&&o.point){const{x:s,y:l}=o.point;this.tippyInstance.setProps({getReferenceClientRect:()=>new DOMRect(s,l,0,0)})}this.clearSelectedItem(),this.tippyInstance.show(),this.parentItem||(document.addEventListener("keydown",this.handleDocumentKeydown),document.addEventListener("mousedown",this.handleDocumentMouseDown)),this.popper&&this.options.id&&this.popper.setAttribute("data-command-bar-id",this.options.id)}}close(t){var o;super.close(t),this.isVisible&&((o=this.tippyInstance)==null||o.hide())}destroy(){var t;(t=this.tippyInstance)==null||t.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var t,o;return(o=(t=this.tippyInstance)==null?void 0:t.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const Z7=S("ui-base");class Ka extends Uh{constructor(e,t){var i;const r=[{id:(i=t==null?void 0:t.id)!=null?i:`popup-${K()}`,name:"",element:e}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(e){W(e,"popper")}initItemElement(e,t){}get popupContent(){const e=this.items[0];m(Z7,e,"no dialog item");const t=typeof e.element=="function"?e.element(e):e.element;return m(Z7,t,"no item element"),t}}const zi=S("filterable-list");function Q7(n){var t,o;const e=w("div",["list-item"],null);return e.setAttribute("data-id",n.id),e.appendChild(w("div",["list-item-text"],null,n.name)),(t=n.states)!=null&&t.includes("selected")&&W(e,"selected"),(o=n.states)!=null&&o.includes("disabled")&&W(e,"disabled"),e}function Y7(n){const e=w("div",["list-root"],null);return n.forEach(t=>{e.appendChild(Q7(t))}),n.length||e.appendChild(Q7({id:"placeholder",states:["disabled"],name:O.t("search.emptyTips")})),e}function J7(n,e){let t=n;return e&&(t=n.map(o=>({...o,states:o.id===e?["selected"]:void 0}))),t}function cL(n,e){const t=w("div",["filterable-list"],null),o=w("div",["filter"],t),r=w("div",["filter-container"],o),i=w("input",["filter-input"],r);e&&e.placeholder&&(i.placeholder=e.placeholder);const s=w("div",["list"],t),l=Y7(J7(n,e==null?void 0:e.initialSelectedId));return s.appendChild(l),t}function K7(n,e,t){const o=n.querySelector(".list");m(zi,o,"no list root");const r=Y7(J7(e,t)),i=o.querySelector(".list-root");if(m(zi,i,"no exists menu"),ma(i,r),t){const s=o.querySelector(".list-item.selected");s&&(m(zi,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class aL{constructor(e,t){g(this,"root");g(this,"visibleItems");g(this,"selectedId");g(this,"filter","");g(this,"onSelected",null);g(this,"handleKeydown",e=>{this.processKeyDown(e)});g(this,"handleInputChanged",()=>{const e=this.root.querySelector(".filter-input");m(zi,e,"no input");const t=e.value.toLocaleLowerCase();this.setFilter(t)});g(this,"handleClick",e=>{this.processClick(e)});var o;this.items=e,this.options=t,this.root=cL(e,t),this.bindEvents(),this.selectedId=(o=t==null?void 0:t.initialSelectedId)!=null?o:"",this.visibleItems=e}bindEvents(){const e=this.root.querySelector(".filter-input");m(zi,e,"no input"),e.addEventListener("keyup",this.handleInputChanged),e.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const e=this.root.querySelector(".filter-input");m(zi,e,"no input"),e.removeEventListener("keyup",this.handleInputChanged),e.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(e=>e.id===this.selectedId):-1}setSelectedId(e){this.selectedId=e,K7(this.root,this.visibleItems,e)}focus(){const e=this.root.querySelector(".filter-input");m(zi,e,"no input"),e.focus()}reset(){this.setFilter("");const e=this.root.querySelector(".filter-input");m(zi,e,"no input"),e.value=""}setFilter(e){this.filter!==e&&(this.filter=e,this.visibleItems=this.items.filter(t=>t.name.toLocaleLowerCase().includes(e)),K7(this.root,this.visibleItems,this.selectedId))}processClick(e){var s,l;const t=e.target;if(!(t instanceof HTMLElement))return;const o=t.closest(".list-item");if(!o)return;const r=(s=o.getAttribute("data-id"))!=null?s:"",i=(l=this.visibleItems.find(a=>a.id===r))!=null?l:null;this.onSelected&&this.onSelected(this,i)}processKeyDown(e){var t;if(e.key==="ArrowUp"){let o=this.getSelectedIndex();o===-1?o=this.visibleItems.length-1:o>0&&(o-=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(e.key==="ArrowDown"){let o=this.getSelectedIndex();o===-1?o=0:o<this.visibleItems.length-1&&(o+=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(e.key==="Enter"){const o=(t=this.visibleItems.find(r=>r.id===this.selectedId))!=null?t:null;this.onSelected&&this.onSelected(this,o)}}}class uL extends aL{constructor(t,o,r){super(t,r);g(this,"popup");g(this,"onShow",null);g(this,"onHide",null);g(this,"custom",null);g(this,"handleShow",()=>{this.onShow&&this.onShow(this)});g(this,"handleHide",()=>{this.onHide&&this.onHide(this)});g(this,"handleShown",()=>{this.focus()});this.popup=new Ka(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(t){this.reset(),this.popup.manualShow(t,{theme:"dropdown-list"}),this.focus()}processKeyDown(t){super.processKeyDown(t),(t.key==="Esc"||t.key==="Enter")&&this.popup.close("cancelBar")}processClick(t){super.processClick(t);const o=t.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close("clickItem")}}const Qte="",Yte="";function dL(n,e){const t=document.createElement("div");t.classList.add("toast","show"),e!=null&&e.theme&&t.setAttribute("data-theme",e.theme),e!=null&&e.id&&t.setAttribute("data-id",e.id),e!=null&&e.html?t.innerHTML=n:t.textContent=n,e!=null&&e.position&&(t.style.left=`${e.position.x}px`,t.style.top=`${e.position.y}px`,t.classList.add("positioned")),document.body.appendChild(t),setTimeout(()=>{t.classList.remove("show"),setTimeout(()=>{t.remove()},500)},(e==null?void 0:e.duration)||3e3)}const X7=`<?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">